interpreter.cpp 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019
  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 <map>
  8. #include <optional>
  9. #include <random>
  10. #include <utility>
  11. #include <variant>
  12. #include <vector>
  13. #include "common/check.h"
  14. #include "explorer/ast/declaration.h"
  15. #include "explorer/ast/expression.h"
  16. #include "explorer/common/arena.h"
  17. #include "explorer/common/error_builders.h"
  18. #include "explorer/interpreter/action.h"
  19. #include "explorer/interpreter/action_stack.h"
  20. #include "explorer/interpreter/stack.h"
  21. #include "llvm/ADT/StringExtras.h"
  22. #include "llvm/Support/Casting.h"
  23. #include "llvm/Support/Error.h"
  24. #include "llvm/Support/FormatVariadic.h"
  25. using llvm::cast;
  26. using llvm::dyn_cast;
  27. using llvm::isa;
  28. namespace Carbon {
  29. static std::mt19937 generator(12);
  30. // Constructs an ActionStack suitable for the specified phase.
  31. static auto MakeTodo(Phase phase, Nonnull<Heap*> heap) -> ActionStack {
  32. switch (phase) {
  33. case Phase::CompileTime:
  34. return ActionStack();
  35. case Phase::RunTime:
  36. return ActionStack(heap);
  37. }
  38. }
  39. // An Interpreter represents an instance of the Carbon abstract machine. It
  40. // manages the state of the abstract machine, and executes the steps of Actions
  41. // passed to it.
  42. class Interpreter {
  43. public:
  44. // Constructs an Interpreter which allocates values on `arena`, and prints
  45. // traces if `trace` is true. `phase` indicates whether it executes at
  46. // compile time or run time.
  47. Interpreter(Phase phase, Nonnull<Arena*> arena,
  48. std::optional<Nonnull<llvm::raw_ostream*>> trace_stream)
  49. : arena_(arena),
  50. heap_(arena),
  51. todo_(MakeTodo(phase, &heap_)),
  52. trace_stream_(trace_stream),
  53. phase_(phase) {}
  54. ~Interpreter();
  55. // Runs all the steps of `action`.
  56. // It's not safe to call `RunAllSteps()` or `result()` after an error.
  57. auto RunAllSteps(std::unique_ptr<Action> action) -> ErrorOr<Success>;
  58. // The result produced by the `action` argument of the most recent
  59. // RunAllSteps call. Cannot be called if `action` was an action that doesn't
  60. // produce results.
  61. auto result() const -> Nonnull<const Value*> { return todo_.result(); }
  62. private:
  63. auto Step() -> ErrorOr<Success>;
  64. // State transitions for expressions.
  65. auto StepExp() -> ErrorOr<Success>;
  66. // State transitions for lvalues.
  67. auto StepLvalue() -> ErrorOr<Success>;
  68. // State transitions for patterns.
  69. auto StepPattern() -> ErrorOr<Success>;
  70. // State transition for statements.
  71. auto StepStmt() -> ErrorOr<Success>;
  72. // State transition for declarations.
  73. auto StepDeclaration() -> ErrorOr<Success>;
  74. // State transition for object destruction.
  75. auto StepCleanUp() -> ErrorOr<Success>;
  76. auto CreateStruct(const std::vector<FieldInitializer>& fields,
  77. const std::vector<Nonnull<const Value*>>& values)
  78. -> Nonnull<const Value*>;
  79. auto EvalPrim(Operator op, Nonnull<const Value*> static_type,
  80. const std::vector<Nonnull<const Value*>>& args,
  81. SourceLocation source_loc) -> ErrorOr<Nonnull<const Value*>>;
  82. // Returns the result of converting `value` to type `destination_type`.
  83. auto Convert(Nonnull<const Value*> value,
  84. Nonnull<const Value*> destination_type,
  85. SourceLocation source_loc) -> ErrorOr<Nonnull<const Value*>>;
  86. // Evaluate an expression immediately, recursively.
  87. //
  88. // TODO: Stop using this.
  89. auto EvalExpRecursively(Nonnull<const Expression*> exp)
  90. -> ErrorOr<Nonnull<const Value*>>;
  91. // Evaluate an associated constant by evaluating its witness and looking
  92. // inside the impl for the corresponding value.
  93. //
  94. // TODO: This approach doesn't provide values that are known because they
  95. // appear in constraints:
  96. //
  97. // interface Iface { let N:! i32; }
  98. // fn PickType(N: i32) -> Type { return i32; }
  99. // fn F[T:! Iface where .N == 5](x: T) {
  100. // var x: PickType(T.N) = 0;
  101. // }
  102. //
  103. // ... will fail because we can't resolve T.N to 5 at compile time.
  104. auto EvalAssociatedConstant(Nonnull<const AssociatedConstant*> assoc,
  105. SourceLocation source_loc)
  106. -> ErrorOr<Nonnull<const Value*>>;
  107. // Instantiate a type by replacing all type variables that occur inside the
  108. // type by the current values of those variables.
  109. //
  110. // For example, suppose T=i32 and U=bool. Then
  111. // __Fn (Point(T)) -> Point(U)
  112. // becomes
  113. // __Fn (Point(i32)) -> Point(bool)
  114. auto InstantiateType(Nonnull<const Value*> type, SourceLocation source_loc)
  115. -> ErrorOr<Nonnull<const Value*>>;
  116. // Instantiate a set of bindings by replacing all type variables that occur
  117. // within it by the current values of those variables.
  118. auto InstantiateBindings(Nonnull<const Bindings*> bindings,
  119. SourceLocation source_loc)
  120. -> ErrorOr<Nonnull<const Bindings*>>;
  121. // Call the function `fun` with the given `arg` and the `witnesses`
  122. // for the function's impl bindings.
  123. auto CallFunction(const CallExpression& call, Nonnull<const Value*> fun,
  124. Nonnull<const Value*> arg, ImplWitnessMap&& witnesses)
  125. -> ErrorOr<Success>;
  126. auto CallDestructor(Nonnull<const DestructorDeclaration*> fun,
  127. Nonnull<const Value*> receiver) -> ErrorOr<Success>;
  128. void PrintState(llvm::raw_ostream& out);
  129. Phase phase() const { return phase_; }
  130. Nonnull<Arena*> arena_;
  131. Heap heap_;
  132. ActionStack todo_;
  133. // The underlying states of continuation values. All StackFragments created
  134. // during execution are tracked here, in order to safely deallocate the
  135. // contents of any non-completed continuations at the end of execution.
  136. std::vector<Nonnull<ContinuationValue::StackFragment*>> stack_fragments_;
  137. std::optional<Nonnull<llvm::raw_ostream*>> trace_stream_;
  138. Phase phase_;
  139. };
  140. Interpreter::~Interpreter() {
  141. // Clean up any remaining suspended continuations.
  142. for (Nonnull<ContinuationValue::StackFragment*> fragment : stack_fragments_) {
  143. fragment->Clear();
  144. }
  145. }
  146. //
  147. // State Operations
  148. //
  149. void Interpreter::PrintState(llvm::raw_ostream& out) {
  150. out << "{\nstack: " << todo_;
  151. out << "\nmemory: " << heap_;
  152. out << "\n}\n";
  153. }
  154. auto Interpreter::EvalPrim(Operator op, Nonnull<const Value*> static_type,
  155. const std::vector<Nonnull<const Value*>>& args,
  156. SourceLocation source_loc)
  157. -> ErrorOr<Nonnull<const Value*>> {
  158. switch (op) {
  159. case Operator::Neg:
  160. return arena_->New<IntValue>(-cast<IntValue>(*args[0]).value());
  161. case Operator::Add:
  162. return arena_->New<IntValue>(cast<IntValue>(*args[0]).value() +
  163. cast<IntValue>(*args[1]).value());
  164. case Operator::Sub:
  165. return arena_->New<IntValue>(cast<IntValue>(*args[0]).value() -
  166. cast<IntValue>(*args[1]).value());
  167. case Operator::Mul:
  168. return arena_->New<IntValue>(cast<IntValue>(*args[0]).value() *
  169. cast<IntValue>(*args[1]).value());
  170. case Operator::Div:
  171. return arena_->New<IntValue>(cast<IntValue>(*args[0]).value() /
  172. cast<IntValue>(*args[1]).value());
  173. case Operator::Mod:
  174. return arena_->New<IntValue>(cast<IntValue>(*args[0]).value() %
  175. cast<IntValue>(*args[1]).value());
  176. case Operator::Not:
  177. return arena_->New<BoolValue>(!cast<BoolValue>(*args[0]).value());
  178. case Operator::And:
  179. return arena_->New<BoolValue>(cast<BoolValue>(*args[0]).value() &&
  180. cast<BoolValue>(*args[1]).value());
  181. case Operator::Or:
  182. return arena_->New<BoolValue>(cast<BoolValue>(*args[0]).value() ||
  183. cast<BoolValue>(*args[1]).value());
  184. case Operator::Ptr:
  185. return arena_->New<PointerType>(args[0]);
  186. case Operator::Deref:
  187. return heap_.Read(cast<PointerValue>(*args[0]).address(), source_loc);
  188. case Operator::AddressOf:
  189. return arena_->New<PointerValue>(cast<LValue>(*args[0]).address());
  190. case Operator::BitwiseAnd:
  191. // If & wasn't rewritten, it's being used to form a constraint.
  192. return &cast<TypeOfConstraintType>(static_type)->constraint_type();
  193. case Operator::As:
  194. case Operator::Eq:
  195. case Operator::NotEq:
  196. case Operator::Less:
  197. case Operator::LessEq:
  198. case Operator::Greater:
  199. case Operator::GreaterEq:
  200. case Operator::BitwiseOr:
  201. case Operator::BitwiseXor:
  202. case Operator::BitShiftLeft:
  203. case Operator::BitShiftRight:
  204. case Operator::Complement:
  205. CARBON_FATAL() << "operator " << ToString(op)
  206. << " should always be rewritten";
  207. }
  208. }
  209. auto Interpreter::CreateStruct(const std::vector<FieldInitializer>& fields,
  210. const std::vector<Nonnull<const Value*>>& values)
  211. -> Nonnull<const Value*> {
  212. CARBON_CHECK(fields.size() == values.size());
  213. std::vector<NamedValue> elements;
  214. for (size_t i = 0; i < fields.size(); ++i) {
  215. elements.push_back({.name = fields[i].name(), .value = values[i]});
  216. }
  217. return arena_->New<StructValue>(std::move(elements));
  218. }
  219. auto PatternMatch(Nonnull<const Value*> p, Nonnull<const Value*> v,
  220. SourceLocation source_loc,
  221. std::optional<Nonnull<RuntimeScope*>> bindings,
  222. BindingMap& generic_args,
  223. std::optional<Nonnull<llvm::raw_ostream*>> trace_stream,
  224. Nonnull<Arena*> arena) -> bool {
  225. if (trace_stream) {
  226. **trace_stream << "match pattern " << *p << "\nwith value " << *v << "\n";
  227. }
  228. switch (p->kind()) {
  229. case Value::Kind::BindingPlaceholderValue: {
  230. CARBON_CHECK(bindings.has_value());
  231. const auto& placeholder = cast<BindingPlaceholderValue>(*p);
  232. if (placeholder.value_node().has_value()) {
  233. (*bindings)->Initialize(*placeholder.value_node(), v);
  234. }
  235. return true;
  236. }
  237. case Value::Kind::AddrValue: {
  238. const auto& addr = cast<AddrValue>(*p);
  239. CARBON_CHECK(v->kind() == Value::Kind::LValue);
  240. const auto& lvalue = cast<LValue>(*v);
  241. return PatternMatch(
  242. &addr.pattern(), arena->New<PointerValue>(lvalue.address()),
  243. source_loc, bindings, generic_args, trace_stream, arena);
  244. }
  245. case Value::Kind::VariableType: {
  246. const auto& var_type = cast<VariableType>(*p);
  247. generic_args[&var_type.binding()] = v;
  248. return true;
  249. }
  250. case Value::Kind::TupleValue:
  251. switch (v->kind()) {
  252. case Value::Kind::TupleValue: {
  253. const auto& p_tup = cast<TupleValue>(*p);
  254. const auto& v_tup = cast<TupleValue>(*v);
  255. CARBON_CHECK(p_tup.elements().size() == v_tup.elements().size());
  256. for (size_t i = 0; i < p_tup.elements().size(); ++i) {
  257. if (!PatternMatch(p_tup.elements()[i], v_tup.elements()[i],
  258. source_loc, bindings, generic_args, trace_stream,
  259. arena)) {
  260. return false;
  261. }
  262. } // for
  263. return true;
  264. }
  265. case Value::Kind::UninitializedValue: {
  266. const auto& p_tup = cast<TupleValue>(*p);
  267. for (auto& ele : p_tup.elements()) {
  268. if (!PatternMatch(ele, arena->New<UninitializedValue>(ele),
  269. source_loc, bindings, generic_args, trace_stream,
  270. arena)) {
  271. return false;
  272. }
  273. }
  274. return true;
  275. }
  276. default:
  277. CARBON_FATAL() << "expected a tuple value in pattern, not " << *v;
  278. }
  279. case Value::Kind::StructValue: {
  280. const auto& p_struct = cast<StructValue>(*p);
  281. const auto& v_struct = cast<StructValue>(*v);
  282. CARBON_CHECK(p_struct.elements().size() == v_struct.elements().size());
  283. for (size_t i = 0; i < p_struct.elements().size(); ++i) {
  284. CARBON_CHECK(p_struct.elements()[i].name ==
  285. v_struct.elements()[i].name);
  286. if (!PatternMatch(p_struct.elements()[i].value,
  287. v_struct.elements()[i].value, source_loc, bindings,
  288. generic_args, trace_stream, arena)) {
  289. return false;
  290. }
  291. }
  292. return true;
  293. }
  294. case Value::Kind::AlternativeValue:
  295. switch (v->kind()) {
  296. case Value::Kind::AlternativeValue: {
  297. const auto& p_alt = cast<AlternativeValue>(*p);
  298. const auto& v_alt = cast<AlternativeValue>(*v);
  299. if (p_alt.choice_name() != v_alt.choice_name() ||
  300. p_alt.alt_name() != v_alt.alt_name()) {
  301. return false;
  302. }
  303. return PatternMatch(&p_alt.argument(), &v_alt.argument(), source_loc,
  304. bindings, generic_args, trace_stream, arena);
  305. }
  306. default:
  307. CARBON_FATAL() << "expected a choice alternative in pattern, not "
  308. << *v;
  309. }
  310. case Value::Kind::UninitializedValue:
  311. CARBON_FATAL() << "uninitialized value is not allowed in pattern " << *v;
  312. case Value::Kind::FunctionType:
  313. switch (v->kind()) {
  314. case Value::Kind::FunctionType: {
  315. const auto& p_fn = cast<FunctionType>(*p);
  316. const auto& v_fn = cast<FunctionType>(*v);
  317. if (!PatternMatch(&p_fn.parameters(), &v_fn.parameters(), source_loc,
  318. bindings, generic_args, trace_stream, arena)) {
  319. return false;
  320. }
  321. if (!PatternMatch(&p_fn.return_type(), &v_fn.return_type(),
  322. source_loc, bindings, generic_args, trace_stream,
  323. arena)) {
  324. return false;
  325. }
  326. return true;
  327. }
  328. default:
  329. return false;
  330. }
  331. case Value::Kind::AutoType:
  332. // `auto` matches any type, without binding any new names. We rely
  333. // on the typechecker to ensure that `v` is a type.
  334. return true;
  335. default:
  336. return ValueEqual(p, v, std::nullopt);
  337. }
  338. }
  339. auto Interpreter::StepLvalue() -> ErrorOr<Success> {
  340. Action& act = todo_.CurrentAction();
  341. const Expression& exp = cast<LValAction>(act).expression();
  342. if (trace_stream_) {
  343. **trace_stream_ << "--- step lvalue " << exp << " ." << act.pos() << "."
  344. << " (" << exp.source_loc() << ") --->\n";
  345. }
  346. switch (exp.kind()) {
  347. case ExpressionKind::IdentifierExpression: {
  348. // { {x :: C, E, F} :: S, H}
  349. // -> { {E(x) :: C, E, F} :: S, H}
  350. CARBON_ASSIGN_OR_RETURN(
  351. Nonnull<const Value*> value,
  352. todo_.ValueOfNode(cast<IdentifierExpression>(exp).value_node(),
  353. exp.source_loc()));
  354. CARBON_CHECK(isa<LValue>(value)) << *value;
  355. return todo_.FinishAction(value);
  356. }
  357. case ExpressionKind::SimpleMemberAccessExpression: {
  358. if (act.pos() == 0) {
  359. // { {e.f :: C, E, F} :: S, H}
  360. // -> { e :: [].f :: C, E, F} :: S, H}
  361. return todo_.Spawn(std::make_unique<LValAction>(
  362. &cast<SimpleMemberAccessExpression>(exp).object()));
  363. } else {
  364. // { v :: [].f :: C, E, F} :: S, H}
  365. // -> { { &v.f :: C, E, F} :: S, H }
  366. Address object = cast<LValue>(*act.results()[0]).address();
  367. Address member = object.SubobjectAddress(
  368. cast<SimpleMemberAccessExpression>(exp).member());
  369. return todo_.FinishAction(arena_->New<LValue>(member));
  370. }
  371. }
  372. case ExpressionKind::CompoundMemberAccessExpression: {
  373. const auto& access = cast<CompoundMemberAccessExpression>(exp);
  374. if (act.pos() == 0) {
  375. return todo_.Spawn(std::make_unique<LValAction>(&access.object()));
  376. } else {
  377. CARBON_CHECK(!access.member().interface().has_value())
  378. << "unexpected lvalue interface member";
  379. CARBON_ASSIGN_OR_RETURN(
  380. Nonnull<const Value*> val,
  381. Convert(act.results()[0], *access.member().base_type(),
  382. exp.source_loc()));
  383. Address object = cast<LValue>(*val).address();
  384. Address field = object.SubobjectAddress(access.member().member());
  385. return todo_.FinishAction(arena_->New<LValue>(field));
  386. }
  387. }
  388. case ExpressionKind::IndexExpression: {
  389. if (act.pos() == 0) {
  390. // { {e[i] :: C, E, F} :: S, H}
  391. // -> { e :: [][i] :: C, E, F} :: S, H}
  392. return todo_.Spawn(
  393. std::make_unique<LValAction>(&cast<IndexExpression>(exp).object()));
  394. } else if (act.pos() == 1) {
  395. return todo_.Spawn(std::make_unique<ExpressionAction>(
  396. &cast<IndexExpression>(exp).offset()));
  397. } else {
  398. // { v :: [][i] :: C, E, F} :: S, H}
  399. // -> { { &v[i] :: C, E, F} :: S, H }
  400. Address object = cast<LValue>(*act.results()[0]).address();
  401. // TODO: Add support to `Member` for naming tuple fields rather than
  402. // pretending we have struct fields with numerical names.
  403. std::string f =
  404. std::to_string(cast<IntValue>(*act.results()[1]).value());
  405. auto* tuple_field_as_struct_field =
  406. arena_->New<NamedValue>(NamedValue{f, &exp.static_type()});
  407. Address field =
  408. object.SubobjectAddress(Member(tuple_field_as_struct_field));
  409. return todo_.FinishAction(arena_->New<LValue>(field));
  410. }
  411. }
  412. case ExpressionKind::OperatorExpression: {
  413. const auto& op = cast<OperatorExpression>(exp);
  414. if (auto rewrite = op.rewritten_form()) {
  415. return todo_.ReplaceWith(std::make_unique<LValAction>(*rewrite));
  416. }
  417. if (op.op() != Operator::Deref) {
  418. CARBON_FATAL()
  419. << "Can't treat primitive operator expression as lvalue: " << exp;
  420. }
  421. if (act.pos() == 0) {
  422. return todo_.Spawn(
  423. std::make_unique<ExpressionAction>(op.arguments()[0]));
  424. } else {
  425. const auto& res = cast<PointerValue>(*act.results()[0]);
  426. return todo_.FinishAction(arena_->New<LValue>(res.address()));
  427. }
  428. break;
  429. }
  430. case ExpressionKind::TupleLiteral:
  431. case ExpressionKind::StructLiteral:
  432. case ExpressionKind::StructTypeLiteral:
  433. case ExpressionKind::IntLiteral:
  434. case ExpressionKind::BoolLiteral:
  435. case ExpressionKind::CallExpression:
  436. case ExpressionKind::IntTypeLiteral:
  437. case ExpressionKind::BoolTypeLiteral:
  438. case ExpressionKind::TypeTypeLiteral:
  439. case ExpressionKind::FunctionTypeLiteral:
  440. case ExpressionKind::ContinuationTypeLiteral:
  441. case ExpressionKind::StringLiteral:
  442. case ExpressionKind::StringTypeLiteral:
  443. case ExpressionKind::ValueLiteral:
  444. case ExpressionKind::IntrinsicExpression:
  445. case ExpressionKind::IfExpression:
  446. case ExpressionKind::WhereExpression:
  447. case ExpressionKind::DotSelfExpression:
  448. case ExpressionKind::ArrayTypeLiteral:
  449. case ExpressionKind::InstantiateImpl:
  450. CARBON_FATAL() << "Can't treat expression as lvalue: " << exp;
  451. case ExpressionKind::UnimplementedExpression:
  452. CARBON_FATAL() << "Unimplemented: " << exp;
  453. }
  454. }
  455. auto Interpreter::EvalExpRecursively(Nonnull<const Expression*> exp)
  456. -> ErrorOr<Nonnull<const Value*>> {
  457. if (trace_stream_) {
  458. **trace_stream_ << "--- recursive eval of " << *exp << "\n";
  459. PrintState(**trace_stream_);
  460. }
  461. todo_.BeginRecursiveAction();
  462. CARBON_RETURN_IF_ERROR(todo_.Spawn(std::make_unique<ExpressionAction>(exp)));
  463. // Note that the only `RecursiveAction` we can encounter here is our own --
  464. // if a nested action begins a recursive action, it will run until that
  465. // action is finished and popped off the queue before returning to us.
  466. while (!isa<RecursiveAction>(todo_.CurrentAction())) {
  467. CARBON_RETURN_IF_ERROR(Step());
  468. if (trace_stream_) {
  469. PrintState(**trace_stream_);
  470. }
  471. }
  472. if (trace_stream_) {
  473. **trace_stream_ << "--- recursive eval done\n";
  474. }
  475. Nonnull<const Value*> result =
  476. cast<RecursiveAction>(todo_.CurrentAction()).results()[0];
  477. CARBON_RETURN_IF_ERROR(todo_.FinishAction());
  478. return result;
  479. }
  480. auto Interpreter::EvalAssociatedConstant(
  481. Nonnull<const AssociatedConstant*> assoc, SourceLocation source_loc)
  482. -> ErrorOr<Nonnull<const Value*>> {
  483. // Find the witness.
  484. Nonnull<const Value*> witness = &assoc->witness();
  485. if (auto* sym = dyn_cast<SymbolicWitness>(witness)) {
  486. CARBON_ASSIGN_OR_RETURN(witness,
  487. EvalExpRecursively(&sym->impl_expression()));
  488. }
  489. if (!isa<ImplWitness>(witness)) {
  490. CARBON_CHECK(phase() == Phase::CompileTime)
  491. << "symbolic witnesses should only be formed at compile time";
  492. return CompilationError(source_loc)
  493. << "value of associated constant " << *assoc << " is not known";
  494. }
  495. auto& impl_witness = cast<ImplWitness>(*witness);
  496. Nonnull<const ConstraintType*> constraint =
  497. impl_witness.declaration().constraint_type();
  498. Nonnull<const Value*> expected = arena_->New<AssociatedConstant>(
  499. &constraint->self_binding()->value(), &assoc->interface(),
  500. &assoc->constant(), &impl_witness);
  501. std::optional<Nonnull<const Value*>> result;
  502. constraint->VisitEqualValues(expected,
  503. [&](Nonnull<const Value*> equal_value) {
  504. // TODO: The value might depend on the
  505. // parameters of the impl. We need to
  506. // substitute impl_witness.type_args() into the
  507. // value.
  508. if (isa<AssociatedConstant>(equal_value)) {
  509. return true;
  510. }
  511. // TODO: This makes an arbitrary choice if
  512. // there's more than one equal value. It's not
  513. // clear how to handle that case.
  514. result = equal_value;
  515. return false;
  516. });
  517. if (!result) {
  518. CARBON_FATAL() << impl_witness.declaration()
  519. << " is missing value for associated constant " << *assoc;
  520. }
  521. return *result;
  522. }
  523. auto Interpreter::InstantiateType(Nonnull<const Value*> type,
  524. SourceLocation source_loc)
  525. -> ErrorOr<Nonnull<const Value*>> {
  526. switch (type->kind()) {
  527. case Value::Kind::VariableType: {
  528. CARBON_ASSIGN_OR_RETURN(
  529. Nonnull<const Value*> value,
  530. todo_.ValueOfNode(&cast<VariableType>(*type).binding(), source_loc));
  531. if (const auto* lvalue = dyn_cast<LValue>(value)) {
  532. CARBON_ASSIGN_OR_RETURN(value,
  533. heap_.Read(lvalue->address(), source_loc));
  534. }
  535. return value;
  536. }
  537. case Value::Kind::NominalClassType: {
  538. const auto& class_type = cast<NominalClassType>(*type);
  539. CARBON_ASSIGN_OR_RETURN(
  540. Nonnull<const Bindings*> bindings,
  541. InstantiateBindings(&class_type.bindings(), source_loc));
  542. return arena_->New<NominalClassType>(&class_type.declaration(), bindings);
  543. }
  544. case Value::Kind::AssociatedConstant: {
  545. CARBON_ASSIGN_OR_RETURN(
  546. Nonnull<const Value*> type_value,
  547. EvalAssociatedConstant(cast<AssociatedConstant>(type), source_loc));
  548. return InstantiateType(type_value, source_loc);
  549. }
  550. default:
  551. return type;
  552. }
  553. }
  554. auto Interpreter::InstantiateBindings(Nonnull<const Bindings*> bindings,
  555. SourceLocation source_loc)
  556. -> ErrorOr<Nonnull<const Bindings*>> {
  557. BindingMap args = bindings->args();
  558. for (auto& [var, arg] : args) {
  559. CARBON_ASSIGN_OR_RETURN(arg, InstantiateType(arg, source_loc));
  560. }
  561. ImplWitnessMap witnesses = bindings->witnesses();
  562. for (auto& [bind, witness] : witnesses) {
  563. if (auto* sym = dyn_cast<SymbolicWitness>(witness)) {
  564. CARBON_ASSIGN_OR_RETURN(witness,
  565. EvalExpRecursively(&sym->impl_expression()));
  566. }
  567. }
  568. if (args == bindings->args() && witnesses == bindings->witnesses()) {
  569. return bindings;
  570. }
  571. return arena_->New<Bindings>(std::move(args), std::move(witnesses));
  572. }
  573. auto Interpreter::Convert(Nonnull<const Value*> value,
  574. Nonnull<const Value*> destination_type,
  575. SourceLocation source_loc)
  576. -> ErrorOr<Nonnull<const Value*>> {
  577. switch (value->kind()) {
  578. case Value::Kind::IntValue:
  579. case Value::Kind::FunctionValue:
  580. case Value::Kind::DestructorValue:
  581. case Value::Kind::BoundMethodValue:
  582. case Value::Kind::PointerValue:
  583. case Value::Kind::LValue:
  584. case Value::Kind::BoolValue:
  585. case Value::Kind::NominalClassValue:
  586. case Value::Kind::AlternativeValue:
  587. case Value::Kind::UninitializedValue:
  588. case Value::Kind::IntType:
  589. case Value::Kind::BoolType:
  590. case Value::Kind::TypeType:
  591. case Value::Kind::FunctionType:
  592. case Value::Kind::PointerType:
  593. case Value::Kind::AutoType:
  594. case Value::Kind::NominalClassType:
  595. case Value::Kind::MixinPseudoType:
  596. case Value::Kind::InterfaceType:
  597. case Value::Kind::ConstraintType:
  598. case Value::Kind::ImplWitness:
  599. case Value::Kind::SymbolicWitness:
  600. case Value::Kind::ParameterizedEntityName:
  601. case Value::Kind::ChoiceType:
  602. case Value::Kind::ContinuationType:
  603. case Value::Kind::VariableType:
  604. case Value::Kind::BindingPlaceholderValue:
  605. case Value::Kind::AddrValue:
  606. case Value::Kind::AlternativeConstructorValue:
  607. case Value::Kind::ContinuationValue:
  608. case Value::Kind::StringType:
  609. case Value::Kind::StringValue:
  610. case Value::Kind::TypeOfClassType:
  611. case Value::Kind::TypeOfMixinPseudoType:
  612. case Value::Kind::TypeOfInterfaceType:
  613. case Value::Kind::TypeOfConstraintType:
  614. case Value::Kind::TypeOfChoiceType:
  615. case Value::Kind::TypeOfParameterizedEntityName:
  616. case Value::Kind::TypeOfMemberName:
  617. case Value::Kind::StaticArrayType:
  618. case Value::Kind::MemberName:
  619. // TODO: add `CARBON_CHECK(TypeEqual(type, value->dynamic_type()))`, once
  620. // we have Value::dynamic_type.
  621. return value;
  622. case Value::Kind::StructValue: {
  623. const auto& struct_val = cast<StructValue>(*value);
  624. switch (destination_type->kind()) {
  625. case Value::Kind::StructType: {
  626. const auto& destination_struct_type =
  627. cast<StructType>(*destination_type);
  628. std::vector<NamedValue> new_elements;
  629. for (const auto& [field_name, field_type] :
  630. destination_struct_type.fields()) {
  631. std::optional<Nonnull<const Value*>> old_value =
  632. struct_val.FindField(field_name);
  633. CARBON_ASSIGN_OR_RETURN(
  634. Nonnull<const Value*> val,
  635. Convert(*old_value, field_type, source_loc));
  636. new_elements.push_back({.name = field_name, .value = val});
  637. }
  638. return arena_->New<StructValue>(std::move(new_elements));
  639. }
  640. case Value::Kind::NominalClassType: {
  641. // Instantiate the `destination_type` to obtain the runtime
  642. // type of the object.
  643. CARBON_ASSIGN_OR_RETURN(
  644. Nonnull<const Value*> inst_dest,
  645. InstantiateType(destination_type, source_loc));
  646. return arena_->New<NominalClassValue>(inst_dest, value);
  647. }
  648. default:
  649. CARBON_FATAL() << "Can't convert value " << *value << " to type "
  650. << *destination_type;
  651. }
  652. }
  653. case Value::Kind::StructType: {
  654. // The value `{}` has kind `StructType` not `StructValue`. This value can
  655. // be converted to an empty class type.
  656. if (auto* destination_class_type =
  657. dyn_cast<NominalClassType>(destination_type)) {
  658. CARBON_CHECK(cast<StructType>(*value).fields().empty())
  659. << "only an empty struct type value converts to class type";
  660. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> inst_dest,
  661. InstantiateType(destination_type, source_loc));
  662. return arena_->New<NominalClassValue>(inst_dest, value);
  663. }
  664. return value;
  665. }
  666. case Value::Kind::TupleValue: {
  667. const auto& tuple = cast<TupleValue>(value);
  668. std::vector<Nonnull<const Value*>> destination_element_types;
  669. switch (destination_type->kind()) {
  670. case Value::Kind::TupleValue:
  671. destination_element_types =
  672. cast<TupleValue>(destination_type)->elements();
  673. break;
  674. case Value::Kind::StaticArrayType: {
  675. const auto& array_type = cast<StaticArrayType>(*destination_type);
  676. destination_element_types.resize(array_type.size(),
  677. &array_type.element_type());
  678. break;
  679. }
  680. default:
  681. CARBON_FATAL() << "Can't convert value " << *value << " to type "
  682. << *destination_type;
  683. }
  684. CARBON_CHECK(tuple->elements().size() ==
  685. destination_element_types.size());
  686. std::vector<Nonnull<const Value*>> new_elements;
  687. for (size_t i = 0; i < tuple->elements().size(); ++i) {
  688. CARBON_ASSIGN_OR_RETURN(
  689. Nonnull<const Value*> val,
  690. Convert(tuple->elements()[i], destination_element_types[i],
  691. source_loc));
  692. new_elements.push_back(val);
  693. }
  694. return arena_->New<TupleValue>(std::move(new_elements));
  695. }
  696. case Value::Kind::AssociatedConstant: {
  697. CARBON_ASSIGN_OR_RETURN(
  698. Nonnull<const Value*> value,
  699. EvalAssociatedConstant(cast<AssociatedConstant>(value), source_loc));
  700. return Convert(value, destination_type, source_loc);
  701. }
  702. }
  703. }
  704. auto Interpreter::CallDestructor(Nonnull<const DestructorDeclaration*> fun,
  705. Nonnull<const Value*> receiver)
  706. -> ErrorOr<Success> {
  707. const DestructorDeclaration& method = *fun;
  708. CARBON_CHECK(method.is_method());
  709. RuntimeScope method_scope(&heap_);
  710. BindingMap generic_args;
  711. CARBON_CHECK(PatternMatch(&method.me_pattern().value(), receiver,
  712. fun->source_loc(), &method_scope, generic_args,
  713. trace_stream_, this->arena_));
  714. CARBON_CHECK(method.body().has_value())
  715. << "Calling a method that's missing a body";
  716. auto act = std::make_unique<StatementAction>(*method.body());
  717. method_scope.TransitState();
  718. return todo_.Spawn(std::unique_ptr<Action>(std::move(act)),
  719. std::move(method_scope));
  720. }
  721. auto Interpreter::CallFunction(const CallExpression& call,
  722. Nonnull<const Value*> fun,
  723. Nonnull<const Value*> arg,
  724. ImplWitnessMap&& witnesses) -> ErrorOr<Success> {
  725. if (trace_stream_) {
  726. **trace_stream_ << "calling function: " << *fun << "\n";
  727. }
  728. switch (fun->kind()) {
  729. case Value::Kind::AlternativeConstructorValue: {
  730. const auto& alt = cast<AlternativeConstructorValue>(*fun);
  731. return todo_.FinishAction(arena_->New<AlternativeValue>(
  732. alt.alt_name(), alt.choice_name(), arg));
  733. }
  734. case Value::Kind::FunctionValue: {
  735. const FunctionValue& fun_val = cast<FunctionValue>(*fun);
  736. const FunctionDeclaration& function = fun_val.declaration();
  737. RuntimeScope binding_scope(&heap_);
  738. // Bring the class type arguments into scope.
  739. for (const auto& [bind, val] : fun_val.type_args()) {
  740. binding_scope.Initialize(bind, val);
  741. }
  742. // Bring the deduced type arguments into scope.
  743. for (const auto& [bind, val] : call.deduced_args()) {
  744. binding_scope.Initialize(bind, val);
  745. }
  746. // Bring the impl witness tables into scope.
  747. for (const auto& [impl_bind, witness] : witnesses) {
  748. binding_scope.Initialize(impl_bind, witness);
  749. }
  750. for (const auto& [impl_bind, witness] : fun_val.witnesses()) {
  751. binding_scope.Initialize(impl_bind, witness);
  752. }
  753. // Enter the binding scope to make any deduced arguments visible before
  754. // we resolve the parameter type.
  755. todo_.CurrentAction().StartScope(std::move(binding_scope));
  756. CARBON_ASSIGN_OR_RETURN(
  757. Nonnull<const Value*> converted_args,
  758. Convert(arg, &function.param_pattern().static_type(),
  759. call.source_loc()));
  760. RuntimeScope function_scope(&heap_);
  761. BindingMap generic_args;
  762. CARBON_CHECK(PatternMatch(
  763. &function.param_pattern().value(), converted_args, call.source_loc(),
  764. &function_scope, generic_args, trace_stream_, this->arena_));
  765. CARBON_CHECK(function.body().has_value())
  766. << "Calling a function that's missing a body";
  767. return todo_.Spawn(std::make_unique<StatementAction>(*function.body()),
  768. std::move(function_scope));
  769. }
  770. case Value::Kind::BoundMethodValue: {
  771. const auto& m = cast<BoundMethodValue>(*fun);
  772. const FunctionDeclaration& method = m.declaration();
  773. CARBON_CHECK(method.is_method());
  774. CARBON_ASSIGN_OR_RETURN(
  775. Nonnull<const Value*> converted_args,
  776. Convert(arg, &method.param_pattern().static_type(),
  777. call.source_loc()));
  778. RuntimeScope method_scope(&heap_);
  779. BindingMap generic_args;
  780. // Bind the receiver to the `me` parameter.
  781. CARBON_CHECK(PatternMatch(&method.me_pattern().value(), m.receiver(),
  782. call.source_loc(), &method_scope, generic_args,
  783. trace_stream_, this->arena_));
  784. // Bind the arguments to the parameters.
  785. CARBON_CHECK(PatternMatch(&method.param_pattern().value(), converted_args,
  786. call.source_loc(), &method_scope, generic_args,
  787. trace_stream_, this->arena_));
  788. // Bring the class type arguments into scope.
  789. for (const auto& [bind, val] : m.type_args()) {
  790. method_scope.Initialize(bind->original(), val);
  791. }
  792. // Bring the deduced type arguments into scope.
  793. for (const auto& [bind, val] : call.deduced_args()) {
  794. method_scope.Initialize(bind->original(), val);
  795. }
  796. // Bring the impl witness tables into scope.
  797. for (const auto& [impl_bind, witness] : witnesses) {
  798. method_scope.Initialize(impl_bind->original(), witness);
  799. }
  800. for (const auto& [impl_bind, witness] : m.witnesses()) {
  801. method_scope.Initialize(impl_bind->original(), witness);
  802. }
  803. CARBON_CHECK(method.body().has_value())
  804. << "Calling a method that's missing a body";
  805. return todo_.Spawn(std::make_unique<StatementAction>(*method.body()),
  806. std::move(method_scope));
  807. }
  808. case Value::Kind::ParameterizedEntityName: {
  809. const auto& name = cast<ParameterizedEntityName>(*fun);
  810. const Declaration& decl = name.declaration();
  811. RuntimeScope params_scope(&heap_);
  812. BindingMap generic_args;
  813. CARBON_CHECK(PatternMatch(&name.params().value(), arg, call.source_loc(),
  814. &params_scope, generic_args, trace_stream_,
  815. this->arena_));
  816. Nonnull<const Bindings*> bindings =
  817. arena_->New<Bindings>(std::move(generic_args), std::move(witnesses));
  818. switch (decl.kind()) {
  819. case DeclarationKind::ClassDeclaration:
  820. return todo_.FinishAction(arena_->New<NominalClassType>(
  821. &cast<ClassDeclaration>(decl), bindings));
  822. case DeclarationKind::InterfaceDeclaration:
  823. return todo_.FinishAction(arena_->New<InterfaceType>(
  824. &cast<InterfaceDeclaration>(decl), bindings));
  825. case DeclarationKind::ChoiceDeclaration:
  826. return todo_.FinishAction(arena_->New<ChoiceType>(
  827. &cast<ChoiceDeclaration>(decl), bindings));
  828. default:
  829. CARBON_FATAL() << "unknown kind of ParameterizedEntityName " << decl;
  830. }
  831. }
  832. default:
  833. return RuntimeError(call.source_loc())
  834. << "in call, expected a function, not " << *fun;
  835. }
  836. }
  837. auto Interpreter::StepExp() -> ErrorOr<Success> {
  838. Action& act = todo_.CurrentAction();
  839. const Expression& exp = cast<ExpressionAction>(act).expression();
  840. if (trace_stream_) {
  841. **trace_stream_ << "--- step exp " << exp << " ." << act.pos() << "."
  842. << " (" << exp.source_loc() << ") --->\n";
  843. }
  844. switch (exp.kind()) {
  845. case ExpressionKind::InstantiateImpl: {
  846. const InstantiateImpl& inst_impl = cast<InstantiateImpl>(exp);
  847. if (act.pos() == 0) {
  848. return todo_.Spawn(
  849. std::make_unique<ExpressionAction>(inst_impl.generic_impl()));
  850. }
  851. if (act.pos() == 1 && isa<SymbolicWitness>(act.results()[0])) {
  852. return todo_.FinishAction(arena_->New<SymbolicWitness>(&exp));
  853. }
  854. if (act.pos() - 1 < int(inst_impl.impls().size())) {
  855. auto iter = inst_impl.impls().begin();
  856. std::advance(iter, act.pos() - 1);
  857. return todo_.Spawn(std::make_unique<ExpressionAction>(iter->second));
  858. } else {
  859. Nonnull<const ImplWitness*> generic_witness =
  860. cast<ImplWitness>(act.results()[0]);
  861. ImplWitnessMap witnesses;
  862. int i = 0;
  863. for (const auto& [impl_bind, impl_exp] : inst_impl.impls()) {
  864. witnesses[impl_bind] = cast<Witness>(act.results()[i + 1]);
  865. ++i;
  866. }
  867. return todo_.FinishAction(arena_->New<ImplWitness>(
  868. &generic_witness->declaration(),
  869. arena_->New<Bindings>(inst_impl.type_args(),
  870. std::move(witnesses))));
  871. }
  872. }
  873. case ExpressionKind::IndexExpression: {
  874. if (act.pos() == 0) {
  875. // { { e[i] :: C, E, F} :: S, H}
  876. // -> { { e :: [][i] :: C, E, F} :: S, H}
  877. return todo_.Spawn(std::make_unique<ExpressionAction>(
  878. &cast<IndexExpression>(exp).object()));
  879. } else if (act.pos() == 1) {
  880. if (isa<SymbolicWitness>(act.results()[0])) {
  881. return todo_.FinishAction(arena_->New<SymbolicWitness>(&exp));
  882. }
  883. return todo_.Spawn(std::make_unique<ExpressionAction>(
  884. &cast<IndexExpression>(exp).offset()));
  885. } else {
  886. // { { v :: [][i] :: C, E, F} :: S, H}
  887. // -> { { v_i :: C, E, F} : S, H}
  888. const auto& tuple = cast<TupleValue>(*act.results()[0]);
  889. int i = cast<IntValue>(*act.results()[1]).value();
  890. if (i < 0 || i >= static_cast<int>(tuple.elements().size())) {
  891. return RuntimeError(exp.source_loc())
  892. << "index " << i << " out of range in " << tuple;
  893. }
  894. return todo_.FinishAction(tuple.elements()[i]);
  895. }
  896. }
  897. case ExpressionKind::TupleLiteral: {
  898. if (act.pos() <
  899. static_cast<int>(cast<TupleLiteral>(exp).fields().size())) {
  900. // { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
  901. // H}
  902. // -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
  903. // H}
  904. return todo_.Spawn(std::make_unique<ExpressionAction>(
  905. cast<TupleLiteral>(exp).fields()[act.pos()]));
  906. } else {
  907. return todo_.FinishAction(arena_->New<TupleValue>(act.results()));
  908. }
  909. }
  910. case ExpressionKind::StructLiteral: {
  911. const auto& literal = cast<StructLiteral>(exp);
  912. if (act.pos() < static_cast<int>(literal.fields().size())) {
  913. return todo_.Spawn(std::make_unique<ExpressionAction>(
  914. &literal.fields()[act.pos()].expression()));
  915. } else {
  916. return todo_.FinishAction(
  917. CreateStruct(literal.fields(), act.results()));
  918. }
  919. }
  920. case ExpressionKind::StructTypeLiteral: {
  921. const auto& struct_type = cast<StructTypeLiteral>(exp);
  922. if (act.pos() < static_cast<int>(struct_type.fields().size())) {
  923. return todo_.Spawn(std::make_unique<ExpressionAction>(
  924. &struct_type.fields()[act.pos()].expression()));
  925. } else {
  926. std::vector<NamedValue> fields;
  927. for (size_t i = 0; i < struct_type.fields().size(); ++i) {
  928. fields.push_back({struct_type.fields()[i].name(), act.results()[i]});
  929. }
  930. return todo_.FinishAction(arena_->New<StructType>(std::move(fields)));
  931. }
  932. }
  933. case ExpressionKind::SimpleMemberAccessExpression: {
  934. const auto& access = cast<SimpleMemberAccessExpression>(exp);
  935. bool forming_member_name = isa<TypeOfMemberName>(&access.static_type());
  936. if (act.pos() == 0) {
  937. // First, evaluate the first operand.
  938. if (access.is_field_addr_me_method()) {
  939. return todo_.Spawn(std::make_unique<LValAction>(&access.object()));
  940. } else {
  941. return todo_.Spawn(
  942. std::make_unique<ExpressionAction>(&access.object()));
  943. }
  944. } else if (act.pos() == 1 && access.impl().has_value() &&
  945. !forming_member_name) {
  946. // Next, if we're accessing an interface member, evaluate the `impl`
  947. // expression to find the corresponding witness.
  948. return todo_.Spawn(
  949. std::make_unique<ExpressionAction>(access.impl().value()));
  950. } else {
  951. // Finally, produce the result.
  952. std::optional<Nonnull<const InterfaceType*>> found_in_interface =
  953. access.found_in_interface();
  954. if (found_in_interface) {
  955. CARBON_ASSIGN_OR_RETURN(
  956. Nonnull<const Value*> instantiated,
  957. InstantiateType(*found_in_interface, exp.source_loc()));
  958. found_in_interface = cast<InterfaceType>(instantiated);
  959. }
  960. if (const auto* member_name_type =
  961. dyn_cast<TypeOfMemberName>(&access.static_type())) {
  962. // The result is a member name, such as in `Type.field_name`. Form a
  963. // suitable member name value.
  964. CARBON_CHECK(phase() == Phase::CompileTime)
  965. << "should not form MemberNames at runtime";
  966. std::optional<const Value*> type_result;
  967. if (!isa<InterfaceType, ConstraintType>(act.results()[0])) {
  968. type_result = act.results()[0];
  969. }
  970. MemberName* member_name = arena_->New<MemberName>(
  971. type_result, found_in_interface, member_name_type->member());
  972. return todo_.FinishAction(member_name);
  973. } else {
  974. // The result is the value of the named field, such as in
  975. // `value.field_name`. Extract the value within the given object.
  976. std::optional<Nonnull<const Witness*>> witness;
  977. if (access.impl().has_value()) {
  978. witness = cast<Witness>(act.results()[1]);
  979. }
  980. FieldPath::Component member(access.member(), found_in_interface,
  981. witness);
  982. const Value* aggregate;
  983. if (const auto* lvalue = dyn_cast<LValue>(act.results()[0])) {
  984. CARBON_ASSIGN_OR_RETURN(
  985. aggregate,
  986. this->heap_.Read(lvalue->address(), exp.source_loc()));
  987. } else {
  988. aggregate = act.results()[0];
  989. }
  990. CARBON_ASSIGN_OR_RETURN(
  991. Nonnull<const Value*> member_value,
  992. aggregate->GetMember(arena_, FieldPath(member), exp.source_loc(),
  993. act.results()[0]));
  994. return todo_.FinishAction(member_value);
  995. }
  996. }
  997. }
  998. case ExpressionKind::CompoundMemberAccessExpression: {
  999. const auto& access = cast<CompoundMemberAccessExpression>(exp);
  1000. bool forming_member_name = isa<TypeOfMemberName>(&access.static_type());
  1001. if (act.pos() == 0) {
  1002. // First, evaluate the first operand.
  1003. return todo_.Spawn(
  1004. std::make_unique<ExpressionAction>(&access.object()));
  1005. } else if (act.pos() == 1 && access.impl().has_value() &&
  1006. !forming_member_name) {
  1007. // Next, if we're accessing an interface member, evaluate the `impl`
  1008. // expression to find the corresponding witness.
  1009. return todo_.Spawn(
  1010. std::make_unique<ExpressionAction>(access.impl().value()));
  1011. } else {
  1012. // Finally, produce the result.
  1013. std::optional<Nonnull<const InterfaceType*>> found_in_interface =
  1014. access.member().interface();
  1015. if (found_in_interface) {
  1016. CARBON_ASSIGN_OR_RETURN(
  1017. Nonnull<const Value*> instantiated,
  1018. InstantiateType(*found_in_interface, exp.source_loc()));
  1019. found_in_interface = cast<InterfaceType>(instantiated);
  1020. }
  1021. if (forming_member_name) {
  1022. // If we're forming a member name, we must be in the outer evaluation
  1023. // in `Type.(Interface.method)`. Produce the same method name with
  1024. // its `type` field set.
  1025. CARBON_CHECK(phase() == Phase::CompileTime)
  1026. << "should not form MemberNames at runtime";
  1027. CARBON_CHECK(!access.member().base_type().has_value())
  1028. << "compound member access forming a member name should be "
  1029. "performing impl lookup";
  1030. auto* member_name = arena_->New<MemberName>(
  1031. act.results()[0], found_in_interface, access.member().member());
  1032. return todo_.FinishAction(member_name);
  1033. } else {
  1034. // Access the object to find the named member.
  1035. Nonnull<const Value*> object = act.results()[0];
  1036. std::optional<Nonnull<const Witness*>> witness;
  1037. if (access.impl().has_value()) {
  1038. witness = cast<Witness>(act.results()[1]);
  1039. } else {
  1040. CARBON_CHECK(access.member().base_type().has_value())
  1041. << "compound access should have base type or impl";
  1042. CARBON_ASSIGN_OR_RETURN(
  1043. object, Convert(object, *access.member().base_type(),
  1044. exp.source_loc()));
  1045. }
  1046. FieldPath::Component field(access.member().member(),
  1047. found_in_interface, witness);
  1048. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> member,
  1049. object->GetMember(arena_, FieldPath(field),
  1050. exp.source_loc(), object));
  1051. return todo_.FinishAction(member);
  1052. }
  1053. }
  1054. }
  1055. case ExpressionKind::IdentifierExpression: {
  1056. CARBON_CHECK(act.pos() == 0);
  1057. const auto& ident = cast<IdentifierExpression>(exp);
  1058. // { {x :: C, E, F} :: S, H} -> { {H(E(x)) :: C, E, F} :: S, H}
  1059. CARBON_ASSIGN_OR_RETURN(
  1060. Nonnull<const Value*> value,
  1061. todo_.ValueOfNode(ident.value_node(), ident.source_loc()));
  1062. if (const auto* lvalue = dyn_cast<LValue>(value)) {
  1063. CARBON_ASSIGN_OR_RETURN(
  1064. value, heap_.Read(lvalue->address(), exp.source_loc()));
  1065. }
  1066. return todo_.FinishAction(value);
  1067. }
  1068. case ExpressionKind::DotSelfExpression: {
  1069. // `.Self` always symbolically resolves to the self binding, even if it's
  1070. // not yet been type-checked.
  1071. CARBON_CHECK(act.pos() == 0);
  1072. const auto& dot_self = cast<DotSelfExpression>(exp);
  1073. return todo_.FinishAction(
  1074. arena_->New<VariableType>(&dot_self.self_binding()));
  1075. }
  1076. case ExpressionKind::IntLiteral:
  1077. CARBON_CHECK(act.pos() == 0);
  1078. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  1079. return todo_.FinishAction(
  1080. arena_->New<IntValue>(cast<IntLiteral>(exp).value()));
  1081. case ExpressionKind::BoolLiteral:
  1082. CARBON_CHECK(act.pos() == 0);
  1083. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  1084. return todo_.FinishAction(
  1085. arena_->New<BoolValue>(cast<BoolLiteral>(exp).value()));
  1086. case ExpressionKind::OperatorExpression: {
  1087. const auto& op = cast<OperatorExpression>(exp);
  1088. if (auto rewrite = op.rewritten_form()) {
  1089. return todo_.ReplaceWith(std::make_unique<ExpressionAction>(*rewrite));
  1090. }
  1091. if (act.pos() != static_cast<int>(op.arguments().size())) {
  1092. // { {v :: op(vs,[],e,es) :: C, E, F} :: S, H}
  1093. // -> { {e :: op(vs,v,[],es) :: C, E, F} :: S, H}
  1094. Nonnull<const Expression*> arg = op.arguments()[act.pos()];
  1095. if (op.op() == Operator::AddressOf) {
  1096. return todo_.Spawn(std::make_unique<LValAction>(arg));
  1097. } else if ((op.op() == Operator::And || op.op() == Operator::Or) &&
  1098. act.pos() == 1) {
  1099. // Short-circuit evaluation for 'and' & 'or'
  1100. auto operand_value = cast<BoolValue>(act.results()[act.pos() - 1]);
  1101. if ((op.op() == Operator::Or && operand_value->value()) ||
  1102. (op.op() == Operator::And && !operand_value->value())) {
  1103. return todo_.FinishAction(operand_value);
  1104. }
  1105. // No short-circuit, fall through to evaluate 2nd operand.
  1106. }
  1107. return todo_.Spawn(std::make_unique<ExpressionAction>(arg));
  1108. } else {
  1109. // { {v :: op(vs,[]) :: C, E, F} :: S, H}
  1110. // -> { {eval_prim(op, (vs,v)) :: C, E, F} :: S, H}
  1111. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> value,
  1112. EvalPrim(op.op(), &op.static_type(),
  1113. act.results(), exp.source_loc()));
  1114. return todo_.FinishAction(value);
  1115. }
  1116. }
  1117. case ExpressionKind::CallExpression: {
  1118. const CallExpression& call = cast<CallExpression>(exp);
  1119. unsigned int num_impls = call.impls().size();
  1120. if (act.pos() == 0) {
  1121. // { {e1(e2) :: C, E, F} :: S, H}
  1122. // -> { {e1 :: [](e2) :: C, E, F} :: S, H}
  1123. return todo_.Spawn(
  1124. std::make_unique<ExpressionAction>(&call.function()));
  1125. } else if (act.pos() == 1) {
  1126. // { { v :: [](e) :: C, E, F} :: S, H}
  1127. // -> { { e :: v([]) :: C, E, F} :: S, H}
  1128. return todo_.Spawn(
  1129. std::make_unique<ExpressionAction>(&call.argument()));
  1130. } else if (num_impls > 0 && act.pos() < 2 + int(num_impls)) {
  1131. auto iter = call.impls().begin();
  1132. std::advance(iter, act.pos() - 2);
  1133. return todo_.Spawn(std::make_unique<ExpressionAction>(iter->second));
  1134. } else if (act.pos() == 2 + int(num_impls)) {
  1135. // { { v2 :: v1([]) :: C, E, F} :: S, H}
  1136. // -> { {C',E',F'} :: {C, E, F} :: S, H}
  1137. ImplWitnessMap witnesses;
  1138. if (num_impls > 0) {
  1139. int i = 2;
  1140. for (const auto& [impl_bind, impl_exp] : call.impls()) {
  1141. witnesses[impl_bind] = act.results()[i];
  1142. ++i;
  1143. }
  1144. }
  1145. return CallFunction(call, act.results()[0], act.results()[1],
  1146. std::move(witnesses));
  1147. } else if (act.pos() == 3 + int(num_impls)) {
  1148. if (act.results().size() < 3 + num_impls) {
  1149. // Control fell through without explicit return.
  1150. return todo_.FinishAction(TupleValue::Empty());
  1151. } else {
  1152. return todo_.FinishAction(act.results()[2 + int(num_impls)]);
  1153. }
  1154. } else {
  1155. CARBON_FATAL() << "in StepExp with Call pos " << act.pos();
  1156. }
  1157. }
  1158. case ExpressionKind::IntrinsicExpression: {
  1159. const auto& intrinsic = cast<IntrinsicExpression>(exp);
  1160. if (act.pos() == 0) {
  1161. return todo_.Spawn(
  1162. std::make_unique<ExpressionAction>(&intrinsic.args()));
  1163. }
  1164. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  1165. const auto& args = cast<TupleValue>(*act.results()[0]).elements();
  1166. switch (cast<IntrinsicExpression>(exp).intrinsic()) {
  1167. case IntrinsicExpression::Intrinsic::Print: {
  1168. CARBON_ASSIGN_OR_RETURN(
  1169. Nonnull<const Value*> format_string_value,
  1170. Convert(args[0], arena_->New<StringType>(), exp.source_loc()));
  1171. const char* format_string =
  1172. cast<StringValue>(*format_string_value).value().c_str();
  1173. switch (args.size()) {
  1174. case 1:
  1175. llvm::outs() << llvm::formatv(format_string);
  1176. break;
  1177. case 2:
  1178. llvm::outs() << llvm::formatv(format_string,
  1179. cast<IntValue>(*args[1]).value());
  1180. break;
  1181. default:
  1182. CARBON_FATAL() << "Unexpected arg count: " << args.size();
  1183. }
  1184. // Implicit newline; currently no way to disable it.
  1185. llvm::outs() << "\n";
  1186. return todo_.FinishAction(TupleValue::Empty());
  1187. }
  1188. case IntrinsicExpression::Intrinsic::Assert: {
  1189. CARBON_CHECK(args.size() == 2);
  1190. CARBON_ASSIGN_OR_RETURN(
  1191. Nonnull<const Value*> condition,
  1192. Convert(args[0], arena_->New<BoolType>(), exp.source_loc()));
  1193. CARBON_ASSIGN_OR_RETURN(
  1194. Nonnull<const Value*> string_value,
  1195. Convert(args[1], arena_->New<StringType>(), exp.source_loc()));
  1196. if (cast<BoolValue>(condition)->value() == false) {
  1197. return RuntimeError(exp.source_loc()) << *string_value;
  1198. }
  1199. return todo_.FinishAction(TupleValue::Empty());
  1200. }
  1201. case IntrinsicExpression::Intrinsic::Alloc: {
  1202. CARBON_CHECK(args.size() == 1);
  1203. Address addr(heap_.AllocateValue(args[0]));
  1204. return todo_.FinishAction(arena_->New<PointerValue>(addr));
  1205. }
  1206. case IntrinsicExpression::Intrinsic::Dealloc: {
  1207. CARBON_CHECK(args.size() == 1);
  1208. heap_.Deallocate(cast<PointerValue>(args[0])->address());
  1209. return todo_.FinishAction(TupleValue::Empty());
  1210. }
  1211. case IntrinsicExpression::Intrinsic::Rand: {
  1212. CARBON_CHECK(args.size() == 2);
  1213. const auto& low = cast<IntValue>(*args[0]).value();
  1214. const auto& high = cast<IntValue>(*args[1]).value();
  1215. CARBON_CHECK(high > low);
  1216. // We avoid using std::uniform_int_distribution because it's not
  1217. // reproducible across builds/platforms.
  1218. int r = (generator() % (high - low)) + low;
  1219. return todo_.FinishAction(arena_->New<IntValue>(r));
  1220. }
  1221. case IntrinsicExpression::Intrinsic::IntEq: {
  1222. CARBON_CHECK(args.size() == 2);
  1223. auto lhs = cast<IntValue>(*args[0]).value();
  1224. auto rhs = cast<IntValue>(*args[1]).value();
  1225. auto result = arena_->New<BoolValue>(lhs == rhs);
  1226. return todo_.FinishAction(result);
  1227. }
  1228. case IntrinsicExpression::Intrinsic::StrEq: {
  1229. CARBON_CHECK(args.size() == 2);
  1230. auto& lhs = cast<StringValue>(*args[0]).value();
  1231. auto& rhs = cast<StringValue>(*args[1]).value();
  1232. auto result = arena_->New<BoolValue>(lhs == rhs);
  1233. return todo_.FinishAction(result);
  1234. }
  1235. case IntrinsicExpression::Intrinsic::IntCompare: {
  1236. CARBON_CHECK(args.size() == 2);
  1237. auto lhs = cast<IntValue>(*args[0]).value();
  1238. auto rhs = cast<IntValue>(*args[1]).value();
  1239. if (lhs < rhs) {
  1240. auto result = arena_->New<IntValue>(-1);
  1241. return todo_.FinishAction(result);
  1242. }
  1243. if (lhs == rhs) {
  1244. auto result = arena_->New<IntValue>(0);
  1245. return todo_.FinishAction(result);
  1246. }
  1247. auto result = arena_->New<IntValue>(1);
  1248. return todo_.FinishAction(result);
  1249. }
  1250. case IntrinsicExpression::Intrinsic::StrCompare: {
  1251. CARBON_CHECK(args.size() == 2);
  1252. auto& lhs = cast<StringValue>(*args[0]).value();
  1253. auto& rhs = cast<StringValue>(*args[1]).value();
  1254. if (lhs < rhs) {
  1255. auto result = arena_->New<IntValue>(-1);
  1256. return todo_.FinishAction(result);
  1257. }
  1258. if (lhs == rhs) {
  1259. auto result = arena_->New<IntValue>(0);
  1260. return todo_.FinishAction(result);
  1261. }
  1262. auto result = arena_->New<IntValue>(1);
  1263. return todo_.FinishAction(result);
  1264. }
  1265. case IntrinsicExpression::Intrinsic::IntBitComplement: {
  1266. CARBON_CHECK(args.size() == 1);
  1267. return todo_.FinishAction(
  1268. arena_->New<IntValue>(~cast<IntValue>(*args[0]).value()));
  1269. }
  1270. case IntrinsicExpression::Intrinsic::IntBitAnd: {
  1271. CARBON_CHECK(args.size() == 2);
  1272. return todo_.FinishAction(
  1273. arena_->New<IntValue>(cast<IntValue>(*args[0]).value() &
  1274. cast<IntValue>(*args[1]).value()));
  1275. }
  1276. case IntrinsicExpression::Intrinsic::IntBitOr: {
  1277. CARBON_CHECK(args.size() == 2);
  1278. return todo_.FinishAction(
  1279. arena_->New<IntValue>(cast<IntValue>(*args[0]).value() |
  1280. cast<IntValue>(*args[1]).value()));
  1281. }
  1282. case IntrinsicExpression::Intrinsic::IntBitXor: {
  1283. CARBON_CHECK(args.size() == 2);
  1284. return todo_.FinishAction(
  1285. arena_->New<IntValue>(cast<IntValue>(*args[0]).value() ^
  1286. cast<IntValue>(*args[1]).value()));
  1287. }
  1288. case IntrinsicExpression::Intrinsic::IntLeftShift: {
  1289. CARBON_CHECK(args.size() == 2);
  1290. // TODO: Runtime error if RHS is too large.
  1291. return todo_.FinishAction(arena_->New<IntValue>(
  1292. static_cast<uint32_t>(cast<IntValue>(*args[0]).value())
  1293. << cast<IntValue>(*args[1]).value()));
  1294. }
  1295. case IntrinsicExpression::Intrinsic::IntRightShift: {
  1296. CARBON_CHECK(args.size() == 2);
  1297. // TODO: Runtime error if RHS is too large.
  1298. return todo_.FinishAction(
  1299. arena_->New<IntValue>(cast<IntValue>(*args[0]).value() >>
  1300. cast<IntValue>(*args[1]).value()));
  1301. }
  1302. }
  1303. }
  1304. case ExpressionKind::IntTypeLiteral: {
  1305. CARBON_CHECK(act.pos() == 0);
  1306. return todo_.FinishAction(arena_->New<IntType>());
  1307. }
  1308. case ExpressionKind::BoolTypeLiteral: {
  1309. CARBON_CHECK(act.pos() == 0);
  1310. return todo_.FinishAction(arena_->New<BoolType>());
  1311. }
  1312. case ExpressionKind::TypeTypeLiteral: {
  1313. CARBON_CHECK(act.pos() == 0);
  1314. return todo_.FinishAction(arena_->New<TypeType>());
  1315. }
  1316. case ExpressionKind::FunctionTypeLiteral: {
  1317. if (act.pos() == 0) {
  1318. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1319. &cast<FunctionTypeLiteral>(exp).parameter()));
  1320. } else if (act.pos() == 1) {
  1321. // { { pt :: fn [] -> e :: C, E, F} :: S, H}
  1322. // -> { { e :: fn pt -> []) :: C, E, F} :: S, H}
  1323. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1324. &cast<FunctionTypeLiteral>(exp).return_type()));
  1325. } else {
  1326. // { { rt :: fn pt -> [] :: C, E, F} :: S, H}
  1327. // -> { fn pt -> rt :: {C, E, F} :: S, H}
  1328. return todo_.FinishAction(arena_->New<FunctionType>(
  1329. act.results()[0], llvm::None, act.results()[1], llvm::None,
  1330. llvm::None));
  1331. }
  1332. }
  1333. case ExpressionKind::ContinuationTypeLiteral: {
  1334. CARBON_CHECK(act.pos() == 0);
  1335. return todo_.FinishAction(arena_->New<ContinuationType>());
  1336. }
  1337. case ExpressionKind::StringLiteral:
  1338. CARBON_CHECK(act.pos() == 0);
  1339. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  1340. return todo_.FinishAction(
  1341. arena_->New<StringValue>(cast<StringLiteral>(exp).value()));
  1342. case ExpressionKind::StringTypeLiteral: {
  1343. CARBON_CHECK(act.pos() == 0);
  1344. return todo_.FinishAction(arena_->New<StringType>());
  1345. }
  1346. case ExpressionKind::ValueLiteral: {
  1347. CARBON_CHECK(act.pos() == 0);
  1348. return todo_.FinishAction(&cast<ValueLiteral>(exp).value());
  1349. }
  1350. case ExpressionKind::IfExpression: {
  1351. const auto& if_expr = cast<IfExpression>(exp);
  1352. if (act.pos() == 0) {
  1353. return todo_.Spawn(
  1354. std::make_unique<ExpressionAction>(&if_expr.condition()));
  1355. } else if (act.pos() == 1) {
  1356. const auto& condition = cast<BoolValue>(*act.results()[0]);
  1357. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1358. condition.value() ? &if_expr.then_expression()
  1359. : &if_expr.else_expression()));
  1360. } else {
  1361. return todo_.FinishAction(act.results()[1]);
  1362. }
  1363. break;
  1364. }
  1365. case ExpressionKind::WhereExpression: {
  1366. return todo_.FinishAction(
  1367. &cast<TypeOfConstraintType>(exp.static_type()).constraint_type());
  1368. }
  1369. case ExpressionKind::UnimplementedExpression:
  1370. CARBON_FATAL() << "Unimplemented: " << exp;
  1371. case ExpressionKind::ArrayTypeLiteral: {
  1372. const auto& array_literal = cast<ArrayTypeLiteral>(exp);
  1373. if (act.pos() == 0) {
  1374. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1375. &array_literal.element_type_expression()));
  1376. } else if (act.pos() == 1) {
  1377. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1378. &array_literal.size_expression()));
  1379. } else {
  1380. return todo_.FinishAction(arena_->New<StaticArrayType>(
  1381. act.results()[0], cast<IntValue>(act.results()[1])->value()));
  1382. }
  1383. }
  1384. } // switch (exp->kind)
  1385. }
  1386. auto Interpreter::StepPattern() -> ErrorOr<Success> {
  1387. Action& act = todo_.CurrentAction();
  1388. const Pattern& pattern = cast<PatternAction>(act).pattern();
  1389. if (trace_stream_) {
  1390. **trace_stream_ << "--- step pattern " << pattern << " ." << act.pos()
  1391. << ". (" << pattern.source_loc() << ") --->\n";
  1392. }
  1393. switch (pattern.kind()) {
  1394. case PatternKind::AutoPattern: {
  1395. CARBON_CHECK(act.pos() == 0);
  1396. return todo_.FinishAction(arena_->New<AutoType>());
  1397. }
  1398. case PatternKind::BindingPattern: {
  1399. const auto& binding = cast<BindingPattern>(pattern);
  1400. if (binding.name() != AnonymousName) {
  1401. return todo_.FinishAction(
  1402. arena_->New<BindingPlaceholderValue>(&binding));
  1403. } else {
  1404. return todo_.FinishAction(arena_->New<BindingPlaceholderValue>());
  1405. }
  1406. }
  1407. case PatternKind::GenericBinding: {
  1408. const auto& binding = cast<GenericBinding>(pattern);
  1409. return todo_.FinishAction(arena_->New<VariableType>(&binding));
  1410. }
  1411. case PatternKind::TuplePattern: {
  1412. const auto& tuple = cast<TuplePattern>(pattern);
  1413. if (act.pos() < static_cast<int>(tuple.fields().size())) {
  1414. // { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
  1415. // H}
  1416. // -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
  1417. // H}
  1418. return todo_.Spawn(
  1419. std::make_unique<PatternAction>(tuple.fields()[act.pos()]));
  1420. } else {
  1421. return todo_.FinishAction(arena_->New<TupleValue>(act.results()));
  1422. }
  1423. }
  1424. case PatternKind::AlternativePattern: {
  1425. const auto& alternative = cast<AlternativePattern>(pattern);
  1426. if (act.pos() == 0) {
  1427. return todo_.Spawn(
  1428. std::make_unique<ExpressionAction>(&alternative.choice_type()));
  1429. } else if (act.pos() == 1) {
  1430. return todo_.Spawn(
  1431. std::make_unique<PatternAction>(&alternative.arguments()));
  1432. } else {
  1433. CARBON_CHECK(act.pos() == 2);
  1434. const auto& choice_type = cast<ChoiceType>(*act.results()[0]);
  1435. return todo_.FinishAction(arena_->New<AlternativeValue>(
  1436. alternative.alternative_name(), choice_type.name(),
  1437. act.results()[1]));
  1438. }
  1439. }
  1440. case PatternKind::ExpressionPattern:
  1441. if (act.pos() == 0) {
  1442. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1443. &cast<ExpressionPattern>(pattern).expression()));
  1444. } else {
  1445. return todo_.FinishAction(act.results()[0]);
  1446. }
  1447. case PatternKind::VarPattern:
  1448. if (act.pos() == 0) {
  1449. return todo_.Spawn(std::make_unique<PatternAction>(
  1450. &cast<VarPattern>(pattern).pattern()));
  1451. } else {
  1452. return todo_.FinishAction(act.results()[0]);
  1453. }
  1454. case PatternKind::AddrPattern:
  1455. const auto& addr = cast<AddrPattern>(pattern);
  1456. if (act.pos() == 0) {
  1457. return todo_.Spawn(std::make_unique<PatternAction>(&addr.binding()));
  1458. } else {
  1459. return todo_.FinishAction(arena_->New<AddrValue>(act.results()[0]));
  1460. }
  1461. break;
  1462. }
  1463. }
  1464. auto Interpreter::StepStmt() -> ErrorOr<Success> {
  1465. Action& act = todo_.CurrentAction();
  1466. const Statement& stmt = cast<StatementAction>(act).statement();
  1467. if (trace_stream_) {
  1468. **trace_stream_ << "--- step stmt ";
  1469. stmt.PrintDepth(1, **trace_stream_);
  1470. **trace_stream_ << " ." << act.pos() << ". "
  1471. << "(" << stmt.source_loc() << ") --->\n";
  1472. }
  1473. switch (stmt.kind()) {
  1474. case StatementKind::Match: {
  1475. const auto& match_stmt = cast<Match>(stmt);
  1476. if (act.pos() == 0) {
  1477. // { { (match (e) ...) :: C, E, F} :: S, H}
  1478. // -> { { e :: (match ([]) ...) :: C, E, F} :: S, H}
  1479. act.StartScope(RuntimeScope(&heap_));
  1480. return todo_.Spawn(
  1481. std::make_unique<ExpressionAction>(&match_stmt.expression()));
  1482. } else {
  1483. int clause_num = act.pos() - 1;
  1484. if (clause_num >= static_cast<int>(match_stmt.clauses().size())) {
  1485. return todo_.FinishAction();
  1486. }
  1487. auto c = match_stmt.clauses()[clause_num];
  1488. RuntimeScope matches(&heap_);
  1489. BindingMap generic_args;
  1490. CARBON_ASSIGN_OR_RETURN(
  1491. Nonnull<const Value*> val,
  1492. Convert(act.results()[0], &c.pattern().static_type(),
  1493. stmt.source_loc()));
  1494. if (PatternMatch(&c.pattern().value(), val, stmt.source_loc(), &matches,
  1495. generic_args, trace_stream_, this->arena_)) {
  1496. // Ensure we don't process any more clauses.
  1497. act.set_pos(match_stmt.clauses().size() + 1);
  1498. todo_.MergeScope(std::move(matches));
  1499. return todo_.Spawn(std::make_unique<StatementAction>(&c.statement()));
  1500. } else {
  1501. return todo_.RunAgain();
  1502. }
  1503. }
  1504. }
  1505. case StatementKind::For: {
  1506. constexpr int TargetVarPosInResult = 0;
  1507. constexpr int CurrentIndexPosInResult = 1;
  1508. constexpr int EndIndexPosInResult = 2;
  1509. constexpr int LoopVarPosInResult = 3;
  1510. if (act.pos() == 0) {
  1511. return todo_.Spawn(
  1512. std::make_unique<ExpressionAction>(&cast<For>(stmt).loop_target()));
  1513. }
  1514. if (act.pos() == 1) {
  1515. Nonnull<const TupleValue*> source_array =
  1516. cast<const TupleValue>(act.results()[TargetVarPosInResult]);
  1517. auto end_index = static_cast<int>(source_array->elements().size());
  1518. if (end_index == 0) {
  1519. return todo_.FinishAction();
  1520. }
  1521. act.AddResult(arena_->New<IntValue>(0));
  1522. act.AddResult(arena_->New<IntValue>(end_index));
  1523. return todo_.Spawn(std::make_unique<PatternAction>(
  1524. &cast<For>(stmt).variable_declaration()));
  1525. }
  1526. if (act.pos() == 2) {
  1527. Nonnull<const BindingPlaceholderValue*> loop_var =
  1528. cast<const BindingPlaceholderValue>(
  1529. act.results()[LoopVarPosInResult]);
  1530. Nonnull<const TupleValue*> source_array =
  1531. cast<const TupleValue>(act.results()[TargetVarPosInResult]);
  1532. auto start_index =
  1533. cast<IntValue>(act.results()[CurrentIndexPosInResult])->value();
  1534. todo_.Initialize(*(loop_var->value_node()),
  1535. source_array->elements()[start_index]);
  1536. act.ReplaceResult(CurrentIndexPosInResult,
  1537. arena_->New<IntValue>(start_index + 1));
  1538. return todo_.Spawn(
  1539. std::make_unique<StatementAction>(&cast<For>(stmt).body()));
  1540. }
  1541. if (act.pos() >= 3) {
  1542. auto current_index =
  1543. cast<IntValue>(act.results()[CurrentIndexPosInResult])->value();
  1544. auto end_index =
  1545. cast<IntValue>(act.results()[EndIndexPosInResult])->value();
  1546. if (current_index < end_index) {
  1547. Nonnull<const TupleValue*> source_array =
  1548. cast<const TupleValue>(act.results()[TargetVarPosInResult]);
  1549. Nonnull<const BindingPlaceholderValue*> loop_var =
  1550. cast<const BindingPlaceholderValue>(
  1551. act.results()[LoopVarPosInResult]);
  1552. CARBON_ASSIGN_OR_RETURN(
  1553. Nonnull<const Value*> assigned_array_element,
  1554. todo_.ValueOfNode(*(loop_var->value_node()), stmt.source_loc()));
  1555. auto lvalue = cast<LValue>(assigned_array_element);
  1556. CARBON_RETURN_IF_ERROR(heap_.Write(
  1557. lvalue->address(), source_array->elements()[current_index],
  1558. stmt.source_loc()));
  1559. act.ReplaceResult(CurrentIndexPosInResult,
  1560. arena_->New<IntValue>(current_index + 1));
  1561. return todo_.Spawn(
  1562. std::make_unique<StatementAction>(&cast<For>(stmt).body()));
  1563. }
  1564. }
  1565. return todo_.FinishAction();
  1566. }
  1567. case StatementKind::While:
  1568. // TODO: Rewrite While to use ReplaceResult to store condition result.
  1569. // This will remove the inconsistency between the while and for
  1570. // loops.
  1571. if (act.pos() % 2 == 0) {
  1572. // { { (while (e) s) :: C, E, F} :: S, H}
  1573. // -> { { e :: (while ([]) s) :: C, E, F} :: S, H}
  1574. act.Clear();
  1575. return todo_.Spawn(
  1576. std::make_unique<ExpressionAction>(&cast<While>(stmt).condition()));
  1577. } else {
  1578. CARBON_ASSIGN_OR_RETURN(
  1579. Nonnull<const Value*> condition,
  1580. Convert(act.results().back(), arena_->New<BoolType>(),
  1581. stmt.source_loc()));
  1582. if (cast<BoolValue>(*condition).value()) {
  1583. // { {true :: (while ([]) s) :: C, E, F} :: S, H}
  1584. // -> { { s :: (while (e) s) :: C, E, F } :: S, H}
  1585. return todo_.Spawn(
  1586. std::make_unique<StatementAction>(&cast<While>(stmt).body()));
  1587. } else {
  1588. // { {false :: (while ([]) s) :: C, E, F} :: S, H}
  1589. // -> { { C, E, F } :: S, H}
  1590. return todo_.FinishAction();
  1591. }
  1592. }
  1593. case StatementKind::Break: {
  1594. CARBON_CHECK(act.pos() == 0);
  1595. // { { break; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  1596. // -> { { C, E', F} :: S, H}
  1597. return todo_.UnwindPast(&cast<Break>(stmt).loop());
  1598. }
  1599. case StatementKind::Continue: {
  1600. CARBON_CHECK(act.pos() == 0);
  1601. // { { continue; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  1602. // -> { { (while (e) s) :: C, E', F} :: S, H}
  1603. return todo_.UnwindTo(&cast<Continue>(stmt).loop());
  1604. }
  1605. case StatementKind::Block: {
  1606. const auto& block = cast<Block>(stmt);
  1607. if (act.pos() >= static_cast<int>(block.statements().size())) {
  1608. // If the position is past the end of the block, end processing. Note
  1609. // that empty blocks immediately end.
  1610. return todo_.FinishAction();
  1611. }
  1612. // Initialize a scope when starting a block.
  1613. if (act.pos() == 0) {
  1614. act.StartScope(RuntimeScope(&heap_));
  1615. }
  1616. // Process the next statement in the block. The position will be
  1617. // incremented as part of Spawn.
  1618. return todo_.Spawn(
  1619. std::make_unique<StatementAction>(block.statements()[act.pos()]));
  1620. }
  1621. case StatementKind::VariableDefinition: {
  1622. const auto& definition = cast<VariableDefinition>(stmt);
  1623. if (act.pos() == 0 && definition.has_init()) {
  1624. // { {(var x = e) :: C, E, F} :: S, H}
  1625. // -> { {e :: (var x = []) :: C, E, F} :: S, H}
  1626. return todo_.Spawn(
  1627. std::make_unique<ExpressionAction>(&definition.init()));
  1628. } else {
  1629. // { { v :: (x = []) :: C, E, F} :: S, H}
  1630. // -> { { C, E(x := a), F} :: S, H(a := copy(v))}
  1631. Nonnull<const Value*> p =
  1632. &cast<VariableDefinition>(stmt).pattern().value();
  1633. Nonnull<const Value*> v;
  1634. if (definition.has_init()) {
  1635. CARBON_ASSIGN_OR_RETURN(
  1636. v, Convert(act.results()[0], &definition.pattern().static_type(),
  1637. stmt.source_loc()));
  1638. } else {
  1639. v = arena_->New<UninitializedValue>(p);
  1640. }
  1641. RuntimeScope matches(&heap_);
  1642. BindingMap generic_args;
  1643. CARBON_CHECK(PatternMatch(p, v, stmt.source_loc(), &matches,
  1644. generic_args, trace_stream_, this->arena_))
  1645. << stmt.source_loc()
  1646. << ": internal error in variable definition, match failed";
  1647. todo_.MergeScope(std::move(matches));
  1648. return todo_.FinishAction();
  1649. }
  1650. }
  1651. case StatementKind::ExpressionStatement:
  1652. if (act.pos() == 0) {
  1653. // { {e :: C, E, F} :: S, H}
  1654. // -> { {e :: C, E, F} :: S, H}
  1655. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1656. &cast<ExpressionStatement>(stmt).expression()));
  1657. } else {
  1658. return todo_.FinishAction();
  1659. }
  1660. case StatementKind::Assign: {
  1661. const auto& assign = cast<Assign>(stmt);
  1662. if (act.pos() == 0) {
  1663. // { {(lv = e) :: C, E, F} :: S, H}
  1664. // -> { {lv :: ([] = e) :: C, E, F} :: S, H}
  1665. return todo_.Spawn(std::make_unique<LValAction>(&assign.lhs()));
  1666. } else if (act.pos() == 1) {
  1667. // { { a :: ([] = e) :: C, E, F} :: S, H}
  1668. // -> { { e :: (a = []) :: C, E, F} :: S, H}
  1669. return todo_.Spawn(std::make_unique<ExpressionAction>(&assign.rhs()));
  1670. } else {
  1671. // { { v :: (a = []) :: C, E, F} :: S, H}
  1672. // -> { { C, E, F} :: S, H(a := v)}
  1673. const auto& lval = cast<LValue>(*act.results()[0]);
  1674. CARBON_ASSIGN_OR_RETURN(
  1675. Nonnull<const Value*> rval,
  1676. Convert(act.results()[1], &assign.lhs().static_type(),
  1677. stmt.source_loc()));
  1678. CARBON_RETURN_IF_ERROR(
  1679. heap_.Write(lval.address(), rval, stmt.source_loc()));
  1680. return todo_.FinishAction();
  1681. }
  1682. }
  1683. case StatementKind::If:
  1684. if (act.pos() == 0) {
  1685. // { {(if (e) then_stmt else else_stmt) :: C, E, F} :: S, H}
  1686. // -> { { e :: (if ([]) then_stmt else else_stmt) :: C, E, F} :: S, H}
  1687. return todo_.Spawn(
  1688. std::make_unique<ExpressionAction>(&cast<If>(stmt).condition()));
  1689. } else if (act.pos() == 1) {
  1690. CARBON_ASSIGN_OR_RETURN(
  1691. Nonnull<const Value*> condition,
  1692. Convert(act.results()[0], arena_->New<BoolType>(),
  1693. stmt.source_loc()));
  1694. if (cast<BoolValue>(*condition).value()) {
  1695. // { {true :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  1696. // S, H}
  1697. // -> { { then_stmt :: C, E, F } :: S, H}
  1698. return todo_.Spawn(
  1699. std::make_unique<StatementAction>(&cast<If>(stmt).then_block()));
  1700. } else if (cast<If>(stmt).else_block()) {
  1701. // { {false :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  1702. // S, H}
  1703. // -> { { else_stmt :: C, E, F } :: S, H}
  1704. return todo_.Spawn(
  1705. std::make_unique<StatementAction>(*cast<If>(stmt).else_block()));
  1706. } else {
  1707. return todo_.FinishAction();
  1708. }
  1709. } else {
  1710. return todo_.FinishAction();
  1711. }
  1712. case StatementKind::ReturnVar: {
  1713. const auto& ret_var = cast<ReturnVar>(stmt);
  1714. const ValueNodeView& value_node = ret_var.value_node();
  1715. if (trace_stream_) {
  1716. **trace_stream_ << "--- step returned var "
  1717. << cast<BindingPattern>(value_node.base()).name()
  1718. << " ." << act.pos() << "."
  1719. << " (" << stmt.source_loc() << ") --->\n";
  1720. }
  1721. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> value,
  1722. todo_.ValueOfNode(value_node, stmt.source_loc()));
  1723. if (const auto* lvalue = dyn_cast<LValue>(value)) {
  1724. CARBON_ASSIGN_OR_RETURN(
  1725. value, heap_.Read(lvalue->address(), ret_var.source_loc()));
  1726. }
  1727. const CallableDeclaration& function = cast<Return>(stmt).function();
  1728. CARBON_ASSIGN_OR_RETURN(
  1729. Nonnull<const Value*> return_value,
  1730. Convert(value, &function.return_term().static_type(),
  1731. stmt.source_loc()));
  1732. return todo_.UnwindPast(*function.body(), return_value);
  1733. }
  1734. case StatementKind::ReturnExpression:
  1735. if (act.pos() == 0) {
  1736. // { {return e :: C, E, F} :: S, H}
  1737. // -> { {e :: return [] :: C, E, F} :: S, H}
  1738. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1739. &cast<ReturnExpression>(stmt).expression()));
  1740. } else {
  1741. // { {v :: return [] :: C, E, F} :: {C', E', F'} :: S, H}
  1742. // -> { {v :: C', E', F'} :: S, H}
  1743. const CallableDeclaration& function = cast<Return>(stmt).function();
  1744. CARBON_ASSIGN_OR_RETURN(
  1745. Nonnull<const Value*> return_value,
  1746. Convert(act.results()[0], &function.return_term().static_type(),
  1747. stmt.source_loc()));
  1748. return todo_.UnwindPast(*function.body(), return_value);
  1749. }
  1750. case StatementKind::Continuation: {
  1751. CARBON_CHECK(act.pos() == 0);
  1752. const auto& continuation = cast<Continuation>(stmt);
  1753. // Create a continuation object by creating a frame similar the
  1754. // way one is created in a function call.
  1755. auto fragment = arena_->New<ContinuationValue::StackFragment>();
  1756. stack_fragments_.push_back(fragment);
  1757. todo_.InitializeFragment(*fragment, &continuation.body());
  1758. // Bind the continuation object to the continuation variable
  1759. todo_.Initialize(&cast<Continuation>(stmt),
  1760. arena_->New<ContinuationValue>(fragment));
  1761. return todo_.FinishAction();
  1762. }
  1763. case StatementKind::Run: {
  1764. auto& run = cast<Run>(stmt);
  1765. if (act.pos() == 0) {
  1766. // Evaluate the argument of the run statement.
  1767. return todo_.Spawn(std::make_unique<ExpressionAction>(&run.argument()));
  1768. } else if (act.pos() == 1) {
  1769. // Push the continuation onto the current stack.
  1770. return todo_.Resume(cast<const ContinuationValue>(act.results()[0]));
  1771. } else {
  1772. return todo_.FinishAction();
  1773. }
  1774. }
  1775. case StatementKind::Await:
  1776. CARBON_CHECK(act.pos() == 0);
  1777. return todo_.Suspend();
  1778. }
  1779. }
  1780. auto Interpreter::StepDeclaration() -> ErrorOr<Success> {
  1781. Action& act = todo_.CurrentAction();
  1782. const Declaration& decl = cast<DeclarationAction>(act).declaration();
  1783. if (trace_stream_) {
  1784. **trace_stream_ << "--- step decl ";
  1785. decl.PrintID(**trace_stream_);
  1786. **trace_stream_ << " ." << act.pos() << ". "
  1787. << "(" << decl.source_loc() << ") --->\n";
  1788. }
  1789. switch (decl.kind()) {
  1790. case DeclarationKind::VariableDeclaration: {
  1791. const auto& var_decl = cast<VariableDeclaration>(decl);
  1792. if (var_decl.has_initializer()) {
  1793. if (act.pos() == 0) {
  1794. return todo_.Spawn(
  1795. std::make_unique<ExpressionAction>(&var_decl.initializer()));
  1796. } else {
  1797. CARBON_ASSIGN_OR_RETURN(
  1798. Nonnull<const Value*> v,
  1799. Convert(act.results()[0], &var_decl.binding().static_type(),
  1800. var_decl.source_loc()));
  1801. todo_.Initialize(&var_decl.binding(), v);
  1802. return todo_.FinishAction();
  1803. }
  1804. } else {
  1805. Nonnull<const Value*> v =
  1806. arena_->New<UninitializedValue>(&var_decl.binding().value());
  1807. todo_.Initialize(&var_decl.binding(), v);
  1808. return todo_.FinishAction();
  1809. }
  1810. }
  1811. case DeclarationKind::DestructorDeclaration:
  1812. case DeclarationKind::FunctionDeclaration:
  1813. case DeclarationKind::ClassDeclaration:
  1814. case DeclarationKind::MixinDeclaration:
  1815. case DeclarationKind::MixDeclaration:
  1816. case DeclarationKind::ChoiceDeclaration:
  1817. case DeclarationKind::InterfaceDeclaration:
  1818. case DeclarationKind::AssociatedConstantDeclaration:
  1819. case DeclarationKind::ImplDeclaration:
  1820. case DeclarationKind::SelfDeclaration:
  1821. case DeclarationKind::AliasDeclaration:
  1822. // These declarations have no run-time effects.
  1823. return todo_.FinishAction();
  1824. }
  1825. }
  1826. auto Interpreter::StepCleanUp() -> ErrorOr<Success> {
  1827. Action& act = todo_.CurrentAction();
  1828. CleanupAction& cleanup = cast<CleanupAction>(act);
  1829. if (act.pos() < cleanup.locals_count()) {
  1830. auto lvalue = act.scope()->locals()[cleanup.locals_count() - act.pos() - 1];
  1831. SourceLocation source_loc("destructor", 1);
  1832. auto value = heap_.Read(lvalue->address(), source_loc);
  1833. if (value.ok()) {
  1834. if (act.scope()->DestructionState() < RuntimeScope::State::CleanUpped) {
  1835. if (const auto* class_obj = dyn_cast<NominalClassValue>(*value)) {
  1836. const auto& class_type = cast<NominalClassType>(class_obj->type());
  1837. const auto& class_dec = class_type.declaration();
  1838. if (class_dec.destructor().has_value()) {
  1839. return CallDestructor(*class_dec.destructor(), class_obj);
  1840. }
  1841. }
  1842. } else {
  1843. if (const auto* class_obj = dyn_cast<NominalClassValue>(*value)) {
  1844. const auto& class_type = cast<NominalClassType>(class_obj->type());
  1845. const auto& class_dec = class_type.declaration();
  1846. const auto& class_members = class_dec.members();
  1847. for (const auto& member : class_members) {
  1848. if (const auto* var = dyn_cast<VariableDeclaration>(member)) {
  1849. const auto& type = var->static_type();
  1850. if (const auto* c_type = dyn_cast<NominalClassType>(&type)) {
  1851. auto& c_dec = c_type->declaration();
  1852. if (c_dec.destructor().has_value()) {
  1853. Address object = lvalue->address();
  1854. Address mem = object.SubobjectAddress(Member(var));
  1855. auto v = heap_.Read(mem, source_loc);
  1856. act.scope()->TransitState();
  1857. return CallDestructor(*c_dec.destructor(), *v);
  1858. }
  1859. }
  1860. }
  1861. }
  1862. }
  1863. act.scope()->TransitState();
  1864. }
  1865. }
  1866. }
  1867. todo_.Pop();
  1868. return Success();
  1869. }
  1870. // State transition.
  1871. auto Interpreter::Step() -> ErrorOr<Success> {
  1872. Action& act = todo_.CurrentAction();
  1873. switch (act.kind()) {
  1874. case Action::Kind::LValAction:
  1875. CARBON_RETURN_IF_ERROR(StepLvalue());
  1876. break;
  1877. case Action::Kind::ExpressionAction:
  1878. CARBON_RETURN_IF_ERROR(StepExp());
  1879. break;
  1880. case Action::Kind::PatternAction:
  1881. CARBON_RETURN_IF_ERROR(StepPattern());
  1882. break;
  1883. case Action::Kind::StatementAction:
  1884. CARBON_RETURN_IF_ERROR(StepStmt());
  1885. break;
  1886. case Action::Kind::DeclarationAction:
  1887. CARBON_RETURN_IF_ERROR(StepDeclaration());
  1888. break;
  1889. case Action::Kind::CleanUpAction:
  1890. CARBON_RETURN_IF_ERROR(StepCleanUp());
  1891. break;
  1892. case Action::Kind::ScopeAction:
  1893. CARBON_FATAL() << "ScopeAction escaped ActionStack";
  1894. case Action::Kind::RecursiveAction:
  1895. CARBON_FATAL() << "Tried to step a RecursiveAction";
  1896. } // switch
  1897. return Success();
  1898. }
  1899. auto Interpreter::RunAllSteps(std::unique_ptr<Action> action)
  1900. -> ErrorOr<Success> {
  1901. if (trace_stream_) {
  1902. PrintState(**trace_stream_);
  1903. }
  1904. todo_.Start(std::move(action));
  1905. while (!todo_.IsEmpty()) {
  1906. CARBON_RETURN_IF_ERROR(Step());
  1907. if (trace_stream_) {
  1908. PrintState(**trace_stream_);
  1909. }
  1910. }
  1911. return Success();
  1912. }
  1913. auto InterpProgram(const AST& ast, Nonnull<Arena*> arena,
  1914. std::optional<Nonnull<llvm::raw_ostream*>> trace_stream)
  1915. -> ErrorOr<int> {
  1916. Interpreter interpreter(Phase::RunTime, arena, trace_stream);
  1917. if (trace_stream) {
  1918. **trace_stream << "********** initializing globals **********\n";
  1919. }
  1920. for (Nonnull<Declaration*> declaration : ast.declarations) {
  1921. CARBON_RETURN_IF_ERROR(interpreter.RunAllSteps(
  1922. std::make_unique<DeclarationAction>(declaration)));
  1923. }
  1924. if (trace_stream) {
  1925. **trace_stream << "********** calling main function **********\n";
  1926. }
  1927. CARBON_RETURN_IF_ERROR(interpreter.RunAllSteps(
  1928. std::make_unique<ExpressionAction>(*ast.main_call)));
  1929. return cast<IntValue>(*interpreter.result()).value();
  1930. }
  1931. auto InterpExp(Nonnull<const Expression*> e, Nonnull<Arena*> arena,
  1932. std::optional<Nonnull<llvm::raw_ostream*>> trace_stream)
  1933. -> ErrorOr<Nonnull<const Value*>> {
  1934. Interpreter interpreter(Phase::CompileTime, arena, trace_stream);
  1935. CARBON_RETURN_IF_ERROR(
  1936. interpreter.RunAllSteps(std::make_unique<ExpressionAction>(e)));
  1937. return interpreter.result();
  1938. }
  1939. auto InterpPattern(Nonnull<const Pattern*> p, Nonnull<Arena*> arena,
  1940. std::optional<Nonnull<llvm::raw_ostream*>> trace_stream)
  1941. -> ErrorOr<Nonnull<const Value*>> {
  1942. Interpreter interpreter(Phase::CompileTime, arena, trace_stream);
  1943. CARBON_RETURN_IF_ERROR(
  1944. interpreter.RunAllSteps(std::make_unique<PatternAction>(p)));
  1945. return interpreter.result();
  1946. }
  1947. } // namespace Carbon