interpreter.cpp 108 KB

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