interpreter.cpp 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083
  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 "executable_semantics/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 "executable_semantics/ast/declaration.h"
  13. #include "executable_semantics/ast/expression.h"
  14. #include "executable_semantics/common/arena.h"
  15. #include "executable_semantics/common/error.h"
  16. #include "executable_semantics/interpreter/action.h"
  17. #include "executable_semantics/interpreter/action_stack.h"
  18. #include "executable_semantics/interpreter/stack.h"
  19. #include "llvm/ADT/StringExtras.h"
  20. #include "llvm/Support/Casting.h"
  21. using llvm::cast;
  22. using llvm::dyn_cast;
  23. using llvm::isa;
  24. namespace Carbon {
  25. // Selects between compile-time and run-time behavior.
  26. enum class Phase { CompileTime, RunTime };
  27. // Constructs an ActionStack suitable for the specified phase.
  28. static auto MakeTodo(Phase phase, Nonnull<Heap*> heap) -> ActionStack {
  29. switch (phase) {
  30. case Phase::CompileTime:
  31. return ActionStack();
  32. case Phase::RunTime:
  33. return ActionStack(heap);
  34. }
  35. }
  36. // An Interpreter represents an instance of the Carbon abstract machine. It
  37. // manages the state of the abstract machine, and executes the steps of Actions
  38. // passed to it.
  39. class Interpreter {
  40. public:
  41. // Constructs an Interpreter which allocates values on `arena`, and prints
  42. // traces if `trace` is true. `phase` indicates whether it executes at
  43. // compile time or run time.
  44. Interpreter(Phase phase, Nonnull<Arena*> arena, bool trace)
  45. : arena_(arena),
  46. heap_(arena),
  47. todo_(MakeTodo(phase, &heap_)),
  48. trace_(trace) {}
  49. ~Interpreter();
  50. // Runs all the steps of `action`.
  51. void RunAllSteps(std::unique_ptr<Action> action);
  52. // The result produced by the `action` argument of the most recent
  53. // RunAllSteps call. Cannot be called if `action` was an action that doesn't
  54. // produce results.
  55. auto result() const -> Nonnull<const Value*> { return todo_.result(); }
  56. private:
  57. void Step();
  58. // State transitions for expressions.
  59. void StepExp();
  60. // State transitions for lvalues.
  61. void StepLvalue();
  62. // State transitions for patterns.
  63. void StepPattern();
  64. // State transition for statements.
  65. void StepStmt();
  66. // State transition for declarations.
  67. void StepDeclaration();
  68. auto CreateStruct(const std::vector<FieldInitializer>& fields,
  69. const std::vector<Nonnull<const Value*>>& values)
  70. -> Nonnull<const Value*>;
  71. auto EvalPrim(Operator op, const std::vector<Nonnull<const Value*>>& args,
  72. SourceLocation source_loc) -> Nonnull<const Value*>;
  73. // Returns the result of converting `value` to type `destination_type`.
  74. auto Convert(Nonnull<const Value*> value,
  75. Nonnull<const Value*> destination_type) const
  76. -> Nonnull<const Value*>;
  77. void PrintState(llvm::raw_ostream& out);
  78. Nonnull<Arena*> arena_;
  79. Heap heap_;
  80. ActionStack todo_;
  81. // The underlying states of continuation values. All StackFragments created
  82. // during execution are tracked here, in order to safely deallocate the
  83. // contents of any non-completed continuations at the end of execution.
  84. std::vector<Nonnull<ContinuationValue::StackFragment*>> stack_fragments_;
  85. bool trace_;
  86. };
  87. Interpreter::~Interpreter() {
  88. // Clean up any remaining suspended continuations.
  89. for (Nonnull<ContinuationValue::StackFragment*> fragment : stack_fragments_) {
  90. fragment->Clear();
  91. }
  92. }
  93. //
  94. // State Operations
  95. //
  96. void Interpreter::PrintState(llvm::raw_ostream& out) {
  97. out << "{\nstack: " << todo_;
  98. out << "\nheap: " << heap_;
  99. if (!todo_.IsEmpty()) {
  100. out << "\nvalues: ";
  101. todo_.PrintScopes(out);
  102. }
  103. out << "\n}\n";
  104. }
  105. auto Interpreter::EvalPrim(Operator op,
  106. const std::vector<Nonnull<const Value*>>& args,
  107. SourceLocation source_loc) -> Nonnull<const Value*> {
  108. switch (op) {
  109. case Operator::Neg:
  110. return arena_->New<IntValue>(-cast<IntValue>(*args[0]).value());
  111. case Operator::Add:
  112. return arena_->New<IntValue>(cast<IntValue>(*args[0]).value() +
  113. cast<IntValue>(*args[1]).value());
  114. case Operator::Sub:
  115. return arena_->New<IntValue>(cast<IntValue>(*args[0]).value() -
  116. cast<IntValue>(*args[1]).value());
  117. case Operator::Mul:
  118. return arena_->New<IntValue>(cast<IntValue>(*args[0]).value() *
  119. cast<IntValue>(*args[1]).value());
  120. case Operator::Not:
  121. return arena_->New<BoolValue>(!cast<BoolValue>(*args[0]).value());
  122. case Operator::And:
  123. return arena_->New<BoolValue>(cast<BoolValue>(*args[0]).value() &&
  124. cast<BoolValue>(*args[1]).value());
  125. case Operator::Or:
  126. return arena_->New<BoolValue>(cast<BoolValue>(*args[0]).value() ||
  127. cast<BoolValue>(*args[1]).value());
  128. case Operator::Eq:
  129. return arena_->New<BoolValue>(ValueEqual(args[0], args[1]));
  130. case Operator::Ptr:
  131. return arena_->New<PointerType>(args[0]);
  132. case Operator::Deref:
  133. return heap_.Read(cast<PointerValue>(*args[0]).address(), source_loc);
  134. case Operator::AddressOf:
  135. return arena_->New<PointerValue>(cast<LValue>(*args[0]).address());
  136. }
  137. }
  138. auto Interpreter::CreateStruct(const std::vector<FieldInitializer>& fields,
  139. const std::vector<Nonnull<const Value*>>& values)
  140. -> Nonnull<const Value*> {
  141. CHECK(fields.size() == values.size());
  142. std::vector<NamedValue> elements;
  143. for (size_t i = 0; i < fields.size(); ++i) {
  144. elements.push_back({.name = fields[i].name(), .value = values[i]});
  145. }
  146. return arena_->New<StructValue>(std::move(elements));
  147. }
  148. auto PatternMatch(Nonnull<const Value*> p, Nonnull<const Value*> v,
  149. SourceLocation source_loc,
  150. std::optional<Nonnull<RuntimeScope*>> bindings) -> bool {
  151. switch (p->kind()) {
  152. case Value::Kind::BindingPlaceholderValue: {
  153. CHECK(bindings.has_value());
  154. const auto& placeholder = cast<BindingPlaceholderValue>(*p);
  155. if (placeholder.value_node().has_value()) {
  156. (*bindings)->Initialize(*placeholder.value_node(), v);
  157. }
  158. return true;
  159. }
  160. case Value::Kind::TupleValue:
  161. switch (v->kind()) {
  162. case Value::Kind::TupleValue: {
  163. const auto& p_tup = cast<TupleValue>(*p);
  164. const auto& v_tup = cast<TupleValue>(*v);
  165. CHECK(p_tup.elements().size() == v_tup.elements().size());
  166. for (size_t i = 0; i < p_tup.elements().size(); ++i) {
  167. if (!PatternMatch(p_tup.elements()[i], v_tup.elements()[i],
  168. source_loc, bindings)) {
  169. return false;
  170. }
  171. } // for
  172. return true;
  173. }
  174. default:
  175. FATAL() << "expected a tuple value in pattern, not " << *v;
  176. }
  177. case Value::Kind::StructValue: {
  178. const auto& p_struct = cast<StructValue>(*p);
  179. const auto& v_struct = cast<StructValue>(*v);
  180. CHECK(p_struct.elements().size() == v_struct.elements().size());
  181. for (size_t i = 0; i < p_struct.elements().size(); ++i) {
  182. CHECK(p_struct.elements()[i].name == v_struct.elements()[i].name);
  183. if (!PatternMatch(p_struct.elements()[i].value,
  184. v_struct.elements()[i].value, source_loc, bindings)) {
  185. return false;
  186. }
  187. }
  188. return true;
  189. }
  190. case Value::Kind::AlternativeValue:
  191. switch (v->kind()) {
  192. case Value::Kind::AlternativeValue: {
  193. const auto& p_alt = cast<AlternativeValue>(*p);
  194. const auto& v_alt = cast<AlternativeValue>(*v);
  195. if (p_alt.choice_name() != v_alt.choice_name() ||
  196. p_alt.alt_name() != v_alt.alt_name()) {
  197. return false;
  198. }
  199. return PatternMatch(&p_alt.argument(), &v_alt.argument(), source_loc,
  200. bindings);
  201. }
  202. default:
  203. FATAL() << "expected a choice alternative in pattern, not " << *v;
  204. }
  205. case Value::Kind::FunctionType:
  206. switch (v->kind()) {
  207. case Value::Kind::FunctionType: {
  208. const auto& p_fn = cast<FunctionType>(*p);
  209. const auto& v_fn = cast<FunctionType>(*v);
  210. if (!PatternMatch(&p_fn.parameters(), &v_fn.parameters(), source_loc,
  211. bindings)) {
  212. return false;
  213. }
  214. if (!PatternMatch(&p_fn.return_type(), &v_fn.return_type(),
  215. source_loc, bindings)) {
  216. return false;
  217. }
  218. return true;
  219. }
  220. default:
  221. return false;
  222. }
  223. case Value::Kind::AutoType:
  224. // `auto` matches any type, without binding any new names. We rely
  225. // on the typechecker to ensure that `v` is a type.
  226. return true;
  227. default:
  228. return ValueEqual(p, v);
  229. }
  230. }
  231. void Interpreter::StepLvalue() {
  232. Action& act = todo_.CurrentAction();
  233. const Expression& exp = cast<LValAction>(act).expression();
  234. if (trace_) {
  235. llvm::outs() << "--- step lvalue " << exp << " (" << exp.source_loc()
  236. << ") --->\n";
  237. }
  238. switch (exp.kind()) {
  239. case ExpressionKind::IdentifierExpression: {
  240. // { {x :: C, E, F} :: S, H}
  241. // -> { {E(x) :: C, E, F} :: S, H}
  242. Nonnull<const Value*> value = todo_.ValueOfNode(
  243. cast<IdentifierExpression>(exp).value_node(), exp.source_loc());
  244. CHECK(isa<LValue>(value)) << *value;
  245. return todo_.FinishAction(value);
  246. }
  247. case ExpressionKind::FieldAccessExpression: {
  248. if (act.pos() == 0) {
  249. // { {e.f :: C, E, F} :: S, H}
  250. // -> { e :: [].f :: C, E, F} :: S, H}
  251. return todo_.Spawn(std::make_unique<LValAction>(
  252. &cast<FieldAccessExpression>(exp).aggregate()));
  253. } else {
  254. // { v :: [].f :: C, E, F} :: S, H}
  255. // -> { { &v.f :: C, E, F} :: S, H }
  256. Address aggregate = cast<LValue>(*act.results()[0]).address();
  257. Address field = aggregate.SubobjectAddress(
  258. cast<FieldAccessExpression>(exp).field());
  259. return todo_.FinishAction(arena_->New<LValue>(field));
  260. }
  261. }
  262. case ExpressionKind::IndexExpression: {
  263. if (act.pos() == 0) {
  264. // { {e[i] :: C, E, F} :: S, H}
  265. // -> { e :: [][i] :: C, E, F} :: S, H}
  266. return todo_.Spawn(std::make_unique<LValAction>(
  267. &cast<IndexExpression>(exp).aggregate()));
  268. } else if (act.pos() == 1) {
  269. return todo_.Spawn(std::make_unique<ExpressionAction>(
  270. &cast<IndexExpression>(exp).offset()));
  271. } else {
  272. // { v :: [][i] :: C, E, F} :: S, H}
  273. // -> { { &v[i] :: C, E, F} :: S, H }
  274. Address aggregate = cast<LValue>(*act.results()[0]).address();
  275. std::string f =
  276. std::to_string(cast<IntValue>(*act.results()[1]).value());
  277. Address field = aggregate.SubobjectAddress(f);
  278. return todo_.FinishAction(arena_->New<LValue>(field));
  279. }
  280. }
  281. case ExpressionKind::PrimitiveOperatorExpression: {
  282. const PrimitiveOperatorExpression& op =
  283. cast<PrimitiveOperatorExpression>(exp);
  284. if (op.op() != Operator::Deref) {
  285. FATAL() << "Can't treat primitive operator expression as lvalue: "
  286. << exp;
  287. }
  288. if (act.pos() == 0) {
  289. return todo_.Spawn(
  290. std::make_unique<ExpressionAction>(op.arguments()[0]));
  291. } else {
  292. const PointerValue& res = cast<PointerValue>(*act.results()[0]);
  293. return todo_.FinishAction(arena_->New<LValue>(res.address()));
  294. }
  295. break;
  296. }
  297. case ExpressionKind::TupleLiteral:
  298. case ExpressionKind::StructLiteral:
  299. case ExpressionKind::StructTypeLiteral:
  300. case ExpressionKind::IntLiteral:
  301. case ExpressionKind::BoolLiteral:
  302. case ExpressionKind::CallExpression:
  303. case ExpressionKind::IntTypeLiteral:
  304. case ExpressionKind::BoolTypeLiteral:
  305. case ExpressionKind::TypeTypeLiteral:
  306. case ExpressionKind::FunctionTypeLiteral:
  307. case ExpressionKind::ContinuationTypeLiteral:
  308. case ExpressionKind::StringLiteral:
  309. case ExpressionKind::StringTypeLiteral:
  310. case ExpressionKind::IntrinsicExpression:
  311. case ExpressionKind::IfExpression:
  312. FATAL() << "Can't treat expression as lvalue: " << exp;
  313. case ExpressionKind::UnimplementedExpression:
  314. FATAL() << "Unimplemented: " << exp;
  315. }
  316. }
  317. auto Interpreter::Convert(Nonnull<const Value*> value,
  318. Nonnull<const Value*> destination_type) const
  319. -> Nonnull<const Value*> {
  320. switch (value->kind()) {
  321. case Value::Kind::IntValue:
  322. case Value::Kind::FunctionValue:
  323. case Value::Kind::BoundMethodValue:
  324. case Value::Kind::PointerValue:
  325. case Value::Kind::LValue:
  326. case Value::Kind::BoolValue:
  327. case Value::Kind::NominalClassValue:
  328. case Value::Kind::AlternativeValue:
  329. case Value::Kind::IntType:
  330. case Value::Kind::BoolType:
  331. case Value::Kind::TypeType:
  332. case Value::Kind::FunctionType:
  333. case Value::Kind::PointerType:
  334. case Value::Kind::AutoType:
  335. case Value::Kind::StructType:
  336. case Value::Kind::NominalClassType:
  337. case Value::Kind::InterfaceType:
  338. case Value::Kind::Witness:
  339. case Value::Kind::ChoiceType:
  340. case Value::Kind::ContinuationType:
  341. case Value::Kind::VariableType:
  342. case Value::Kind::BindingPlaceholderValue:
  343. case Value::Kind::AlternativeConstructorValue:
  344. case Value::Kind::ContinuationValue:
  345. case Value::Kind::StringType:
  346. case Value::Kind::StringValue:
  347. case Value::Kind::TypeOfClassType:
  348. case Value::Kind::TypeOfInterfaceType:
  349. case Value::Kind::TypeOfChoiceType:
  350. // TODO: add `CHECK(TypeEqual(type, value->dynamic_type()))`, once we
  351. // have Value::dynamic_type.
  352. return value;
  353. case Value::Kind::StructValue: {
  354. const auto& struct_val = cast<StructValue>(*value);
  355. switch (destination_type->kind()) {
  356. case Value::Kind::StructType: {
  357. const auto& destination_struct_type =
  358. cast<StructType>(*destination_type);
  359. std::vector<NamedValue> new_elements;
  360. for (const auto& [field_name, field_type] :
  361. destination_struct_type.fields()) {
  362. std::optional<Nonnull<const Value*>> old_value =
  363. struct_val.FindField(field_name);
  364. new_elements.push_back(
  365. {.name = field_name, .value = Convert(*old_value, field_type)});
  366. }
  367. return arena_->New<StructValue>(std::move(new_elements));
  368. }
  369. case Value::Kind::NominalClassType:
  370. return arena_->New<NominalClassValue>(destination_type, value);
  371. default:
  372. FATAL() << "Can't convert value " << *value << " to type "
  373. << *destination_type;
  374. }
  375. }
  376. case Value::Kind::TupleValue: {
  377. const auto& tuple = cast<TupleValue>(value);
  378. const auto& destination_tuple_type = cast<TupleValue>(destination_type);
  379. CHECK(tuple->elements().size() ==
  380. destination_tuple_type->elements().size());
  381. std::vector<Nonnull<const Value*>> new_elements;
  382. for (size_t i = 0; i < tuple->elements().size(); ++i) {
  383. new_elements.push_back(Convert(tuple->elements()[i],
  384. destination_tuple_type->elements()[i]));
  385. }
  386. return arena_->New<TupleValue>(std::move(new_elements));
  387. }
  388. }
  389. }
  390. void Interpreter::StepExp() {
  391. Action& act = todo_.CurrentAction();
  392. const Expression& exp = cast<ExpressionAction>(act).expression();
  393. if (trace_) {
  394. llvm::outs() << "--- step exp " << exp << " (" << exp.source_loc()
  395. << ") --->\n";
  396. }
  397. switch (exp.kind()) {
  398. case ExpressionKind::IndexExpression: {
  399. if (act.pos() == 0) {
  400. // { { e[i] :: C, E, F} :: S, H}
  401. // -> { { e :: [][i] :: C, E, F} :: S, H}
  402. return todo_.Spawn(std::make_unique<ExpressionAction>(
  403. &cast<IndexExpression>(exp).aggregate()));
  404. } else if (act.pos() == 1) {
  405. return todo_.Spawn(std::make_unique<ExpressionAction>(
  406. &cast<IndexExpression>(exp).offset()));
  407. } else {
  408. // { { v :: [][i] :: C, E, F} :: S, H}
  409. // -> { { v_i :: C, E, F} : S, H}
  410. const auto& tuple = cast<TupleValue>(*act.results()[0]);
  411. int i = cast<IntValue>(*act.results()[1]).value();
  412. if (i < 0 || i >= static_cast<int>(tuple.elements().size())) {
  413. FATAL_RUNTIME_ERROR_NO_LINE()
  414. << "index " << i << " out of range in " << tuple;
  415. }
  416. return todo_.FinishAction(tuple.elements()[i]);
  417. }
  418. }
  419. case ExpressionKind::TupleLiteral: {
  420. if (act.pos() <
  421. static_cast<int>(cast<TupleLiteral>(exp).fields().size())) {
  422. // { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
  423. // H}
  424. // -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
  425. // H}
  426. return todo_.Spawn(std::make_unique<ExpressionAction>(
  427. cast<TupleLiteral>(exp).fields()[act.pos()]));
  428. } else {
  429. return todo_.FinishAction(arena_->New<TupleValue>(act.results()));
  430. }
  431. }
  432. case ExpressionKind::StructLiteral: {
  433. const auto& literal = cast<StructLiteral>(exp);
  434. if (act.pos() < static_cast<int>(literal.fields().size())) {
  435. return todo_.Spawn(std::make_unique<ExpressionAction>(
  436. &literal.fields()[act.pos()].expression()));
  437. } else {
  438. return todo_.FinishAction(
  439. CreateStruct(literal.fields(), act.results()));
  440. }
  441. }
  442. case ExpressionKind::StructTypeLiteral: {
  443. const auto& struct_type = cast<StructTypeLiteral>(exp);
  444. if (act.pos() < static_cast<int>(struct_type.fields().size())) {
  445. return todo_.Spawn(std::make_unique<ExpressionAction>(
  446. &struct_type.fields()[act.pos()].expression()));
  447. } else {
  448. std::vector<NamedValue> fields;
  449. for (size_t i = 0; i < struct_type.fields().size(); ++i) {
  450. fields.push_back({struct_type.fields()[i].name(), act.results()[i]});
  451. }
  452. return todo_.FinishAction(arena_->New<StructType>(std::move(fields)));
  453. }
  454. }
  455. case ExpressionKind::FieldAccessExpression: {
  456. const auto& access = cast<FieldAccessExpression>(exp);
  457. if (act.pos() == 0) {
  458. // { { e.f :: C, E, F} :: S, H}
  459. // -> { { e :: [].f :: C, E, F} :: S, H}
  460. return todo_.Spawn(
  461. std::make_unique<ExpressionAction>(&access.aggregate()));
  462. } else {
  463. // { { v :: [].f :: C, E, F} :: S, H}
  464. // -> { { v_f :: C, E, F} : S, H}
  465. std::optional<Nonnull<const Witness*>> witness = std::nullopt;
  466. if (access.impl().has_value()) {
  467. auto witness_addr =
  468. todo_.ValueOfNode(*access.impl(), access.source_loc());
  469. witness = cast<Witness>(
  470. heap_.Read(llvm::cast<LValue>(witness_addr)->address(),
  471. access.source_loc()));
  472. }
  473. FieldPath::Component field(access.field(), witness);
  474. Nonnull<const Value*> member = act.results()[0]->GetField(
  475. arena_, FieldPath(field), exp.source_loc());
  476. return todo_.FinishAction(member);
  477. }
  478. }
  479. case ExpressionKind::IdentifierExpression: {
  480. CHECK(act.pos() == 0);
  481. const auto& ident = cast<IdentifierExpression>(exp);
  482. // { {x :: C, E, F} :: S, H} -> { {H(E(x)) :: C, E, F} :: S, H}
  483. Nonnull<const Value*> value =
  484. todo_.ValueOfNode(ident.value_node(), ident.source_loc());
  485. if (const auto* lvalue = dyn_cast<LValue>(value)) {
  486. value = heap_.Read(lvalue->address(), exp.source_loc());
  487. }
  488. return todo_.FinishAction(value);
  489. }
  490. case ExpressionKind::IntLiteral:
  491. CHECK(act.pos() == 0);
  492. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  493. return todo_.FinishAction(
  494. arena_->New<IntValue>(cast<IntLiteral>(exp).value()));
  495. case ExpressionKind::BoolLiteral:
  496. CHECK(act.pos() == 0);
  497. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  498. return todo_.FinishAction(
  499. arena_->New<BoolValue>(cast<BoolLiteral>(exp).value()));
  500. case ExpressionKind::PrimitiveOperatorExpression: {
  501. const auto& op = cast<PrimitiveOperatorExpression>(exp);
  502. if (act.pos() != static_cast<int>(op.arguments().size())) {
  503. // { {v :: op(vs,[],e,es) :: C, E, F} :: S, H}
  504. // -> { {e :: op(vs,v,[],es) :: C, E, F} :: S, H}
  505. Nonnull<const Expression*> arg = op.arguments()[act.pos()];
  506. if (op.op() == Operator::AddressOf) {
  507. return todo_.Spawn(std::make_unique<LValAction>(arg));
  508. } else {
  509. return todo_.Spawn(std::make_unique<ExpressionAction>(arg));
  510. }
  511. } else {
  512. // { {v :: op(vs,[]) :: C, E, F} :: S, H}
  513. // -> { {eval_prim(op, (vs,v)) :: C, E, F} :: S, H}
  514. return todo_.FinishAction(
  515. EvalPrim(op.op(), act.results(), exp.source_loc()));
  516. }
  517. }
  518. case ExpressionKind::CallExpression:
  519. if (act.pos() == 0) {
  520. // { {e1(e2) :: C, E, F} :: S, H}
  521. // -> { {e1 :: [](e2) :: C, E, F} :: S, H}
  522. return todo_.Spawn(std::make_unique<ExpressionAction>(
  523. &cast<CallExpression>(exp).function()));
  524. } else if (act.pos() == 1) {
  525. // { { v :: [](e) :: C, E, F} :: S, H}
  526. // -> { { e :: v([]) :: C, E, F} :: S, H}
  527. return todo_.Spawn(std::make_unique<ExpressionAction>(
  528. &cast<CallExpression>(exp).argument()));
  529. } else if (act.pos() == 2) {
  530. // { { v2 :: v1([]) :: C, E, F} :: S, H}
  531. // -> { {C',E',F'} :: {C, E, F} :: S, H}
  532. switch (act.results()[0]->kind()) {
  533. case Value::Kind::AlternativeConstructorValue: {
  534. const auto& alt =
  535. cast<AlternativeConstructorValue>(*act.results()[0]);
  536. return todo_.FinishAction(arena_->New<AlternativeValue>(
  537. alt.alt_name(), alt.choice_name(), act.results()[1]));
  538. }
  539. case Value::Kind::FunctionValue: {
  540. const FunctionDeclaration& function =
  541. cast<FunctionValue>(*act.results()[0]).declaration();
  542. Nonnull<const Value*> converted_args = Convert(
  543. act.results()[1], &function.param_pattern().static_type());
  544. RuntimeScope function_scope(&heap_);
  545. // Bring the impl witness tables into scope.
  546. for (const auto& [impl_bind, impl_node] :
  547. cast<CallExpression>(exp).impls()) {
  548. Nonnull<const Value*> witness =
  549. todo_.ValueOfNode(impl_node, exp.source_loc());
  550. if (witness->kind() == Value::Kind::LValue) {
  551. const LValue& lval = cast<LValue>(*witness);
  552. witness = heap_.Read(lval.address(), exp.source_loc());
  553. }
  554. function_scope.Initialize(impl_bind, witness);
  555. }
  556. CHECK(PatternMatch(&function.param_pattern().value(),
  557. converted_args, exp.source_loc(),
  558. &function_scope));
  559. CHECK(function.body().has_value())
  560. << "Calling a function that's missing a body";
  561. return todo_.Spawn(
  562. std::make_unique<StatementAction>(*function.body()),
  563. std::move(function_scope));
  564. }
  565. case Value::Kind::BoundMethodValue: {
  566. const BoundMethodValue& m =
  567. cast<BoundMethodValue>(*act.results()[0]);
  568. const FunctionDeclaration& method = m.declaration();
  569. Nonnull<const Value*> converted_args = Convert(
  570. act.results()[1], &method.param_pattern().static_type());
  571. RuntimeScope method_scope(&heap_);
  572. CHECK(PatternMatch(&method.me_pattern().value(), m.receiver(),
  573. exp.source_loc(), &method_scope));
  574. CHECK(PatternMatch(&method.param_pattern().value(), converted_args,
  575. exp.source_loc(), &method_scope));
  576. CHECK(method.body().has_value())
  577. << "Calling a method that's missing a body";
  578. return todo_.Spawn(
  579. std::make_unique<StatementAction>(*method.body()),
  580. std::move(method_scope));
  581. }
  582. default:
  583. FATAL_RUNTIME_ERROR(exp.source_loc())
  584. << "in call, expected a function, not " << *act.results()[0];
  585. }
  586. } else if (act.pos() == 3) {
  587. if (act.results().size() < 3) {
  588. // Control fell through without explicit return.
  589. return todo_.FinishAction(TupleValue::Empty());
  590. } else {
  591. return todo_.FinishAction(act.results()[2]);
  592. }
  593. } else {
  594. FATAL() << "in handle_value with Call pos " << act.pos();
  595. }
  596. case ExpressionKind::IntrinsicExpression: {
  597. const auto& intrinsic = cast<IntrinsicExpression>(exp);
  598. if (act.pos() == 0) {
  599. return todo_.Spawn(
  600. std::make_unique<ExpressionAction>(&intrinsic.args()));
  601. }
  602. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  603. switch (cast<IntrinsicExpression>(exp).intrinsic()) {
  604. case IntrinsicExpression::Intrinsic::Print: {
  605. const auto& args = cast<TupleValue>(*act.results()[0]);
  606. // TODO: This could eventually use something like llvm::formatv.
  607. llvm::outs() << cast<StringValue>(*args.elements()[0]).value();
  608. return todo_.FinishAction(TupleValue::Empty());
  609. }
  610. }
  611. }
  612. case ExpressionKind::IntTypeLiteral: {
  613. CHECK(act.pos() == 0);
  614. return todo_.FinishAction(arena_->New<IntType>());
  615. }
  616. case ExpressionKind::BoolTypeLiteral: {
  617. CHECK(act.pos() == 0);
  618. return todo_.FinishAction(arena_->New<BoolType>());
  619. }
  620. case ExpressionKind::TypeTypeLiteral: {
  621. CHECK(act.pos() == 0);
  622. return todo_.FinishAction(arena_->New<TypeType>());
  623. }
  624. case ExpressionKind::FunctionTypeLiteral: {
  625. if (act.pos() == 0) {
  626. return todo_.Spawn(std::make_unique<ExpressionAction>(
  627. &cast<FunctionTypeLiteral>(exp).parameter()));
  628. } else if (act.pos() == 1) {
  629. // { { pt :: fn [] -> e :: C, E, F} :: S, H}
  630. // -> { { e :: fn pt -> []) :: C, E, F} :: S, H}
  631. return todo_.Spawn(std::make_unique<ExpressionAction>(
  632. &cast<FunctionTypeLiteral>(exp).return_type()));
  633. } else {
  634. // { { rt :: fn pt -> [] :: C, E, F} :: S, H}
  635. // -> { fn pt -> rt :: {C, E, F} :: S, H}
  636. return todo_.FinishAction(arena_->New<FunctionType>(
  637. std::vector<Nonnull<const GenericBinding*>>(), act.results()[0],
  638. act.results()[1], std::vector<Nonnull<const ImplBinding*>>()));
  639. }
  640. }
  641. case ExpressionKind::ContinuationTypeLiteral: {
  642. CHECK(act.pos() == 0);
  643. return todo_.FinishAction(arena_->New<ContinuationType>());
  644. }
  645. case ExpressionKind::StringLiteral:
  646. CHECK(act.pos() == 0);
  647. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  648. return todo_.FinishAction(
  649. arena_->New<StringValue>(cast<StringLiteral>(exp).value()));
  650. case ExpressionKind::StringTypeLiteral: {
  651. CHECK(act.pos() == 0);
  652. return todo_.FinishAction(arena_->New<StringType>());
  653. }
  654. case ExpressionKind::IfExpression: {
  655. const auto& if_expr = cast<IfExpression>(exp);
  656. if (act.pos() == 0) {
  657. return todo_.Spawn(
  658. std::make_unique<ExpressionAction>(if_expr.condition()));
  659. } else if (act.pos() == 1) {
  660. const BoolValue& condition = cast<BoolValue>(*act.results()[0]);
  661. return todo_.Spawn(std::make_unique<ExpressionAction>(
  662. condition.value() ? if_expr.then_expression()
  663. : if_expr.else_expression()));
  664. } else {
  665. return todo_.FinishAction(act.results()[1]);
  666. }
  667. break;
  668. }
  669. case ExpressionKind::UnimplementedExpression:
  670. FATAL() << "Unimplemented: " << exp;
  671. } // switch (exp->kind)
  672. }
  673. void Interpreter::StepPattern() {
  674. Action& act = todo_.CurrentAction();
  675. const Pattern& pattern = cast<PatternAction>(act).pattern();
  676. if (trace_) {
  677. llvm::outs() << "--- step pattern " << pattern << " ("
  678. << pattern.source_loc() << ") --->\n";
  679. }
  680. switch (pattern.kind()) {
  681. case PatternKind::AutoPattern: {
  682. CHECK(act.pos() == 0);
  683. return todo_.FinishAction(arena_->New<AutoType>());
  684. }
  685. case PatternKind::BindingPattern: {
  686. const auto& binding = cast<BindingPattern>(pattern);
  687. if (binding.name() != AnonymousName) {
  688. return todo_.FinishAction(
  689. arena_->New<BindingPlaceholderValue>(&binding));
  690. } else {
  691. return todo_.FinishAction(arena_->New<BindingPlaceholderValue>());
  692. }
  693. }
  694. case PatternKind::TuplePattern: {
  695. const auto& tuple = cast<TuplePattern>(pattern);
  696. if (act.pos() < static_cast<int>(tuple.fields().size())) {
  697. // { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
  698. // H}
  699. // -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
  700. // H}
  701. return todo_.Spawn(
  702. std::make_unique<PatternAction>(tuple.fields()[act.pos()]));
  703. } else {
  704. return todo_.FinishAction(arena_->New<TupleValue>(act.results()));
  705. }
  706. }
  707. case PatternKind::AlternativePattern: {
  708. const auto& alternative = cast<AlternativePattern>(pattern);
  709. if (act.pos() == 0) {
  710. return todo_.Spawn(
  711. std::make_unique<ExpressionAction>(&alternative.choice_type()));
  712. } else if (act.pos() == 1) {
  713. return todo_.Spawn(
  714. std::make_unique<PatternAction>(&alternative.arguments()));
  715. } else {
  716. CHECK(act.pos() == 2);
  717. const auto& choice_type = cast<ChoiceType>(*act.results()[0]);
  718. return todo_.FinishAction(arena_->New<AlternativeValue>(
  719. alternative.alternative_name(), choice_type.name(),
  720. act.results()[1]));
  721. }
  722. }
  723. case PatternKind::ExpressionPattern:
  724. if (act.pos() == 0) {
  725. return todo_.Spawn(std::make_unique<ExpressionAction>(
  726. &cast<ExpressionPattern>(pattern).expression()));
  727. } else {
  728. return todo_.FinishAction(act.results()[0]);
  729. }
  730. case PatternKind::VarPattern:
  731. if (act.pos() == 0) {
  732. return todo_.Spawn(std::make_unique<PatternAction>(
  733. &cast<VarPattern>(pattern).pattern()));
  734. } else {
  735. return todo_.FinishAction(act.results()[0]);
  736. }
  737. }
  738. }
  739. void Interpreter::StepStmt() {
  740. Action& act = todo_.CurrentAction();
  741. const Statement& stmt = cast<StatementAction>(act).statement();
  742. if (trace_) {
  743. llvm::outs() << "--- step stmt ";
  744. stmt.PrintDepth(1, llvm::outs());
  745. llvm::outs() << " (" << stmt.source_loc() << ") --->\n";
  746. }
  747. switch (stmt.kind()) {
  748. case StatementKind::Match: {
  749. const auto& match_stmt = cast<Match>(stmt);
  750. if (act.pos() == 0) {
  751. // { { (match (e) ...) :: C, E, F} :: S, H}
  752. // -> { { e :: (match ([]) ...) :: C, E, F} :: S, H}
  753. act.StartScope(RuntimeScope(&heap_));
  754. return todo_.Spawn(
  755. std::make_unique<ExpressionAction>(&match_stmt.expression()));
  756. } else {
  757. int clause_num = act.pos() - 1;
  758. if (clause_num >= static_cast<int>(match_stmt.clauses().size())) {
  759. return todo_.FinishAction();
  760. }
  761. auto c = match_stmt.clauses()[clause_num];
  762. RuntimeScope matches(&heap_);
  763. if (PatternMatch(&c.pattern().value(),
  764. Convert(act.results()[0], &c.pattern().static_type()),
  765. stmt.source_loc(), &matches)) {
  766. // Ensure we don't process any more clauses.
  767. act.set_pos(match_stmt.clauses().size() + 1);
  768. todo_.MergeScope(std::move(matches));
  769. return todo_.Spawn(std::make_unique<StatementAction>(&c.statement()));
  770. } else {
  771. return todo_.RunAgain();
  772. }
  773. }
  774. }
  775. case StatementKind::While:
  776. if (act.pos() % 2 == 0) {
  777. // { { (while (e) s) :: C, E, F} :: S, H}
  778. // -> { { e :: (while ([]) s) :: C, E, F} :: S, H}
  779. act.Clear();
  780. return todo_.Spawn(
  781. std::make_unique<ExpressionAction>(&cast<While>(stmt).condition()));
  782. } else {
  783. Nonnull<const Value*> condition =
  784. Convert(act.results().back(), arena_->New<BoolType>());
  785. if (cast<BoolValue>(*condition).value()) {
  786. // { {true :: (while ([]) s) :: C, E, F} :: S, H}
  787. // -> { { s :: (while (e) s) :: C, E, F } :: S, H}
  788. return todo_.Spawn(
  789. std::make_unique<StatementAction>(&cast<While>(stmt).body()));
  790. } else {
  791. // { {false :: (while ([]) s) :: C, E, F} :: S, H}
  792. // -> { { C, E, F } :: S, H}
  793. return todo_.FinishAction();
  794. }
  795. }
  796. case StatementKind::Break: {
  797. CHECK(act.pos() == 0);
  798. // { { break; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  799. // -> { { C, E', F} :: S, H}
  800. return todo_.UnwindPast(&cast<Break>(stmt).loop());
  801. }
  802. case StatementKind::Continue: {
  803. CHECK(act.pos() == 0);
  804. // { { continue; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  805. // -> { { (while (e) s) :: C, E', F} :: S, H}
  806. return todo_.UnwindTo(&cast<Continue>(stmt).loop());
  807. }
  808. case StatementKind::Block: {
  809. const auto& block = cast<Block>(stmt);
  810. if (act.pos() >= static_cast<int>(block.statements().size())) {
  811. // If the position is past the end of the block, end processing. Note
  812. // that empty blocks immediately end.
  813. return todo_.FinishAction();
  814. }
  815. // Initialize a scope when starting a block.
  816. if (act.pos() == 0) {
  817. act.StartScope(RuntimeScope(&heap_));
  818. }
  819. // Process the next statement in the block. The position will be
  820. // incremented as part of Spawn.
  821. return todo_.Spawn(
  822. std::make_unique<StatementAction>(block.statements()[act.pos()]));
  823. }
  824. case StatementKind::VariableDefinition: {
  825. const auto& definition = cast<VariableDefinition>(stmt);
  826. if (act.pos() == 0) {
  827. // { {(var x = e) :: C, E, F} :: S, H}
  828. // -> { {e :: (var x = []) :: C, E, F} :: S, H}
  829. return todo_.Spawn(
  830. std::make_unique<ExpressionAction>(&definition.init()));
  831. } else {
  832. // { { v :: (x = []) :: C, E, F} :: S, H}
  833. // -> { { C, E(x := a), F} :: S, H(a := copy(v))}
  834. Nonnull<const Value*> v =
  835. Convert(act.results()[0], &definition.pattern().static_type());
  836. Nonnull<const Value*> p =
  837. &cast<VariableDefinition>(stmt).pattern().value();
  838. RuntimeScope matches(&heap_);
  839. CHECK(PatternMatch(p, v, stmt.source_loc(), &matches))
  840. << stmt.source_loc()
  841. << ": internal error in variable definition, match failed";
  842. todo_.MergeScope(std::move(matches));
  843. return todo_.FinishAction();
  844. }
  845. }
  846. case StatementKind::ExpressionStatement:
  847. if (act.pos() == 0) {
  848. // { {e :: C, E, F} :: S, H}
  849. // -> { {e :: C, E, F} :: S, H}
  850. return todo_.Spawn(std::make_unique<ExpressionAction>(
  851. &cast<ExpressionStatement>(stmt).expression()));
  852. } else {
  853. return todo_.FinishAction();
  854. }
  855. case StatementKind::Assign: {
  856. const auto& assign = cast<Assign>(stmt);
  857. if (act.pos() == 0) {
  858. // { {(lv = e) :: C, E, F} :: S, H}
  859. // -> { {lv :: ([] = e) :: C, E, F} :: S, H}
  860. return todo_.Spawn(std::make_unique<LValAction>(&assign.lhs()));
  861. } else if (act.pos() == 1) {
  862. // { { a :: ([] = e) :: C, E, F} :: S, H}
  863. // -> { { e :: (a = []) :: C, E, F} :: S, H}
  864. return todo_.Spawn(std::make_unique<ExpressionAction>(&assign.rhs()));
  865. } else {
  866. // { { v :: (a = []) :: C, E, F} :: S, H}
  867. // -> { { C, E, F} :: S, H(a := v)}
  868. const auto& lval = cast<LValue>(*act.results()[0]);
  869. Nonnull<const Value*> rval =
  870. Convert(act.results()[1], &assign.lhs().static_type());
  871. heap_.Write(lval.address(), rval, stmt.source_loc());
  872. return todo_.FinishAction();
  873. }
  874. }
  875. case StatementKind::If:
  876. if (act.pos() == 0) {
  877. // { {(if (e) then_stmt else else_stmt) :: C, E, F} :: S, H}
  878. // -> { { e :: (if ([]) then_stmt else else_stmt) :: C, E, F} :: S, H}
  879. return todo_.Spawn(
  880. std::make_unique<ExpressionAction>(&cast<If>(stmt).condition()));
  881. } else if (act.pos() == 1) {
  882. Nonnull<const Value*> condition =
  883. Convert(act.results()[0], arena_->New<BoolType>());
  884. if (cast<BoolValue>(*condition).value()) {
  885. // { {true :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  886. // S, H}
  887. // -> { { then_stmt :: C, E, F } :: S, H}
  888. return todo_.Spawn(
  889. std::make_unique<StatementAction>(&cast<If>(stmt).then_block()));
  890. } else if (cast<If>(stmt).else_block()) {
  891. // { {false :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  892. // S, H}
  893. // -> { { else_stmt :: C, E, F } :: S, H}
  894. return todo_.Spawn(
  895. std::make_unique<StatementAction>(*cast<If>(stmt).else_block()));
  896. } else {
  897. return todo_.FinishAction();
  898. }
  899. } else {
  900. return todo_.FinishAction();
  901. }
  902. case StatementKind::Return:
  903. if (act.pos() == 0) {
  904. // { {return e :: C, E, F} :: S, H}
  905. // -> { {e :: return [] :: C, E, F} :: S, H}
  906. return todo_.Spawn(std::make_unique<ExpressionAction>(
  907. &cast<Return>(stmt).expression()));
  908. } else {
  909. // { {v :: return [] :: C, E, F} :: {C', E', F'} :: S, H}
  910. // -> { {v :: C', E', F'} :: S, H}
  911. const FunctionDeclaration& function = cast<Return>(stmt).function();
  912. return todo_.UnwindPast(
  913. *function.body(),
  914. Convert(act.results()[0], &function.return_term().static_type()));
  915. }
  916. case StatementKind::Continuation: {
  917. CHECK(act.pos() == 0);
  918. const auto& continuation = cast<Continuation>(stmt);
  919. // Create a continuation object by creating a frame similar the
  920. // way one is created in a function call.
  921. auto fragment = arena_->New<ContinuationValue::StackFragment>();
  922. stack_fragments_.push_back(fragment);
  923. todo_.InitializeFragment(*fragment, &continuation.body());
  924. // Bind the continuation object to the continuation variable
  925. todo_.Initialize(&cast<Continuation>(stmt),
  926. arena_->New<ContinuationValue>(fragment));
  927. return todo_.FinishAction();
  928. }
  929. case StatementKind::Run: {
  930. auto& run = cast<Run>(stmt);
  931. if (act.pos() == 0) {
  932. // Evaluate the argument of the run statement.
  933. return todo_.Spawn(std::make_unique<ExpressionAction>(&run.argument()));
  934. } else if (act.pos() == 1) {
  935. // Push the continuation onto the current stack.
  936. return todo_.Resume(cast<const ContinuationValue>(act.results()[0]));
  937. } else {
  938. return todo_.FinishAction();
  939. }
  940. }
  941. case StatementKind::Await:
  942. CHECK(act.pos() == 0);
  943. return todo_.Suspend();
  944. }
  945. }
  946. void Interpreter::StepDeclaration() {
  947. Action& act = todo_.CurrentAction();
  948. const Declaration& decl = cast<DeclarationAction>(act).declaration();
  949. if (trace_) {
  950. llvm::outs() << "--- step declaration (" << decl.source_loc() << ") --->\n";
  951. }
  952. switch (decl.kind()) {
  953. case DeclarationKind::VariableDeclaration: {
  954. const auto& var_decl = cast<VariableDeclaration>(decl);
  955. if (var_decl.has_initializer()) {
  956. if (act.pos() == 0) {
  957. return todo_.Spawn(
  958. std::make_unique<ExpressionAction>(&var_decl.initializer()));
  959. } else {
  960. todo_.Initialize(&var_decl.binding(), act.results()[0]);
  961. return todo_.FinishAction();
  962. }
  963. } else {
  964. return todo_.FinishAction();
  965. }
  966. }
  967. case DeclarationKind::FunctionDeclaration:
  968. case DeclarationKind::ClassDeclaration:
  969. case DeclarationKind::ChoiceDeclaration:
  970. case DeclarationKind::InterfaceDeclaration:
  971. case DeclarationKind::ImplDeclaration:
  972. // These declarations have no run-time effects.
  973. return todo_.FinishAction();
  974. }
  975. }
  976. // State transition.
  977. void Interpreter::Step() {
  978. Action& act = todo_.CurrentAction();
  979. switch (act.kind()) {
  980. case Action::Kind::LValAction:
  981. StepLvalue();
  982. break;
  983. case Action::Kind::ExpressionAction:
  984. StepExp();
  985. break;
  986. case Action::Kind::PatternAction:
  987. StepPattern();
  988. break;
  989. case Action::Kind::StatementAction:
  990. StepStmt();
  991. break;
  992. case Action::Kind::DeclarationAction:
  993. StepDeclaration();
  994. break;
  995. case Action::Kind::ScopeAction:
  996. FATAL() << "ScopeAction escaped ActionStack";
  997. } // switch
  998. }
  999. void Interpreter::RunAllSteps(std::unique_ptr<Action> action) {
  1000. if (trace_) {
  1001. PrintState(llvm::outs());
  1002. }
  1003. todo_.Start(std::move(action));
  1004. while (!todo_.IsEmpty()) {
  1005. Step();
  1006. if (trace_) {
  1007. PrintState(llvm::outs());
  1008. }
  1009. }
  1010. }
  1011. auto InterpProgram(const AST& ast, Nonnull<Arena*> arena, bool trace) -> int {
  1012. Interpreter interpreter(Phase::RunTime, arena, trace);
  1013. if (trace) {
  1014. llvm::outs() << "********** initializing globals **********\n";
  1015. }
  1016. for (Nonnull<Declaration*> declaration : ast.declarations) {
  1017. interpreter.RunAllSteps(std::make_unique<DeclarationAction>(declaration));
  1018. }
  1019. if (trace) {
  1020. llvm::outs() << "********** calling main function **********\n";
  1021. }
  1022. interpreter.RunAllSteps(std::make_unique<ExpressionAction>(*ast.main_call));
  1023. return cast<IntValue>(*interpreter.result()).value();
  1024. }
  1025. auto InterpExp(Nonnull<const Expression*> e, Nonnull<Arena*> arena, bool trace)
  1026. -> Nonnull<const Value*> {
  1027. Interpreter interpreter(Phase::CompileTime, arena, trace);
  1028. interpreter.RunAllSteps(std::make_unique<ExpressionAction>(e));
  1029. return interpreter.result();
  1030. }
  1031. auto InterpPattern(Nonnull<const Pattern*> p, Nonnull<Arena*> arena, bool trace)
  1032. -> Nonnull<const Value*> {
  1033. Interpreter interpreter(Phase::CompileTime, arena, trace);
  1034. interpreter.RunAllSteps(std::make_unique<PatternAction>(p));
  1035. return interpreter.result();
  1036. }
  1037. } // namespace Carbon