interpreter.cpp 109 KB

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