interpreter.cpp 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "explorer/interpreter/interpreter.h"
  5. #include <iterator>
  6. #include <map>
  7. #include <optional>
  8. #include <utility>
  9. #include <variant>
  10. #include <vector>
  11. #include "common/check.h"
  12. #include "explorer/ast/declaration.h"
  13. #include "explorer/ast/expression.h"
  14. #include "explorer/common/arena.h"
  15. #include "explorer/common/error_builders.h"
  16. #include "explorer/interpreter/action.h"
  17. #include "explorer/interpreter/action_stack.h"
  18. #include "explorer/interpreter/stack.h"
  19. #include "llvm/ADT/StringExtras.h"
  20. #include "llvm/Support/Casting.h"
  21. #include "llvm/Support/Error.h"
  22. using llvm::cast;
  23. using llvm::dyn_cast;
  24. using llvm::isa;
  25. namespace Carbon {
  26. // Constructs an ActionStack suitable for the specified phase.
  27. static auto MakeTodo(Phase phase, Nonnull<Heap*> heap) -> ActionStack {
  28. switch (phase) {
  29. case Phase::CompileTime:
  30. return ActionStack();
  31. case Phase::RunTime:
  32. return ActionStack(heap);
  33. }
  34. }
  35. // An Interpreter represents an instance of the Carbon abstract machine. It
  36. // manages the state of the abstract machine, and executes the steps of Actions
  37. // passed to it.
  38. class Interpreter {
  39. public:
  40. // Constructs an Interpreter which allocates values on `arena`, and prints
  41. // traces if `trace` is true. `phase` indicates whether it executes at
  42. // compile time or run time.
  43. Interpreter(Phase phase, Nonnull<Arena*> arena,
  44. std::optional<Nonnull<llvm::raw_ostream*>> trace_stream)
  45. : arena_(arena),
  46. heap_(arena),
  47. todo_(MakeTodo(phase, &heap_)),
  48. trace_stream_(trace_stream),
  49. phase_(phase) {}
  50. ~Interpreter();
  51. // Runs all the steps of `action`.
  52. // It's not safe to call `RunAllSteps()` or `result()` after an error.
  53. auto RunAllSteps(std::unique_ptr<Action> action) -> ErrorOr<Success>;
  54. // The result produced by the `action` argument of the most recent
  55. // RunAllSteps call. Cannot be called if `action` was an action that doesn't
  56. // produce results.
  57. auto result() const -> Nonnull<const Value*> { return todo_.result(); }
  58. private:
  59. auto Step() -> ErrorOr<Success>;
  60. // State transitions for expressions.
  61. auto StepExp() -> ErrorOr<Success>;
  62. // State transitions for lvalues.
  63. auto StepLvalue() -> ErrorOr<Success>;
  64. // State transitions for patterns.
  65. auto StepPattern() -> ErrorOr<Success>;
  66. // State transition for statements.
  67. auto StepStmt() -> ErrorOr<Success>;
  68. // State transition for declarations.
  69. auto StepDeclaration() -> ErrorOr<Success>;
  70. auto CreateStruct(const std::vector<FieldInitializer>& fields,
  71. const std::vector<Nonnull<const Value*>>& values)
  72. -> Nonnull<const Value*>;
  73. auto EvalPrim(Operator op, Nonnull<const Value*> static_type,
  74. const std::vector<Nonnull<const Value*>>& args,
  75. SourceLocation source_loc) -> ErrorOr<Nonnull<const Value*>>;
  76. // Returns the result of converting `value` to type `destination_type`.
  77. auto Convert(Nonnull<const Value*> value,
  78. Nonnull<const Value*> destination_type,
  79. SourceLocation source_loc) -> ErrorOr<Nonnull<const Value*>>;
  80. // Evaluate an expression immediately, recursively.
  81. //
  82. // TODO: Stop using this.
  83. auto EvalExpRecursively(Nonnull<const Expression*> exp)
  84. -> ErrorOr<Nonnull<const Value*>>;
  85. // Instantiate a type by replacing all type variables that occur inside the
  86. // type by the current values of those variables.
  87. //
  88. // For example, suppose T=i32 and U=Bool. Then
  89. // __Fn (Point(T)) -> Point(U)
  90. // becomes
  91. // __Fn (Point(i32)) -> Point(Bool)
  92. auto InstantiateType(Nonnull<const Value*> type, SourceLocation source_loc)
  93. -> ErrorOr<Nonnull<const Value*>>;
  94. // Call the function `fun` with the given `arg` and the `witnesses`
  95. // for the function's impl bindings.
  96. auto CallFunction(const CallExpression& call, Nonnull<const Value*> fun,
  97. Nonnull<const Value*> arg, const ImplWitnessMap& witnesses)
  98. -> ErrorOr<Success>;
  99. void PrintState(llvm::raw_ostream& out);
  100. Phase phase() const { return phase_; }
  101. Nonnull<Arena*> arena_;
  102. Heap heap_;
  103. ActionStack todo_;
  104. // The underlying states of continuation values. All StackFragments created
  105. // during execution are tracked here, in order to safely deallocate the
  106. // contents of any non-completed continuations at the end of execution.
  107. std::vector<Nonnull<ContinuationValue::StackFragment*>> stack_fragments_;
  108. std::optional<Nonnull<llvm::raw_ostream*>> trace_stream_;
  109. Phase phase_;
  110. };
  111. Interpreter::~Interpreter() {
  112. // Clean up any remaining suspended continuations.
  113. for (Nonnull<ContinuationValue::StackFragment*> fragment : stack_fragments_) {
  114. fragment->Clear();
  115. }
  116. }
  117. //
  118. // State Operations
  119. //
  120. void Interpreter::PrintState(llvm::raw_ostream& out) {
  121. out << "{\nstack: " << todo_;
  122. out << "\nmemory: " << heap_;
  123. out << "\n}\n";
  124. }
  125. auto Interpreter::EvalPrim(Operator op, Nonnull<const Value*> static_type,
  126. const std::vector<Nonnull<const Value*>>& args,
  127. SourceLocation source_loc)
  128. -> ErrorOr<Nonnull<const Value*>> {
  129. switch (op) {
  130. case Operator::Neg:
  131. return arena_->New<IntValue>(-cast<IntValue>(*args[0]).value());
  132. case Operator::Add:
  133. return arena_->New<IntValue>(cast<IntValue>(*args[0]).value() +
  134. cast<IntValue>(*args[1]).value());
  135. case Operator::Sub:
  136. return arena_->New<IntValue>(cast<IntValue>(*args[0]).value() -
  137. cast<IntValue>(*args[1]).value());
  138. case Operator::Mul:
  139. return arena_->New<IntValue>(cast<IntValue>(*args[0]).value() *
  140. cast<IntValue>(*args[1]).value());
  141. case Operator::Not:
  142. return arena_->New<BoolValue>(!cast<BoolValue>(*args[0]).value());
  143. case Operator::And:
  144. return arena_->New<BoolValue>(cast<BoolValue>(*args[0]).value() &&
  145. cast<BoolValue>(*args[1]).value());
  146. case Operator::Or:
  147. return arena_->New<BoolValue>(cast<BoolValue>(*args[0]).value() ||
  148. cast<BoolValue>(*args[1]).value());
  149. case Operator::Eq:
  150. return arena_->New<BoolValue>(ValueEqual(args[0], args[1]));
  151. case Operator::Ptr:
  152. return arena_->New<PointerType>(args[0]);
  153. case Operator::Deref:
  154. return heap_.Read(cast<PointerValue>(*args[0]).address(), source_loc);
  155. case Operator::AddressOf:
  156. return arena_->New<PointerValue>(cast<LValue>(*args[0]).address());
  157. case Operator::Combine:
  158. return &cast<TypeOfConstraintType>(static_type)->constraint_type();
  159. }
  160. }
  161. auto Interpreter::CreateStruct(const std::vector<FieldInitializer>& fields,
  162. const std::vector<Nonnull<const Value*>>& values)
  163. -> Nonnull<const Value*> {
  164. CARBON_CHECK(fields.size() == values.size());
  165. std::vector<NamedValue> elements;
  166. for (size_t i = 0; i < fields.size(); ++i) {
  167. elements.push_back({.name = fields[i].name(), .value = values[i]});
  168. }
  169. return arena_->New<StructValue>(std::move(elements));
  170. }
  171. auto PatternMatch(Nonnull<const Value*> p, Nonnull<const Value*> v,
  172. SourceLocation source_loc,
  173. std::optional<Nonnull<RuntimeScope*>> bindings,
  174. BindingMap& generic_args,
  175. std::optional<Nonnull<llvm::raw_ostream*>> trace_stream,
  176. Nonnull<Arena*> arena) -> bool {
  177. if (trace_stream) {
  178. **trace_stream << "match pattern " << *p << "\nwith value " << *v << "\n";
  179. }
  180. switch (p->kind()) {
  181. case Value::Kind::BindingPlaceholderValue: {
  182. CARBON_CHECK(bindings.has_value());
  183. const auto& placeholder = cast<BindingPlaceholderValue>(*p);
  184. if (placeholder.value_node().has_value()) {
  185. (*bindings)->Initialize(*placeholder.value_node(), v);
  186. }
  187. return true;
  188. }
  189. case Value::Kind::AddrValue: {
  190. const auto& addr = cast<AddrValue>(*p);
  191. CARBON_CHECK(v->kind() == Value::Kind::LValue);
  192. const auto& lvalue = cast<LValue>(*v);
  193. return PatternMatch(
  194. &addr.pattern(), arena->New<PointerValue>(lvalue.address()),
  195. source_loc, bindings, generic_args, trace_stream, arena);
  196. }
  197. case Value::Kind::VariableType: {
  198. const auto& var_type = cast<VariableType>(*p);
  199. generic_args[&var_type.binding()] = v;
  200. return true;
  201. }
  202. case Value::Kind::TupleValue:
  203. switch (v->kind()) {
  204. case Value::Kind::TupleValue: {
  205. const auto& p_tup = cast<TupleValue>(*p);
  206. const auto& v_tup = cast<TupleValue>(*v);
  207. CARBON_CHECK(p_tup.elements().size() == v_tup.elements().size());
  208. for (size_t i = 0; i < p_tup.elements().size(); ++i) {
  209. if (!PatternMatch(p_tup.elements()[i], v_tup.elements()[i],
  210. source_loc, bindings, generic_args, trace_stream,
  211. arena)) {
  212. return false;
  213. }
  214. } // for
  215. return true;
  216. }
  217. default:
  218. CARBON_FATAL() << "expected a tuple value in pattern, not " << *v;
  219. }
  220. case Value::Kind::StructValue: {
  221. const auto& p_struct = cast<StructValue>(*p);
  222. const auto& v_struct = cast<StructValue>(*v);
  223. CARBON_CHECK(p_struct.elements().size() == v_struct.elements().size());
  224. for (size_t i = 0; i < p_struct.elements().size(); ++i) {
  225. CARBON_CHECK(p_struct.elements()[i].name ==
  226. v_struct.elements()[i].name);
  227. if (!PatternMatch(p_struct.elements()[i].value,
  228. v_struct.elements()[i].value, source_loc, bindings,
  229. generic_args, trace_stream, arena)) {
  230. return false;
  231. }
  232. }
  233. return true;
  234. }
  235. case Value::Kind::AlternativeValue:
  236. switch (v->kind()) {
  237. case Value::Kind::AlternativeValue: {
  238. const auto& p_alt = cast<AlternativeValue>(*p);
  239. const auto& v_alt = cast<AlternativeValue>(*v);
  240. if (p_alt.choice_name() != v_alt.choice_name() ||
  241. p_alt.alt_name() != v_alt.alt_name()) {
  242. return false;
  243. }
  244. return PatternMatch(&p_alt.argument(), &v_alt.argument(), source_loc,
  245. bindings, generic_args, trace_stream, arena);
  246. }
  247. default:
  248. CARBON_FATAL() << "expected a choice alternative in pattern, not "
  249. << *v;
  250. }
  251. case Value::Kind::FunctionType:
  252. switch (v->kind()) {
  253. case Value::Kind::FunctionType: {
  254. const auto& p_fn = cast<FunctionType>(*p);
  255. const auto& v_fn = cast<FunctionType>(*v);
  256. if (!PatternMatch(&p_fn.parameters(), &v_fn.parameters(), source_loc,
  257. bindings, generic_args, trace_stream, arena)) {
  258. return false;
  259. }
  260. if (!PatternMatch(&p_fn.return_type(), &v_fn.return_type(),
  261. source_loc, bindings, generic_args, trace_stream,
  262. arena)) {
  263. return false;
  264. }
  265. return true;
  266. }
  267. default:
  268. return false;
  269. }
  270. case Value::Kind::AutoType:
  271. // `auto` matches any type, without binding any new names. We rely
  272. // on the typechecker to ensure that `v` is a type.
  273. return true;
  274. default:
  275. return ValueEqual(p, v);
  276. }
  277. }
  278. auto Interpreter::StepLvalue() -> ErrorOr<Success> {
  279. Action& act = todo_.CurrentAction();
  280. const Expression& exp = cast<LValAction>(act).expression();
  281. if (trace_stream_) {
  282. **trace_stream_ << "--- step lvalue " << exp << " ." << act.pos() << "."
  283. << " (" << exp.source_loc() << ") --->\n";
  284. }
  285. switch (exp.kind()) {
  286. case ExpressionKind::IdentifierExpression: {
  287. // { {x :: C, E, F} :: S, H}
  288. // -> { {E(x) :: C, E, F} :: S, H}
  289. CARBON_ASSIGN_OR_RETURN(
  290. Nonnull<const Value*> value,
  291. todo_.ValueOfNode(cast<IdentifierExpression>(exp).value_node(),
  292. exp.source_loc()));
  293. CARBON_CHECK(isa<LValue>(value)) << *value;
  294. return todo_.FinishAction(value);
  295. }
  296. case ExpressionKind::SimpleMemberAccessExpression: {
  297. if (act.pos() == 0) {
  298. // { {e.f :: C, E, F} :: S, H}
  299. // -> { e :: [].f :: C, E, F} :: S, H}
  300. return todo_.Spawn(std::make_unique<LValAction>(
  301. &cast<SimpleMemberAccessExpression>(exp).object()));
  302. } else {
  303. // { v :: [].f :: C, E, F} :: S, H}
  304. // -> { { &v.f :: C, E, F} :: S, H }
  305. Address object = cast<LValue>(*act.results()[0]).address();
  306. Address member = object.SubobjectAddress(
  307. cast<SimpleMemberAccessExpression>(exp).member());
  308. return todo_.FinishAction(arena_->New<LValue>(member));
  309. }
  310. }
  311. case ExpressionKind::CompoundMemberAccessExpression: {
  312. const auto& access = cast<CompoundMemberAccessExpression>(exp);
  313. if (act.pos() == 0) {
  314. return todo_.Spawn(std::make_unique<LValAction>(&access.object()));
  315. } else {
  316. CARBON_CHECK(!access.member().interface().has_value())
  317. << "unexpected lvalue interface member";
  318. CARBON_ASSIGN_OR_RETURN(
  319. Nonnull<const Value*> val,
  320. Convert(act.results()[0], *access.member().base_type(),
  321. exp.source_loc()));
  322. Address object = cast<LValue>(*val).address();
  323. Address field = object.SubobjectAddress(access.member().name());
  324. return todo_.FinishAction(arena_->New<LValue>(field));
  325. }
  326. }
  327. case ExpressionKind::IndexExpression: {
  328. if (act.pos() == 0) {
  329. // { {e[i] :: C, E, F} :: S, H}
  330. // -> { e :: [][i] :: C, E, F} :: S, H}
  331. return todo_.Spawn(
  332. std::make_unique<LValAction>(&cast<IndexExpression>(exp).object()));
  333. } else if (act.pos() == 1) {
  334. return todo_.Spawn(std::make_unique<ExpressionAction>(
  335. &cast<IndexExpression>(exp).offset()));
  336. } else {
  337. // { v :: [][i] :: C, E, F} :: S, H}
  338. // -> { { &v[i] :: C, E, F} :: S, H }
  339. Address object = cast<LValue>(*act.results()[0]).address();
  340. std::string f =
  341. std::to_string(cast<IntValue>(*act.results()[1]).value());
  342. Address field = object.SubobjectAddress(f);
  343. return todo_.FinishAction(arena_->New<LValue>(field));
  344. }
  345. }
  346. case ExpressionKind::PrimitiveOperatorExpression: {
  347. const auto& op = cast<PrimitiveOperatorExpression>(exp);
  348. if (op.op() != Operator::Deref) {
  349. CARBON_FATAL()
  350. << "Can't treat primitive operator expression as lvalue: " << exp;
  351. }
  352. if (act.pos() == 0) {
  353. return todo_.Spawn(
  354. std::make_unique<ExpressionAction>(op.arguments()[0]));
  355. } else {
  356. const auto& res = cast<PointerValue>(*act.results()[0]);
  357. return todo_.FinishAction(arena_->New<LValue>(res.address()));
  358. }
  359. break;
  360. }
  361. case ExpressionKind::TupleLiteral:
  362. case ExpressionKind::StructLiteral:
  363. case ExpressionKind::StructTypeLiteral:
  364. case ExpressionKind::IntLiteral:
  365. case ExpressionKind::BoolLiteral:
  366. case ExpressionKind::CallExpression:
  367. case ExpressionKind::IntTypeLiteral:
  368. case ExpressionKind::BoolTypeLiteral:
  369. case ExpressionKind::TypeTypeLiteral:
  370. case ExpressionKind::FunctionTypeLiteral:
  371. case ExpressionKind::ContinuationTypeLiteral:
  372. case ExpressionKind::StringLiteral:
  373. case ExpressionKind::StringTypeLiteral:
  374. case ExpressionKind::ValueLiteral:
  375. case ExpressionKind::IntrinsicExpression:
  376. case ExpressionKind::IfExpression:
  377. case ExpressionKind::WhereExpression:
  378. case ExpressionKind::ArrayTypeLiteral:
  379. case ExpressionKind::InstantiateImpl:
  380. CARBON_FATAL() << "Can't treat expression as lvalue: " << exp;
  381. case ExpressionKind::UnimplementedExpression:
  382. CARBON_FATAL() << "Unimplemented: " << exp;
  383. }
  384. }
  385. auto Interpreter::EvalExpRecursively(Nonnull<const Expression*> exp)
  386. -> ErrorOr<Nonnull<const Value*>> {
  387. if (trace_stream_) {
  388. **trace_stream_ << "--- recursive eval of " << *exp << "\n";
  389. PrintState(**trace_stream_);
  390. }
  391. todo_.BeginRecursiveAction();
  392. CARBON_RETURN_IF_ERROR(todo_.Spawn(std::make_unique<ExpressionAction>(exp)));
  393. // Note that the only `RecursiveAction` we can encounter here is our own --
  394. // if a nested action begins a recursive action, it will run until that
  395. // action is finished and popped off the queue before returning to us.
  396. while (!isa<RecursiveAction>(todo_.CurrentAction())) {
  397. CARBON_RETURN_IF_ERROR(Step());
  398. if (trace_stream_) {
  399. PrintState(**trace_stream_);
  400. }
  401. }
  402. if (trace_stream_) {
  403. **trace_stream_ << "--- recursive eval done\n";
  404. }
  405. Nonnull<const Value*> result =
  406. cast<RecursiveAction>(todo_.CurrentAction()).results()[0];
  407. CARBON_RETURN_IF_ERROR(todo_.FinishAction());
  408. return result;
  409. }
  410. auto Interpreter::InstantiateType(Nonnull<const Value*> type,
  411. SourceLocation source_loc)
  412. -> ErrorOr<Nonnull<const Value*>> {
  413. switch (type->kind()) {
  414. case Value::Kind::VariableType: {
  415. CARBON_ASSIGN_OR_RETURN(
  416. Nonnull<const Value*> value,
  417. todo_.ValueOfNode(&cast<VariableType>(*type).binding(), source_loc));
  418. if (const auto* lvalue = dyn_cast<LValue>(value)) {
  419. CARBON_ASSIGN_OR_RETURN(value,
  420. heap_.Read(lvalue->address(), source_loc));
  421. }
  422. return value;
  423. }
  424. case Value::Kind::NominalClassType: {
  425. const auto& class_type = cast<NominalClassType>(*type);
  426. BindingMap inst_type_args;
  427. for (const auto& [ty_var, ty_arg] : class_type.type_args()) {
  428. CARBON_ASSIGN_OR_RETURN(inst_type_args[ty_var],
  429. InstantiateType(ty_arg, source_loc));
  430. }
  431. ImplWitnessMap witnesses = class_type.witnesses();
  432. for (auto& [bind, witness] : witnesses) {
  433. if (auto* sym = dyn_cast<SymbolicWitness>(witness)) {
  434. CARBON_ASSIGN_OR_RETURN(witness,
  435. EvalExpRecursively(&sym->impl_expression()));
  436. }
  437. }
  438. return arena_->New<NominalClassType>(&class_type.declaration(),
  439. inst_type_args, witnesses);
  440. }
  441. default:
  442. return type;
  443. }
  444. }
  445. auto Interpreter::Convert(Nonnull<const Value*> value,
  446. Nonnull<const Value*> destination_type,
  447. SourceLocation source_loc)
  448. -> ErrorOr<Nonnull<const Value*>> {
  449. switch (value->kind()) {
  450. case Value::Kind::IntValue:
  451. case Value::Kind::FunctionValue:
  452. case Value::Kind::BoundMethodValue:
  453. case Value::Kind::PointerValue:
  454. case Value::Kind::LValue:
  455. case Value::Kind::BoolValue:
  456. case Value::Kind::NominalClassValue:
  457. case Value::Kind::AlternativeValue:
  458. case Value::Kind::IntType:
  459. case Value::Kind::BoolType:
  460. case Value::Kind::TypeType:
  461. case Value::Kind::FunctionType:
  462. case Value::Kind::PointerType:
  463. case Value::Kind::AutoType:
  464. case Value::Kind::NominalClassType:
  465. case Value::Kind::InterfaceType:
  466. case Value::Kind::ConstraintType:
  467. case Value::Kind::ImplWitness:
  468. case Value::Kind::SymbolicWitness:
  469. case Value::Kind::ParameterizedEntityName:
  470. case Value::Kind::ChoiceType:
  471. case Value::Kind::ContinuationType:
  472. case Value::Kind::VariableType:
  473. case Value::Kind::BindingPlaceholderValue:
  474. case Value::Kind::AddrValue:
  475. case Value::Kind::AlternativeConstructorValue:
  476. case Value::Kind::ContinuationValue:
  477. case Value::Kind::StringType:
  478. case Value::Kind::StringValue:
  479. case Value::Kind::TypeOfClassType:
  480. case Value::Kind::TypeOfInterfaceType:
  481. case Value::Kind::TypeOfConstraintType:
  482. case Value::Kind::TypeOfChoiceType:
  483. case Value::Kind::TypeOfParameterizedEntityName:
  484. case Value::Kind::TypeOfMemberName:
  485. case Value::Kind::StaticArrayType:
  486. case Value::Kind::MemberName:
  487. // TODO: add `CARBON_CHECK(TypeEqual(type, value->dynamic_type()))`, once
  488. // we have Value::dynamic_type.
  489. return value;
  490. case Value::Kind::StructValue: {
  491. const auto& struct_val = cast<StructValue>(*value);
  492. switch (destination_type->kind()) {
  493. case Value::Kind::StructType: {
  494. const auto& destination_struct_type =
  495. cast<StructType>(*destination_type);
  496. std::vector<NamedValue> new_elements;
  497. for (const auto& [field_name, field_type] :
  498. destination_struct_type.fields()) {
  499. std::optional<Nonnull<const Value*>> old_value =
  500. struct_val.FindField(field_name);
  501. CARBON_ASSIGN_OR_RETURN(
  502. Nonnull<const Value*> val,
  503. Convert(*old_value, field_type, source_loc));
  504. new_elements.push_back({.name = field_name, .value = val});
  505. }
  506. return arena_->New<StructValue>(std::move(new_elements));
  507. }
  508. case Value::Kind::NominalClassType: {
  509. // Instantiate the `destintation_type` to obtain the runtime
  510. // type of the object.
  511. CARBON_ASSIGN_OR_RETURN(
  512. Nonnull<const Value*> inst_dest,
  513. InstantiateType(destination_type, source_loc));
  514. return arena_->New<NominalClassValue>(inst_dest, value);
  515. }
  516. default:
  517. CARBON_FATAL() << "Can't convert value " << *value << " to type "
  518. << *destination_type;
  519. }
  520. }
  521. case Value::Kind::StructType: {
  522. // The value `{}` has kind `StructType` not `StructValue`. This value can
  523. // be converted to an empty class type.
  524. if (auto* destination_class_type =
  525. dyn_cast<NominalClassType>(destination_type)) {
  526. CARBON_CHECK(cast<StructType>(*value).fields().empty())
  527. << "only an empty struct type value converts to class type";
  528. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> inst_dest,
  529. InstantiateType(destination_type, source_loc));
  530. return arena_->New<NominalClassValue>(inst_dest, value);
  531. }
  532. return value;
  533. }
  534. case Value::Kind::TupleValue: {
  535. const auto& tuple = cast<TupleValue>(value);
  536. std::vector<Nonnull<const Value*>> destination_element_types;
  537. switch (destination_type->kind()) {
  538. case Value::Kind::TupleValue:
  539. destination_element_types =
  540. cast<TupleValue>(destination_type)->elements();
  541. break;
  542. case Value::Kind::StaticArrayType: {
  543. const auto& array_type = cast<StaticArrayType>(*destination_type);
  544. destination_element_types.resize(array_type.size(),
  545. &array_type.element_type());
  546. break;
  547. }
  548. default:
  549. CARBON_FATAL() << "Can't convert value " << *value << " to type "
  550. << *destination_type;
  551. }
  552. CARBON_CHECK(tuple->elements().size() ==
  553. destination_element_types.size());
  554. std::vector<Nonnull<const Value*>> new_elements;
  555. for (size_t i = 0; i < tuple->elements().size(); ++i) {
  556. CARBON_ASSIGN_OR_RETURN(
  557. Nonnull<const Value*> val,
  558. Convert(tuple->elements()[i], destination_element_types[i],
  559. source_loc));
  560. new_elements.push_back(val);
  561. }
  562. return arena_->New<TupleValue>(std::move(new_elements));
  563. }
  564. }
  565. }
  566. auto Interpreter::CallFunction(const CallExpression& call,
  567. Nonnull<const Value*> fun,
  568. Nonnull<const Value*> arg,
  569. const ImplWitnessMap& witnesses)
  570. -> ErrorOr<Success> {
  571. if (trace_stream_) {
  572. **trace_stream_ << "calling function: " << *fun << "\n";
  573. }
  574. switch (fun->kind()) {
  575. case Value::Kind::AlternativeConstructorValue: {
  576. const auto& alt = cast<AlternativeConstructorValue>(*fun);
  577. return todo_.FinishAction(arena_->New<AlternativeValue>(
  578. alt.alt_name(), alt.choice_name(), arg));
  579. }
  580. case Value::Kind::FunctionValue: {
  581. const FunctionValue& fun_val = cast<FunctionValue>(*fun);
  582. const FunctionDeclaration& function = fun_val.declaration();
  583. RuntimeScope binding_scope(&heap_);
  584. // Bring the class type arguments into scope.
  585. for (const auto& [bind, val] : fun_val.type_args()) {
  586. binding_scope.Initialize(bind, val);
  587. }
  588. // Bring the deduced type arguments into scope.
  589. for (const auto& [bind, val] : call.deduced_args()) {
  590. binding_scope.Initialize(bind, val);
  591. }
  592. // Bring the impl witness tables into scope.
  593. for (const auto& [impl_bind, witness] : witnesses) {
  594. binding_scope.Initialize(impl_bind, witness);
  595. }
  596. for (const auto& [impl_bind, witness] : fun_val.witnesses()) {
  597. binding_scope.Initialize(impl_bind, witness);
  598. }
  599. // Enter the binding scope to make any deduced arguments visible before
  600. // we resolve the parameter type.
  601. todo_.CurrentAction().StartScope(std::move(binding_scope));
  602. CARBON_ASSIGN_OR_RETURN(
  603. Nonnull<const Value*> converted_args,
  604. Convert(arg, &function.param_pattern().static_type(),
  605. call.source_loc()));
  606. RuntimeScope function_scope(&heap_);
  607. BindingMap generic_args;
  608. CARBON_CHECK(PatternMatch(
  609. &function.param_pattern().value(), converted_args, call.source_loc(),
  610. &function_scope, generic_args, trace_stream_, this->arena_));
  611. CARBON_CHECK(function.body().has_value())
  612. << "Calling a function that's missing a body";
  613. return todo_.Spawn(std::make_unique<StatementAction>(*function.body()),
  614. std::move(function_scope));
  615. }
  616. case Value::Kind::BoundMethodValue: {
  617. const auto& m = cast<BoundMethodValue>(*fun);
  618. const FunctionDeclaration& method = m.declaration();
  619. CARBON_CHECK(method.is_method());
  620. CARBON_ASSIGN_OR_RETURN(
  621. Nonnull<const Value*> converted_args,
  622. Convert(arg, &method.param_pattern().static_type(),
  623. call.source_loc()));
  624. RuntimeScope method_scope(&heap_);
  625. BindingMap generic_args;
  626. // Bind the receiver to the `me` parameter.
  627. CARBON_CHECK(PatternMatch(&method.me_pattern().value(), m.receiver(),
  628. call.source_loc(), &method_scope, generic_args,
  629. trace_stream_, this->arena_));
  630. // Bind the arguments to the parameters.
  631. CARBON_CHECK(PatternMatch(&method.param_pattern().value(), converted_args,
  632. call.source_loc(), &method_scope, generic_args,
  633. trace_stream_, this->arena_));
  634. // Bring the class type arguments into scope.
  635. for (const auto& [bind, val] : m.type_args()) {
  636. method_scope.Initialize(bind->original(), val);
  637. }
  638. // Bring the deduced type arguments into scope.
  639. for (const auto& [bind, val] : call.deduced_args()) {
  640. method_scope.Initialize(bind->original(), val);
  641. }
  642. // Bring the impl witness tables into scope.
  643. for (const auto& [impl_bind, witness] : witnesses) {
  644. method_scope.Initialize(impl_bind->original(), witness);
  645. }
  646. for (const auto& [impl_bind, witness] : m.witnesses()) {
  647. method_scope.Initialize(impl_bind->original(), witness);
  648. }
  649. CARBON_CHECK(method.body().has_value())
  650. << "Calling a method that's missing a body";
  651. return todo_.Spawn(std::make_unique<StatementAction>(*method.body()),
  652. std::move(method_scope));
  653. }
  654. case Value::Kind::ParameterizedEntityName: {
  655. const auto& name = cast<ParameterizedEntityName>(*fun);
  656. const Declaration& decl = name.declaration();
  657. RuntimeScope params_scope(&heap_);
  658. BindingMap generic_args;
  659. CARBON_CHECK(PatternMatch(&name.params().value(), arg, call.source_loc(),
  660. &params_scope, generic_args, trace_stream_,
  661. this->arena_));
  662. switch (decl.kind()) {
  663. case DeclarationKind::ClassDeclaration:
  664. return todo_.FinishAction(arena_->New<NominalClassType>(
  665. &cast<ClassDeclaration>(decl), generic_args, witnesses));
  666. case DeclarationKind::InterfaceDeclaration:
  667. return todo_.FinishAction(arena_->New<InterfaceType>(
  668. &cast<InterfaceDeclaration>(decl), generic_args, witnesses));
  669. default:
  670. CARBON_FATAL() << "unknown kind of ParameterizedEntityName " << decl;
  671. }
  672. }
  673. default:
  674. return RuntimeError(call.source_loc())
  675. << "in call, expected a function, not " << *fun;
  676. }
  677. }
  678. auto Interpreter::StepExp() -> ErrorOr<Success> {
  679. Action& act = todo_.CurrentAction();
  680. const Expression& exp = cast<ExpressionAction>(act).expression();
  681. if (trace_stream_) {
  682. **trace_stream_ << "--- step exp " << exp << " ." << act.pos() << "."
  683. << " (" << exp.source_loc() << ") --->\n";
  684. }
  685. switch (exp.kind()) {
  686. case ExpressionKind::InstantiateImpl: {
  687. const InstantiateImpl& inst_impl = cast<InstantiateImpl>(exp);
  688. if (act.pos() == 0) {
  689. return todo_.Spawn(
  690. std::make_unique<ExpressionAction>(inst_impl.generic_impl()));
  691. }
  692. if (act.pos() == 1 && isa<SymbolicWitness>(act.results()[0])) {
  693. return todo_.FinishAction(arena_->New<SymbolicWitness>(&exp));
  694. }
  695. if (act.pos() - 1 < int(inst_impl.impls().size())) {
  696. auto iter = inst_impl.impls().begin();
  697. std::advance(iter, act.pos() - 1);
  698. return todo_.Spawn(std::make_unique<ExpressionAction>(iter->second));
  699. } else {
  700. Nonnull<const ImplWitness*> generic_witness =
  701. cast<ImplWitness>(act.results()[0]);
  702. ImplWitnessMap witnesses;
  703. int i = 0;
  704. for (const auto& [impl_bind, impl_exp] : inst_impl.impls()) {
  705. witnesses[impl_bind] = cast<Witness>(act.results()[i + 1]);
  706. ++i;
  707. }
  708. return todo_.FinishAction(arena_->New<ImplWitness>(
  709. &generic_witness->declaration(), inst_impl.type_args(), witnesses));
  710. }
  711. }
  712. case ExpressionKind::IndexExpression: {
  713. if (act.pos() == 0) {
  714. // { { e[i] :: C, E, F} :: S, H}
  715. // -> { { e :: [][i] :: C, E, F} :: S, H}
  716. return todo_.Spawn(std::make_unique<ExpressionAction>(
  717. &cast<IndexExpression>(exp).object()));
  718. } else if (act.pos() == 1) {
  719. if (isa<SymbolicWitness>(act.results()[0])) {
  720. return todo_.FinishAction(arena_->New<SymbolicWitness>(&exp));
  721. }
  722. return todo_.Spawn(std::make_unique<ExpressionAction>(
  723. &cast<IndexExpression>(exp).offset()));
  724. } else {
  725. // { { v :: [][i] :: C, E, F} :: S, H}
  726. // -> { { v_i :: C, E, F} : S, H}
  727. const auto& tuple = cast<TupleValue>(*act.results()[0]);
  728. int i = cast<IntValue>(*act.results()[1]).value();
  729. if (i < 0 || i >= static_cast<int>(tuple.elements().size())) {
  730. return RuntimeError(exp.source_loc())
  731. << "index " << i << " out of range in " << tuple;
  732. }
  733. return todo_.FinishAction(tuple.elements()[i]);
  734. }
  735. }
  736. case ExpressionKind::TupleLiteral: {
  737. if (act.pos() <
  738. static_cast<int>(cast<TupleLiteral>(exp).fields().size())) {
  739. // { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
  740. // H}
  741. // -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
  742. // H}
  743. return todo_.Spawn(std::make_unique<ExpressionAction>(
  744. cast<TupleLiteral>(exp).fields()[act.pos()]));
  745. } else {
  746. return todo_.FinishAction(arena_->New<TupleValue>(act.results()));
  747. }
  748. }
  749. case ExpressionKind::StructLiteral: {
  750. const auto& literal = cast<StructLiteral>(exp);
  751. if (act.pos() < static_cast<int>(literal.fields().size())) {
  752. return todo_.Spawn(std::make_unique<ExpressionAction>(
  753. &literal.fields()[act.pos()].expression()));
  754. } else {
  755. return todo_.FinishAction(
  756. CreateStruct(literal.fields(), act.results()));
  757. }
  758. }
  759. case ExpressionKind::StructTypeLiteral: {
  760. const auto& struct_type = cast<StructTypeLiteral>(exp);
  761. if (act.pos() < static_cast<int>(struct_type.fields().size())) {
  762. return todo_.Spawn(std::make_unique<ExpressionAction>(
  763. &struct_type.fields()[act.pos()].expression()));
  764. } else {
  765. std::vector<NamedValue> fields;
  766. for (size_t i = 0; i < struct_type.fields().size(); ++i) {
  767. fields.push_back({struct_type.fields()[i].name(), act.results()[i]});
  768. }
  769. return todo_.FinishAction(arena_->New<StructType>(std::move(fields)));
  770. }
  771. }
  772. case ExpressionKind::SimpleMemberAccessExpression: {
  773. const auto& access = cast<SimpleMemberAccessExpression>(exp);
  774. bool forming_member_name = isa<TypeOfMemberName>(&access.static_type());
  775. if (act.pos() == 0) {
  776. // First, evaluate the first operand.
  777. if (access.is_field_addr_me_method()) {
  778. return todo_.Spawn(std::make_unique<LValAction>(&access.object()));
  779. } else {
  780. return todo_.Spawn(
  781. std::make_unique<ExpressionAction>(&access.object()));
  782. }
  783. } else if (act.pos() == 1 && access.impl().has_value() &&
  784. !forming_member_name) {
  785. // Next, if we're accessing an interface member, evaluate the `impl`
  786. // expression to find the corresponding witness.
  787. return todo_.Spawn(
  788. std::make_unique<ExpressionAction>(access.impl().value()));
  789. } else {
  790. // Finally, produce the result.
  791. if (const auto* member_name_type =
  792. dyn_cast<TypeOfMemberName>(&access.static_type())) {
  793. // The result is a member name, such as in `Type.field_name`. Form a
  794. // suitable member name value.
  795. CARBON_CHECK(phase() == Phase::CompileTime)
  796. << "should not form MemberNames at runtime";
  797. std::optional<const Value*> type_result;
  798. if (!isa<InterfaceType, ConstraintType>(act.results()[0])) {
  799. type_result = act.results()[0];
  800. }
  801. MemberName* member_name =
  802. arena_->New<MemberName>(type_result, access.found_in_interface(),
  803. member_name_type->member());
  804. return todo_.FinishAction(member_name);
  805. } else {
  806. // The result is the value of the named field, such as in
  807. // `value.field_name`. Extract the value within the given object.
  808. std::optional<Nonnull<const Witness*>> witness;
  809. if (access.impl().has_value()) {
  810. witness = cast<Witness>(act.results()[1]);
  811. }
  812. FieldPath::Component member(access.member(), witness);
  813. const Value* aggregate;
  814. if (const auto* lvalue = dyn_cast<LValue>(act.results()[0])) {
  815. CARBON_ASSIGN_OR_RETURN(
  816. aggregate,
  817. this->heap_.Read(lvalue->address(), exp.source_loc()));
  818. } else {
  819. aggregate = act.results()[0];
  820. }
  821. CARBON_ASSIGN_OR_RETURN(
  822. Nonnull<const Value*> member_value,
  823. aggregate->GetMember(arena_, FieldPath(member), exp.source_loc(),
  824. act.results()[0]));
  825. return todo_.FinishAction(member_value);
  826. }
  827. }
  828. }
  829. case ExpressionKind::CompoundMemberAccessExpression: {
  830. const auto& access = cast<CompoundMemberAccessExpression>(exp);
  831. bool forming_member_name = isa<TypeOfMemberName>(&access.static_type());
  832. if (act.pos() == 0) {
  833. // First, evaluate the first operand.
  834. return todo_.Spawn(
  835. std::make_unique<ExpressionAction>(&access.object()));
  836. } else if (act.pos() == 1 && access.impl().has_value() &&
  837. !forming_member_name) {
  838. // Next, if we're accessing an interface member, evaluate the `impl`
  839. // expression to find the corresponding witness.
  840. return todo_.Spawn(
  841. std::make_unique<ExpressionAction>(access.impl().value()));
  842. } else {
  843. // Finally, produce the result.
  844. if (forming_member_name) {
  845. // If we're forming a member name, we must be in the outer evaluation
  846. // in `Type.(Interface.method)`. Produce the same method name with
  847. // its `type` field set.
  848. CARBON_CHECK(phase() == Phase::CompileTime)
  849. << "should not form MemberNames at runtime";
  850. CARBON_CHECK(!access.member().base_type().has_value())
  851. << "compound member access forming a member name should be "
  852. "performing impl lookup";
  853. auto* member_name = arena_->New<MemberName>(
  854. act.results()[0], access.member().interface(),
  855. access.member().member());
  856. return todo_.FinishAction(member_name);
  857. } else {
  858. // Access the object to find the named member.
  859. Nonnull<const Value*> object = act.results()[0];
  860. std::optional<Nonnull<const Witness*>> witness;
  861. if (access.impl().has_value()) {
  862. witness = cast<Witness>(act.results()[1]);
  863. } else {
  864. CARBON_CHECK(access.member().base_type().has_value())
  865. << "compound access should have base type or impl";
  866. CARBON_ASSIGN_OR_RETURN(
  867. object, Convert(object, *access.member().base_type(),
  868. exp.source_loc()));
  869. }
  870. FieldPath::Component field(access.member().name(), witness);
  871. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> member,
  872. object->GetMember(arena_, FieldPath(field),
  873. exp.source_loc(), object));
  874. return todo_.FinishAction(member);
  875. }
  876. }
  877. }
  878. case ExpressionKind::IdentifierExpression: {
  879. CARBON_CHECK(act.pos() == 0);
  880. const auto& ident = cast<IdentifierExpression>(exp);
  881. // { {x :: C, E, F} :: S, H} -> { {H(E(x)) :: C, E, F} :: S, H}
  882. auto value_or_error =
  883. todo_.ValueOfNode(ident.value_node(), ident.source_loc());
  884. if (!value_or_error.ok() && phase() == Phase::CompileTime &&
  885. isa<ImplBinding>(ident.value_node().base())) {
  886. // The `ImplBinding` might not be in scope. If so, just remember the
  887. // expression from which it was derived.
  888. return todo_.FinishAction(arena_->New<SymbolicWitness>(&exp));
  889. }
  890. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> value,
  891. std::move(value_or_error));
  892. if (const auto* lvalue = dyn_cast<LValue>(value)) {
  893. CARBON_ASSIGN_OR_RETURN(
  894. value, heap_.Read(lvalue->address(), exp.source_loc()));
  895. }
  896. return todo_.FinishAction(value);
  897. }
  898. case ExpressionKind::IntLiteral:
  899. CARBON_CHECK(act.pos() == 0);
  900. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  901. return todo_.FinishAction(
  902. arena_->New<IntValue>(cast<IntLiteral>(exp).value()));
  903. case ExpressionKind::BoolLiteral:
  904. CARBON_CHECK(act.pos() == 0);
  905. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  906. return todo_.FinishAction(
  907. arena_->New<BoolValue>(cast<BoolLiteral>(exp).value()));
  908. case ExpressionKind::PrimitiveOperatorExpression: {
  909. const auto& op = cast<PrimitiveOperatorExpression>(exp);
  910. if (act.pos() != static_cast<int>(op.arguments().size())) {
  911. // { {v :: op(vs,[],e,es) :: C, E, F} :: S, H}
  912. // -> { {e :: op(vs,v,[],es) :: C, E, F} :: S, H}
  913. Nonnull<const Expression*> arg = op.arguments()[act.pos()];
  914. if (op.op() == Operator::AddressOf) {
  915. return todo_.Spawn(std::make_unique<LValAction>(arg));
  916. } else {
  917. return todo_.Spawn(std::make_unique<ExpressionAction>(arg));
  918. }
  919. } else {
  920. // { {v :: op(vs,[]) :: C, E, F} :: S, H}
  921. // -> { {eval_prim(op, (vs,v)) :: C, E, F} :: S, H}
  922. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> value,
  923. EvalPrim(op.op(), &op.static_type(),
  924. act.results(), exp.source_loc()));
  925. return todo_.FinishAction(value);
  926. }
  927. }
  928. case ExpressionKind::CallExpression: {
  929. const CallExpression& call = cast<CallExpression>(exp);
  930. unsigned int num_impls = call.impls().size();
  931. if (act.pos() == 0) {
  932. // { {e1(e2) :: C, E, F} :: S, H}
  933. // -> { {e1 :: [](e2) :: C, E, F} :: S, H}
  934. return todo_.Spawn(
  935. std::make_unique<ExpressionAction>(&call.function()));
  936. } else if (act.pos() == 1) {
  937. // { { v :: [](e) :: C, E, F} :: S, H}
  938. // -> { { e :: v([]) :: C, E, F} :: S, H}
  939. return todo_.Spawn(
  940. std::make_unique<ExpressionAction>(&call.argument()));
  941. } else if (num_impls > 0 && act.pos() < 2 + int(num_impls)) {
  942. auto iter = call.impls().begin();
  943. std::advance(iter, act.pos() - 2);
  944. return todo_.Spawn(std::make_unique<ExpressionAction>(iter->second));
  945. } else if (act.pos() == 2 + int(num_impls)) {
  946. // { { v2 :: v1([]) :: C, E, F} :: S, H}
  947. // -> { {C',E',F'} :: {C, E, F} :: S, H}
  948. ImplWitnessMap witnesses;
  949. if (num_impls > 0) {
  950. int i = 2;
  951. for (const auto& [impl_bind, impl_exp] : call.impls()) {
  952. witnesses[impl_bind] = act.results()[i];
  953. ++i;
  954. }
  955. }
  956. return CallFunction(call, act.results()[0], act.results()[1],
  957. witnesses);
  958. } else if (act.pos() == 3 + int(num_impls)) {
  959. if (act.results().size() < 3 + num_impls) {
  960. // Control fell through without explicit return.
  961. return todo_.FinishAction(TupleValue::Empty());
  962. } else {
  963. return todo_.FinishAction(act.results()[2 + int(num_impls)]);
  964. }
  965. } else {
  966. CARBON_FATAL() << "in StepExp with Call pos " << act.pos();
  967. }
  968. }
  969. case ExpressionKind::IntrinsicExpression: {
  970. const auto& intrinsic = cast<IntrinsicExpression>(exp);
  971. if (act.pos() == 0) {
  972. return todo_.Spawn(
  973. std::make_unique<ExpressionAction>(&intrinsic.args()));
  974. }
  975. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  976. switch (cast<IntrinsicExpression>(exp).intrinsic()) {
  977. case IntrinsicExpression::Intrinsic::Print: {
  978. const auto& args = cast<TupleValue>(*act.results()[0]);
  979. // TODO: This could eventually use something like llvm::formatv.
  980. llvm::outs() << cast<StringValue>(*args.elements()[0]).value();
  981. return todo_.FinishAction(TupleValue::Empty());
  982. }
  983. case IntrinsicExpression::Intrinsic::Alloc: {
  984. const auto& args = cast<TupleValue>(*act.results()[0]);
  985. CARBON_CHECK(args.elements().size() == 1);
  986. Address addr(heap_.AllocateValue(args.elements()[0]));
  987. return todo_.FinishAction(arena_->New<PointerValue>(addr));
  988. }
  989. case IntrinsicExpression::Intrinsic::Dealloc: {
  990. const auto& args = cast<TupleValue>(*act.results()[0]);
  991. CARBON_CHECK(args.elements().size() == 1);
  992. heap_.Deallocate(cast<PointerValue>(args.elements()[0])->address());
  993. return todo_.FinishAction(TupleValue::Empty());
  994. }
  995. }
  996. }
  997. case ExpressionKind::IntTypeLiteral: {
  998. CARBON_CHECK(act.pos() == 0);
  999. return todo_.FinishAction(arena_->New<IntType>());
  1000. }
  1001. case ExpressionKind::BoolTypeLiteral: {
  1002. CARBON_CHECK(act.pos() == 0);
  1003. return todo_.FinishAction(arena_->New<BoolType>());
  1004. }
  1005. case ExpressionKind::TypeTypeLiteral: {
  1006. CARBON_CHECK(act.pos() == 0);
  1007. return todo_.FinishAction(arena_->New<TypeType>());
  1008. }
  1009. case ExpressionKind::FunctionTypeLiteral: {
  1010. if (act.pos() == 0) {
  1011. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1012. &cast<FunctionTypeLiteral>(exp).parameter()));
  1013. } else if (act.pos() == 1) {
  1014. // { { pt :: fn [] -> e :: C, E, F} :: S, H}
  1015. // -> { { e :: fn pt -> []) :: C, E, F} :: S, H}
  1016. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1017. &cast<FunctionTypeLiteral>(exp).return_type()));
  1018. } else {
  1019. // { { rt :: fn pt -> [] :: C, E, F} :: S, H}
  1020. // -> { fn pt -> rt :: {C, E, F} :: S, H}
  1021. return todo_.FinishAction(arena_->New<FunctionType>(
  1022. act.results()[0], llvm::None, act.results()[1], llvm::None,
  1023. llvm::None));
  1024. }
  1025. }
  1026. case ExpressionKind::ContinuationTypeLiteral: {
  1027. CARBON_CHECK(act.pos() == 0);
  1028. return todo_.FinishAction(arena_->New<ContinuationType>());
  1029. }
  1030. case ExpressionKind::StringLiteral:
  1031. CARBON_CHECK(act.pos() == 0);
  1032. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  1033. return todo_.FinishAction(
  1034. arena_->New<StringValue>(cast<StringLiteral>(exp).value()));
  1035. case ExpressionKind::StringTypeLiteral: {
  1036. CARBON_CHECK(act.pos() == 0);
  1037. return todo_.FinishAction(arena_->New<StringType>());
  1038. }
  1039. case ExpressionKind::ValueLiteral: {
  1040. CARBON_CHECK(act.pos() == 0);
  1041. return todo_.FinishAction(&cast<ValueLiteral>(exp).value());
  1042. }
  1043. case ExpressionKind::IfExpression: {
  1044. const auto& if_expr = cast<IfExpression>(exp);
  1045. if (act.pos() == 0) {
  1046. return todo_.Spawn(
  1047. std::make_unique<ExpressionAction>(&if_expr.condition()));
  1048. } else if (act.pos() == 1) {
  1049. const auto& condition = cast<BoolValue>(*act.results()[0]);
  1050. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1051. condition.value() ? &if_expr.then_expression()
  1052. : &if_expr.else_expression()));
  1053. } else {
  1054. return todo_.FinishAction(act.results()[1]);
  1055. }
  1056. break;
  1057. }
  1058. case ExpressionKind::WhereExpression: {
  1059. return todo_.FinishAction(
  1060. &cast<TypeOfConstraintType>(exp.static_type()).constraint_type());
  1061. }
  1062. case ExpressionKind::UnimplementedExpression:
  1063. CARBON_FATAL() << "Unimplemented: " << exp;
  1064. case ExpressionKind::ArrayTypeLiteral: {
  1065. const auto& array_literal = cast<ArrayTypeLiteral>(exp);
  1066. if (act.pos() == 0) {
  1067. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1068. &array_literal.element_type_expression()));
  1069. } else if (act.pos() == 1) {
  1070. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1071. &array_literal.size_expression()));
  1072. } else {
  1073. return todo_.FinishAction(arena_->New<StaticArrayType>(
  1074. act.results()[0], cast<IntValue>(act.results()[1])->value()));
  1075. }
  1076. }
  1077. } // switch (exp->kind)
  1078. }
  1079. auto Interpreter::StepPattern() -> ErrorOr<Success> {
  1080. Action& act = todo_.CurrentAction();
  1081. const Pattern& pattern = cast<PatternAction>(act).pattern();
  1082. if (trace_stream_) {
  1083. **trace_stream_ << "--- step pattern " << pattern << " ." << act.pos()
  1084. << ". (" << pattern.source_loc() << ") --->\n";
  1085. }
  1086. switch (pattern.kind()) {
  1087. case PatternKind::AutoPattern: {
  1088. CARBON_CHECK(act.pos() == 0);
  1089. return todo_.FinishAction(arena_->New<AutoType>());
  1090. }
  1091. case PatternKind::BindingPattern: {
  1092. const auto& binding = cast<BindingPattern>(pattern);
  1093. if (binding.name() != AnonymousName) {
  1094. return todo_.FinishAction(
  1095. arena_->New<BindingPlaceholderValue>(&binding));
  1096. } else {
  1097. return todo_.FinishAction(arena_->New<BindingPlaceholderValue>());
  1098. }
  1099. }
  1100. case PatternKind::GenericBinding: {
  1101. const auto& binding = cast<GenericBinding>(pattern);
  1102. return todo_.FinishAction(arena_->New<VariableType>(&binding));
  1103. }
  1104. case PatternKind::TuplePattern: {
  1105. const auto& tuple = cast<TuplePattern>(pattern);
  1106. if (act.pos() < static_cast<int>(tuple.fields().size())) {
  1107. // { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
  1108. // H}
  1109. // -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
  1110. // H}
  1111. return todo_.Spawn(
  1112. std::make_unique<PatternAction>(tuple.fields()[act.pos()]));
  1113. } else {
  1114. return todo_.FinishAction(arena_->New<TupleValue>(act.results()));
  1115. }
  1116. }
  1117. case PatternKind::AlternativePattern: {
  1118. const auto& alternative = cast<AlternativePattern>(pattern);
  1119. if (act.pos() == 0) {
  1120. return todo_.Spawn(
  1121. std::make_unique<ExpressionAction>(&alternative.choice_type()));
  1122. } else if (act.pos() == 1) {
  1123. return todo_.Spawn(
  1124. std::make_unique<PatternAction>(&alternative.arguments()));
  1125. } else {
  1126. CARBON_CHECK(act.pos() == 2);
  1127. const auto& choice_type = cast<ChoiceType>(*act.results()[0]);
  1128. return todo_.FinishAction(arena_->New<AlternativeValue>(
  1129. alternative.alternative_name(), choice_type.name(),
  1130. act.results()[1]));
  1131. }
  1132. }
  1133. case PatternKind::ExpressionPattern:
  1134. if (act.pos() == 0) {
  1135. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1136. &cast<ExpressionPattern>(pattern).expression()));
  1137. } else {
  1138. return todo_.FinishAction(act.results()[0]);
  1139. }
  1140. case PatternKind::VarPattern:
  1141. if (act.pos() == 0) {
  1142. return todo_.Spawn(std::make_unique<PatternAction>(
  1143. &cast<VarPattern>(pattern).pattern()));
  1144. } else {
  1145. return todo_.FinishAction(act.results()[0]);
  1146. }
  1147. case PatternKind::AddrPattern:
  1148. const auto& addr = cast<AddrPattern>(pattern);
  1149. if (act.pos() == 0) {
  1150. return todo_.Spawn(std::make_unique<PatternAction>(&addr.binding()));
  1151. } else {
  1152. return todo_.FinishAction(arena_->New<AddrValue>(act.results()[0]));
  1153. }
  1154. break;
  1155. }
  1156. }
  1157. auto Interpreter::StepStmt() -> ErrorOr<Success> {
  1158. Action& act = todo_.CurrentAction();
  1159. const Statement& stmt = cast<StatementAction>(act).statement();
  1160. if (trace_stream_) {
  1161. **trace_stream_ << "--- step stmt ";
  1162. stmt.PrintDepth(1, **trace_stream_);
  1163. **trace_stream_ << " ." << act.pos() << ". "
  1164. << "(" << stmt.source_loc() << ") --->\n";
  1165. }
  1166. switch (stmt.kind()) {
  1167. case StatementKind::Match: {
  1168. const auto& match_stmt = cast<Match>(stmt);
  1169. if (act.pos() == 0) {
  1170. // { { (match (e) ...) :: C, E, F} :: S, H}
  1171. // -> { { e :: (match ([]) ...) :: C, E, F} :: S, H}
  1172. act.StartScope(RuntimeScope(&heap_));
  1173. return todo_.Spawn(
  1174. std::make_unique<ExpressionAction>(&match_stmt.expression()));
  1175. } else {
  1176. int clause_num = act.pos() - 1;
  1177. if (clause_num >= static_cast<int>(match_stmt.clauses().size())) {
  1178. return todo_.FinishAction();
  1179. }
  1180. auto c = match_stmt.clauses()[clause_num];
  1181. RuntimeScope matches(&heap_);
  1182. BindingMap generic_args;
  1183. CARBON_ASSIGN_OR_RETURN(
  1184. Nonnull<const Value*> val,
  1185. Convert(act.results()[0], &c.pattern().static_type(),
  1186. stmt.source_loc()));
  1187. if (PatternMatch(&c.pattern().value(), val, stmt.source_loc(), &matches,
  1188. generic_args, trace_stream_, this->arena_)) {
  1189. // Ensure we don't process any more clauses.
  1190. act.set_pos(match_stmt.clauses().size() + 1);
  1191. todo_.MergeScope(std::move(matches));
  1192. return todo_.Spawn(std::make_unique<StatementAction>(&c.statement()));
  1193. } else {
  1194. return todo_.RunAgain();
  1195. }
  1196. }
  1197. }
  1198. case StatementKind::While:
  1199. if (act.pos() % 2 == 0) {
  1200. // { { (while (e) s) :: C, E, F} :: S, H}
  1201. // -> { { e :: (while ([]) s) :: C, E, F} :: S, H}
  1202. act.Clear();
  1203. return todo_.Spawn(
  1204. std::make_unique<ExpressionAction>(&cast<While>(stmt).condition()));
  1205. } else {
  1206. CARBON_ASSIGN_OR_RETURN(
  1207. Nonnull<const Value*> condition,
  1208. Convert(act.results().back(), arena_->New<BoolType>(),
  1209. stmt.source_loc()));
  1210. if (cast<BoolValue>(*condition).value()) {
  1211. // { {true :: (while ([]) s) :: C, E, F} :: S, H}
  1212. // -> { { s :: (while (e) s) :: C, E, F } :: S, H}
  1213. return todo_.Spawn(
  1214. std::make_unique<StatementAction>(&cast<While>(stmt).body()));
  1215. } else {
  1216. // { {false :: (while ([]) s) :: C, E, F} :: S, H}
  1217. // -> { { C, E, F } :: S, H}
  1218. return todo_.FinishAction();
  1219. }
  1220. }
  1221. case StatementKind::Break: {
  1222. CARBON_CHECK(act.pos() == 0);
  1223. // { { break; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  1224. // -> { { C, E', F} :: S, H}
  1225. return todo_.UnwindPast(&cast<Break>(stmt).loop());
  1226. }
  1227. case StatementKind::Continue: {
  1228. CARBON_CHECK(act.pos() == 0);
  1229. // { { continue; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  1230. // -> { { (while (e) s) :: C, E', F} :: S, H}
  1231. return todo_.UnwindTo(&cast<Continue>(stmt).loop());
  1232. }
  1233. case StatementKind::Block: {
  1234. const auto& block = cast<Block>(stmt);
  1235. if (act.pos() >= static_cast<int>(block.statements().size())) {
  1236. // If the position is past the end of the block, end processing. Note
  1237. // that empty blocks immediately end.
  1238. return todo_.FinishAction();
  1239. }
  1240. // Initialize a scope when starting a block.
  1241. if (act.pos() == 0) {
  1242. act.StartScope(RuntimeScope(&heap_));
  1243. }
  1244. // Process the next statement in the block. The position will be
  1245. // incremented as part of Spawn.
  1246. return todo_.Spawn(
  1247. std::make_unique<StatementAction>(block.statements()[act.pos()]));
  1248. }
  1249. case StatementKind::VariableDefinition: {
  1250. const auto& definition = cast<VariableDefinition>(stmt);
  1251. if (act.pos() == 0) {
  1252. // { {(var x = e) :: C, E, F} :: S, H}
  1253. // -> { {e :: (var x = []) :: C, E, F} :: S, H}
  1254. return todo_.Spawn(
  1255. std::make_unique<ExpressionAction>(&definition.init()));
  1256. } else {
  1257. // { { v :: (x = []) :: C, E, F} :: S, H}
  1258. // -> { { C, E(x := a), F} :: S, H(a := copy(v))}
  1259. CARBON_ASSIGN_OR_RETURN(
  1260. Nonnull<const Value*> v,
  1261. Convert(act.results()[0], &definition.pattern().static_type(),
  1262. stmt.source_loc()));
  1263. Nonnull<const Value*> p =
  1264. &cast<VariableDefinition>(stmt).pattern().value();
  1265. RuntimeScope matches(&heap_);
  1266. BindingMap generic_args;
  1267. CARBON_CHECK(PatternMatch(p, v, stmt.source_loc(), &matches,
  1268. generic_args, trace_stream_, this->arena_))
  1269. << stmt.source_loc()
  1270. << ": internal error in variable definition, match failed";
  1271. todo_.MergeScope(std::move(matches));
  1272. return todo_.FinishAction();
  1273. }
  1274. }
  1275. case StatementKind::ExpressionStatement:
  1276. if (act.pos() == 0) {
  1277. // { {e :: C, E, F} :: S, H}
  1278. // -> { {e :: C, E, F} :: S, H}
  1279. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1280. &cast<ExpressionStatement>(stmt).expression()));
  1281. } else {
  1282. return todo_.FinishAction();
  1283. }
  1284. case StatementKind::Assign: {
  1285. const auto& assign = cast<Assign>(stmt);
  1286. if (act.pos() == 0) {
  1287. // { {(lv = e) :: C, E, F} :: S, H}
  1288. // -> { {lv :: ([] = e) :: C, E, F} :: S, H}
  1289. return todo_.Spawn(std::make_unique<LValAction>(&assign.lhs()));
  1290. } else if (act.pos() == 1) {
  1291. // { { a :: ([] = e) :: C, E, F} :: S, H}
  1292. // -> { { e :: (a = []) :: C, E, F} :: S, H}
  1293. return todo_.Spawn(std::make_unique<ExpressionAction>(&assign.rhs()));
  1294. } else {
  1295. // { { v :: (a = []) :: C, E, F} :: S, H}
  1296. // -> { { C, E, F} :: S, H(a := v)}
  1297. const auto& lval = cast<LValue>(*act.results()[0]);
  1298. CARBON_ASSIGN_OR_RETURN(
  1299. Nonnull<const Value*> rval,
  1300. Convert(act.results()[1], &assign.lhs().static_type(),
  1301. stmt.source_loc()));
  1302. CARBON_RETURN_IF_ERROR(
  1303. heap_.Write(lval.address(), rval, stmt.source_loc()));
  1304. return todo_.FinishAction();
  1305. }
  1306. }
  1307. case StatementKind::If:
  1308. if (act.pos() == 0) {
  1309. // { {(if (e) then_stmt else else_stmt) :: C, E, F} :: S, H}
  1310. // -> { { e :: (if ([]) then_stmt else else_stmt) :: C, E, F} :: S, H}
  1311. return todo_.Spawn(
  1312. std::make_unique<ExpressionAction>(&cast<If>(stmt).condition()));
  1313. } else if (act.pos() == 1) {
  1314. CARBON_ASSIGN_OR_RETURN(
  1315. Nonnull<const Value*> condition,
  1316. Convert(act.results()[0], arena_->New<BoolType>(),
  1317. stmt.source_loc()));
  1318. if (cast<BoolValue>(*condition).value()) {
  1319. // { {true :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  1320. // S, H}
  1321. // -> { { then_stmt :: C, E, F } :: S, H}
  1322. return todo_.Spawn(
  1323. std::make_unique<StatementAction>(&cast<If>(stmt).then_block()));
  1324. } else if (cast<If>(stmt).else_block()) {
  1325. // { {false :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  1326. // S, H}
  1327. // -> { { else_stmt :: C, E, F } :: S, H}
  1328. return todo_.Spawn(
  1329. std::make_unique<StatementAction>(*cast<If>(stmt).else_block()));
  1330. } else {
  1331. return todo_.FinishAction();
  1332. }
  1333. } else {
  1334. return todo_.FinishAction();
  1335. }
  1336. case StatementKind::Return:
  1337. if (act.pos() == 0) {
  1338. // { {return e :: C, E, F} :: S, H}
  1339. // -> { {e :: return [] :: C, E, F} :: S, H}
  1340. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1341. &cast<Return>(stmt).expression()));
  1342. } else {
  1343. // { {v :: return [] :: C, E, F} :: {C', E', F'} :: S, H}
  1344. // -> { {v :: C', E', F'} :: S, H}
  1345. const FunctionDeclaration& function = cast<Return>(stmt).function();
  1346. CARBON_ASSIGN_OR_RETURN(
  1347. Nonnull<const Value*> return_value,
  1348. Convert(act.results()[0], &function.return_term().static_type(),
  1349. stmt.source_loc()));
  1350. return todo_.UnwindPast(*function.body(), return_value);
  1351. }
  1352. case StatementKind::Continuation: {
  1353. CARBON_CHECK(act.pos() == 0);
  1354. const auto& continuation = cast<Continuation>(stmt);
  1355. // Create a continuation object by creating a frame similar the
  1356. // way one is created in a function call.
  1357. auto fragment = arena_->New<ContinuationValue::StackFragment>();
  1358. stack_fragments_.push_back(fragment);
  1359. todo_.InitializeFragment(*fragment, &continuation.body());
  1360. // Bind the continuation object to the continuation variable
  1361. todo_.Initialize(&cast<Continuation>(stmt),
  1362. arena_->New<ContinuationValue>(fragment));
  1363. return todo_.FinishAction();
  1364. }
  1365. case StatementKind::Run: {
  1366. auto& run = cast<Run>(stmt);
  1367. if (act.pos() == 0) {
  1368. // Evaluate the argument of the run statement.
  1369. return todo_.Spawn(std::make_unique<ExpressionAction>(&run.argument()));
  1370. } else if (act.pos() == 1) {
  1371. // Push the continuation onto the current stack.
  1372. return todo_.Resume(cast<const ContinuationValue>(act.results()[0]));
  1373. } else {
  1374. return todo_.FinishAction();
  1375. }
  1376. }
  1377. case StatementKind::Await:
  1378. CARBON_CHECK(act.pos() == 0);
  1379. return todo_.Suspend();
  1380. }
  1381. }
  1382. auto Interpreter::StepDeclaration() -> ErrorOr<Success> {
  1383. Action& act = todo_.CurrentAction();
  1384. const Declaration& decl = cast<DeclarationAction>(act).declaration();
  1385. if (trace_stream_) {
  1386. **trace_stream_ << "--- step decl ";
  1387. decl.PrintID(**trace_stream_);
  1388. **trace_stream_ << " ." << act.pos() << ". "
  1389. << "(" << decl.source_loc() << ") --->\n";
  1390. }
  1391. switch (decl.kind()) {
  1392. case DeclarationKind::VariableDeclaration: {
  1393. const auto& var_decl = cast<VariableDeclaration>(decl);
  1394. if (var_decl.has_initializer()) {
  1395. if (act.pos() == 0) {
  1396. return todo_.Spawn(
  1397. std::make_unique<ExpressionAction>(&var_decl.initializer()));
  1398. } else {
  1399. CARBON_ASSIGN_OR_RETURN(
  1400. Nonnull<const Value*> v,
  1401. Convert(act.results()[0], &var_decl.binding().static_type(),
  1402. var_decl.source_loc()));
  1403. todo_.Initialize(&var_decl.binding(), v);
  1404. return todo_.FinishAction();
  1405. }
  1406. } else {
  1407. return todo_.FinishAction();
  1408. }
  1409. }
  1410. case DeclarationKind::FunctionDeclaration:
  1411. case DeclarationKind::ClassDeclaration:
  1412. case DeclarationKind::ChoiceDeclaration:
  1413. case DeclarationKind::InterfaceDeclaration:
  1414. case DeclarationKind::ImplDeclaration:
  1415. case DeclarationKind::SelfDeclaration:
  1416. case DeclarationKind::AliasDeclaration:
  1417. // These declarations have no run-time effects.
  1418. return todo_.FinishAction();
  1419. }
  1420. }
  1421. // State transition.
  1422. auto Interpreter::Step() -> ErrorOr<Success> {
  1423. Action& act = todo_.CurrentAction();
  1424. switch (act.kind()) {
  1425. case Action::Kind::LValAction:
  1426. CARBON_RETURN_IF_ERROR(StepLvalue());
  1427. break;
  1428. case Action::Kind::ExpressionAction:
  1429. CARBON_RETURN_IF_ERROR(StepExp());
  1430. break;
  1431. case Action::Kind::PatternAction:
  1432. CARBON_RETURN_IF_ERROR(StepPattern());
  1433. break;
  1434. case Action::Kind::StatementAction:
  1435. CARBON_RETURN_IF_ERROR(StepStmt());
  1436. break;
  1437. case Action::Kind::DeclarationAction:
  1438. CARBON_RETURN_IF_ERROR(StepDeclaration());
  1439. break;
  1440. case Action::Kind::ScopeAction:
  1441. CARBON_FATAL() << "ScopeAction escaped ActionStack";
  1442. case Action::Kind::RecursiveAction:
  1443. CARBON_FATAL() << "Tried to step a RecursiveAction";
  1444. } // switch
  1445. return Success();
  1446. }
  1447. auto Interpreter::RunAllSteps(std::unique_ptr<Action> action)
  1448. -> ErrorOr<Success> {
  1449. if (trace_stream_) {
  1450. PrintState(**trace_stream_);
  1451. }
  1452. todo_.Start(std::move(action));
  1453. while (!todo_.IsEmpty()) {
  1454. CARBON_RETURN_IF_ERROR(Step());
  1455. if (trace_stream_) {
  1456. PrintState(**trace_stream_);
  1457. }
  1458. }
  1459. return Success();
  1460. }
  1461. auto InterpProgram(const AST& ast, Nonnull<Arena*> arena,
  1462. std::optional<Nonnull<llvm::raw_ostream*>> trace_stream)
  1463. -> ErrorOr<int> {
  1464. Interpreter interpreter(Phase::RunTime, arena, trace_stream);
  1465. if (trace_stream) {
  1466. **trace_stream << "********** initializing globals **********\n";
  1467. }
  1468. for (Nonnull<Declaration*> declaration : ast.declarations) {
  1469. CARBON_RETURN_IF_ERROR(interpreter.RunAllSteps(
  1470. std::make_unique<DeclarationAction>(declaration)));
  1471. }
  1472. if (trace_stream) {
  1473. **trace_stream << "********** calling main function **********\n";
  1474. }
  1475. CARBON_RETURN_IF_ERROR(interpreter.RunAllSteps(
  1476. std::make_unique<ExpressionAction>(*ast.main_call)));
  1477. return cast<IntValue>(*interpreter.result()).value();
  1478. }
  1479. auto InterpExp(Nonnull<const Expression*> e, Nonnull<Arena*> arena,
  1480. std::optional<Nonnull<llvm::raw_ostream*>> trace_stream)
  1481. -> ErrorOr<Nonnull<const Value*>> {
  1482. Interpreter interpreter(Phase::CompileTime, arena, trace_stream);
  1483. CARBON_RETURN_IF_ERROR(
  1484. interpreter.RunAllSteps(std::make_unique<ExpressionAction>(e)));
  1485. return interpreter.result();
  1486. }
  1487. auto InterpPattern(Nonnull<const Pattern*> p, Nonnull<Arena*> arena,
  1488. std::optional<Nonnull<llvm::raw_ostream*>> trace_stream)
  1489. -> ErrorOr<Nonnull<const Value*>> {
  1490. Interpreter interpreter(Phase::CompileTime, arena, trace_stream);
  1491. CARBON_RETURN_IF_ERROR(
  1492. interpreter.RunAllSteps(std::make_unique<PatternAction>(p)));
  1493. return interpreter.result();
  1494. }
  1495. } // namespace Carbon