interpreter.cpp 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076
  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. }
  731. }
  732. void Interpreter::StepStmt() {
  733. Action& act = todo_.CurrentAction();
  734. const Statement& stmt = cast<StatementAction>(act).statement();
  735. if (trace_) {
  736. llvm::outs() << "--- step stmt ";
  737. stmt.PrintDepth(1, llvm::outs());
  738. llvm::outs() << " (" << stmt.source_loc() << ") --->\n";
  739. }
  740. switch (stmt.kind()) {
  741. case StatementKind::Match: {
  742. const auto& match_stmt = cast<Match>(stmt);
  743. if (act.pos() == 0) {
  744. // { { (match (e) ...) :: C, E, F} :: S, H}
  745. // -> { { e :: (match ([]) ...) :: C, E, F} :: S, H}
  746. act.StartScope(RuntimeScope(&heap_));
  747. return todo_.Spawn(
  748. std::make_unique<ExpressionAction>(&match_stmt.expression()));
  749. } else {
  750. int clause_num = act.pos() - 1;
  751. if (clause_num >= static_cast<int>(match_stmt.clauses().size())) {
  752. return todo_.FinishAction();
  753. }
  754. auto c = match_stmt.clauses()[clause_num];
  755. RuntimeScope matches(&heap_);
  756. if (PatternMatch(&c.pattern().value(),
  757. Convert(act.results()[0], &c.pattern().static_type()),
  758. stmt.source_loc(), &matches)) {
  759. // Ensure we don't process any more clauses.
  760. act.set_pos(match_stmt.clauses().size() + 1);
  761. todo_.MergeScope(std::move(matches));
  762. return todo_.Spawn(std::make_unique<StatementAction>(&c.statement()));
  763. } else {
  764. return todo_.RunAgain();
  765. }
  766. }
  767. }
  768. case StatementKind::While:
  769. if (act.pos() % 2 == 0) {
  770. // { { (while (e) s) :: C, E, F} :: S, H}
  771. // -> { { e :: (while ([]) s) :: C, E, F} :: S, H}
  772. act.Clear();
  773. return todo_.Spawn(
  774. std::make_unique<ExpressionAction>(&cast<While>(stmt).condition()));
  775. } else {
  776. Nonnull<const Value*> condition =
  777. Convert(act.results().back(), arena_->New<BoolType>());
  778. if (cast<BoolValue>(*condition).value()) {
  779. // { {true :: (while ([]) s) :: C, E, F} :: S, H}
  780. // -> { { s :: (while (e) s) :: C, E, F } :: S, H}
  781. return todo_.Spawn(
  782. std::make_unique<StatementAction>(&cast<While>(stmt).body()));
  783. } else {
  784. // { {false :: (while ([]) s) :: C, E, F} :: S, H}
  785. // -> { { C, E, F } :: S, H}
  786. return todo_.FinishAction();
  787. }
  788. }
  789. case StatementKind::Break: {
  790. CHECK(act.pos() == 0);
  791. // { { break; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  792. // -> { { C, E', F} :: S, H}
  793. return todo_.UnwindPast(&cast<Break>(stmt).loop());
  794. }
  795. case StatementKind::Continue: {
  796. CHECK(act.pos() == 0);
  797. // { { continue; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  798. // -> { { (while (e) s) :: C, E', F} :: S, H}
  799. return todo_.UnwindTo(&cast<Continue>(stmt).loop());
  800. }
  801. case StatementKind::Block: {
  802. const auto& block = cast<Block>(stmt);
  803. if (act.pos() >= static_cast<int>(block.statements().size())) {
  804. // If the position is past the end of the block, end processing. Note
  805. // that empty blocks immediately end.
  806. return todo_.FinishAction();
  807. }
  808. // Initialize a scope when starting a block.
  809. if (act.pos() == 0) {
  810. act.StartScope(RuntimeScope(&heap_));
  811. }
  812. // Process the next statement in the block. The position will be
  813. // incremented as part of Spawn.
  814. return todo_.Spawn(
  815. std::make_unique<StatementAction>(block.statements()[act.pos()]));
  816. }
  817. case StatementKind::VariableDefinition: {
  818. const auto& definition = cast<VariableDefinition>(stmt);
  819. if (act.pos() == 0) {
  820. // { {(var x = e) :: C, E, F} :: S, H}
  821. // -> { {e :: (var x = []) :: C, E, F} :: S, H}
  822. return todo_.Spawn(
  823. std::make_unique<ExpressionAction>(&definition.init()));
  824. } else {
  825. // { { v :: (x = []) :: C, E, F} :: S, H}
  826. // -> { { C, E(x := a), F} :: S, H(a := copy(v))}
  827. Nonnull<const Value*> v =
  828. Convert(act.results()[0], &definition.pattern().static_type());
  829. Nonnull<const Value*> p =
  830. &cast<VariableDefinition>(stmt).pattern().value();
  831. RuntimeScope matches(&heap_);
  832. CHECK(PatternMatch(p, v, stmt.source_loc(), &matches))
  833. << stmt.source_loc()
  834. << ": internal error in variable definition, match failed";
  835. todo_.MergeScope(std::move(matches));
  836. return todo_.FinishAction();
  837. }
  838. }
  839. case StatementKind::ExpressionStatement:
  840. if (act.pos() == 0) {
  841. // { {e :: C, E, F} :: S, H}
  842. // -> { {e :: C, E, F} :: S, H}
  843. return todo_.Spawn(std::make_unique<ExpressionAction>(
  844. &cast<ExpressionStatement>(stmt).expression()));
  845. } else {
  846. return todo_.FinishAction();
  847. }
  848. case StatementKind::Assign: {
  849. const auto& assign = cast<Assign>(stmt);
  850. if (act.pos() == 0) {
  851. // { {(lv = e) :: C, E, F} :: S, H}
  852. // -> { {lv :: ([] = e) :: C, E, F} :: S, H}
  853. return todo_.Spawn(std::make_unique<LValAction>(&assign.lhs()));
  854. } else if (act.pos() == 1) {
  855. // { { a :: ([] = e) :: C, E, F} :: S, H}
  856. // -> { { e :: (a = []) :: C, E, F} :: S, H}
  857. return todo_.Spawn(std::make_unique<ExpressionAction>(&assign.rhs()));
  858. } else {
  859. // { { v :: (a = []) :: C, E, F} :: S, H}
  860. // -> { { C, E, F} :: S, H(a := v)}
  861. const auto& lval = cast<LValue>(*act.results()[0]);
  862. Nonnull<const Value*> rval =
  863. Convert(act.results()[1], &assign.lhs().static_type());
  864. heap_.Write(lval.address(), rval, stmt.source_loc());
  865. return todo_.FinishAction();
  866. }
  867. }
  868. case StatementKind::If:
  869. if (act.pos() == 0) {
  870. // { {(if (e) then_stmt else else_stmt) :: C, E, F} :: S, H}
  871. // -> { { e :: (if ([]) then_stmt else else_stmt) :: C, E, F} :: S, H}
  872. return todo_.Spawn(
  873. std::make_unique<ExpressionAction>(&cast<If>(stmt).condition()));
  874. } else if (act.pos() == 1) {
  875. Nonnull<const Value*> condition =
  876. Convert(act.results()[0], arena_->New<BoolType>());
  877. if (cast<BoolValue>(*condition).value()) {
  878. // { {true :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  879. // S, H}
  880. // -> { { then_stmt :: C, E, F } :: S, H}
  881. return todo_.Spawn(
  882. std::make_unique<StatementAction>(&cast<If>(stmt).then_block()));
  883. } else if (cast<If>(stmt).else_block()) {
  884. // { {false :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  885. // S, H}
  886. // -> { { else_stmt :: C, E, F } :: S, H}
  887. return todo_.Spawn(
  888. std::make_unique<StatementAction>(*cast<If>(stmt).else_block()));
  889. } else {
  890. return todo_.FinishAction();
  891. }
  892. } else {
  893. return todo_.FinishAction();
  894. }
  895. case StatementKind::Return:
  896. if (act.pos() == 0) {
  897. // { {return e :: C, E, F} :: S, H}
  898. // -> { {e :: return [] :: C, E, F} :: S, H}
  899. return todo_.Spawn(std::make_unique<ExpressionAction>(
  900. &cast<Return>(stmt).expression()));
  901. } else {
  902. // { {v :: return [] :: C, E, F} :: {C', E', F'} :: S, H}
  903. // -> { {v :: C', E', F'} :: S, H}
  904. const FunctionDeclaration& function = cast<Return>(stmt).function();
  905. return todo_.UnwindPast(
  906. *function.body(),
  907. Convert(act.results()[0], &function.return_term().static_type()));
  908. }
  909. case StatementKind::Continuation: {
  910. CHECK(act.pos() == 0);
  911. const auto& continuation = cast<Continuation>(stmt);
  912. // Create a continuation object by creating a frame similar the
  913. // way one is created in a function call.
  914. auto fragment = arena_->New<ContinuationValue::StackFragment>();
  915. stack_fragments_.push_back(fragment);
  916. todo_.InitializeFragment(*fragment, &continuation.body());
  917. // Bind the continuation object to the continuation variable
  918. todo_.Initialize(&cast<Continuation>(stmt),
  919. arena_->New<ContinuationValue>(fragment));
  920. return todo_.FinishAction();
  921. }
  922. case StatementKind::Run: {
  923. auto& run = cast<Run>(stmt);
  924. if (act.pos() == 0) {
  925. // Evaluate the argument of the run statement.
  926. return todo_.Spawn(std::make_unique<ExpressionAction>(&run.argument()));
  927. } else if (act.pos() == 1) {
  928. // Push the continuation onto the current stack.
  929. return todo_.Resume(cast<const ContinuationValue>(act.results()[0]));
  930. } else {
  931. return todo_.FinishAction();
  932. }
  933. }
  934. case StatementKind::Await:
  935. CHECK(act.pos() == 0);
  936. return todo_.Suspend();
  937. }
  938. }
  939. void Interpreter::StepDeclaration() {
  940. Action& act = todo_.CurrentAction();
  941. const Declaration& decl = cast<DeclarationAction>(act).declaration();
  942. if (trace_) {
  943. llvm::outs() << "--- step declaration (" << decl.source_loc() << ") --->\n";
  944. }
  945. switch (decl.kind()) {
  946. case DeclarationKind::VariableDeclaration: {
  947. const auto& var_decl = cast<VariableDeclaration>(decl);
  948. if (var_decl.has_initializer()) {
  949. if (act.pos() == 0) {
  950. return todo_.Spawn(
  951. std::make_unique<ExpressionAction>(&var_decl.initializer()));
  952. } else {
  953. todo_.Initialize(&var_decl.binding(), act.results()[0]);
  954. return todo_.FinishAction();
  955. }
  956. } else {
  957. return todo_.FinishAction();
  958. }
  959. }
  960. case DeclarationKind::FunctionDeclaration:
  961. case DeclarationKind::ClassDeclaration:
  962. case DeclarationKind::ChoiceDeclaration:
  963. case DeclarationKind::InterfaceDeclaration:
  964. case DeclarationKind::ImplDeclaration:
  965. // These declarations have no run-time effects.
  966. return todo_.FinishAction();
  967. }
  968. }
  969. // State transition.
  970. void Interpreter::Step() {
  971. Action& act = todo_.CurrentAction();
  972. switch (act.kind()) {
  973. case Action::Kind::LValAction:
  974. StepLvalue();
  975. break;
  976. case Action::Kind::ExpressionAction:
  977. StepExp();
  978. break;
  979. case Action::Kind::PatternAction:
  980. StepPattern();
  981. break;
  982. case Action::Kind::StatementAction:
  983. StepStmt();
  984. break;
  985. case Action::Kind::DeclarationAction:
  986. StepDeclaration();
  987. break;
  988. case Action::Kind::ScopeAction:
  989. FATAL() << "ScopeAction escaped ActionStack";
  990. } // switch
  991. }
  992. void Interpreter::RunAllSteps(std::unique_ptr<Action> action) {
  993. if (trace_) {
  994. PrintState(llvm::outs());
  995. }
  996. todo_.Start(std::move(action));
  997. while (!todo_.IsEmpty()) {
  998. Step();
  999. if (trace_) {
  1000. PrintState(llvm::outs());
  1001. }
  1002. }
  1003. }
  1004. auto InterpProgram(const AST& ast, Nonnull<Arena*> arena, bool trace) -> int {
  1005. Interpreter interpreter(Phase::RunTime, arena, trace);
  1006. if (trace) {
  1007. llvm::outs() << "********** initializing globals **********\n";
  1008. }
  1009. for (Nonnull<Declaration*> declaration : ast.declarations) {
  1010. interpreter.RunAllSteps(std::make_unique<DeclarationAction>(declaration));
  1011. }
  1012. if (trace) {
  1013. llvm::outs() << "********** calling main function **********\n";
  1014. }
  1015. interpreter.RunAllSteps(std::make_unique<ExpressionAction>(*ast.main_call));
  1016. return cast<IntValue>(*interpreter.result()).value();
  1017. }
  1018. auto InterpExp(Nonnull<const Expression*> e, Nonnull<Arena*> arena, bool trace)
  1019. -> Nonnull<const Value*> {
  1020. Interpreter interpreter(Phase::CompileTime, arena, trace);
  1021. interpreter.RunAllSteps(std::make_unique<ExpressionAction>(e));
  1022. return interpreter.result();
  1023. }
  1024. auto InterpPattern(Nonnull<const Pattern*> p, Nonnull<Arena*> arena, bool trace)
  1025. -> Nonnull<const Value*> {
  1026. Interpreter interpreter(Phase::CompileTime, arena, trace);
  1027. interpreter.RunAllSteps(std::make_unique<PatternAction>(p));
  1028. return interpreter.result();
  1029. }
  1030. } // namespace Carbon