interpreter.cpp 102 KB

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