interpreter.cpp 116 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "explorer/interpreter/interpreter.h"
  5. #include <iterator>
  6. #include <limits>
  7. #include <map>
  8. #include <memory>
  9. #include <optional>
  10. #include <random>
  11. #include <utility>
  12. #include <variant>
  13. #include <vector>
  14. #include "common/check.h"
  15. #include "common/error.h"
  16. #include "explorer/ast/address.h"
  17. #include "explorer/ast/declaration.h"
  18. #include "explorer/ast/element.h"
  19. #include "explorer/ast/expression.h"
  20. #include "explorer/ast/expression_category.h"
  21. #include "explorer/ast/value.h"
  22. #include "explorer/common/arena.h"
  23. #include "explorer/common/error_builders.h"
  24. #include "explorer/common/source_location.h"
  25. #include "explorer/common/trace_stream.h"
  26. #include "explorer/interpreter/action.h"
  27. #include "explorer/interpreter/action_stack.h"
  28. #include "explorer/interpreter/stack.h"
  29. #include "llvm/ADT/APInt.h"
  30. #include "llvm/ADT/StringExtras.h"
  31. #include "llvm/Support/Casting.h"
  32. #include "llvm/Support/Error.h"
  33. #include "llvm/Support/FormatVariadic.h"
  34. #include "llvm/Support/raw_ostream.h"
  35. using llvm::cast;
  36. using llvm::dyn_cast;
  37. using llvm::isa;
  38. namespace Carbon {
  39. // Limits for various overflow conditions.
  40. static constexpr int64_t MaxTodoSize = 1e3;
  41. static constexpr int64_t MaxStepsTaken = 1e6;
  42. static constexpr int64_t MaxArenaAllocated = 1e9;
  43. // Constructs an ActionStack suitable for the specified phase.
  44. static auto MakeTodo(Phase phase, Nonnull<Heap*> heap,
  45. Nonnull<TraceStream*> trace_stream) -> ActionStack {
  46. switch (phase) {
  47. case Phase::CompileTime:
  48. return ActionStack(trace_stream);
  49. case Phase::RunTime:
  50. return ActionStack(trace_stream, heap);
  51. }
  52. }
  53. // An Interpreter represents an instance of the Carbon abstract machine. It
  54. // manages the state of the abstract machine, and executes the steps of Actions
  55. // passed to it.
  56. class Interpreter {
  57. public:
  58. // Constructs an Interpreter which allocates values on `arena`, and prints
  59. // traces if `trace` is true. `phase` indicates whether it executes at
  60. // compile time or run time.
  61. Interpreter(Phase phase, Nonnull<Arena*> arena,
  62. Nonnull<TraceStream*> trace_stream,
  63. Nonnull<llvm::raw_ostream*> print_stream)
  64. : arena_(arena),
  65. heap_(trace_stream, arena),
  66. todo_(MakeTodo(phase, &heap_, trace_stream)),
  67. trace_stream_(trace_stream),
  68. print_stream_(print_stream),
  69. phase_(phase) {}
  70. // Runs all the steps of `action`.
  71. // It's not safe to call `RunAllSteps()` or `result()` after an error.
  72. auto RunAllSteps(std::unique_ptr<Action> action) -> ErrorOr<Success>;
  73. // The result produced by the `action` argument of the most recent
  74. // RunAllSteps call. Cannot be called if `action` was an action that doesn't
  75. // produce results.
  76. auto result() const -> Nonnull<const Value*> { return todo_.result(); }
  77. private:
  78. auto Step() -> ErrorOr<Success>;
  79. // State transitions for expressions value generation.
  80. auto StepValueExp() -> ErrorOr<Success>;
  81. // State transitions for expressions.
  82. auto StepExp() -> ErrorOr<Success>;
  83. // State transitions for lvalues.
  84. auto StepLocation() -> ErrorOr<Success>;
  85. // State transitions for witnesses.
  86. auto StepWitness() -> ErrorOr<Success>;
  87. // State transition for statements.
  88. auto StepStmt() -> ErrorOr<Success>;
  89. // State transition for declarations.
  90. auto StepDeclaration() -> ErrorOr<Success>;
  91. // State transition for object destruction.
  92. auto StepCleanUp() -> ErrorOr<Success>;
  93. auto StepDestroy() -> ErrorOr<Success>;
  94. // State transition for type instantiation.
  95. auto StepInstantiateType() -> ErrorOr<Success>;
  96. auto CreateStruct(const std::vector<FieldInitializer>& fields,
  97. const std::vector<Nonnull<const Value*>>& values)
  98. -> Nonnull<const Value*>;
  99. auto EvalPrim(Operator op, Nonnull<const Value*> static_type,
  100. const std::vector<Nonnull<const Value*>>& args,
  101. SourceLocation source_loc) -> ErrorOr<Nonnull<const Value*>>;
  102. // Returns the result of converting `value` to type `destination_type`.
  103. auto Convert(Nonnull<const Value*> value,
  104. Nonnull<const Value*> destination_type,
  105. SourceLocation source_loc) -> ErrorOr<Nonnull<const Value*>>;
  106. // Create a class value and its base class(es) from an init struct.
  107. auto ConvertStructToClass(Nonnull<const StructValue*> init,
  108. Nonnull<const NominalClassType*> class_type,
  109. SourceLocation source_loc)
  110. -> ErrorOr<Nonnull<NominalClassValue*>>;
  111. // Evaluate an expression immediately, recursively, and return its result.
  112. //
  113. // TODO: Stop using this.
  114. auto EvalRecursively(std::unique_ptr<Action> action)
  115. -> ErrorOr<Nonnull<const Value*>>;
  116. // Evaluate an associated constant by evaluating its witness and looking
  117. // inside the impl for the corresponding value.
  118. //
  119. // TODO: This approach doesn't provide values that are known because they
  120. // appear in constraints:
  121. //
  122. // interface Iface { let N:! i32; }
  123. // fn PickType(N: i32) -> type { return i32; }
  124. // fn F[T:! Iface where .N == 5](x: T) {
  125. // var x: PickType(T.N) = 0;
  126. // }
  127. //
  128. // ... will fail because we can't resolve T.N to 5 at compile time.
  129. auto EvalAssociatedConstant(Nonnull<const AssociatedConstant*> assoc,
  130. SourceLocation source_loc)
  131. -> ErrorOr<Nonnull<const Value*>>;
  132. // Instantiate a type by replacing all type variables that occur inside the
  133. // type by the current values of those variables.
  134. //
  135. // For example, suppose T=i32 and U=bool. Then
  136. // __Fn (Point(T)) -> Point(U)
  137. // becomes
  138. // __Fn (Point(i32)) -> Point(bool)
  139. //
  140. // TODO: This should be an Action.
  141. auto InstantiateType(Nonnull<const Value*> type, SourceLocation source_loc)
  142. -> ErrorOr<Nonnull<const Value*>>;
  143. // Instantiate a set of bindings by replacing all type variables that occur
  144. // within it by the current values of those variables.
  145. auto InstantiateBindings(Nonnull<const Bindings*> bindings,
  146. SourceLocation source_loc)
  147. -> ErrorOr<Nonnull<const Bindings*>>;
  148. // Instantiate a witness by replacing all type variables and impl binding
  149. // references that occur within it by the current values of those variables.
  150. auto InstantiateWitness(Nonnull<const Witness*> witness,
  151. SourceLocation source_loc)
  152. -> ErrorOr<Nonnull<const Witness*>>;
  153. // Call the function `fun` with the given `arg` and the `witnesses`
  154. // for the function's impl bindings.
  155. auto CallFunction(const CallExpression& call, Nonnull<const Value*> fun,
  156. Nonnull<const Value*> arg, ImplWitnessMap&& witnesses,
  157. std::optional<AllocationId> location_received)
  158. -> ErrorOr<Success>;
  159. auto CallDestructor(Nonnull<const DestructorDeclaration*> fun,
  160. Nonnull<const Value*> receiver) -> ErrorOr<Success>;
  161. auto phase() const -> Phase { return phase_; }
  162. Nonnull<Arena*> arena_;
  163. Heap heap_;
  164. ActionStack todo_;
  165. Nonnull<TraceStream*> trace_stream_;
  166. // The stream for the Print intrinsic.
  167. Nonnull<llvm::raw_ostream*> print_stream_;
  168. Phase phase_;
  169. // The number of steps taken by the interpreter. Used for infinite loop
  170. // detection.
  171. int64_t steps_taken_ = 0;
  172. };
  173. //
  174. // State Operations
  175. //
  176. auto Interpreter::EvalPrim(Operator op, Nonnull<const Value*> /*static_type*/,
  177. const std::vector<Nonnull<const Value*>>& args,
  178. SourceLocation source_loc)
  179. -> ErrorOr<Nonnull<const Value*>> {
  180. switch (op) {
  181. case Operator::Neg:
  182. case Operator::Add:
  183. case Operator::Sub:
  184. case Operator::Div:
  185. case Operator::Mul: {
  186. llvm::APInt op0(64, cast<IntValue>(*args[0]).value());
  187. llvm::APInt result;
  188. if (op == Operator::Neg) {
  189. result = -op0;
  190. } else {
  191. llvm::APInt op1(64, cast<IntValue>(*args[1]).value());
  192. if (op == Operator::Add) {
  193. result = op0 + op1;
  194. } else if (op == Operator::Sub) {
  195. result = op0 - op1;
  196. } else if (op == Operator::Mul) {
  197. result = op0 * op1;
  198. } else if (op == Operator::Div) {
  199. if (op1.getSExtValue() == 0) {
  200. return ProgramError(source_loc) << "division by zero";
  201. }
  202. result = op0.sdiv(op1);
  203. }
  204. }
  205. if (result.isSignedIntN(32)) {
  206. return arena_->New<IntValue>(result.getSExtValue());
  207. } else {
  208. return ProgramError(source_loc) << "integer overflow";
  209. }
  210. }
  211. case Operator::Mod: {
  212. const auto& lhs = cast<IntValue>(*args[0]).value();
  213. const auto& rhs = cast<IntValue>(*args[1]).value();
  214. if (rhs == 0) {
  215. return ProgramError(source_loc) << "division by zero";
  216. }
  217. return arena_->New<IntValue>(lhs % rhs);
  218. }
  219. case Operator::Not:
  220. return arena_->New<BoolValue>(!cast<BoolValue>(*args[0]).value());
  221. case Operator::And:
  222. return arena_->New<BoolValue>(cast<BoolValue>(*args[0]).value() &&
  223. cast<BoolValue>(*args[1]).value());
  224. case Operator::Or:
  225. return arena_->New<BoolValue>(cast<BoolValue>(*args[0]).value() ||
  226. cast<BoolValue>(*args[1]).value());
  227. case Operator::Ptr:
  228. return arena_->New<PointerType>(args[0]);
  229. case Operator::Deref: {
  230. CARBON_ASSIGN_OR_RETURN(
  231. const auto* value,
  232. heap_.Read(cast<PointerValue>(*args[0]).address(), source_loc));
  233. return arena_->New<ReferenceExpressionValue>(
  234. value, cast<PointerValue>(*args[0]).address());
  235. }
  236. case Operator::AddressOf:
  237. return arena_->New<PointerValue>(cast<LocationValue>(*args[0]).address());
  238. case Operator::As:
  239. case Operator::Eq:
  240. case Operator::NotEq:
  241. case Operator::Less:
  242. case Operator::LessEq:
  243. case Operator::Greater:
  244. case Operator::GreaterEq:
  245. case Operator::BitwiseAnd:
  246. case Operator::BitwiseOr:
  247. case Operator::BitwiseXor:
  248. case Operator::BitShiftLeft:
  249. case Operator::BitShiftRight:
  250. case Operator::Complement:
  251. CARBON_FATAL() << "operator " << OperatorToString(op)
  252. << " should always be rewritten";
  253. }
  254. }
  255. auto Interpreter::CreateStruct(const std::vector<FieldInitializer>& fields,
  256. const std::vector<Nonnull<const Value*>>& values)
  257. -> Nonnull<const Value*> {
  258. CARBON_CHECK(fields.size() == values.size());
  259. std::vector<NamedValue> elements;
  260. for (size_t i = 0; i < fields.size(); ++i) {
  261. elements.push_back({fields[i].name(), values[i]});
  262. }
  263. return arena_->New<StructValue>(std::move(elements));
  264. }
  265. static auto InitializePlaceholderValue(const ValueNodeView& value_node,
  266. ExpressionResult v,
  267. Nonnull<RuntimeScope*> bindings) {
  268. switch (value_node.expression_category()) {
  269. case ExpressionCategory::Reference:
  270. if (v.expression_category() == ExpressionCategory::Value ||
  271. v.expression_category() == ExpressionCategory::Reference) {
  272. // Build by copying from value or reference expression.
  273. bindings->Initialize(value_node, v.value());
  274. } else {
  275. // Location initialized by initializing expression, bind node to
  276. // address.
  277. CARBON_CHECK(v.address())
  278. << "Missing location from initializing expression";
  279. bindings->Bind(value_node, *v.address());
  280. }
  281. break;
  282. case ExpressionCategory::Value:
  283. if (v.expression_category() == ExpressionCategory::Value) {
  284. // TODO: Ensure value expressions of temporaries are registered as
  285. // allocation to allow us to reference it without the need for a copy.
  286. bindings->Initialize(value_node, v.value());
  287. } else if (v.expression_category() == ExpressionCategory::Reference) {
  288. // Bind the reference expression value directly.
  289. CARBON_CHECK(v.address())
  290. << "Missing location from reference expression";
  291. bindings->BindAndPin(value_node, *v.address());
  292. } else {
  293. // Location initialized by initializing expression, bind node to
  294. // address.
  295. CARBON_CHECK(v.address())
  296. << "Missing location from initializing expression";
  297. bindings->Bind(value_node, *v.address());
  298. }
  299. break;
  300. case ExpressionCategory::Initializing:
  301. CARBON_FATAL() << "Cannot pattern match an initializing expression";
  302. break;
  303. }
  304. }
  305. auto PatternMatch(Nonnull<const Value*> p, ExpressionResult v,
  306. SourceLocation source_loc,
  307. std::optional<Nonnull<RuntimeScope*>> bindings,
  308. BindingMap& generic_args, Nonnull<TraceStream*> trace_stream,
  309. Nonnull<Arena*> arena) -> bool {
  310. if (trace_stream->is_enabled()) {
  311. *trace_stream << "match pattern " << *p << "\nfrom "
  312. << ExpressionCategoryToString(v.expression_category())
  313. << " expression with value " << *v.value() << "\n";
  314. }
  315. const auto make_expr_result =
  316. [](Nonnull<const Value*> v) -> ExpressionResult {
  317. if (const auto* expr_v = dyn_cast<ReferenceExpressionValue>(v)) {
  318. return ExpressionResult::Reference(expr_v->value(), expr_v->address());
  319. }
  320. return ExpressionResult::Value(v);
  321. };
  322. if (v.value()->kind() == Value::Kind::ReferenceExpressionValue) {
  323. return PatternMatch(p, make_expr_result(v.value()), source_loc, bindings,
  324. generic_args, trace_stream, arena);
  325. }
  326. switch (p->kind()) {
  327. case Value::Kind::BindingPlaceholderValue: {
  328. CARBON_CHECK(bindings.has_value());
  329. const auto& placeholder = cast<BindingPlaceholderValue>(*p);
  330. if (placeholder.value_node().has_value()) {
  331. InitializePlaceholderValue(*placeholder.value_node(), v, *bindings);
  332. }
  333. return true;
  334. }
  335. case Value::Kind::AddrValue: {
  336. const auto& addr = cast<AddrValue>(*p);
  337. CARBON_CHECK(v.value()->kind() == Value::Kind::LocationValue);
  338. const auto& location = cast<LocationValue>(*v.value());
  339. return PatternMatch(
  340. &addr.pattern(),
  341. ExpressionResult::Value(arena->New<PointerValue>(location.address())),
  342. source_loc, bindings, generic_args, trace_stream, arena);
  343. }
  344. case Value::Kind::VariableType: {
  345. const auto& var_type = cast<VariableType>(*p);
  346. generic_args[&var_type.binding()] = v.value();
  347. return true;
  348. }
  349. case Value::Kind::TupleType:
  350. case Value::Kind::TupleValue:
  351. switch (v.value()->kind()) {
  352. case Value::Kind::TupleType:
  353. case Value::Kind::TupleValue: {
  354. const auto& p_tup = cast<TupleValueBase>(*p);
  355. const auto& v_tup = cast<TupleValueBase>(*v.value());
  356. CARBON_CHECK(p_tup.elements().size() == v_tup.elements().size());
  357. for (size_t i = 0; i < p_tup.elements().size(); ++i) {
  358. if (!PatternMatch(p_tup.elements()[i],
  359. make_expr_result(v_tup.elements()[i]), source_loc,
  360. bindings, generic_args, trace_stream, arena)) {
  361. return false;
  362. }
  363. } // for
  364. return true;
  365. }
  366. case Value::Kind::UninitializedValue: {
  367. const auto& p_tup = cast<TupleValueBase>(*p);
  368. for (const auto& ele : p_tup.elements()) {
  369. if (!PatternMatch(ele,
  370. ExpressionResult::Value(
  371. arena->New<UninitializedValue>(ele)),
  372. source_loc, bindings, generic_args, trace_stream,
  373. arena)) {
  374. return false;
  375. }
  376. }
  377. return true;
  378. }
  379. default:
  380. CARBON_FATAL() << "expected a tuple value in pattern, not "
  381. << *v.value();
  382. }
  383. case Value::Kind::StructValue: {
  384. const auto& p_struct = cast<StructValue>(*p);
  385. const auto& v_struct = cast<StructValue>(*v.value());
  386. CARBON_CHECK(p_struct.elements().size() == v_struct.elements().size());
  387. for (size_t i = 0; i < p_struct.elements().size(); ++i) {
  388. CARBON_CHECK(p_struct.elements()[i].name ==
  389. v_struct.elements()[i].name);
  390. if (!PatternMatch(p_struct.elements()[i].value,
  391. ExpressionResult::Value(v_struct.elements()[i].value),
  392. source_loc, bindings, generic_args, trace_stream,
  393. arena)) {
  394. return false;
  395. }
  396. }
  397. return true;
  398. }
  399. case Value::Kind::AlternativeValue:
  400. switch (v.value()->kind()) {
  401. case Value::Kind::AlternativeValue: {
  402. const auto& p_alt = cast<AlternativeValue>(*p);
  403. const auto& v_alt = cast<AlternativeValue>(*v.value());
  404. if (&p_alt.alternative() != &v_alt.alternative()) {
  405. return false;
  406. }
  407. CARBON_CHECK(p_alt.argument().has_value() ==
  408. v_alt.argument().has_value());
  409. if (!p_alt.argument().has_value()) {
  410. return true;
  411. }
  412. return PatternMatch(
  413. *p_alt.argument(), ExpressionResult::Value(*v_alt.argument()),
  414. source_loc, bindings, generic_args, trace_stream, arena);
  415. }
  416. default:
  417. CARBON_FATAL() << "expected a choice alternative in pattern, not "
  418. << *v.value();
  419. }
  420. case Value::Kind::UninitializedValue:
  421. CARBON_FATAL() << "uninitialized value is not allowed in pattern "
  422. << *v.value();
  423. case Value::Kind::FunctionType:
  424. switch (v.value()->kind()) {
  425. case Value::Kind::FunctionType: {
  426. const auto& p_fn = cast<FunctionType>(*p);
  427. const auto& v_fn = cast<FunctionType>(*v.value());
  428. if (!PatternMatch(&p_fn.parameters(),
  429. ExpressionResult::Value(&v_fn.parameters()),
  430. source_loc, bindings, generic_args, trace_stream,
  431. arena)) {
  432. return false;
  433. }
  434. if (!PatternMatch(&p_fn.return_type(),
  435. ExpressionResult::Value(&v_fn.return_type()),
  436. source_loc, bindings, generic_args, trace_stream,
  437. arena)) {
  438. return false;
  439. }
  440. return true;
  441. }
  442. default:
  443. return false;
  444. }
  445. case Value::Kind::AutoType:
  446. // `auto` matches any type, without binding any new names. We rely
  447. // on the typechecker to ensure that `v.value()` is a type.
  448. return true;
  449. case Value::Kind::StaticArrayType: {
  450. switch (v.value()->kind()) {
  451. case Value::Kind::TupleType:
  452. case Value::Kind::TupleValue: {
  453. return true;
  454. }
  455. case Value::Kind::StaticArrayType: {
  456. const auto& v_arr = cast<StaticArrayType>(*v.value());
  457. return v_arr.has_size();
  458. }
  459. default:
  460. return false;
  461. }
  462. }
  463. default:
  464. return ValueEqual(p, v.value(), std::nullopt);
  465. }
  466. }
  467. auto Interpreter::StepLocation() -> ErrorOr<Success> {
  468. Action& act = todo_.CurrentAction();
  469. const Expression& exp = cast<LocationAction>(act).expression();
  470. if (trace_stream_->is_enabled()) {
  471. *trace_stream_ << "--- step location " << exp << " ." << act.pos() << "."
  472. << " (" << exp.source_loc() << ") --->\n";
  473. }
  474. switch (exp.kind()) {
  475. case ExpressionKind::IdentifierExpression: {
  476. // { {x :: C, E, F} :: S, H}
  477. // -> { {E(x) :: C, E, F} :: S, H}
  478. CARBON_ASSIGN_OR_RETURN(
  479. Nonnull<const Value*> value,
  480. todo_.ValueOfNode(cast<IdentifierExpression>(exp).value_node(),
  481. exp.source_loc()));
  482. CARBON_CHECK(isa<LocationValue>(value)) << *value;
  483. return todo_.FinishAction(value);
  484. }
  485. case ExpressionKind::SimpleMemberAccessExpression: {
  486. const auto& access = cast<SimpleMemberAccessExpression>(exp);
  487. const auto constant_value = access.constant_value();
  488. if (auto rewrite = access.rewritten_form()) {
  489. return todo_.ReplaceWith(std::make_unique<LocationAction>(*rewrite));
  490. }
  491. if (act.pos() == 0) {
  492. // { {e.f :: C, E, F} :: S, H}
  493. // -> { e :: [].f :: C, E, F} :: S, H}
  494. return todo_.Spawn(std::make_unique<LocationAction>(&access.object()));
  495. } else if (act.pos() == 1 && constant_value) {
  496. return todo_.Spawn(std::make_unique<TypeInstantiationAction>(
  497. *constant_value, access.source_loc()));
  498. } else {
  499. if (constant_value) {
  500. return todo_.FinishAction(act.results().back());
  501. } else {
  502. // { v :: [].f :: C, E, F} :: S, H}
  503. // -> { { &v.f :: C, E, F} :: S, H }
  504. Address object = cast<LocationValue>(*act.results()[0]).address();
  505. Address member = object.ElementAddress(&access.member());
  506. return todo_.FinishAction(arena_->New<LocationValue>(member));
  507. }
  508. }
  509. }
  510. case ExpressionKind::CompoundMemberAccessExpression: {
  511. const auto& access = cast<CompoundMemberAccessExpression>(exp);
  512. const auto constant_value = access.constant_value();
  513. if (act.pos() == 0) {
  514. return todo_.Spawn(std::make_unique<LocationAction>(&access.object()));
  515. }
  516. if (act.pos() == 1 && constant_value) {
  517. return todo_.Spawn(std::make_unique<TypeInstantiationAction>(
  518. *constant_value, access.source_loc()));
  519. } else {
  520. if (constant_value) {
  521. return todo_.FinishAction(act.results().back());
  522. }
  523. CARBON_CHECK(!access.member().interface().has_value())
  524. << "unexpected location interface member";
  525. CARBON_ASSIGN_OR_RETURN(
  526. Nonnull<const Value*> val,
  527. Convert(act.results()[0], *access.member().base_type(),
  528. exp.source_loc()));
  529. Address object = cast<LocationValue>(*val).address();
  530. Address field = object.ElementAddress(&access.member().member());
  531. return todo_.FinishAction(arena_->New<LocationValue>(field));
  532. }
  533. }
  534. case ExpressionKind::BaseAccessExpression: {
  535. const auto& access = cast<BaseAccessExpression>(exp);
  536. if (act.pos() == 0) {
  537. // Get LocationValue for expression.
  538. return todo_.Spawn(std::make_unique<LocationAction>(&access.object()));
  539. } else {
  540. // Append `.base` element to the address, and return the new
  541. // LocationValue.
  542. Address object = cast<LocationValue>(*act.results()[0]).address();
  543. Address base = object.ElementAddress(&access.element());
  544. return todo_.FinishAction(arena_->New<LocationValue>(base));
  545. }
  546. }
  547. case ExpressionKind::IndexExpression: {
  548. if (act.pos() == 0) {
  549. // { {e[i] :: C, E, F} :: S, H}
  550. // -> { e :: [][i] :: C, E, F} :: S, H}
  551. return todo_.Spawn(std::make_unique<LocationAction>(
  552. &cast<IndexExpression>(exp).object()));
  553. } else if (act.pos() == 1) {
  554. return todo_.Spawn(std::make_unique<ValueExpressionAction>(
  555. &cast<IndexExpression>(exp).offset()));
  556. } else {
  557. // { v :: [][i] :: C, E, F} :: S, H}
  558. // -> { { &v[i] :: C, E, F} :: S, H }
  559. Address object = cast<LocationValue>(*act.results()[0]).address();
  560. const auto index = cast<IntValue>(*act.results()[1]).value();
  561. Address field = object.ElementAddress(
  562. arena_->New<PositionalElement>(index, &exp.static_type()));
  563. return todo_.FinishAction(arena_->New<LocationValue>(field));
  564. }
  565. }
  566. case ExpressionKind::OperatorExpression: {
  567. const auto& op = cast<OperatorExpression>(exp);
  568. if (auto rewrite = op.rewritten_form()) {
  569. return todo_.ReplaceWith(std::make_unique<LocationAction>(*rewrite));
  570. }
  571. if (op.op() != Operator::Deref) {
  572. CARBON_FATAL()
  573. << "Can't treat primitive operator expression as location: " << exp;
  574. }
  575. if (act.pos() == 0) {
  576. return todo_.Spawn(
  577. std::make_unique<ValueExpressionAction>(op.arguments()[0]));
  578. } else {
  579. const auto& res = cast<PointerValue>(*act.results()[0]);
  580. return todo_.FinishAction(arena_->New<LocationValue>(res.address()));
  581. }
  582. break;
  583. }
  584. case ExpressionKind::TupleLiteral:
  585. case ExpressionKind::StructLiteral:
  586. case ExpressionKind::StructTypeLiteral:
  587. case ExpressionKind::IntLiteral:
  588. case ExpressionKind::BoolLiteral:
  589. case ExpressionKind::CallExpression:
  590. case ExpressionKind::IntTypeLiteral:
  591. case ExpressionKind::BoolTypeLiteral:
  592. case ExpressionKind::TypeTypeLiteral:
  593. case ExpressionKind::FunctionTypeLiteral:
  594. case ExpressionKind::StringLiteral:
  595. case ExpressionKind::StringTypeLiteral:
  596. case ExpressionKind::ValueLiteral:
  597. case ExpressionKind::IntrinsicExpression:
  598. case ExpressionKind::IfExpression:
  599. case ExpressionKind::WhereExpression:
  600. case ExpressionKind::DotSelfExpression:
  601. case ExpressionKind::ArrayTypeLiteral:
  602. case ExpressionKind::BuiltinConvertExpression:
  603. CARBON_FATAL() << "Can't treat expression as location: " << exp;
  604. case ExpressionKind::UnimplementedExpression:
  605. CARBON_FATAL() << "Unimplemented: " << exp;
  606. }
  607. }
  608. auto Interpreter::EvalRecursively(std::unique_ptr<Action> action)
  609. -> ErrorOr<Nonnull<const Value*>> {
  610. todo_.BeginRecursiveAction();
  611. CARBON_RETURN_IF_ERROR(todo_.Spawn(std::move(action)));
  612. // Note that the only `RecursiveAction` we can encounter here is our own --
  613. // if a nested action begins a recursive action, it will run until that
  614. // action is finished and popped off the queue before returning to us.
  615. while (!isa<RecursiveAction>(todo_.CurrentAction())) {
  616. CARBON_RETURN_IF_ERROR(Step());
  617. }
  618. if (trace_stream_->is_enabled()) {
  619. *trace_stream_ << "--- recursive eval done\n";
  620. }
  621. Nonnull<const Value*> result =
  622. cast<RecursiveAction>(todo_.CurrentAction()).results()[0];
  623. CARBON_RETURN_IF_ERROR(todo_.FinishAction());
  624. return result;
  625. }
  626. auto Interpreter::EvalAssociatedConstant(
  627. Nonnull<const AssociatedConstant*> assoc, SourceLocation source_loc)
  628. -> ErrorOr<Nonnull<const Value*>> {
  629. // Instantiate the associated constant.
  630. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> interface,
  631. InstantiateType(&assoc->interface(), source_loc));
  632. CARBON_ASSIGN_OR_RETURN(Nonnull<const Witness*> witness,
  633. InstantiateWitness(&assoc->witness(), source_loc));
  634. const auto* impl_witness = dyn_cast<ImplWitness>(witness);
  635. if (!impl_witness) {
  636. CARBON_CHECK(phase() == Phase::CompileTime)
  637. << "symbolic witnesses should only be formed at compile time";
  638. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> base,
  639. InstantiateType(&assoc->base(), source_loc));
  640. return arena_->New<AssociatedConstant>(base, cast<InterfaceType>(interface),
  641. &assoc->constant(), witness);
  642. }
  643. // We have an impl. Extract the value from it.
  644. Nonnull<const ConstraintType*> constraint =
  645. impl_witness->declaration().constraint_type();
  646. std::optional<Nonnull<const Value*>> result;
  647. for (const auto& rewrite : constraint->rewrite_constraints()) {
  648. if (&rewrite.constant->constant() == &assoc->constant() &&
  649. TypeEqual(&rewrite.constant->interface(), interface, std::nullopt)) {
  650. // TODO: The value might depend on the parameters of the impl. We need to
  651. // substitute impl_witness->type_args() into the value.
  652. result = rewrite.converted_replacement;
  653. break;
  654. }
  655. }
  656. if (!result) {
  657. CARBON_FATAL() << impl_witness->declaration() << " with constraint "
  658. << *constraint
  659. << " is missing value for associated constant "
  660. << *interface << "." << assoc->constant().binding().name();
  661. }
  662. return *result;
  663. }
  664. auto Interpreter::InstantiateType(Nonnull<const Value*> type,
  665. SourceLocation source_loc)
  666. -> ErrorOr<Nonnull<const Value*>> {
  667. switch (type->kind()) {
  668. case Value::Kind::VariableType: {
  669. CARBON_ASSIGN_OR_RETURN(
  670. Nonnull<const Value*> value,
  671. todo_.ValueOfNode(&cast<VariableType>(*type).binding(), source_loc));
  672. if (const auto* location = dyn_cast<LocationValue>(value)) {
  673. CARBON_ASSIGN_OR_RETURN(value,
  674. heap_.Read(location->address(), source_loc));
  675. }
  676. return value;
  677. }
  678. case Value::Kind::InterfaceType: {
  679. const auto& interface_type = cast<InterfaceType>(*type);
  680. CARBON_ASSIGN_OR_RETURN(
  681. Nonnull<const Bindings*> bindings,
  682. InstantiateBindings(&interface_type.bindings(), source_loc));
  683. return arena_->New<InterfaceType>(&interface_type.declaration(),
  684. bindings);
  685. }
  686. case Value::Kind::NamedConstraintType: {
  687. const auto& constraint_type = cast<NamedConstraintType>(*type);
  688. CARBON_ASSIGN_OR_RETURN(
  689. Nonnull<const Bindings*> bindings,
  690. InstantiateBindings(&constraint_type.bindings(), source_loc));
  691. return arena_->New<NamedConstraintType>(&constraint_type.declaration(),
  692. bindings);
  693. }
  694. case Value::Kind::ChoiceType: {
  695. const auto& choice_type = cast<ChoiceType>(*type);
  696. CARBON_ASSIGN_OR_RETURN(
  697. Nonnull<const Bindings*> bindings,
  698. InstantiateBindings(&choice_type.bindings(), source_loc));
  699. return arena_->New<ChoiceType>(&choice_type.declaration(), bindings);
  700. }
  701. case Value::Kind::AssociatedConstant: {
  702. CARBON_ASSIGN_OR_RETURN(
  703. Nonnull<const Value*> type_value,
  704. EvalAssociatedConstant(cast<AssociatedConstant>(type), source_loc));
  705. return type_value;
  706. }
  707. default:
  708. return type;
  709. }
  710. }
  711. auto Interpreter::InstantiateBindings(Nonnull<const Bindings*> bindings,
  712. SourceLocation source_loc)
  713. -> ErrorOr<Nonnull<const Bindings*>> {
  714. BindingMap args = bindings->args();
  715. for (auto& [var, arg] : args) {
  716. CARBON_ASSIGN_OR_RETURN(arg, InstantiateType(arg, source_loc));
  717. }
  718. ImplWitnessMap witnesses = bindings->witnesses();
  719. for (auto& [bind, witness] : witnesses) {
  720. CARBON_ASSIGN_OR_RETURN(
  721. witness, InstantiateWitness(cast<Witness>(witness), source_loc));
  722. }
  723. if (args == bindings->args() && witnesses == bindings->witnesses()) {
  724. return bindings;
  725. }
  726. return arena_->New<Bindings>(std::move(args), std::move(witnesses));
  727. }
  728. auto Interpreter::InstantiateWitness(Nonnull<const Witness*> witness,
  729. SourceLocation source_loc)
  730. -> ErrorOr<Nonnull<const Witness*>> {
  731. CARBON_ASSIGN_OR_RETURN(
  732. Nonnull<const Value*> value,
  733. EvalRecursively(std::make_unique<WitnessAction>(witness, source_loc)));
  734. return cast<Witness>(value);
  735. }
  736. auto Interpreter::ConvertStructToClass(
  737. Nonnull<const StructValue*> init_struct,
  738. Nonnull<const NominalClassType*> class_type, SourceLocation source_loc)
  739. -> ErrorOr<Nonnull<NominalClassValue*>> {
  740. std::vector<NamedValue> struct_values;
  741. std::optional<Nonnull<const NominalClassValue*>> base_instance;
  742. // Instantiate the `destination_type` to obtain the runtime
  743. // type of the object.
  744. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> inst_class,
  745. InstantiateType(class_type, source_loc));
  746. for (const auto& field : init_struct->elements()) {
  747. if (field.name == NominalClassValue::BaseField) {
  748. CARBON_CHECK(class_type->base().has_value())
  749. << "Invalid 'base' field for class '"
  750. << class_type->declaration().name() << "' without base class.";
  751. CARBON_ASSIGN_OR_RETURN(
  752. auto base,
  753. Convert(field.value, class_type->base().value(), source_loc));
  754. base_instance = cast<NominalClassValue>(base);
  755. } else {
  756. struct_values.push_back(field);
  757. }
  758. }
  759. CARBON_CHECK(!cast<NominalClassType>(inst_class)->base() || base_instance)
  760. << "Invalid conversion for `" << *inst_class << "`: base class missing";
  761. auto* converted_init_struct =
  762. arena_->New<StructValue>(std::move(struct_values));
  763. Nonnull<const NominalClassValue** const> class_value_ptr =
  764. base_instance ? (*base_instance)->class_value_ptr()
  765. : arena_->New<const NominalClassValue*>();
  766. return arena_->New<NominalClassValue>(inst_class, converted_init_struct,
  767. base_instance, class_value_ptr);
  768. }
  769. auto Interpreter::Convert(Nonnull<const Value*> value,
  770. Nonnull<const Value*> destination_type,
  771. SourceLocation source_loc)
  772. -> ErrorOr<Nonnull<const Value*>> {
  773. switch (value->kind()) {
  774. case Value::Kind::IntValue:
  775. case Value::Kind::FunctionValue:
  776. case Value::Kind::DestructorValue:
  777. case Value::Kind::BoundMethodValue:
  778. case Value::Kind::LocationValue:
  779. case Value::Kind::BoolValue:
  780. case Value::Kind::NominalClassValue:
  781. case Value::Kind::AlternativeValue:
  782. case Value::Kind::UninitializedValue:
  783. case Value::Kind::IntType:
  784. case Value::Kind::BoolType:
  785. case Value::Kind::TypeType:
  786. case Value::Kind::FunctionType:
  787. case Value::Kind::PointerType:
  788. case Value::Kind::TupleType:
  789. case Value::Kind::StructType:
  790. case Value::Kind::AutoType:
  791. case Value::Kind::NominalClassType:
  792. case Value::Kind::MixinPseudoType:
  793. case Value::Kind::InterfaceType:
  794. case Value::Kind::NamedConstraintType:
  795. case Value::Kind::ConstraintType:
  796. case Value::Kind::ImplWitness:
  797. case Value::Kind::BindingWitness:
  798. case Value::Kind::ConstraintWitness:
  799. case Value::Kind::ConstraintImplWitness:
  800. case Value::Kind::ParameterizedEntityName:
  801. case Value::Kind::ChoiceType:
  802. case Value::Kind::BindingPlaceholderValue:
  803. case Value::Kind::AddrValue:
  804. case Value::Kind::AlternativeConstructorValue:
  805. case Value::Kind::StringType:
  806. case Value::Kind::StringValue:
  807. case Value::Kind::TypeOfMixinPseudoType:
  808. case Value::Kind::TypeOfParameterizedEntityName:
  809. case Value::Kind::TypeOfMemberName:
  810. case Value::Kind::TypeOfNamespaceName:
  811. case Value::Kind::StaticArrayType:
  812. case Value::Kind::MemberName:
  813. // TODO: add `CARBON_CHECK(TypeEqual(type, value->dynamic_type()))`, once
  814. // we have Value::dynamic_type.
  815. return value;
  816. case Value::Kind::StructValue: {
  817. const auto& struct_val = cast<StructValue>(*value);
  818. switch (destination_type->kind()) {
  819. case Value::Kind::StructType: {
  820. const auto& destination_struct_type =
  821. cast<StructType>(*destination_type);
  822. std::vector<NamedValue> new_elements;
  823. for (const auto& [field_name, field_type] :
  824. destination_struct_type.fields()) {
  825. std::optional<Nonnull<const Value*>> old_value =
  826. struct_val.FindField(field_name);
  827. CARBON_ASSIGN_OR_RETURN(
  828. Nonnull<const Value*> val,
  829. Convert(*old_value, field_type, source_loc));
  830. new_elements.push_back({field_name, val});
  831. }
  832. return arena_->New<StructValue>(std::move(new_elements));
  833. }
  834. case Value::Kind::NominalClassType: {
  835. CARBON_ASSIGN_OR_RETURN(
  836. auto class_value,
  837. ConvertStructToClass(cast<StructValue>(value),
  838. cast<NominalClassType>(destination_type),
  839. source_loc));
  840. return class_value;
  841. }
  842. case Value::Kind::TypeType:
  843. case Value::Kind::ConstraintType:
  844. case Value::Kind::NamedConstraintType:
  845. case Value::Kind::InterfaceType: {
  846. CARBON_CHECK(struct_val.elements().empty())
  847. << "only empty structs convert to `type`";
  848. return arena_->New<StructType>();
  849. }
  850. default: {
  851. CARBON_CHECK(IsValueKindDependent(destination_type) ||
  852. isa<TypeType, ConstraintType>(destination_type))
  853. << "Can't convert value " << *value << " to type "
  854. << *destination_type;
  855. return value;
  856. }
  857. }
  858. }
  859. case Value::Kind::TupleValue: {
  860. const auto* tuple = cast<TupleValue>(value);
  861. std::vector<Nonnull<const Value*>> destination_element_types;
  862. switch (destination_type->kind()) {
  863. case Value::Kind::TupleType:
  864. destination_element_types =
  865. cast<TupleType>(destination_type)->elements();
  866. break;
  867. case Value::Kind::StaticArrayType: {
  868. const auto& array_type = cast<StaticArrayType>(*destination_type);
  869. CARBON_CHECK(array_type.has_size());
  870. destination_element_types.resize(array_type.size(),
  871. &array_type.element_type());
  872. break;
  873. }
  874. case Value::Kind::TypeType:
  875. case Value::Kind::ConstraintType:
  876. case Value::Kind::NamedConstraintType:
  877. case Value::Kind::InterfaceType: {
  878. std::vector<Nonnull<const Value*>> new_elements;
  879. Nonnull<const Value*> type_type = arena_->New<TypeType>();
  880. for (Nonnull<const Value*> value : tuple->elements()) {
  881. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> value_as_type,
  882. Convert(value, type_type, source_loc));
  883. new_elements.push_back(value_as_type);
  884. }
  885. return arena_->New<TupleType>(std::move(new_elements));
  886. }
  887. default: {
  888. CARBON_CHECK(IsValueKindDependent(destination_type) ||
  889. isa<TypeType, ConstraintType>(destination_type))
  890. << "Can't convert value " << *value << " to type "
  891. << *destination_type;
  892. return value;
  893. }
  894. }
  895. CARBON_CHECK(tuple->elements().size() ==
  896. destination_element_types.size());
  897. std::vector<Nonnull<const Value*>> new_elements;
  898. for (size_t i = 0; i < tuple->elements().size(); ++i) {
  899. CARBON_ASSIGN_OR_RETURN(
  900. Nonnull<const Value*> val,
  901. Convert(tuple->elements()[i], destination_element_types[i],
  902. source_loc));
  903. new_elements.push_back(val);
  904. }
  905. return arena_->New<TupleValue>(std::move(new_elements));
  906. }
  907. case Value::Kind::VariableType: {
  908. std::optional<Nonnull<const Value*>> source_type;
  909. // While type-checking a `where` expression, we can evaluate a reference
  910. // to its self binding before we know its type. In this case, the self
  911. // binding is always a type.
  912. //
  913. // TODO: Add a conversion kind to BuiltinConvertExpression so that we
  914. // don't need to look at the types and reconstruct what kind of
  915. // conversion is being performed from here.
  916. if (cast<VariableType>(value)->binding().is_type_checked()) {
  917. CARBON_ASSIGN_OR_RETURN(
  918. source_type,
  919. InstantiateType(&cast<VariableType>(value)->binding().static_type(),
  920. source_loc));
  921. }
  922. if (isa<TypeType, ConstraintType, NamedConstraintType, InterfaceType>(
  923. destination_type) &&
  924. (!source_type ||
  925. isa<TypeType, ConstraintType, NamedConstraintType, InterfaceType>(
  926. *source_type))) {
  927. // No further conversions are required.
  928. return value;
  929. }
  930. // We need to convert this, and we don't know how because we don't have
  931. // the value yet.
  932. return ProgramError(source_loc)
  933. << "value of generic binding " << *value << " is not known";
  934. }
  935. case Value::Kind::AssociatedConstant: {
  936. CARBON_ASSIGN_OR_RETURN(
  937. Nonnull<const Value*> value,
  938. EvalAssociatedConstant(cast<AssociatedConstant>(value), source_loc));
  939. if (const auto* new_const = dyn_cast<AssociatedConstant>(value)) {
  940. // TODO: Detect whether conversions are required in type-checking.
  941. if (isa<TypeType, ConstraintType, NamedConstraintType, InterfaceType>(
  942. destination_type) &&
  943. isa<TypeType, ConstraintType, NamedConstraintType, InterfaceType>(
  944. new_const->constant().static_type())) {
  945. // No further conversions are required.
  946. return value;
  947. }
  948. // We need to convert this, and we don't know how because we don't have
  949. // the value yet.
  950. return ProgramError(source_loc)
  951. << "value of associated constant " << *value << " is not known";
  952. }
  953. return Convert(value, destination_type, source_loc);
  954. }
  955. case Value::Kind::PointerValue: {
  956. if (destination_type->kind() != Value::Kind::PointerType ||
  957. cast<PointerType>(destination_type)->pointee_type().kind() !=
  958. Value::Kind::NominalClassType) {
  959. // No conversion needed.
  960. return value;
  961. }
  962. // Get pointee value.
  963. const auto* src_ptr = cast<PointerValue>(value);
  964. CARBON_ASSIGN_OR_RETURN(const auto* pointee,
  965. heap_.Read(src_ptr->address(), source_loc))
  966. CARBON_CHECK(pointee->kind() == Value::Kind::NominalClassValue)
  967. << "Unexpected pointer type";
  968. // Conversion logic for subtyping for function arguments only.
  969. // TODO: Drop when able to rewrite subtyping in TypeChecker for arguments.
  970. const auto* dest_ptr = cast<PointerType>(destination_type);
  971. std::optional<Nonnull<const NominalClassValue*>> class_subobj =
  972. cast<NominalClassValue>(pointee);
  973. auto new_addr = src_ptr->address();
  974. while (class_subobj) {
  975. if (TypeEqual(&(*class_subobj)->type(), &dest_ptr->pointee_type(),
  976. std::nullopt)) {
  977. return arena_->New<PointerValue>(new_addr);
  978. }
  979. class_subobj = (*class_subobj)->base();
  980. new_addr = new_addr.ElementAddress(
  981. arena_->New<BaseElement>(&dest_ptr->pointee_type()));
  982. }
  983. // Unable to resolve, return as-is.
  984. // TODO: Produce error instead once we can properly substitute
  985. // parameterized types for pointers in function call parameters.
  986. return value;
  987. }
  988. case Value::Kind::ReferenceExpressionValue: {
  989. const auto* expr_value = cast<ReferenceExpressionValue>(value);
  990. CARBON_ASSIGN_OR_RETURN(
  991. Nonnull<const Value*> converted,
  992. Convert(expr_value->value(), destination_type, source_loc));
  993. if (converted == expr_value->value()) {
  994. return expr_value;
  995. } else {
  996. return converted;
  997. }
  998. }
  999. }
  1000. }
  1001. auto Interpreter::CallDestructor(Nonnull<const DestructorDeclaration*> fun,
  1002. Nonnull<const Value*> receiver)
  1003. -> ErrorOr<Success> {
  1004. const DestructorDeclaration& method = *fun;
  1005. CARBON_CHECK(method.is_method());
  1006. RuntimeScope method_scope(&heap_);
  1007. BindingMap generic_args;
  1008. // TODO: move this logic into PatternMatch, and call it here.
  1009. const auto* p = &method.self_pattern().value();
  1010. const auto* placeholder = dyn_cast<BindingPlaceholderValue>(p);
  1011. if (!placeholder) {
  1012. // TODO: Fix this, probably merging logic with CallFunction.
  1013. // https://github.com/carbon-language/carbon-lang/issues/2802
  1014. return ProgramError(fun->source_loc())
  1015. << "destructors currently don't support `addr self` bindings";
  1016. }
  1017. if (auto& value_node = placeholder->value_node()) {
  1018. if (value_node->expression_category() == ExpressionCategory::Value) {
  1019. method_scope.BindValue(*placeholder->value_node(), receiver);
  1020. } else {
  1021. CARBON_FATAL()
  1022. << "TODO: [self addr: Self*] destructors not implemented yet";
  1023. }
  1024. }
  1025. CARBON_CHECK(method.body().has_value())
  1026. << "Calling a method that's missing a body";
  1027. auto act = std::make_unique<StatementAction>(*method.body(), std::nullopt);
  1028. return todo_.Spawn(std::unique_ptr<Action>(std::move(act)),
  1029. std::move(method_scope));
  1030. }
  1031. auto Interpreter::CallFunction(const CallExpression& call,
  1032. Nonnull<const Value*> fun,
  1033. Nonnull<const Value*> arg,
  1034. ImplWitnessMap&& witnesses,
  1035. std::optional<AllocationId> location_received)
  1036. -> ErrorOr<Success> {
  1037. if (trace_stream_->is_enabled()) {
  1038. *trace_stream_ << "calling function: " << *fun << "\n";
  1039. }
  1040. switch (fun->kind()) {
  1041. case Value::Kind::AlternativeConstructorValue: {
  1042. const auto& alt = cast<AlternativeConstructorValue>(*fun);
  1043. return todo_.FinishAction(arena_->New<AlternativeValue>(
  1044. &alt.choice(), &alt.alternative(), cast<TupleValue>(arg)));
  1045. }
  1046. case Value::Kind::FunctionValue:
  1047. case Value::Kind::BoundMethodValue: {
  1048. const auto* func_val = cast<FunctionOrMethodValue>(fun);
  1049. const FunctionDeclaration& function = func_val->declaration();
  1050. if (!function.body().has_value()) {
  1051. return ProgramError(call.source_loc())
  1052. << "attempt to call function `" << function.name()
  1053. << "` that has not been defined";
  1054. }
  1055. if (!function.is_type_checked()) {
  1056. return ProgramError(call.source_loc())
  1057. << "attempt to call function `" << function.name()
  1058. << "` that has not been fully type-checked";
  1059. }
  1060. RuntimeScope binding_scope(&heap_);
  1061. // Bring the deduced arguments and their witnesses into scope.
  1062. for (const auto& [bind, val] : call.deduced_args()) {
  1063. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> inst_val,
  1064. InstantiateType(val, call.source_loc()));
  1065. binding_scope.BindValue(bind->original(), inst_val);
  1066. }
  1067. for (const auto& [impl_bind, witness] : witnesses) {
  1068. binding_scope.BindValue(impl_bind->original(), witness);
  1069. }
  1070. // Bring the arguments that are determined by the function value into
  1071. // scope. This includes the arguments for the class of which the function
  1072. // is a member.
  1073. for (const auto& [bind, val] : func_val->type_args()) {
  1074. binding_scope.BindValue(bind->original(), val);
  1075. }
  1076. for (const auto& [impl_bind, witness] : func_val->witnesses()) {
  1077. binding_scope.BindValue(impl_bind->original(), witness);
  1078. }
  1079. // Enter the binding scope to make any deduced arguments visible before
  1080. // we resolve the self type and parameter type.
  1081. todo_.CurrentAction().StartScope(std::move(binding_scope));
  1082. RuntimeScope function_scope(&heap_);
  1083. BindingMap generic_args;
  1084. // Bind the receiver to the `self` parameter, if there is one.
  1085. if (const auto* method_val = dyn_cast<BoundMethodValue>(func_val)) {
  1086. CARBON_CHECK(function.is_method());
  1087. const auto* self_pattern = &function.self_pattern().value();
  1088. if (const auto* placeholder =
  1089. dyn_cast<BindingPlaceholderValue>(self_pattern)) {
  1090. // Immutable self with `[self: Self]`
  1091. // TODO: move this logic into PatternMatch
  1092. if (placeholder->value_node().has_value()) {
  1093. function_scope.BindValue(*placeholder->value_node(),
  1094. method_val->receiver());
  1095. }
  1096. } else {
  1097. // Mutable self with `[addr self: Self*]`
  1098. CARBON_CHECK(isa<AddrValue>(self_pattern));
  1099. bool success = PatternMatch(
  1100. self_pattern, ExpressionResult::Value(method_val->receiver()),
  1101. call.source_loc(), &function_scope, generic_args, trace_stream_,
  1102. this->arena_);
  1103. CARBON_CHECK(success) << "Failed to bind addr self";
  1104. }
  1105. }
  1106. CARBON_ASSIGN_OR_RETURN(
  1107. Nonnull<const Value*> converted_args,
  1108. Convert(arg, &function.param_pattern().static_type(),
  1109. call.source_loc()));
  1110. // Bind the arguments to the parameters.
  1111. bool success = PatternMatch(&function.param_pattern().value(),
  1112. ExpressionResult::Value(converted_args),
  1113. call.source_loc(), &function_scope,
  1114. generic_args, trace_stream_, this->arena_);
  1115. CARBON_CHECK(success) << "Failed to bind arguments to parameters";
  1116. return todo_.Spawn(std::make_unique<StatementAction>(*function.body(),
  1117. location_received),
  1118. std::move(function_scope));
  1119. }
  1120. case Value::Kind::ParameterizedEntityName: {
  1121. const auto& name = cast<ParameterizedEntityName>(*fun);
  1122. const Declaration& decl = name.declaration();
  1123. RuntimeScope params_scope(&heap_);
  1124. BindingMap generic_args;
  1125. CARBON_CHECK(PatternMatch(&name.params().value(),
  1126. ExpressionResult::Value(arg), call.source_loc(),
  1127. &params_scope, generic_args, trace_stream_,
  1128. this->arena_));
  1129. Nonnull<const Bindings*> bindings =
  1130. arena_->New<Bindings>(std::move(generic_args), std::move(witnesses));
  1131. switch (decl.kind()) {
  1132. case DeclarationKind::ClassDeclaration: {
  1133. const auto& class_decl = cast<ClassDeclaration>(decl);
  1134. return todo_.FinishAction(arena_->New<NominalClassType>(
  1135. &class_decl, bindings, class_decl.base_type(), VTable()));
  1136. }
  1137. case DeclarationKind::InterfaceDeclaration:
  1138. return todo_.FinishAction(arena_->New<InterfaceType>(
  1139. &cast<InterfaceDeclaration>(decl), bindings));
  1140. case DeclarationKind::ConstraintDeclaration:
  1141. return todo_.FinishAction(arena_->New<NamedConstraintType>(
  1142. &cast<ConstraintDeclaration>(decl), bindings));
  1143. case DeclarationKind::ChoiceDeclaration:
  1144. return todo_.FinishAction(arena_->New<ChoiceType>(
  1145. &cast<ChoiceDeclaration>(decl), bindings));
  1146. default:
  1147. CARBON_FATAL() << "unknown kind of ParameterizedEntityName " << decl;
  1148. }
  1149. }
  1150. default:
  1151. return ProgramError(call.source_loc())
  1152. << "in call, expected a function, not " << *fun;
  1153. }
  1154. }
  1155. // Returns true if the format string is okay to pass to formatv. This only
  1156. // supports `{{` and `{N}` as special syntax.
  1157. static auto ValidateFormatString(SourceLocation source_loc,
  1158. const char* format_string, int num_args)
  1159. -> ErrorOr<Success> {
  1160. const char* cursor = format_string;
  1161. while (true) {
  1162. switch (*cursor) {
  1163. case '\0':
  1164. // End of string.
  1165. return Success();
  1166. case '{':
  1167. // `{` is a special character.
  1168. ++cursor;
  1169. switch (*cursor) {
  1170. case '\0':
  1171. return ProgramError(source_loc)
  1172. << "`{` must be followed by a second `{` or index in `"
  1173. << format_string << "`";
  1174. case '{':
  1175. // Escaped `{`.
  1176. ++cursor;
  1177. break;
  1178. case '}':
  1179. return ProgramError(source_loc)
  1180. << "Invalid `{}` in `" << format_string << "`";
  1181. default:
  1182. int index = 0;
  1183. while (*cursor != '}') {
  1184. if (*cursor == '\0') {
  1185. return ProgramError(source_loc)
  1186. << "Index incomplete in `" << format_string << "`";
  1187. }
  1188. if (*cursor < '0' || *cursor > '9') {
  1189. return ProgramError(source_loc)
  1190. << "Non-numeric character in index at offset "
  1191. << cursor - format_string << " in `" << format_string
  1192. << "`";
  1193. }
  1194. index = (10 * index) + (*cursor - '0');
  1195. if (index >= num_args) {
  1196. return ProgramError(source_loc)
  1197. << "Index invalid with argument count of " << num_args
  1198. << " at offset " << cursor - format_string << " in `"
  1199. << format_string << "`";
  1200. }
  1201. ++cursor;
  1202. }
  1203. // Move past the `}`.
  1204. ++cursor;
  1205. }
  1206. break;
  1207. default:
  1208. // Arbitrary text.
  1209. ++cursor;
  1210. }
  1211. }
  1212. llvm_unreachable("Loop returns directly");
  1213. }
  1214. auto Interpreter::StepInstantiateType() -> ErrorOr<Success> {
  1215. const Action& act = todo_.CurrentAction();
  1216. const Nonnull<const Value*> type = cast<TypeInstantiationAction>(act).type();
  1217. SourceLocation source_loc = cast<TypeInstantiationAction>(act).source_loc();
  1218. switch (type->kind()) {
  1219. case Value::Kind::NominalClassType: {
  1220. const auto& class_type = cast<NominalClassType>(*type);
  1221. std::optional<Nonnull<const NominalClassType*>> base = class_type.base();
  1222. if (act.pos() == 0 && base.has_value()) {
  1223. return todo_.Spawn(std::make_unique<TypeInstantiationAction>(
  1224. base.value(), source_loc));
  1225. } else {
  1226. if (base.has_value()) {
  1227. base = cast<NominalClassType>(act.results().back());
  1228. }
  1229. CARBON_ASSIGN_OR_RETURN(
  1230. Nonnull<const Bindings*> bindings,
  1231. InstantiateBindings(&class_type.bindings(), source_loc));
  1232. return todo_.FinishAction(arena_->New<NominalClassType>(
  1233. &class_type.declaration(), bindings, base, class_type.vtable()));
  1234. }
  1235. }
  1236. case Value::Kind::PointerType: {
  1237. const auto* ptr = cast<PointerType>(type);
  1238. if (act.pos() == 0) {
  1239. return todo_.Spawn(std::make_unique<TypeInstantiationAction>(
  1240. &ptr->pointee_type(), source_loc));
  1241. } else {
  1242. const auto* actual_type = act.results().back();
  1243. return todo_.FinishAction(arena_->New<PointerType>(actual_type));
  1244. }
  1245. }
  1246. default:
  1247. CARBON_ASSIGN_OR_RETURN(auto inst_type, InstantiateType(type, source_loc))
  1248. return todo_.FinishAction(inst_type);
  1249. }
  1250. }
  1251. auto Interpreter::StepValueExp() -> ErrorOr<Success> {
  1252. auto& act = cast<ValueExpressionAction>(todo_.CurrentAction());
  1253. if (act.pos() == 0) {
  1254. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1255. &act.expression(), /*preserve_nested_categories=*/false,
  1256. act.location_received()));
  1257. } else {
  1258. CARBON_CHECK(act.results().size() == 1);
  1259. if (const auto* expr_value =
  1260. dyn_cast<ReferenceExpressionValue>(act.results()[0])) {
  1261. // Unwrap the ExpressionAction to only keep the resulting
  1262. // `Value*`.
  1263. return todo_.FinishAction(expr_value->value());
  1264. } else {
  1265. return todo_.FinishAction(act.results()[0]);
  1266. }
  1267. }
  1268. }
  1269. auto Interpreter::StepExp() -> ErrorOr<Success> {
  1270. auto& act = cast<ExpressionAction>(todo_.CurrentAction());
  1271. const Expression& exp = act.expression();
  1272. if (trace_stream_->is_enabled()) {
  1273. *trace_stream_ << "--- step exp " << exp << " ." << act.pos() << "."
  1274. << " (" << exp.source_loc() << ") --->\n";
  1275. }
  1276. switch (exp.kind()) {
  1277. case ExpressionKind::IndexExpression: {
  1278. if (act.pos() == 0) {
  1279. // { { e[i] :: C, E, F} :: S, H}
  1280. // -> { { e :: [][i] :: C, E, F} :: S, H}
  1281. return todo_.Spawn(std::make_unique<ValueExpressionAction>(
  1282. &cast<IndexExpression>(exp).object()));
  1283. } else if (act.pos() == 1) {
  1284. return todo_.Spawn(std::make_unique<ValueExpressionAction>(
  1285. &cast<IndexExpression>(exp).offset()));
  1286. } else {
  1287. // { { v :: [][i] :: C, E, F} :: S, H}
  1288. // -> { { v_i :: C, E, F} : S, H}
  1289. CARBON_ASSIGN_OR_RETURN(
  1290. auto converted,
  1291. Convert(act.results()[0],
  1292. &cast<IndexExpression>(exp).object().static_type(),
  1293. exp.source_loc()));
  1294. const auto& tuple = cast<TupleValue>(*converted);
  1295. int i = cast<IntValue>(*act.results()[1]).value();
  1296. if (i < 0 || i >= static_cast<int>(tuple.elements().size())) {
  1297. return ProgramError(exp.source_loc())
  1298. << "index " << i << " out of range in " << tuple;
  1299. }
  1300. return todo_.FinishAction(tuple.elements()[i]);
  1301. }
  1302. }
  1303. case ExpressionKind::TupleLiteral: {
  1304. if (act.pos() <
  1305. static_cast<int>(cast<TupleLiteral>(exp).fields().size())) {
  1306. // { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
  1307. // H}
  1308. // -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
  1309. // H}
  1310. const auto* field = cast<TupleLiteral>(exp).fields()[act.pos()];
  1311. if (act.preserve_nested_categories()) {
  1312. return todo_.Spawn(std::make_unique<ExpressionAction>(field, false));
  1313. } else {
  1314. return todo_.Spawn(std::make_unique<ValueExpressionAction>(field));
  1315. }
  1316. } else {
  1317. return todo_.FinishAction(arena_->New<TupleValue>(act.results()));
  1318. }
  1319. }
  1320. case ExpressionKind::StructLiteral: {
  1321. const auto& literal = cast<StructLiteral>(exp);
  1322. if (act.pos() < static_cast<int>(literal.fields().size())) {
  1323. return todo_.Spawn(std::make_unique<ValueExpressionAction>(
  1324. &literal.fields()[act.pos()].expression()));
  1325. } else {
  1326. return todo_.FinishAction(
  1327. CreateStruct(literal.fields(), act.results()));
  1328. }
  1329. }
  1330. case ExpressionKind::SimpleMemberAccessExpression: {
  1331. const auto& access = cast<SimpleMemberAccessExpression>(exp);
  1332. if (auto rewrite = access.rewritten_form()) {
  1333. return todo_.ReplaceWith(std::make_unique<ExpressionAction>(
  1334. *rewrite, act.preserve_nested_categories(),
  1335. act.location_received()));
  1336. }
  1337. if (act.pos() == 0) {
  1338. // First, evaluate the first operand.
  1339. if (access.is_addr_me_method()) {
  1340. return todo_.Spawn(
  1341. std::make_unique<LocationAction>(&access.object()));
  1342. } else {
  1343. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1344. &access.object(), /*preserve_nested_categories=*/false));
  1345. }
  1346. } else {
  1347. if (auto constant_value = access.constant_value()) {
  1348. if (act.pos() == 1) {
  1349. return todo_.Spawn(std::make_unique<TypeInstantiationAction>(
  1350. *constant_value, access.source_loc()));
  1351. } else {
  1352. return todo_.FinishAction(act.results().back());
  1353. }
  1354. } else if (const auto* member_name_type =
  1355. dyn_cast<TypeOfMemberName>(&access.static_type())) {
  1356. // The result is a member name, such as in `Type.field_name`. Form a
  1357. // suitable member name value.
  1358. CARBON_CHECK(phase() == Phase::CompileTime)
  1359. << "should not form MemberNames at runtime";
  1360. auto found_in_interface = access.found_in_interface();
  1361. if (act.pos() == 1 && found_in_interface) {
  1362. return todo_.Spawn(std::make_unique<TypeInstantiationAction>(
  1363. *found_in_interface, exp.source_loc()));
  1364. } else {
  1365. if (found_in_interface) {
  1366. found_in_interface = cast<InterfaceType>(act.results().back());
  1367. }
  1368. std::optional<const Value*> type_result;
  1369. const auto* result =
  1370. act.results()[0]->kind() ==
  1371. Value::Kind::ReferenceExpressionValue
  1372. ? cast<ReferenceExpressionValue>(act.results()[0])->value()
  1373. : act.results()[0];
  1374. if (!isa<InterfaceType, NamedConstraintType, ConstraintType>(
  1375. result)) {
  1376. type_result = result;
  1377. }
  1378. MemberName* member_name = arena_->New<MemberName>(
  1379. type_result, found_in_interface, member_name_type->member());
  1380. return todo_.FinishAction(member_name);
  1381. }
  1382. } else {
  1383. // The result is the value of the named field, such as in
  1384. // `value.field_name`. Extract the value within the given object.
  1385. auto impl_has_value = access.impl().has_value();
  1386. if (act.pos() == 1) {
  1387. // Next, if we're accessing an interface member, evaluate the `impl`
  1388. // expression to find the corresponding witness.
  1389. if (impl_has_value) {
  1390. return todo_.Spawn(std::make_unique<WitnessAction>(
  1391. access.impl().value(), access.source_loc()));
  1392. } else {
  1393. return todo_.RunAgain();
  1394. }
  1395. } else if (act.pos() == 2) {
  1396. if (auto found_in_interface = access.found_in_interface()) {
  1397. return todo_.Spawn(std::make_unique<TypeInstantiationAction>(
  1398. *found_in_interface, exp.source_loc()));
  1399. } else {
  1400. return todo_.RunAgain();
  1401. }
  1402. } else if (act.pos() == 3) {
  1403. if (access.is_type_access()) {
  1404. return todo_.Spawn(std::make_unique<TypeInstantiationAction>(
  1405. &access.object().static_type(), access.source_loc()));
  1406. } else {
  1407. return todo_.RunAgain();
  1408. }
  1409. } else {
  1410. auto found_in_interface = access.found_in_interface();
  1411. if (found_in_interface) {
  1412. found_in_interface = cast<InterfaceType>(
  1413. impl_has_value ? act.results()[2] : act.results()[1]);
  1414. }
  1415. std::optional<Nonnull<const Witness*>> witness;
  1416. if (access.impl().has_value()) {
  1417. witness = cast<Witness>(act.results()[1]);
  1418. }
  1419. ElementPath::Component member(&access.member(), found_in_interface,
  1420. witness);
  1421. const Value* aggregate;
  1422. const Value* me_value;
  1423. std::optional<Address> lhs_address;
  1424. if (access.is_type_access()) {
  1425. aggregate = act.results().back();
  1426. } else if (const auto* location =
  1427. dyn_cast<LocationValue>(act.results()[0])) {
  1428. lhs_address = location->address();
  1429. me_value = act.results()[0];
  1430. CARBON_ASSIGN_OR_RETURN(
  1431. aggregate,
  1432. this->heap_.Read(location->address(), exp.source_loc()));
  1433. } else if (const auto* expr_value =
  1434. dyn_cast<ReferenceExpressionValue>(
  1435. act.results()[0])) {
  1436. lhs_address = expr_value->address();
  1437. aggregate = expr_value->value();
  1438. me_value = aggregate;
  1439. } else {
  1440. aggregate = act.results()[0];
  1441. me_value = aggregate;
  1442. }
  1443. CARBON_ASSIGN_OR_RETURN(
  1444. Nonnull<const Value*> member_value,
  1445. aggregate->GetElement(arena_, ElementPath(member),
  1446. exp.source_loc(), me_value));
  1447. if (lhs_address) {
  1448. return todo_.FinishAction(arena_->New<ReferenceExpressionValue>(
  1449. member_value, lhs_address->ElementAddress(member.element())));
  1450. } else {
  1451. return todo_.FinishAction(member_value);
  1452. }
  1453. }
  1454. }
  1455. }
  1456. }
  1457. case ExpressionKind::CompoundMemberAccessExpression: {
  1458. const auto& access = cast<CompoundMemberAccessExpression>(exp);
  1459. bool forming_member_name = isa<TypeOfMemberName>(&access.static_type());
  1460. if (act.pos() == 0) {
  1461. // First, evaluate the first operand.
  1462. if (access.is_addr_me_method()) {
  1463. return todo_.Spawn(
  1464. std::make_unique<LocationAction>(&access.object()));
  1465. } else {
  1466. return todo_.Spawn(
  1467. std::make_unique<ValueExpressionAction>(&access.object()));
  1468. }
  1469. } else {
  1470. if (auto constant_value = access.constant_value()) {
  1471. if (act.pos() == 1) {
  1472. return todo_.Spawn(std::make_unique<TypeInstantiationAction>(
  1473. *constant_value, access.source_loc()));
  1474. } else {
  1475. return todo_.FinishAction(act.results().back());
  1476. }
  1477. } else if (forming_member_name) {
  1478. CARBON_CHECK(phase() == Phase::CompileTime)
  1479. << "should not form MemberNames at runtime";
  1480. if (auto found_in_interface = access.member().interface();
  1481. found_in_interface && act.pos() == 1) {
  1482. return todo_.Spawn(std::make_unique<TypeInstantiationAction>(
  1483. *found_in_interface, exp.source_loc()));
  1484. } else {
  1485. // If we're forming a member name, we must be in the outer
  1486. // evaluation in `Type.(Interface.method)`. Produce the same method
  1487. // name with its `type` field set.
  1488. if (found_in_interface) {
  1489. found_in_interface = cast<InterfaceType>(act.results().back());
  1490. }
  1491. CARBON_CHECK(!access.member().base_type().has_value())
  1492. << "compound member access forming a member name should be "
  1493. "performing impl lookup";
  1494. auto* member_name = arena_->New<MemberName>(
  1495. act.results()[0], found_in_interface, access.member().member());
  1496. return todo_.FinishAction(member_name);
  1497. }
  1498. } else {
  1499. auto impl_has_value = access.impl().has_value();
  1500. if (act.pos() == 1) {
  1501. if (impl_has_value) {
  1502. // Next, if we're accessing an interface member, evaluate the
  1503. // `impl` expression to find the corresponding witness.
  1504. return todo_.Spawn(std::make_unique<WitnessAction>(
  1505. access.impl().value(), access.source_loc()));
  1506. } else {
  1507. return todo_.RunAgain();
  1508. }
  1509. } else if (act.pos() == 2) {
  1510. if (auto found_in_interface = access.member().interface()) {
  1511. return todo_.Spawn(std::make_unique<TypeInstantiationAction>(
  1512. *found_in_interface, exp.source_loc()));
  1513. } else {
  1514. return todo_.RunAgain();
  1515. }
  1516. } else if (act.pos() == 3) {
  1517. if (access.is_type_access()) {
  1518. return todo_.Spawn(std::make_unique<TypeInstantiationAction>(
  1519. &access.object().static_type(), access.source_loc()));
  1520. } else {
  1521. return todo_.RunAgain();
  1522. }
  1523. } else {
  1524. // Access the object to find the named member.
  1525. auto found_in_interface = access.member().interface();
  1526. if (found_in_interface) {
  1527. found_in_interface = cast<InterfaceType>(
  1528. impl_has_value ? act.results()[2] : act.results()[1]);
  1529. }
  1530. Nonnull<const Value*> object = act.results()[0];
  1531. if (access.is_type_access()) {
  1532. object = act.results().back();
  1533. }
  1534. std::optional<Nonnull<const Witness*>> witness;
  1535. if (access.impl().has_value()) {
  1536. witness = cast<Witness>(act.results()[1]);
  1537. } else {
  1538. CARBON_CHECK(access.member().base_type().has_value())
  1539. << "compound access should have base type or impl";
  1540. CARBON_ASSIGN_OR_RETURN(
  1541. object, Convert(object, *access.member().base_type(),
  1542. exp.source_loc()));
  1543. }
  1544. ElementPath::Component field(&access.member().member(),
  1545. found_in_interface, witness);
  1546. CARBON_ASSIGN_OR_RETURN(
  1547. Nonnull<const Value*> member,
  1548. object->GetElement(arena_, ElementPath(field), exp.source_loc(),
  1549. object));
  1550. return todo_.FinishAction(member);
  1551. }
  1552. }
  1553. }
  1554. }
  1555. case ExpressionKind::BaseAccessExpression: {
  1556. const auto& access = cast<BaseAccessExpression>(exp);
  1557. if (act.pos() == 0) {
  1558. return todo_.Spawn(
  1559. std::make_unique<ValueExpressionAction>(&access.object()));
  1560. } else {
  1561. ElementPath::Component base_elt(&access.element(), std::nullopt,
  1562. std::nullopt);
  1563. const Value* value = act.results()[0];
  1564. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> base_value,
  1565. value->GetElement(arena_, ElementPath(base_elt),
  1566. exp.source_loc(), value));
  1567. return todo_.FinishAction(base_value);
  1568. }
  1569. }
  1570. case ExpressionKind::IdentifierExpression: {
  1571. CARBON_CHECK(act.pos() == 0);
  1572. const auto& ident = cast<IdentifierExpression>(exp);
  1573. // { {x :: C, E, F} :: S, H} -> { {H(E(x)) :: C, E, F} :: S, H}
  1574. CARBON_ASSIGN_OR_RETURN(
  1575. Nonnull<const Value*> value,
  1576. todo_.ValueOfNode(ident.value_node(), ident.source_loc()));
  1577. if (const auto* location = dyn_cast<LocationValue>(value)) {
  1578. CARBON_ASSIGN_OR_RETURN(
  1579. value, heap_.Read(location->address(), exp.source_loc()));
  1580. if (ident.expression_category() == ExpressionCategory::Reference) {
  1581. return todo_.FinishAction(arena_->New<ReferenceExpressionValue>(
  1582. value, location->address()));
  1583. }
  1584. }
  1585. return todo_.FinishAction(value);
  1586. }
  1587. case ExpressionKind::DotSelfExpression: {
  1588. CARBON_CHECK(act.pos() == 0);
  1589. const auto& dot_self = cast<DotSelfExpression>(exp);
  1590. return todo_.FinishAction(*dot_self.self_binding().symbolic_identity());
  1591. }
  1592. case ExpressionKind::IntLiteral:
  1593. CARBON_CHECK(act.pos() == 0);
  1594. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  1595. return todo_.FinishAction(
  1596. arena_->New<IntValue>(cast<IntLiteral>(exp).value()));
  1597. case ExpressionKind::BoolLiteral:
  1598. CARBON_CHECK(act.pos() == 0);
  1599. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  1600. return todo_.FinishAction(
  1601. arena_->New<BoolValue>(cast<BoolLiteral>(exp).value()));
  1602. case ExpressionKind::OperatorExpression: {
  1603. const auto& op = cast<OperatorExpression>(exp);
  1604. if (auto rewrite = op.rewritten_form()) {
  1605. return todo_.ReplaceWith(std::make_unique<ExpressionAction>(
  1606. *rewrite, act.preserve_nested_categories(),
  1607. act.location_received()));
  1608. }
  1609. if (act.pos() != static_cast<int>(op.arguments().size())) {
  1610. // { {v :: op(vs,[],e,es) :: C, E, F} :: S, H}
  1611. // -> { {e :: op(vs,v,[],es) :: C, E, F} :: S, H}
  1612. Nonnull<const Expression*> arg = op.arguments()[act.pos()];
  1613. if (op.op() == Operator::AddressOf) {
  1614. return todo_.Spawn(std::make_unique<LocationAction>(arg));
  1615. } else if ((op.op() == Operator::And || op.op() == Operator::Or) &&
  1616. act.pos() == 1) {
  1617. // Short-circuit evaluation for 'and' & 'or'
  1618. const auto* operand_value =
  1619. cast<BoolValue>(act.results()[act.pos() - 1]);
  1620. if ((op.op() == Operator::Or && operand_value->value()) ||
  1621. (op.op() == Operator::And && !operand_value->value())) {
  1622. return todo_.FinishAction(operand_value);
  1623. }
  1624. // No short-circuit, fall through to evaluate 2nd operand.
  1625. }
  1626. return todo_.Spawn(std::make_unique<ValueExpressionAction>(arg));
  1627. } else {
  1628. // { {v :: op(vs,[]) :: C, E, F} :: S, H}
  1629. // -> { {eval_prim(op, (vs,v)) :: C, E, F} :: S, H}
  1630. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> value,
  1631. EvalPrim(op.op(), &op.static_type(),
  1632. act.results(), exp.source_loc()));
  1633. return todo_.FinishAction(value);
  1634. }
  1635. }
  1636. case ExpressionKind::CallExpression: {
  1637. const auto& call = cast<CallExpression>(exp);
  1638. unsigned int num_witnesses = call.witnesses().size();
  1639. if (act.pos() == 0) {
  1640. // { {e1(e2) :: C, E, F} :: S, H}
  1641. // -> { {e1 :: [](e2) :: C, E, F} :: S, H}
  1642. return todo_.Spawn(
  1643. std::make_unique<ValueExpressionAction>(&call.function()));
  1644. } else if (act.pos() == 1) {
  1645. // { { v :: [](e) :: C, E, F} :: S, H}
  1646. // -> { { e :: v([]) :: C, E, F} :: S, H}
  1647. bool preserve_nested_categories =
  1648. (act.results()[0]->kind() !=
  1649. Value::Kind::AlternativeConstructorValue);
  1650. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1651. &call.argument(), preserve_nested_categories));
  1652. } else if (num_witnesses > 0 &&
  1653. act.pos() < 2 + static_cast<int>(num_witnesses)) {
  1654. auto iter = call.witnesses().begin();
  1655. std::advance(iter, act.pos() - 2);
  1656. return todo_.Spawn(std::make_unique<WitnessAction>(
  1657. cast<Witness>(iter->second), call.source_loc()));
  1658. } else if (act.pos() == 2 + static_cast<int>(num_witnesses)) {
  1659. // { { v2 :: v1([]) :: C, E, F} :: S, H}
  1660. // -> { {C',E',F'} :: {C, E, F} :: S, H}
  1661. ImplWitnessMap witnesses;
  1662. if (num_witnesses > 0) {
  1663. int i = 2;
  1664. for (const auto& [impl_bind, impl_exp] : call.witnesses()) {
  1665. witnesses[impl_bind] = act.results()[i];
  1666. ++i;
  1667. }
  1668. }
  1669. return CallFunction(call, act.results()[0], act.results()[1],
  1670. std::move(witnesses), act.location_received());
  1671. } else if (act.pos() == 3 + static_cast<int>(num_witnesses)) {
  1672. if (act.results().size() < 3 + num_witnesses) {
  1673. // Control fell through without explicit return.
  1674. return todo_.FinishAction(TupleValue::Empty());
  1675. } else {
  1676. return todo_.FinishAction(
  1677. act.results()[2 + static_cast<int>(num_witnesses)]);
  1678. }
  1679. } else {
  1680. CARBON_FATAL() << "in StepValueExp with Call pos " << act.pos();
  1681. }
  1682. }
  1683. case ExpressionKind::IntrinsicExpression: {
  1684. const auto& intrinsic = cast<IntrinsicExpression>(exp);
  1685. if (auto rewrite = intrinsic.rewritten_form()) {
  1686. return todo_.ReplaceWith(std::make_unique<ExpressionAction>(
  1687. *rewrite, act.preserve_nested_categories(),
  1688. act.location_received()));
  1689. }
  1690. if (act.pos() == 0) {
  1691. return todo_.Spawn(
  1692. std::make_unique<ValueExpressionAction>(&intrinsic.args()));
  1693. }
  1694. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  1695. const auto& args = cast<TupleValue>(*act.results()[0]).elements();
  1696. switch (cast<IntrinsicExpression>(exp).intrinsic()) {
  1697. case IntrinsicExpression::Intrinsic::Print: {
  1698. if (phase_ != Phase::RunTime) {
  1699. return ProgramError(exp.source_loc())
  1700. << "Print called before run time";
  1701. }
  1702. CARBON_ASSIGN_OR_RETURN(
  1703. Nonnull<const Value*> format_string_value,
  1704. Convert(args[0], arena_->New<StringType>(), exp.source_loc()));
  1705. const char* format_string =
  1706. cast<StringValue>(*format_string_value).value().c_str();
  1707. int num_format_args = args.size() - 1;
  1708. CARBON_RETURN_IF_ERROR(ValidateFormatString(
  1709. intrinsic.source_loc(), format_string, num_format_args));
  1710. switch (num_format_args) {
  1711. case 0:
  1712. *print_stream_ << llvm::formatv(format_string);
  1713. break;
  1714. case 1: {
  1715. *print_stream_ << llvm::formatv(format_string,
  1716. cast<IntValue>(*args[1]).value());
  1717. break;
  1718. }
  1719. default:
  1720. CARBON_FATAL() << "Too many format args: " << num_format_args;
  1721. }
  1722. // Implicit newline; currently no way to disable it.
  1723. *print_stream_ << "\n";
  1724. return todo_.FinishAction(TupleValue::Empty());
  1725. }
  1726. case IntrinsicExpression::Intrinsic::Assert: {
  1727. CARBON_CHECK(args.size() == 2);
  1728. CARBON_ASSIGN_OR_RETURN(
  1729. Nonnull<const Value*> condition,
  1730. Convert(args[0], arena_->New<BoolType>(), exp.source_loc()));
  1731. CARBON_ASSIGN_OR_RETURN(
  1732. Nonnull<const Value*> string_value,
  1733. Convert(args[1], arena_->New<StringType>(), exp.source_loc()));
  1734. bool condition_value = cast<BoolValue>(condition)->value();
  1735. if (!condition_value) {
  1736. return ProgramError(exp.source_loc()) << *string_value;
  1737. }
  1738. return todo_.FinishAction(TupleValue::Empty());
  1739. }
  1740. case IntrinsicExpression::Intrinsic::Alloc: {
  1741. CARBON_CHECK(args.size() == 1);
  1742. Address addr(heap_.AllocateValue(args[0]));
  1743. return todo_.FinishAction(arena_->New<PointerValue>(addr));
  1744. }
  1745. case IntrinsicExpression::Intrinsic::Dealloc: {
  1746. CARBON_CHECK(args.size() == 1);
  1747. CARBON_CHECK(act.pos() > 0);
  1748. const auto* ptr = cast<PointerValue>(args[0]);
  1749. CARBON_ASSIGN_OR_RETURN(const auto* pointee,
  1750. heap_.Read(ptr->address(), exp.source_loc()));
  1751. if (const auto* class_value = dyn_cast<NominalClassValue>(pointee)) {
  1752. // Handle destruction from base class pointer.
  1753. const auto* child_class_value = *class_value->class_value_ptr();
  1754. bool is_subtyped = child_class_value != class_value;
  1755. if (is_subtyped) {
  1756. // Error if destructor is not virtual.
  1757. const auto& class_type =
  1758. cast<NominalClassType>(class_value->type());
  1759. const auto& class_decl = class_type.declaration();
  1760. if ((*class_decl.destructor())->virt_override() ==
  1761. VirtualOverride::None) {
  1762. return ProgramError(exp.source_loc())
  1763. << "Deallocating a derived class from base class "
  1764. "pointer requires a virtual destructor";
  1765. }
  1766. }
  1767. const Address obj_addr = is_subtyped
  1768. ? ptr->address().DowncastedAddress()
  1769. : ptr->address();
  1770. if (act.pos() == 1) {
  1771. return todo_.Spawn(std::make_unique<DestroyAction>(
  1772. arena_->New<LocationValue>(obj_addr), child_class_value));
  1773. } else {
  1774. CARBON_RETURN_IF_ERROR(heap_.Deallocate(obj_addr));
  1775. return todo_.FinishAction(TupleValue::Empty());
  1776. }
  1777. } else {
  1778. if (act.pos() == 1) {
  1779. return todo_.Spawn(std::make_unique<DestroyAction>(
  1780. arena_->New<LocationValue>(ptr->address()), pointee));
  1781. } else {
  1782. CARBON_RETURN_IF_ERROR(heap_.Deallocate(ptr->address()));
  1783. return todo_.FinishAction(TupleValue::Empty());
  1784. }
  1785. }
  1786. }
  1787. case IntrinsicExpression::Intrinsic::PrintAllocs: {
  1788. CARBON_CHECK(args.empty());
  1789. heap_.Print(*print_stream_);
  1790. *print_stream_ << "\n";
  1791. return todo_.FinishAction(TupleValue::Empty());
  1792. }
  1793. case IntrinsicExpression::Intrinsic::Rand: {
  1794. CARBON_CHECK(args.size() == 2);
  1795. const int64_t low = cast<IntValue>(*args[0]).value();
  1796. const int64_t high = cast<IntValue>(*args[1]).value();
  1797. if (low >= high) {
  1798. return ProgramError(exp.source_loc())
  1799. << "Rand inputs must be ordered for a non-empty range: "
  1800. << low << " must be less than " << high;
  1801. }
  1802. // Use 64-bit to handle large ranges where `high - low` might exceed
  1803. // int32_t maximums.
  1804. static std::mt19937_64 generator(12);
  1805. const int64_t range = high - low;
  1806. // We avoid using std::uniform_int_distribution because it's not
  1807. // reproducible across builds/platforms.
  1808. int64_t r = (generator() % range) + low;
  1809. CARBON_CHECK(r >= std::numeric_limits<int32_t>::min() &&
  1810. r <= std::numeric_limits<int32_t>::max())
  1811. << "Non-int32 result: " << r;
  1812. CARBON_CHECK(r >= low && r <= high) << "Out-of-range result: " << r;
  1813. return todo_.FinishAction(arena_->New<IntValue>(r));
  1814. }
  1815. case IntrinsicExpression::Intrinsic::ImplicitAs: {
  1816. CARBON_CHECK(args.size() == 1);
  1817. // Build a constraint type that constrains its .Self type to satisfy
  1818. // the "ImplicitAs" intrinsic constraint. This involves creating a
  1819. // number of objects that all point to each other.
  1820. // TODO: Factor out a simple version of ConstraintTypeBuilder and
  1821. // use it from here.
  1822. auto* self_binding = arena_->New<GenericBinding>(
  1823. exp.source_loc(), ".Self",
  1824. arena_->New<TypeTypeLiteral>(exp.source_loc()),
  1825. GenericBinding::BindingKind::Checked);
  1826. auto* self = arena_->New<VariableType>(self_binding);
  1827. auto* impl_binding = arena_->New<ImplBinding>(
  1828. exp.source_loc(), self_binding, std::nullopt);
  1829. impl_binding->set_symbolic_identity(
  1830. arena_->New<BindingWitness>(impl_binding));
  1831. self_binding->set_symbolic_identity(self);
  1832. self_binding->set_value(self);
  1833. self_binding->set_impl_binding(impl_binding);
  1834. IntrinsicConstraint constraint = {
  1835. .type = self,
  1836. .kind = IntrinsicConstraint::ImplicitAs,
  1837. .arguments = args};
  1838. auto* result = arena_->New<ConstraintType>(
  1839. self_binding, std::vector<ImplsConstraint>{},
  1840. std::vector<IntrinsicConstraint>{std::move(constraint)},
  1841. std::vector<EqualityConstraint>{},
  1842. std::vector<RewriteConstraint>{}, std::vector<LookupContext>{});
  1843. impl_binding->set_interface(result);
  1844. return todo_.FinishAction(result);
  1845. }
  1846. case IntrinsicExpression::Intrinsic::ImplicitAsConvert: {
  1847. CARBON_FATAL()
  1848. << "__intrinsic_implicit_as_convert should have been rewritten";
  1849. }
  1850. case IntrinsicExpression::Intrinsic::IntEq: {
  1851. CARBON_CHECK(args.size() == 2);
  1852. auto lhs = cast<IntValue>(*args[0]).value();
  1853. auto rhs = cast<IntValue>(*args[1]).value();
  1854. auto* result = arena_->New<BoolValue>(lhs == rhs);
  1855. return todo_.FinishAction(result);
  1856. }
  1857. case IntrinsicExpression::Intrinsic::StrEq: {
  1858. CARBON_CHECK(args.size() == 2);
  1859. const auto& lhs = cast<StringValue>(*args[0]).value();
  1860. const auto& rhs = cast<StringValue>(*args[1]).value();
  1861. auto* result = arena_->New<BoolValue>(lhs == rhs);
  1862. return todo_.FinishAction(result);
  1863. }
  1864. case IntrinsicExpression::Intrinsic::IntCompare: {
  1865. CARBON_CHECK(args.size() == 2);
  1866. auto lhs = cast<IntValue>(*args[0]).value();
  1867. auto rhs = cast<IntValue>(*args[1]).value();
  1868. if (lhs < rhs) {
  1869. auto* result = arena_->New<IntValue>(-1);
  1870. return todo_.FinishAction(result);
  1871. }
  1872. if (lhs == rhs) {
  1873. auto* result = arena_->New<IntValue>(0);
  1874. return todo_.FinishAction(result);
  1875. }
  1876. auto* result = arena_->New<IntValue>(1);
  1877. return todo_.FinishAction(result);
  1878. }
  1879. case IntrinsicExpression::Intrinsic::StrCompare: {
  1880. CARBON_CHECK(args.size() == 2);
  1881. const auto& lhs = cast<StringValue>(*args[0]).value();
  1882. const auto& rhs = cast<StringValue>(*args[1]).value();
  1883. if (lhs < rhs) {
  1884. auto* result = arena_->New<IntValue>(-1);
  1885. return todo_.FinishAction(result);
  1886. }
  1887. if (lhs == rhs) {
  1888. auto* result = arena_->New<IntValue>(0);
  1889. return todo_.FinishAction(result);
  1890. }
  1891. auto* result = arena_->New<IntValue>(1);
  1892. return todo_.FinishAction(result);
  1893. }
  1894. case IntrinsicExpression::Intrinsic::IntBitComplement: {
  1895. CARBON_CHECK(args.size() == 1);
  1896. return todo_.FinishAction(
  1897. arena_->New<IntValue>(~cast<IntValue>(*args[0]).value()));
  1898. }
  1899. case IntrinsicExpression::Intrinsic::IntBitAnd: {
  1900. CARBON_CHECK(args.size() == 2);
  1901. return todo_.FinishAction(
  1902. arena_->New<IntValue>(cast<IntValue>(*args[0]).value() &
  1903. cast<IntValue>(*args[1]).value()));
  1904. }
  1905. case IntrinsicExpression::Intrinsic::IntBitOr: {
  1906. CARBON_CHECK(args.size() == 2);
  1907. return todo_.FinishAction(
  1908. arena_->New<IntValue>(cast<IntValue>(*args[0]).value() |
  1909. cast<IntValue>(*args[1]).value()));
  1910. }
  1911. case IntrinsicExpression::Intrinsic::IntBitXor: {
  1912. CARBON_CHECK(args.size() == 2);
  1913. return todo_.FinishAction(
  1914. arena_->New<IntValue>(cast<IntValue>(*args[0]).value() ^
  1915. cast<IntValue>(*args[1]).value()));
  1916. }
  1917. case IntrinsicExpression::Intrinsic::IntLeftShift: {
  1918. CARBON_CHECK(args.size() == 2);
  1919. const auto& lhs = cast<IntValue>(*args[0]).value();
  1920. const auto& rhs = cast<IntValue>(*args[1]).value();
  1921. if (rhs >= 0 && rhs < 32) {
  1922. return todo_.FinishAction(
  1923. arena_->New<IntValue>(static_cast<uint32_t>(lhs) << rhs));
  1924. }
  1925. return ProgramError(exp.source_loc()) << "Integer overflow";
  1926. }
  1927. case IntrinsicExpression::Intrinsic::IntRightShift: {
  1928. CARBON_CHECK(args.size() == 2);
  1929. const auto& lhs = cast<IntValue>(*args[0]).value();
  1930. const auto& rhs = cast<IntValue>(*args[1]).value();
  1931. if (rhs >= 0 && rhs < 32) {
  1932. return todo_.FinishAction(arena_->New<IntValue>(lhs >> rhs));
  1933. }
  1934. return ProgramError(exp.source_loc()) << "Integer overflow";
  1935. }
  1936. }
  1937. }
  1938. case ExpressionKind::IntTypeLiteral: {
  1939. CARBON_CHECK(act.pos() == 0);
  1940. return todo_.FinishAction(arena_->New<IntType>());
  1941. }
  1942. case ExpressionKind::BoolTypeLiteral: {
  1943. CARBON_CHECK(act.pos() == 0);
  1944. return todo_.FinishAction(arena_->New<BoolType>());
  1945. }
  1946. case ExpressionKind::TypeTypeLiteral: {
  1947. CARBON_CHECK(act.pos() == 0);
  1948. return todo_.FinishAction(arena_->New<TypeType>());
  1949. }
  1950. case ExpressionKind::StringLiteral:
  1951. CARBON_CHECK(act.pos() == 0);
  1952. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  1953. return todo_.FinishAction(
  1954. arena_->New<StringValue>(cast<StringLiteral>(exp).value()));
  1955. case ExpressionKind::StringTypeLiteral: {
  1956. CARBON_CHECK(act.pos() == 0);
  1957. return todo_.FinishAction(arena_->New<StringType>());
  1958. }
  1959. case ExpressionKind::FunctionTypeLiteral:
  1960. case ExpressionKind::StructTypeLiteral:
  1961. case ExpressionKind::ArrayTypeLiteral:
  1962. case ExpressionKind::ValueLiteral: {
  1963. if (act.pos() == 0) {
  1964. return todo_.Spawn(std::make_unique<TypeInstantiationAction>(
  1965. &exp.static_type(), exp.source_loc()));
  1966. } else {
  1967. const auto* value = &cast<ConstantValueLiteral>(exp).constant_value();
  1968. Nonnull<const Value*> destination = act.results().back();
  1969. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> result,
  1970. Convert(value, destination, exp.source_loc()));
  1971. return todo_.FinishAction(result);
  1972. }
  1973. }
  1974. case ExpressionKind::IfExpression: {
  1975. const auto& if_expr = cast<IfExpression>(exp);
  1976. if (act.pos() == 0) {
  1977. return todo_.Spawn(
  1978. std::make_unique<ValueExpressionAction>(&if_expr.condition()));
  1979. } else if (act.pos() == 1) {
  1980. const auto& condition = cast<BoolValue>(*act.results()[0]);
  1981. return todo_.Spawn(std::make_unique<ValueExpressionAction>(
  1982. condition.value() ? &if_expr.then_expression()
  1983. : &if_expr.else_expression()));
  1984. } else {
  1985. return todo_.FinishAction(act.results()[1]);
  1986. }
  1987. break;
  1988. }
  1989. case ExpressionKind::WhereExpression: {
  1990. auto rewrite = cast<WhereExpression>(exp).rewritten_form();
  1991. CARBON_CHECK(rewrite) << "where expression should be rewritten";
  1992. return todo_.ReplaceWith(std::make_unique<ExpressionAction>(
  1993. *rewrite, act.preserve_nested_categories(), act.location_received()));
  1994. }
  1995. case ExpressionKind::BuiltinConvertExpression: {
  1996. const auto& convert_expr = cast<BuiltinConvertExpression>(exp);
  1997. if (auto rewrite = convert_expr.rewritten_form()) {
  1998. return todo_.ReplaceWith(std::make_unique<ExpressionAction>(
  1999. *rewrite, act.preserve_nested_categories(),
  2000. act.location_received()));
  2001. }
  2002. if (act.pos() == 0) {
  2003. return todo_.Spawn(std::make_unique<ValueExpressionAction>(
  2004. convert_expr.source_expression()));
  2005. } else if (act.pos() == 1) {
  2006. return todo_.Spawn(std::make_unique<TypeInstantiationAction>(
  2007. &convert_expr.static_type(), convert_expr.source_loc()));
  2008. } else {
  2009. // TODO: Remove all calls to Convert other than this one. We shouldn't
  2010. // need them any more.
  2011. Nonnull<const Value*> destination = act.results().back();
  2012. CARBON_ASSIGN_OR_RETURN(
  2013. Nonnull<const Value*> result,
  2014. Convert(act.results()[0], destination, convert_expr.source_loc()));
  2015. return todo_.FinishAction(result);
  2016. }
  2017. }
  2018. case ExpressionKind::UnimplementedExpression:
  2019. CARBON_FATAL() << "Unimplemented: " << exp;
  2020. } // switch (exp->kind)
  2021. }
  2022. auto Interpreter::StepWitness() -> ErrorOr<Success> {
  2023. auto& act = cast<WitnessAction>(todo_.CurrentAction());
  2024. const Witness* witness = act.witness();
  2025. if (trace_stream_->is_enabled()) {
  2026. *trace_stream_ << "--- step witness " << *witness << " ." << act.pos()
  2027. << ". --->\n";
  2028. }
  2029. switch (witness->kind()) {
  2030. case Value::Kind::BindingWitness: {
  2031. const ImplBinding* binding = cast<BindingWitness>(witness)->binding();
  2032. CARBON_ASSIGN_OR_RETURN(
  2033. Nonnull<const Value*> value,
  2034. todo_.ValueOfNode(binding, binding->type_var()->source_loc()));
  2035. if (const auto* location = dyn_cast<LocationValue>(value)) {
  2036. // TODO: Why do we store values for impl bindings on the heap?
  2037. CARBON_ASSIGN_OR_RETURN(
  2038. value,
  2039. heap_.Read(location->address(), binding->type_var()->source_loc()));
  2040. }
  2041. return todo_.FinishAction(value);
  2042. }
  2043. case Value::Kind::ConstraintWitness: {
  2044. llvm::ArrayRef<Nonnull<const Witness*>> witnesses =
  2045. cast<ConstraintWitness>(witness)->witnesses();
  2046. if (act.pos() < static_cast<int>(witnesses.size())) {
  2047. return todo_.Spawn(std::make_unique<WitnessAction>(witnesses[act.pos()],
  2048. act.source_loc()));
  2049. }
  2050. std::vector<Nonnull<const Witness*>> new_witnesses;
  2051. new_witnesses.reserve(witnesses.size());
  2052. for (const auto* witness : act.results()) {
  2053. new_witnesses.push_back(cast<Witness>(witness));
  2054. }
  2055. return todo_.FinishAction(
  2056. arena_->New<ConstraintWitness>(std::move(new_witnesses)));
  2057. }
  2058. case Value::Kind::ConstraintImplWitness: {
  2059. const auto* constraint_impl = cast<ConstraintImplWitness>(witness);
  2060. if (act.pos() == 0) {
  2061. return todo_.Spawn(std::make_unique<WitnessAction>(
  2062. constraint_impl->constraint_witness(), act.source_loc()));
  2063. }
  2064. return todo_.FinishAction(ConstraintImplWitness::Make(
  2065. arena_, cast<Witness>(act.results()[0]), constraint_impl->index()));
  2066. }
  2067. case Value::Kind::ImplWitness: {
  2068. const auto* impl_witness = cast<ImplWitness>(witness);
  2069. CARBON_ASSIGN_OR_RETURN(
  2070. Nonnull<const Bindings*> new_bindings,
  2071. InstantiateBindings(&impl_witness->bindings(),
  2072. impl_witness->declaration().source_loc()));
  2073. return todo_.FinishAction(
  2074. new_bindings == &impl_witness->bindings()
  2075. ? impl_witness
  2076. : arena_->New<ImplWitness>(&impl_witness->declaration(),
  2077. new_bindings));
  2078. }
  2079. default:
  2080. CARBON_FATAL() << "unexpected kind of witness " << *witness;
  2081. }
  2082. }
  2083. auto Interpreter::StepStmt() -> ErrorOr<Success> {
  2084. auto& act = cast<StatementAction>(todo_.CurrentAction());
  2085. const Statement& stmt = act.statement();
  2086. if (trace_stream_->is_enabled()) {
  2087. *trace_stream_ << "--- step stmt ";
  2088. stmt.PrintDepth(1, trace_stream_->stream());
  2089. *trace_stream_ << " ." << act.pos() << ". "
  2090. << "(" << stmt.source_loc() << ") --->\n";
  2091. }
  2092. switch (stmt.kind()) {
  2093. case StatementKind::Match: {
  2094. const auto& match_stmt = cast<Match>(stmt);
  2095. if (act.pos() == 0) {
  2096. // { { (match (e) ...) :: C, E, F} :: S, H}
  2097. // -> { { e :: (match ([]) ...) :: C, E, F} :: S, H}
  2098. act.StartScope(RuntimeScope(&heap_));
  2099. return todo_.Spawn(
  2100. std::make_unique<ValueExpressionAction>(&match_stmt.expression()));
  2101. } else {
  2102. int clause_num = act.pos() - 1;
  2103. if (clause_num >= static_cast<int>(match_stmt.clauses().size())) {
  2104. return todo_.FinishAction();
  2105. }
  2106. auto c = match_stmt.clauses()[clause_num];
  2107. RuntimeScope matches(&heap_);
  2108. BindingMap generic_args;
  2109. CARBON_ASSIGN_OR_RETURN(
  2110. Nonnull<const Value*> val,
  2111. Convert(act.results()[0], &c.pattern().static_type(),
  2112. stmt.source_loc()));
  2113. if (PatternMatch(&c.pattern().value(), ExpressionResult::Value(val),
  2114. stmt.source_loc(), &matches, generic_args,
  2115. trace_stream_, this->arena_)) {
  2116. // Ensure we don't process any more clauses.
  2117. act.set_pos(match_stmt.clauses().size() + 1);
  2118. todo_.MergeScope(std::move(matches));
  2119. return todo_.Spawn(
  2120. std::make_unique<StatementAction>(&c.statement(), std::nullopt));
  2121. } else {
  2122. return todo_.RunAgain();
  2123. }
  2124. }
  2125. }
  2126. case StatementKind::For: {
  2127. constexpr int TargetVarPosInResult = 0;
  2128. constexpr int CurrentIndexPosInResult = 1;
  2129. constexpr int EndIndexPosInResult = 2;
  2130. const auto* loop_var = &cast<BindingPlaceholderValue>(
  2131. cast<For>(stmt).variable_declaration().value());
  2132. if (act.pos() == 0) {
  2133. return todo_.Spawn(std::make_unique<ValueExpressionAction>(
  2134. &cast<For>(stmt).loop_target()));
  2135. }
  2136. if (act.pos() == 1) {
  2137. const auto* source_array =
  2138. cast<TupleValue>(act.results()[TargetVarPosInResult]);
  2139. int start_index = 0;
  2140. auto end_index = static_cast<int>(source_array->elements().size());
  2141. if (end_index == 0) {
  2142. return todo_.FinishAction();
  2143. }
  2144. act.AddResult(arena_->New<IntValue>(start_index));
  2145. act.AddResult(arena_->New<IntValue>(end_index));
  2146. todo_.Initialize(*(loop_var->value_node()),
  2147. source_array->elements()[start_index]);
  2148. act.ReplaceResult(CurrentIndexPosInResult,
  2149. arena_->New<IntValue>(start_index + 1));
  2150. return todo_.Spawn(std::make_unique<StatementAction>(
  2151. &cast<For>(stmt).body(), std::nullopt));
  2152. }
  2153. if (act.pos() >= 2) {
  2154. auto current_index =
  2155. cast<IntValue>(act.results()[CurrentIndexPosInResult])->value();
  2156. auto end_index =
  2157. cast<IntValue>(act.results()[EndIndexPosInResult])->value();
  2158. if (current_index < end_index) {
  2159. const auto* source_array =
  2160. cast<const TupleValue>(act.results()[TargetVarPosInResult]);
  2161. CARBON_ASSIGN_OR_RETURN(
  2162. Nonnull<const Value*> assigned_array_element,
  2163. todo_.ValueOfNode(*(loop_var->value_node()), stmt.source_loc()));
  2164. const auto* location = cast<LocationValue>(assigned_array_element);
  2165. CARBON_RETURN_IF_ERROR(heap_.Write(
  2166. location->address(), source_array->elements()[current_index],
  2167. stmt.source_loc()));
  2168. act.ReplaceResult(CurrentIndexPosInResult,
  2169. arena_->New<IntValue>(current_index + 1));
  2170. return todo_.Spawn(std::make_unique<StatementAction>(
  2171. &cast<For>(stmt).body(), std::nullopt));
  2172. }
  2173. }
  2174. return todo_.FinishAction();
  2175. }
  2176. case StatementKind::While:
  2177. // TODO: Rewrite While to use ReplaceResult to store condition result.
  2178. // This will remove the inconsistency between the while and for
  2179. // loops.
  2180. if (act.pos() % 2 == 0) {
  2181. // { { (while (e) s) :: C, E, F} :: S, H}
  2182. // -> { { e :: (while ([]) s) :: C, E, F} :: S, H}
  2183. act.Clear();
  2184. return todo_.Spawn(std::make_unique<ValueExpressionAction>(
  2185. &cast<While>(stmt).condition()));
  2186. } else {
  2187. CARBON_ASSIGN_OR_RETURN(
  2188. Nonnull<const Value*> condition,
  2189. Convert(act.results().back(), arena_->New<BoolType>(),
  2190. stmt.source_loc()));
  2191. if (cast<BoolValue>(*condition).value()) {
  2192. // { {true :: (while ([]) s) :: C, E, F} :: S, H}
  2193. // -> { { s :: (while (e) s) :: C, E, F } :: S, H}
  2194. return todo_.Spawn(std::make_unique<StatementAction>(
  2195. &cast<While>(stmt).body(), std::nullopt));
  2196. } else {
  2197. // { {false :: (while ([]) s) :: C, E, F} :: S, H}
  2198. // -> { { C, E, F } :: S, H}
  2199. return todo_.FinishAction();
  2200. }
  2201. }
  2202. case StatementKind::Break: {
  2203. CARBON_CHECK(act.pos() == 0);
  2204. // { { break; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  2205. // -> { { C, E', F} :: S, H}
  2206. return todo_.UnwindPast(&cast<Break>(stmt).loop());
  2207. }
  2208. case StatementKind::Continue: {
  2209. CARBON_CHECK(act.pos() == 0);
  2210. // { { continue; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  2211. // -> { { (while (e) s) :: C, E', F} :: S, H}
  2212. return todo_.UnwindTo(&cast<Continue>(stmt).loop());
  2213. }
  2214. case StatementKind::Block: {
  2215. const auto& block = cast<Block>(stmt);
  2216. if (act.pos() >= static_cast<int>(block.statements().size())) {
  2217. // If the position is past the end of the block, end processing. Note
  2218. // that empty blocks immediately end.
  2219. return todo_.FinishAction();
  2220. }
  2221. // Initialize a scope when starting a block.
  2222. if (act.pos() == 0) {
  2223. act.StartScope(RuntimeScope(&heap_));
  2224. }
  2225. // Process the next statement in the block. The position will be
  2226. // incremented as part of Spawn.
  2227. return todo_.Spawn(std::make_unique<StatementAction>(
  2228. block.statements()[act.pos()], act.location_received()));
  2229. }
  2230. case StatementKind::VariableDefinition: {
  2231. const auto& definition = cast<VariableDefinition>(stmt);
  2232. const bool has_initializing_expr =
  2233. definition.has_init() &&
  2234. definition.init().kind() == ExpressionKind::CallExpression &&
  2235. definition.init().expression_category() ==
  2236. ExpressionCategory::Initializing;
  2237. auto init_location = (act.location_received() && definition.is_returned())
  2238. ? act.location_received()
  2239. : act.location_created();
  2240. if (act.pos() == 0 && definition.has_init()) {
  2241. // { {(var x = e) :: C, E, F} :: S, H}
  2242. // -> { {e :: (var x = []) :: C, E, F} :: S, H}
  2243. if (has_initializing_expr && !init_location) {
  2244. // Allocate storage for initializing expression.
  2245. const auto allocation_id =
  2246. heap_.AllocateValue(arena_->New<UninitializedValue>(
  2247. &definition.init().static_type()));
  2248. act.set_location_created(allocation_id);
  2249. init_location = allocation_id;
  2250. RuntimeScope scope(&heap_);
  2251. scope.BindLifetimeToScope(Address(allocation_id));
  2252. todo_.MergeScope(std::move(scope));
  2253. }
  2254. return todo_.Spawn(std::make_unique<ExpressionAction>(
  2255. &definition.init(), /*preserve_nested_categories=*/false,
  2256. init_location));
  2257. } else {
  2258. // { { v :: (x = []) :: C, E, F} :: S, H}
  2259. // -> { { C, E(x := a), F} :: S, H(a := copy(v))}
  2260. Nonnull<const Value*> p = &definition.pattern().value();
  2261. Nonnull<const Value*> v;
  2262. std::optional<Address> v_location;
  2263. ExpressionCategory expr_category =
  2264. definition.has_init() ? definition.init().expression_category()
  2265. : ExpressionCategory::Value;
  2266. if (definition.has_init()) {
  2267. Nonnull<const Value*> result = act.results()[0];
  2268. std::optional<Nonnull<const ReferenceExpressionValue*>> v_expr =
  2269. (result->kind() == Value::Kind::ReferenceExpressionValue)
  2270. ? std::optional{cast<ReferenceExpressionValue>(result)}
  2271. : std::nullopt;
  2272. const auto init_location = act.location_created();
  2273. v = v_expr ? (*v_expr)->value() : result;
  2274. if (expr_category == ExpressionCategory::Reference) {
  2275. CARBON_CHECK(v_expr) << "Expecting ReferenceExpressionValue from "
  2276. "reference expression";
  2277. v_location = (*v_expr)->address();
  2278. CARBON_CHECK(v_location)
  2279. << "Expecting a valid address from reference expression";
  2280. } else if (has_initializing_expr && init_location &&
  2281. heap_.is_initialized(*init_location)) {
  2282. // Bind even if a conversion is necessary.
  2283. v_location = Address(*init_location);
  2284. CARBON_ASSIGN_OR_RETURN(
  2285. result, heap_.Read(*v_location, definition.source_loc()));
  2286. CARBON_CHECK(v == result);
  2287. } else {
  2288. // TODO: Prevent copies for Value expressions from Reference
  2289. // expression, once able to prevent mutations.
  2290. if (init_location && act.location_created()) {
  2291. // Location provided to initializing expression was not used.
  2292. heap_.Discard(*init_location);
  2293. }
  2294. expr_category = ExpressionCategory::Value;
  2295. const auto* dest_type = &definition.pattern().static_type();
  2296. CARBON_ASSIGN_OR_RETURN(v,
  2297. Convert(v, dest_type, stmt.source_loc()));
  2298. }
  2299. } else {
  2300. v = arena_->New<UninitializedValue>(p);
  2301. }
  2302. // If declaring a returned var, bind name to the location provided to
  2303. // initializing expression, if any.
  2304. RuntimeScope scope(&heap_);
  2305. if (definition.is_returned() && init_location) {
  2306. CARBON_CHECK(p->kind() == Value::Kind::BindingPlaceholderValue);
  2307. const auto value_node =
  2308. cast<BindingPlaceholderValue>(*p).value_node();
  2309. CARBON_CHECK(value_node);
  2310. const auto address = Address(*init_location);
  2311. scope.Bind(*value_node, address);
  2312. CARBON_RETURN_IF_ERROR(heap_.Write(address, v, stmt.source_loc()));
  2313. } else {
  2314. BindingMap generic_args;
  2315. bool matched =
  2316. PatternMatch(p, ExpressionResult(v, v_location, expr_category),
  2317. stmt.source_loc(), &scope, generic_args,
  2318. trace_stream_, this->arena_);
  2319. CARBON_CHECK(matched)
  2320. << stmt.source_loc()
  2321. << ": internal error in variable definition, match failed";
  2322. }
  2323. todo_.MergeScope(std::move(scope));
  2324. return todo_.FinishAction();
  2325. }
  2326. }
  2327. case StatementKind::ExpressionStatement:
  2328. if (act.pos() == 0) {
  2329. // { {e :: C, E, F} :: S, H}
  2330. // -> { {e :: C, E, F} :: S, H}
  2331. return todo_.Spawn(std::make_unique<ValueExpressionAction>(
  2332. &cast<ExpressionStatement>(stmt).expression()));
  2333. } else {
  2334. return todo_.FinishAction();
  2335. }
  2336. case StatementKind::Assign: {
  2337. const auto& assign = cast<Assign>(stmt);
  2338. if (auto rewrite = assign.rewritten_form()) {
  2339. if (act.pos() == 0) {
  2340. return todo_.Spawn(std::make_unique<ValueExpressionAction>(*rewrite));
  2341. } else {
  2342. return todo_.FinishAction();
  2343. }
  2344. }
  2345. if (act.pos() == 0) {
  2346. // { {(lv = e) :: C, E, F} :: S, H}
  2347. // -> { {lv :: ([] = e) :: C, E, F} :: S, H}
  2348. return todo_.Spawn(std::make_unique<LocationAction>(&assign.lhs()));
  2349. } else if (act.pos() == 1) {
  2350. // { { a :: ([] = e) :: C, E, F} :: S, H}
  2351. // -> { { e :: (a = []) :: C, E, F} :: S, H}
  2352. return todo_.Spawn(
  2353. std::make_unique<ValueExpressionAction>(&assign.rhs()));
  2354. } else {
  2355. // { { v :: (a = []) :: C, E, F} :: S, H}
  2356. // -> { { C, E, F} :: S, H(a := v)}
  2357. const auto& lval = cast<LocationValue>(*act.results()[0]);
  2358. CARBON_ASSIGN_OR_RETURN(
  2359. Nonnull<const Value*> rval,
  2360. Convert(act.results()[1], &assign.lhs().static_type(),
  2361. stmt.source_loc()));
  2362. CARBON_RETURN_IF_ERROR(
  2363. heap_.Write(lval.address(), rval, stmt.source_loc()));
  2364. return todo_.FinishAction();
  2365. }
  2366. }
  2367. case StatementKind::IncrementDecrement: {
  2368. const auto& inc_dec = cast<IncrementDecrement>(stmt);
  2369. if (act.pos() == 0) {
  2370. return todo_.Spawn(
  2371. std::make_unique<ValueExpressionAction>(*inc_dec.rewritten_form()));
  2372. } else {
  2373. return todo_.FinishAction();
  2374. }
  2375. }
  2376. case StatementKind::If:
  2377. if (act.pos() == 0) {
  2378. // { {(if (e) then_stmt else else_stmt) :: C, E, F} :: S, H}
  2379. // -> { { e :: (if ([]) then_stmt else else_stmt) :: C, E, F} :: S, H}
  2380. return todo_.Spawn(std::make_unique<ValueExpressionAction>(
  2381. &cast<If>(stmt).condition()));
  2382. } else if (act.pos() == 1) {
  2383. CARBON_ASSIGN_OR_RETURN(
  2384. Nonnull<const Value*> condition,
  2385. Convert(act.results()[0], arena_->New<BoolType>(),
  2386. stmt.source_loc()));
  2387. if (cast<BoolValue>(*condition).value()) {
  2388. // { {true :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  2389. // S, H}
  2390. // -> { { then_stmt :: C, E, F } :: S, H}
  2391. return todo_.Spawn(std::make_unique<StatementAction>(
  2392. &cast<If>(stmt).then_block(), std::nullopt));
  2393. } else if (cast<If>(stmt).else_block()) {
  2394. // { {false :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  2395. // S, H}
  2396. // -> { { else_stmt :: C, E, F } :: S, H}
  2397. return todo_.Spawn(std::make_unique<StatementAction>(
  2398. *cast<If>(stmt).else_block(), std::nullopt));
  2399. } else {
  2400. return todo_.FinishAction();
  2401. }
  2402. } else {
  2403. return todo_.FinishAction();
  2404. }
  2405. case StatementKind::ReturnVar: {
  2406. const auto& ret_var = cast<ReturnVar>(stmt);
  2407. const ValueNodeView& value_node = ret_var.value_node();
  2408. if (trace_stream_->is_enabled()) {
  2409. *trace_stream_ << "--- step returned var "
  2410. << cast<BindingPattern>(value_node.base()).name() << " ."
  2411. << act.pos() << "."
  2412. << " (" << stmt.source_loc() << ") --->\n";
  2413. }
  2414. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> value,
  2415. todo_.ValueOfNode(value_node, stmt.source_loc()));
  2416. if (const auto* location = dyn_cast<LocationValue>(value)) {
  2417. CARBON_ASSIGN_OR_RETURN(
  2418. value, heap_.Read(location->address(), ret_var.source_loc()));
  2419. }
  2420. const CallableDeclaration& function = cast<Return>(stmt).function();
  2421. CARBON_ASSIGN_OR_RETURN(
  2422. Nonnull<const Value*> return_value,
  2423. Convert(value, &function.return_term().static_type(),
  2424. stmt.source_loc()));
  2425. return todo_.UnwindPast(*function.body(), return_value);
  2426. }
  2427. case StatementKind::ReturnExpression:
  2428. if (act.pos() == 0) {
  2429. // { {return e :: C, E, F} :: S, H}
  2430. // -> { {e :: return [] :: C, E, F} :: S, H}
  2431. return todo_.Spawn(std::make_unique<ValueExpressionAction>(
  2432. &cast<ReturnExpression>(stmt).expression()));
  2433. } else {
  2434. // { {v :: return [] :: C, E, F} :: {C', E', F'} :: S, H}
  2435. // -> { {v :: C', E', F'} :: S, H}
  2436. const CallableDeclaration& function = cast<Return>(stmt).function();
  2437. CARBON_ASSIGN_OR_RETURN(
  2438. Nonnull<const Value*> return_value,
  2439. Convert(act.results()[0], &function.return_term().static_type(),
  2440. stmt.source_loc()));
  2441. // Write to initialized storage location, if any.
  2442. if (const auto location = act.location_received()) {
  2443. CARBON_RETURN_IF_ERROR(
  2444. heap_.Write(Address(*location), return_value, stmt.source_loc()));
  2445. }
  2446. return todo_.UnwindPast(*function.body(), return_value);
  2447. }
  2448. }
  2449. }
  2450. auto Interpreter::StepDeclaration() -> ErrorOr<Success> {
  2451. Action& act = todo_.CurrentAction();
  2452. const Declaration& decl = cast<DeclarationAction>(act).declaration();
  2453. if (trace_stream_->is_enabled()) {
  2454. *trace_stream_ << "--- step decl ";
  2455. decl.PrintID(trace_stream_->stream());
  2456. *trace_stream_ << " ." << act.pos() << ". "
  2457. << "(" << decl.source_loc() << ") --->\n";
  2458. }
  2459. switch (decl.kind()) {
  2460. case DeclarationKind::VariableDeclaration: {
  2461. const auto& var_decl = cast<VariableDeclaration>(decl);
  2462. if (var_decl.has_initializer()) {
  2463. if (act.pos() == 0) {
  2464. return todo_.Spawn(
  2465. std::make_unique<ValueExpressionAction>(&var_decl.initializer()));
  2466. } else {
  2467. CARBON_ASSIGN_OR_RETURN(
  2468. Nonnull<const Value*> v,
  2469. Convert(act.results()[0], &var_decl.binding().static_type(),
  2470. var_decl.source_loc()));
  2471. todo_.Initialize(&var_decl.binding(), v);
  2472. return todo_.FinishAction();
  2473. }
  2474. } else {
  2475. Nonnull<const Value*> v =
  2476. arena_->New<UninitializedValue>(&var_decl.binding().value());
  2477. todo_.Initialize(&var_decl.binding(), v);
  2478. return todo_.FinishAction();
  2479. }
  2480. }
  2481. case DeclarationKind::NamespaceDeclaration:
  2482. case DeclarationKind::DestructorDeclaration:
  2483. case DeclarationKind::FunctionDeclaration:
  2484. case DeclarationKind::ClassDeclaration:
  2485. case DeclarationKind::MixinDeclaration:
  2486. case DeclarationKind::MixDeclaration:
  2487. case DeclarationKind::ChoiceDeclaration:
  2488. case DeclarationKind::InterfaceDeclaration:
  2489. case DeclarationKind::ConstraintDeclaration:
  2490. case DeclarationKind::InterfaceExtendDeclaration:
  2491. case DeclarationKind::InterfaceRequireDeclaration:
  2492. case DeclarationKind::AssociatedConstantDeclaration:
  2493. case DeclarationKind::ImplDeclaration:
  2494. case DeclarationKind::MatchFirstDeclaration:
  2495. case DeclarationKind::SelfDeclaration:
  2496. case DeclarationKind::AliasDeclaration:
  2497. case DeclarationKind::ExtendBaseDeclaration:
  2498. // These declarations have no run-time effects.
  2499. return todo_.FinishAction();
  2500. }
  2501. }
  2502. auto Interpreter::StepDestroy() -> ErrorOr<Success> {
  2503. const Action& act = todo_.CurrentAction();
  2504. const auto& destroy_act = cast<DestroyAction>(act);
  2505. switch (destroy_act.value()->kind()) {
  2506. case Value::Kind::NominalClassValue: {
  2507. const auto* class_obj = cast<NominalClassValue>(destroy_act.value());
  2508. const auto& class_decl =
  2509. cast<NominalClassType>(class_obj->type()).declaration();
  2510. const int member_count = class_decl.members().size();
  2511. if (act.pos() == 0) {
  2512. // Run the destructor, if there is one.
  2513. if (auto destructor = class_decl.destructor()) {
  2514. return CallDestructor(*destructor, class_obj);
  2515. } else {
  2516. return todo_.RunAgain();
  2517. }
  2518. } else if (act.pos() <= member_count) {
  2519. // Destroy members.
  2520. const int index = class_decl.members().size() - act.pos();
  2521. const auto& member = class_decl.members()[index];
  2522. if (const auto* var = dyn_cast<VariableDeclaration>(member)) {
  2523. const Address object = destroy_act.location()->address();
  2524. const Address var_addr =
  2525. object.ElementAddress(arena_->New<NamedElement>(var));
  2526. const auto v = heap_.Read(var_addr, var->source_loc());
  2527. CARBON_CHECK(v.ok())
  2528. << "Failed to read member `" << var->binding().name()
  2529. << "` from class `" << class_decl.name() << "`";
  2530. return todo_.Spawn(std::make_unique<DestroyAction>(
  2531. arena_->New<LocationValue>(var_addr), *v));
  2532. } else {
  2533. return todo_.RunAgain();
  2534. }
  2535. } else if (act.pos() == member_count + 1) {
  2536. // Destroy the parent, if there is one.
  2537. if (auto base = class_obj->base()) {
  2538. const Address obj_addr = destroy_act.location()->address();
  2539. const Address base_addr =
  2540. obj_addr.ElementAddress(arena_->New<BaseElement>(class_obj));
  2541. return todo_.Spawn(std::make_unique<DestroyAction>(
  2542. arena_->New<LocationValue>(base_addr), base.value()));
  2543. } else {
  2544. return todo_.RunAgain();
  2545. }
  2546. } else {
  2547. todo_.Pop();
  2548. return Success();
  2549. }
  2550. }
  2551. case Value::Kind::TupleValue: {
  2552. const auto* tuple = cast<TupleValue>(destroy_act.value());
  2553. const auto element_count = tuple->elements().size();
  2554. if (static_cast<size_t>(act.pos()) < element_count) {
  2555. const size_t index = element_count - act.pos() - 1;
  2556. const auto& item = tuple->elements()[index];
  2557. const auto object_addr = destroy_act.location()->address();
  2558. Address field_address = object_addr.ElementAddress(
  2559. arena_->New<PositionalElement>(index, item));
  2560. if (item->kind() == Value::Kind::NominalClassValue ||
  2561. item->kind() == Value::Kind::TupleValue) {
  2562. return todo_.Spawn(std::make_unique<DestroyAction>(
  2563. arena_->New<LocationValue>(field_address), item));
  2564. } else {
  2565. // The tuple element's type is an integral type (e.g., i32)
  2566. // or the type doesn't support destruction.
  2567. return todo_.RunAgain();
  2568. }
  2569. } else {
  2570. todo_.Pop();
  2571. return Success();
  2572. }
  2573. }
  2574. default:
  2575. // These declarations have no run-time effects.
  2576. todo_.Pop();
  2577. return Success();
  2578. }
  2579. CARBON_FATAL() << "Unreachable";
  2580. }
  2581. auto Interpreter::StepCleanUp() -> ErrorOr<Success> {
  2582. const Action& act = todo_.CurrentAction();
  2583. const auto& cleanup = cast<CleanUpAction>(act);
  2584. if (act.pos() < cleanup.allocations_count() * 2) {
  2585. const size_t alloc_index = cleanup.allocations_count() - act.pos() / 2 - 1;
  2586. auto allocation = act.scope()->allocations()[alloc_index];
  2587. if (heap_.is_discarded(allocation)) {
  2588. // Initializing expressions can generate discarded allocations.
  2589. return todo_.RunAgain();
  2590. }
  2591. if (act.pos() % 2 == 0) {
  2592. auto* location = arena_->New<LocationValue>(Address(allocation));
  2593. auto value = heap_.Read(location->address(), *cleanup.source_loc());
  2594. // Step over uninitialized values.
  2595. if (value.ok()) {
  2596. return todo_.Spawn(std::make_unique<DestroyAction>(location, *value));
  2597. } else {
  2598. return todo_.RunAgain();
  2599. }
  2600. } else {
  2601. CARBON_RETURN_IF_ERROR(heap_.Deallocate(allocation));
  2602. return todo_.RunAgain();
  2603. }
  2604. }
  2605. todo_.Pop();
  2606. return Success();
  2607. }
  2608. // State transition.
  2609. auto Interpreter::Step() -> ErrorOr<Success> {
  2610. Action& act = todo_.CurrentAction();
  2611. auto error_builder = [&] {
  2612. if (auto loc = act.source_loc()) {
  2613. return ProgramError(*loc);
  2614. }
  2615. return ErrorBuilder();
  2616. };
  2617. // Check for various overflow conditions before stepping.
  2618. if (todo_.size() > MaxTodoSize) {
  2619. return error_builder()
  2620. << "stack overflow: too many interpreter actions on stack";
  2621. }
  2622. if (++steps_taken_ > MaxStepsTaken) {
  2623. return error_builder()
  2624. << "possible infinite loop: too many interpreter steps executed";
  2625. }
  2626. if (arena_->allocated() > MaxArenaAllocated) {
  2627. return error_builder() << "out of memory: exceeded arena allocation limit";
  2628. }
  2629. switch (act.kind()) {
  2630. case Action::Kind::LocationAction:
  2631. CARBON_RETURN_IF_ERROR(StepLocation());
  2632. break;
  2633. case Action::Kind::ValueExpressionAction:
  2634. CARBON_RETURN_IF_ERROR(StepValueExp());
  2635. break;
  2636. case Action::Kind::ExpressionAction:
  2637. CARBON_RETURN_IF_ERROR(StepExp());
  2638. break;
  2639. case Action::Kind::WitnessAction:
  2640. CARBON_RETURN_IF_ERROR(StepWitness());
  2641. break;
  2642. case Action::Kind::StatementAction:
  2643. CARBON_RETURN_IF_ERROR(StepStmt());
  2644. break;
  2645. case Action::Kind::DeclarationAction:
  2646. CARBON_RETURN_IF_ERROR(StepDeclaration());
  2647. break;
  2648. case Action::Kind::CleanUpAction:
  2649. CARBON_RETURN_IF_ERROR(StepCleanUp());
  2650. break;
  2651. case Action::Kind::DestroyAction:
  2652. CARBON_RETURN_IF_ERROR(StepDestroy());
  2653. break;
  2654. case Action::Kind::TypeInstantiationAction:
  2655. CARBON_RETURN_IF_ERROR(StepInstantiateType());
  2656. break;
  2657. case Action::Kind::ScopeAction:
  2658. CARBON_FATAL() << "ScopeAction escaped ActionStack";
  2659. case Action::Kind::RecursiveAction:
  2660. CARBON_FATAL() << "Tried to step a RecursiveAction";
  2661. } // switch
  2662. return Success();
  2663. }
  2664. auto Interpreter::RunAllSteps(std::unique_ptr<Action> action)
  2665. -> ErrorOr<Success> {
  2666. todo_.Start(std::move(action));
  2667. while (!todo_.empty()) {
  2668. CARBON_RETURN_IF_ERROR(Step());
  2669. }
  2670. return Success();
  2671. }
  2672. auto InterpProgram(const AST& ast, Nonnull<Arena*> arena,
  2673. Nonnull<TraceStream*> trace_stream,
  2674. Nonnull<llvm::raw_ostream*> print_stream) -> ErrorOr<int> {
  2675. Interpreter interpreter(Phase::RunTime, arena, trace_stream, print_stream);
  2676. if (trace_stream->is_enabled()) {
  2677. *trace_stream << "********** initializing globals **********\n";
  2678. }
  2679. SetFileContext set_file_ctx(*trace_stream,
  2680. ast.declarations.front()->source_loc());
  2681. for (Nonnull<Declaration*> declaration : ast.declarations) {
  2682. set_file_ctx.update_source_loc(declaration->source_loc());
  2683. CARBON_RETURN_IF_ERROR(interpreter.RunAllSteps(
  2684. std::make_unique<DeclarationAction>(declaration)));
  2685. }
  2686. if (trace_stream->is_enabled()) {
  2687. *trace_stream << "********** calling main function **********\n";
  2688. }
  2689. CARBON_CHECK(ast.main_call);
  2690. set_file_ctx.update_source_loc(ast.main_call.value()->source_loc());
  2691. CARBON_RETURN_IF_ERROR(interpreter.RunAllSteps(
  2692. std::make_unique<ValueExpressionAction>(*ast.main_call)));
  2693. return cast<IntValue>(*interpreter.result()).value();
  2694. }
  2695. auto InterpExp(Nonnull<const Expression*> e, Nonnull<Arena*> arena,
  2696. Nonnull<TraceStream*> trace_stream,
  2697. Nonnull<llvm::raw_ostream*> print_stream)
  2698. -> ErrorOr<Nonnull<const Value*>> {
  2699. Interpreter interpreter(Phase::CompileTime, arena, trace_stream,
  2700. print_stream);
  2701. CARBON_RETURN_IF_ERROR(
  2702. interpreter.RunAllSteps(std::make_unique<ValueExpressionAction>(e)));
  2703. return interpreter.result();
  2704. }
  2705. } // namespace Carbon