interpreter.cpp 42 KB

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