interpreter.cpp 43 KB

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