interpreter.cpp 41 KB

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