interpreter.cpp 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191
  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 <iostream>
  6. #include <iterator>
  7. #include <list>
  8. #include <map>
  9. #include <optional>
  10. #include <utility>
  11. #include <vector>
  12. #include "common/check.h"
  13. #include "executable_semantics/ast/expression.h"
  14. #include "executable_semantics/ast/function_definition.h"
  15. #include "executable_semantics/interpreter/action.h"
  16. #include "executable_semantics/interpreter/frame.h"
  17. #include "executable_semantics/interpreter/stack.h"
  18. #include "executable_semantics/tracing_flag.h"
  19. namespace Carbon {
  20. State* state = nullptr;
  21. auto PatternMatch(const Value* pat, const Value* val, Env,
  22. std::list<std::string>*, int) -> std::optional<Env>;
  23. auto Step() -> void;
  24. //
  25. // Auxiliary Functions
  26. //
  27. void PrintEnv(Env values, std::ostream& out) {
  28. for (const auto& [name, address] : values) {
  29. out << name << ": ";
  30. state->heap.PrintAddress(address, out);
  31. out << ", ";
  32. }
  33. }
  34. //
  35. // State Operations
  36. //
  37. void PrintStack(Stack<Frame*> ls, std::ostream& out) {
  38. if (!ls.IsEmpty()) {
  39. PrintFrame(ls.Pop(), out);
  40. if (!ls.IsEmpty()) {
  41. out << " :: ";
  42. PrintStack(ls, out);
  43. }
  44. }
  45. }
  46. auto CurrentEnv(State* state) -> Env {
  47. Frame* frame = state->stack.Top();
  48. return frame->scopes.Top()->values;
  49. }
  50. void PrintState(std::ostream& out) {
  51. out << "{" << std::endl;
  52. out << "stack: ";
  53. PrintStack(state->stack, out);
  54. out << std::endl << "heap: ";
  55. state->heap.PrintHeap(out);
  56. if (!state->stack.IsEmpty() && !state->stack.Top()->scopes.IsEmpty()) {
  57. out << std::endl << "values: ";
  58. PrintEnv(CurrentEnv(state), out);
  59. }
  60. out << std::endl << "}" << std::endl;
  61. }
  62. auto EvalPrim(Operator op, const std::vector<const Value*>& args, int line_num)
  63. -> const Value* {
  64. switch (op) {
  65. case Operator::Neg:
  66. return Value::MakeIntValue(-args[0]->GetIntValue());
  67. case Operator::Add:
  68. return Value::MakeIntValue(args[0]->GetIntValue() +
  69. args[1]->GetIntValue());
  70. case Operator::Sub:
  71. return Value::MakeIntValue(args[0]->GetIntValue() -
  72. args[1]->GetIntValue());
  73. case Operator::Mul:
  74. return Value::MakeIntValue(args[0]->GetIntValue() *
  75. args[1]->GetIntValue());
  76. case Operator::Not:
  77. return Value::MakeBoolValue(!args[0]->GetBoolValue());
  78. case Operator::And:
  79. return Value::MakeBoolValue(args[0]->GetBoolValue() &&
  80. args[1]->GetBoolValue());
  81. case Operator::Or:
  82. return Value::MakeBoolValue(args[0]->GetBoolValue() ||
  83. args[1]->GetBoolValue());
  84. case Operator::Eq:
  85. return Value::MakeBoolValue(ValueEqual(args[0], args[1], line_num));
  86. case Operator::Ptr:
  87. return Value::MakePointerType(args[0]);
  88. case Operator::Deref:
  89. std::cerr << line_num << ": dereference not implemented yet\n";
  90. exit(-1);
  91. }
  92. }
  93. // Globally-defined entities, such as functions, structs, choices.
  94. static Env globals;
  95. void InitEnv(const Declaration& d, Env* env) {
  96. switch (d.tag()) {
  97. case DeclarationKind::FunctionDeclaration: {
  98. const FunctionDefinition& func_def =
  99. d.GetFunctionDeclaration().definition;
  100. auto pt = InterpExp(*env, func_def.param_pattern);
  101. auto f = Value::MakeFunctionValue(func_def.name, pt, func_def.body);
  102. Address a = state->heap.AllocateValue(f);
  103. env->Set(func_def.name, a);
  104. break;
  105. }
  106. case DeclarationKind::StructDeclaration: {
  107. const StructDefinition& struct_def = d.GetStructDeclaration().definition;
  108. VarValues fields;
  109. VarValues methods;
  110. for (const Member* m : struct_def.members) {
  111. switch (m->tag()) {
  112. case MemberKind::FieldMember: {
  113. const auto& field = m->GetFieldMember();
  114. auto t = InterpExp(Env(), field.type);
  115. fields.push_back(make_pair(field.name, t));
  116. break;
  117. }
  118. }
  119. }
  120. auto st = Value::MakeStructType(struct_def.name, std::move(fields),
  121. std::move(methods));
  122. auto a = state->heap.AllocateValue(st);
  123. env->Set(struct_def.name, a);
  124. break;
  125. }
  126. case DeclarationKind::ChoiceDeclaration: {
  127. const auto& choice = d.GetChoiceDeclaration();
  128. VarValues alts;
  129. for (const auto& [name, signature] : choice.alternatives) {
  130. auto t = InterpExp(Env(), signature);
  131. alts.push_back(make_pair(name, t));
  132. }
  133. auto ct = Value::MakeChoiceType(choice.name, std::move(alts));
  134. auto a = state->heap.AllocateValue(ct);
  135. env->Set(choice.name, a);
  136. break;
  137. }
  138. case DeclarationKind::VariableDeclaration: {
  139. const auto& var = d.GetVariableDeclaration();
  140. // Adds an entry in `globals` mapping the variable's name to the
  141. // result of evaluating the initializer.
  142. auto v = InterpExp(*env, var.initializer);
  143. Address a = state->heap.AllocateValue(v);
  144. env->Set(var.name, a);
  145. break;
  146. }
  147. }
  148. }
  149. static void InitGlobals(std::list<Declaration>* fs) {
  150. for (auto const& d : *fs) {
  151. InitEnv(d, &globals);
  152. }
  153. }
  154. // { S, H} -> { { C, E, F} :: S, H}
  155. // where C is the body of the function,
  156. // E is the environment (functions + parameters + locals)
  157. // F is the function
  158. void CallFunction(int line_num, std::vector<const Value*> operas,
  159. State* state) {
  160. switch (operas[0]->tag()) {
  161. case ValKind::FunctionValue: {
  162. // Bind arguments to parameters
  163. std::list<std::string> params;
  164. std::optional<Env> matches =
  165. PatternMatch(operas[0]->GetFunctionValue().param, operas[1], globals,
  166. &params, line_num);
  167. if (!matches) {
  168. std::cerr << "internal error in call_function, pattern match failed"
  169. << std::endl;
  170. exit(-1);
  171. }
  172. // Create the new frame and push it on the stack
  173. auto* scope = new Scope(*matches, params);
  174. auto* frame = new Frame(operas[0]->GetFunctionValue().name, Stack(scope),
  175. Stack(Action::MakeStatementAction(
  176. operas[0]->GetFunctionValue().body)));
  177. state->stack.Push(frame);
  178. break;
  179. }
  180. case ValKind::StructType: {
  181. const Value* arg = CopyVal(operas[1], line_num);
  182. const Value* sv = Value::MakeStructValue(operas[0], arg);
  183. Frame* frame = state->stack.Top();
  184. frame->todo.Push(Action::MakeValAction(sv));
  185. break;
  186. }
  187. case ValKind::AlternativeConstructorValue: {
  188. const Value* arg = CopyVal(operas[1], line_num);
  189. const Value* av = Value::MakeAlternativeValue(
  190. operas[0]->GetAlternativeConstructorValue().alt_name,
  191. operas[0]->GetAlternativeConstructorValue().choice_name, arg);
  192. Frame* frame = state->stack.Top();
  193. frame->todo.Push(Action::MakeValAction(av));
  194. break;
  195. }
  196. default:
  197. std::cerr << line_num << ": in call, expected a function, not ";
  198. PrintValue(operas[0], std::cerr);
  199. std::cerr << std::endl;
  200. exit(-1);
  201. }
  202. }
  203. void DeallocateScope(int line_num, Scope* scope) {
  204. for (const auto& l : scope->locals) {
  205. std::optional<Address> a = scope->values.Get(l);
  206. if (!a) {
  207. std::cerr << "internal error in DeallocateScope" << std::endl;
  208. exit(-1);
  209. }
  210. state->heap.Deallocate(*a);
  211. }
  212. }
  213. void DeallocateLocals(int line_num, Frame* frame) {
  214. for (auto scope : frame->scopes) {
  215. DeallocateScope(line_num, scope);
  216. }
  217. }
  218. void CreateTuple(Frame* frame, Action* act, const Expression* exp) {
  219. // { { (v1,...,vn) :: C, E, F} :: S, H}
  220. // -> { { `(v1,...,vn) :: C, E, F} :: S, H}
  221. std::vector<TupleElement> elements;
  222. auto f = exp->GetTupleLiteral().fields.begin();
  223. for (auto i = act->results.begin(); i != act->results.end(); ++i, ++f) {
  224. elements.push_back({.name = f->name, .value = *i});
  225. }
  226. const Value* tv = Value::MakeTupleValue(std::move(elements));
  227. frame->todo.Pop(1);
  228. frame->todo.Push(Action::MakeValAction(tv));
  229. }
  230. // Returns an updated environment that includes the bindings of
  231. // pattern variables to their matched values, if matching succeeds.
  232. //
  233. // The names of the pattern variables are added to the vars parameter.
  234. // Returns nullopt if the value doesn't match the pattern.
  235. auto PatternMatch(const Value* p, const Value* v, Env values,
  236. std::list<std::string>* vars, int line_num)
  237. -> std::optional<Env> {
  238. switch (p->tag()) {
  239. case ValKind::BindingPlaceholderValue: {
  240. const BindingPlaceholderValue& placeholder =
  241. p->GetBindingPlaceholderValue();
  242. if (placeholder.name.has_value()) {
  243. Address a = state->heap.AllocateValue(CopyVal(v, line_num));
  244. vars->push_back(*placeholder.name);
  245. values.Set(*placeholder.name, a);
  246. }
  247. return values;
  248. }
  249. case ValKind::TupleValue:
  250. switch (v->tag()) {
  251. case ValKind::TupleValue: {
  252. if (p->GetTupleValue().elements.size() !=
  253. v->GetTupleValue().elements.size()) {
  254. std::cerr << "runtime error: arity mismatch in tuple pattern match"
  255. << std::endl;
  256. exit(-1);
  257. }
  258. for (const TupleElement& pattern_element :
  259. p->GetTupleValue().elements) {
  260. const Value* value_field =
  261. v->GetTupleValue().FindField(pattern_element.name);
  262. if (value_field == nullptr) {
  263. std::cerr << "runtime error: field " << pattern_element.name
  264. << "not in ";
  265. PrintValue(v, std::cerr);
  266. std::cerr << std::endl;
  267. exit(-1);
  268. }
  269. std::optional<Env> matches = PatternMatch(
  270. pattern_element.value, value_field, values, vars, line_num);
  271. if (!matches) {
  272. return std::nullopt;
  273. }
  274. values = *matches;
  275. } // for
  276. return values;
  277. }
  278. default:
  279. std::cerr
  280. << "internal error, expected a tuple value in pattern, not ";
  281. PrintValue(v, std::cerr);
  282. std::cerr << std::endl;
  283. exit(-1);
  284. }
  285. case ValKind::AlternativeValue:
  286. switch (v->tag()) {
  287. case ValKind::AlternativeValue: {
  288. if (p->GetAlternativeValue().choice_name !=
  289. v->GetAlternativeValue().choice_name ||
  290. p->GetAlternativeValue().alt_name !=
  291. v->GetAlternativeValue().alt_name) {
  292. return std::nullopt;
  293. }
  294. std::optional<Env> matches = PatternMatch(
  295. p->GetAlternativeValue().argument,
  296. v->GetAlternativeValue().argument, values, vars, line_num);
  297. if (!matches) {
  298. return std::nullopt;
  299. }
  300. return *matches;
  301. }
  302. default:
  303. std::cerr
  304. << "internal error, expected a choice alternative in pattern, "
  305. "not ";
  306. PrintValue(v, std::cerr);
  307. std::cerr << std::endl;
  308. exit(-1);
  309. }
  310. case ValKind::FunctionType:
  311. switch (v->tag()) {
  312. case ValKind::FunctionType: {
  313. std::optional<Env> matches =
  314. PatternMatch(p->GetFunctionType().param,
  315. v->GetFunctionType().param, values, vars, line_num);
  316. if (!matches) {
  317. return std::nullopt;
  318. }
  319. return PatternMatch(p->GetFunctionType().ret,
  320. v->GetFunctionType().ret, *matches, vars,
  321. line_num);
  322. }
  323. default:
  324. return std::nullopt;
  325. }
  326. default:
  327. if (ValueEqual(p, v, line_num)) {
  328. return values;
  329. } else {
  330. return std::nullopt;
  331. }
  332. }
  333. }
  334. void PatternAssignment(const Value* pat, const Value* val, int line_num) {
  335. switch (pat->tag()) {
  336. case ValKind::PointerValue:
  337. state->heap.Write(pat->GetPointerValue(), CopyVal(val, line_num),
  338. line_num);
  339. break;
  340. case ValKind::TupleValue: {
  341. switch (val->tag()) {
  342. case ValKind::TupleValue: {
  343. if (pat->GetTupleValue().elements.size() !=
  344. val->GetTupleValue().elements.size()) {
  345. std::cerr << "runtime error: arity mismatch in tuple pattern match"
  346. << std::endl;
  347. exit(-1);
  348. }
  349. for (const TupleElement& pattern_element :
  350. pat->GetTupleValue().elements) {
  351. const Value* value_field =
  352. val->GetTupleValue().FindField(pattern_element.name);
  353. if (value_field == nullptr) {
  354. std::cerr << "runtime error: field " << pattern_element.name
  355. << "not in ";
  356. PrintValue(val, std::cerr);
  357. std::cerr << std::endl;
  358. exit(-1);
  359. }
  360. PatternAssignment(pattern_element.value, value_field, line_num);
  361. }
  362. break;
  363. }
  364. default:
  365. std::cerr
  366. << "internal error, expected a tuple value on right-hand-side, "
  367. "not ";
  368. PrintValue(val, std::cerr);
  369. std::cerr << std::endl;
  370. exit(-1);
  371. }
  372. break;
  373. }
  374. case ValKind::AlternativeValue: {
  375. switch (val->tag()) {
  376. case ValKind::AlternativeValue: {
  377. if (pat->GetAlternativeValue().choice_name !=
  378. val->GetAlternativeValue().choice_name ||
  379. pat->GetAlternativeValue().alt_name !=
  380. val->GetAlternativeValue().alt_name) {
  381. std::cerr << "internal error in pattern assignment" << std::endl;
  382. exit(-1);
  383. }
  384. PatternAssignment(pat->GetAlternativeValue().argument,
  385. val->GetAlternativeValue().argument, line_num);
  386. break;
  387. }
  388. default:
  389. std::cerr
  390. << "internal error, expected an alternative in left-hand-side, "
  391. "not ";
  392. PrintValue(val, std::cerr);
  393. std::cerr << std::endl;
  394. exit(-1);
  395. }
  396. break;
  397. }
  398. default:
  399. if (!ValueEqual(pat, val, line_num)) {
  400. std::cerr << "internal error in pattern assignment" << std::endl;
  401. exit(-1);
  402. }
  403. }
  404. }
  405. // State transitions for lvalues.
  406. void StepLvalue() {
  407. Frame* frame = state->stack.Top();
  408. Action* act = frame->todo.Top();
  409. const Expression* exp = act->GetLValAction().exp;
  410. if (tracing_output) {
  411. std::cout << "--- step lvalue ";
  412. PrintExp(exp);
  413. std::cout << " --->" << std::endl;
  414. }
  415. switch (exp->tag()) {
  416. case ExpressionKind::IdentifierExpression: {
  417. // { {x :: C, E, F} :: S, H}
  418. // -> { {E(x) :: C, E, F} :: S, H}
  419. std::optional<Address> pointer =
  420. CurrentEnv(state).Get(exp->GetIdentifierExpression().name);
  421. if (!pointer) {
  422. std::cerr << exp->line_num << ": could not find `"
  423. << exp->GetIdentifierExpression().name << "`" << std::endl;
  424. exit(-1);
  425. }
  426. const Value* v = Value::MakePointerValue(*pointer);
  427. frame->todo.Pop();
  428. frame->todo.Push(Action::MakeValAction(v));
  429. break;
  430. }
  431. case ExpressionKind::FieldAccessExpression: {
  432. if (act->pos == 0) {
  433. // { {e.f :: C, E, F} :: S, H}
  434. // -> { e :: [].f :: C, E, F} :: S, H}
  435. frame->todo.Push(
  436. Action::MakeLValAction(exp->GetFieldAccessExpression().aggregate));
  437. act->pos++;
  438. } else {
  439. // { v :: [].f :: C, E, F} :: S, H}
  440. // -> { { &v.f :: C, E, F} :: S, H }
  441. Address aggregate = act->results[0]->GetPointerValue();
  442. Address field =
  443. aggregate.SubobjectAddress(exp->GetFieldAccessExpression().field);
  444. frame->todo.Pop(1);
  445. frame->todo.Push(Action::MakeValAction(Value::MakePointerValue(field)));
  446. }
  447. break;
  448. }
  449. case ExpressionKind::IndexExpression: {
  450. if (act->pos == 0) {
  451. // { {e[i] :: C, E, F} :: S, H}
  452. // -> { e :: [][i] :: C, E, F} :: S, H}
  453. frame->todo.Push(
  454. Action::MakeLValAction(exp->GetIndexExpression().aggregate));
  455. act->pos++;
  456. } else if (act->pos == 1) {
  457. frame->todo.Push(
  458. Action::MakeExpressionAction(exp->GetIndexExpression().offset));
  459. act->pos++;
  460. } else if (act->pos == 2) {
  461. // { v :: [][i] :: C, E, F} :: S, H}
  462. // -> { { &v[i] :: C, E, F} :: S, H }
  463. Address aggregate = act->results[0]->GetPointerValue();
  464. std::string f = std::to_string(act->results[1]->GetIntValue());
  465. Address field = aggregate.SubobjectAddress(f);
  466. frame->todo.Pop(1);
  467. frame->todo.Push(Action::MakeValAction(Value::MakePointerValue(field)));
  468. }
  469. break;
  470. }
  471. case ExpressionKind::TupleLiteral: {
  472. if (act->pos == 0) {
  473. // { {(f1=e1,...) :: C, E, F} :: S, H}
  474. // -> { {e1 :: (f1=[],...) :: C, E, F} :: S, H}
  475. const Expression* e1 = exp->GetTupleLiteral().fields[0].expression;
  476. frame->todo.Push(Action::MakeLValAction(e1));
  477. act->pos++;
  478. } else if (act->pos !=
  479. static_cast<int>(exp->GetTupleLiteral().fields.size())) {
  480. // { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
  481. // H}
  482. // -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
  483. // H}
  484. const Expression* elt =
  485. exp->GetTupleLiteral().fields[act->pos].expression;
  486. frame->todo.Push(Action::MakeLValAction(elt));
  487. act->pos++;
  488. } else {
  489. CreateTuple(frame, act, exp);
  490. }
  491. break;
  492. }
  493. case ExpressionKind::IntLiteral:
  494. case ExpressionKind::BoolLiteral:
  495. case ExpressionKind::CallExpression:
  496. case ExpressionKind::PrimitiveOperatorExpression:
  497. case ExpressionKind::IntTypeLiteral:
  498. case ExpressionKind::BoolTypeLiteral:
  499. case ExpressionKind::TypeTypeLiteral:
  500. case ExpressionKind::FunctionTypeLiteral:
  501. case ExpressionKind::AutoTypeLiteral:
  502. case ExpressionKind::ContinuationTypeLiteral:
  503. case ExpressionKind::BindingExpression: {
  504. std::cerr << "Can't treat expression as lvalue: ";
  505. PrintExp(exp);
  506. std::cerr << std::endl;
  507. exit(-1);
  508. }
  509. }
  510. }
  511. // State transitions for expressions.
  512. void StepExp() {
  513. Frame* frame = state->stack.Top();
  514. Action* act = frame->todo.Top();
  515. const Expression* exp = act->GetExpressionAction().exp;
  516. if (tracing_output) {
  517. std::cout << "--- step exp ";
  518. PrintExp(exp);
  519. std::cout << " --->" << std::endl;
  520. }
  521. switch (exp->tag()) {
  522. case ExpressionKind::BindingExpression: {
  523. if (act->pos == 0) {
  524. frame->todo.Push(
  525. Action::MakeExpressionAction(exp->GetBindingExpression().type));
  526. act->pos++;
  527. } else {
  528. auto v = Value::MakeBindingPlaceholderValue(
  529. exp->GetBindingExpression().name, act->results[0]);
  530. frame->todo.Pop(1);
  531. frame->todo.Push(Action::MakeValAction(v));
  532. }
  533. break;
  534. }
  535. case ExpressionKind::IndexExpression: {
  536. if (act->pos == 0) {
  537. // { { e[i] :: C, E, F} :: S, H}
  538. // -> { { e :: [][i] :: C, E, F} :: S, H}
  539. frame->todo.Push(
  540. Action::MakeExpressionAction(exp->GetIndexExpression().aggregate));
  541. act->pos++;
  542. } else if (act->pos == 1) {
  543. frame->todo.Push(
  544. Action::MakeExpressionAction(exp->GetIndexExpression().offset));
  545. act->pos++;
  546. } else if (act->pos == 2) {
  547. auto tuple = act->results[0];
  548. switch (tuple->tag()) {
  549. case ValKind::TupleValue: {
  550. // { { v :: [][i] :: C, E, F} :: S, H}
  551. // -> { { v_i :: C, E, F} : S, H}
  552. std::string f = std::to_string(act->results[1]->GetIntValue());
  553. const Value* field = tuple->GetTupleValue().FindField(f);
  554. if (field == nullptr) {
  555. std::cerr << "runtime error, field " << f << " not in ";
  556. PrintValue(tuple, std::cerr);
  557. std::cerr << std::endl;
  558. exit(-1);
  559. }
  560. frame->todo.Pop(1);
  561. frame->todo.Push(Action::MakeValAction(field));
  562. break;
  563. }
  564. default:
  565. std::cerr
  566. << "runtime type error, expected a tuple in field access, "
  567. "not ";
  568. PrintValue(tuple, std::cerr);
  569. exit(-1);
  570. }
  571. }
  572. break;
  573. }
  574. case ExpressionKind::TupleLiteral: {
  575. if (act->pos == 0) {
  576. if (exp->GetTupleLiteral().fields.size() > 0) {
  577. // { {(f1=e1,...) :: C, E, F} :: S, H}
  578. // -> { {e1 :: (f1=[],...) :: C, E, F} :: S, H}
  579. const Expression* e1 = exp->GetTupleLiteral().fields[0].expression;
  580. frame->todo.Push(Action::MakeExpressionAction(e1));
  581. act->pos++;
  582. } else {
  583. CreateTuple(frame, act, exp);
  584. }
  585. } else if (act->pos !=
  586. static_cast<int>(exp->GetTupleLiteral().fields.size())) {
  587. // { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
  588. // H}
  589. // -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
  590. // H}
  591. const Expression* elt =
  592. exp->GetTupleLiteral().fields[act->pos].expression;
  593. frame->todo.Push(Action::MakeExpressionAction(elt));
  594. act->pos++;
  595. } else {
  596. CreateTuple(frame, act, exp);
  597. }
  598. break;
  599. }
  600. case ExpressionKind::FieldAccessExpression: {
  601. if (act->pos == 0) {
  602. // { { e.f :: C, E, F} :: S, H}
  603. // -> { { e :: [].f :: C, E, F} :: S, H}
  604. frame->todo.Push(Action::MakeExpressionAction(
  605. exp->GetFieldAccessExpression().aggregate));
  606. act->pos++;
  607. } else {
  608. // { { v :: [].f :: C, E, F} :: S, H}
  609. // -> { { v_f :: C, E, F} : S, H}
  610. const Value* element = act->results[0]->GetField(
  611. FieldPath(exp->GetFieldAccessExpression().field), exp->line_num);
  612. frame->todo.Pop(1);
  613. frame->todo.Push(Action::MakeValAction(element));
  614. }
  615. break;
  616. }
  617. case ExpressionKind::IdentifierExpression: {
  618. CHECK(act->pos == 0);
  619. // { {x :: C, E, F} :: S, H} -> { {H(E(x)) :: C, E, F} :: S, H}
  620. std::optional<Address> pointer =
  621. CurrentEnv(state).Get(exp->GetIdentifierExpression().name);
  622. if (!pointer) {
  623. std::cerr << exp->line_num << ": could not find `"
  624. << exp->GetIdentifierExpression().name << "`" << std::endl;
  625. exit(-1);
  626. }
  627. const Value* pointee = state->heap.Read(*pointer, exp->line_num);
  628. frame->todo.Pop(1);
  629. frame->todo.Push(Action::MakeValAction(pointee));
  630. break;
  631. }
  632. case ExpressionKind::IntLiteral:
  633. CHECK(act->pos == 0);
  634. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  635. frame->todo.Pop(1);
  636. frame->todo.Push(
  637. Action::MakeValAction(Value::MakeIntValue(exp->GetIntLiteral())));
  638. break;
  639. case ExpressionKind::BoolLiteral:
  640. CHECK(act->pos == 0);
  641. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  642. frame->todo.Pop(1);
  643. frame->todo.Push(
  644. Action::MakeValAction(Value::MakeBoolValue(exp->GetBoolLiteral())));
  645. break;
  646. case ExpressionKind::PrimitiveOperatorExpression:
  647. if (act->pos !=
  648. static_cast<int>(
  649. exp->GetPrimitiveOperatorExpression().arguments.size())) {
  650. // { {v :: op(vs,[],e,es) :: C, E, F} :: S, H}
  651. // -> { {e :: op(vs,v,[],es) :: C, E, F} :: S, H}
  652. const Expression* arg =
  653. exp->GetPrimitiveOperatorExpression().arguments[act->pos];
  654. frame->todo.Push(Action::MakeExpressionAction(arg));
  655. act->pos++;
  656. } else {
  657. // { {v :: op(vs,[]) :: C, E, F} :: S, H}
  658. // -> { {eval_prim(op, (vs,v)) :: C, E, F} :: S, H}
  659. const Value* v = EvalPrim(exp->GetPrimitiveOperatorExpression().op,
  660. act->results, exp->line_num);
  661. frame->todo.Pop(1);
  662. frame->todo.Push(Action::MakeValAction(v));
  663. }
  664. break;
  665. case ExpressionKind::CallExpression:
  666. if (act->pos == 0) {
  667. // { {e1(e2) :: C, E, F} :: S, H}
  668. // -> { {e1 :: [](e2) :: C, E, F} :: S, H}
  669. frame->todo.Push(
  670. Action::MakeExpressionAction(exp->GetCallExpression().function));
  671. act->pos++;
  672. } else if (act->pos == 1) {
  673. // { { v :: [](e) :: C, E, F} :: S, H}
  674. // -> { { e :: v([]) :: C, E, F} :: S, H}
  675. frame->todo.Push(
  676. Action::MakeExpressionAction(exp->GetCallExpression().argument));
  677. act->pos++;
  678. } else if (act->pos == 2) {
  679. // { { v2 :: v1([]) :: C, E, F} :: S, H}
  680. // -> { {C',E',F'} :: {C, E, F} :: S, H}
  681. frame->todo.Pop(1);
  682. CallFunction(exp->line_num, act->results, state);
  683. } else {
  684. std::cerr << "internal error in handle_value with Call" << std::endl;
  685. exit(-1);
  686. }
  687. break;
  688. case ExpressionKind::IntTypeLiteral: {
  689. CHECK(act->pos == 0);
  690. const Value* v = Value::MakeIntType();
  691. frame->todo.Pop(1);
  692. frame->todo.Push(Action::MakeValAction(v));
  693. break;
  694. }
  695. case ExpressionKind::BoolTypeLiteral: {
  696. CHECK(act->pos == 0);
  697. const Value* v = Value::MakeBoolType();
  698. frame->todo.Pop(1);
  699. frame->todo.Push(Action::MakeValAction(v));
  700. break;
  701. }
  702. case ExpressionKind::AutoTypeLiteral: {
  703. CHECK(act->pos == 0);
  704. const Value* v = Value::MakeAutoType();
  705. frame->todo.Pop(1);
  706. frame->todo.Push(Action::MakeValAction(v));
  707. break;
  708. }
  709. case ExpressionKind::TypeTypeLiteral: {
  710. CHECK(act->pos == 0);
  711. const Value* v = Value::MakeTypeType();
  712. frame->todo.Pop(1);
  713. frame->todo.Push(Action::MakeValAction(v));
  714. break;
  715. }
  716. case ExpressionKind::FunctionTypeLiteral: {
  717. if (act->pos == 0) {
  718. frame->todo.Push(Action::MakeExpressionAction(
  719. exp->GetFunctionTypeLiteral().parameter));
  720. act->pos++;
  721. } else if (act->pos == 1) {
  722. // { { pt :: fn [] -> e :: C, E, F} :: S, H}
  723. // -> { { e :: fn pt -> []) :: C, E, F} :: S, H}
  724. frame->todo.Push(Action::MakeExpressionAction(
  725. exp->GetFunctionTypeLiteral().return_type));
  726. act->pos++;
  727. } else if (act->pos == 2) {
  728. // { { rt :: fn pt -> [] :: C, E, F} :: S, H}
  729. // -> { fn pt -> rt :: {C, E, F} :: S, H}
  730. const Value* v =
  731. Value::MakeFunctionType(act->results[0], act->results[1]);
  732. frame->todo.Pop(1);
  733. frame->todo.Push(Action::MakeValAction(v));
  734. }
  735. break;
  736. }
  737. case ExpressionKind::ContinuationTypeLiteral: {
  738. CHECK(act->pos == 0);
  739. const Value* v = Value::MakeContinuationType();
  740. frame->todo.Pop(1);
  741. frame->todo.Push(Action::MakeValAction(v));
  742. break;
  743. }
  744. } // switch (exp->tag)
  745. }
  746. auto IsWhileAct(Action* act) -> bool {
  747. switch (act->tag()) {
  748. case ActionKind::StatementAction:
  749. switch (act->GetStatementAction().stmt->tag()) {
  750. case StatementKind::While:
  751. return true;
  752. default:
  753. return false;
  754. }
  755. default:
  756. return false;
  757. }
  758. }
  759. auto IsBlockAct(Action* act) -> bool {
  760. switch (act->tag()) {
  761. case ActionKind::StatementAction:
  762. switch (act->GetStatementAction().stmt->tag()) {
  763. case StatementKind::Block:
  764. return true;
  765. default:
  766. return false;
  767. }
  768. default:
  769. return false;
  770. }
  771. }
  772. // State transitions for statements.
  773. void StepStmt() {
  774. Frame* frame = state->stack.Top();
  775. Action* act = frame->todo.Top();
  776. const Statement* stmt = act->GetStatementAction().stmt;
  777. CHECK(stmt != nullptr && "null statement!");
  778. if (tracing_output) {
  779. std::cout << "--- step stmt ";
  780. PrintStatement(stmt, 1);
  781. std::cout << " --->" << std::endl;
  782. }
  783. switch (stmt->tag()) {
  784. case StatementKind::Match:
  785. if (act->pos == 0) {
  786. // { { (match (e) ...) :: C, E, F} :: S, H}
  787. // -> { { e :: (match ([]) ...) :: C, E, F} :: S, H}
  788. frame->todo.Push(Action::MakeExpressionAction(stmt->GetMatch().exp));
  789. act->pos++;
  790. } else {
  791. // Regarding act->pos:
  792. // * odd: start interpreting the pattern of a clause
  793. // * even: finished interpreting the pattern, now try to match
  794. //
  795. // Regarding act->results:
  796. // * 0: the value that we're matching
  797. // * 1: the pattern for clause 0
  798. // * 2: the pattern for clause 1
  799. // * ...
  800. auto clause_num = (act->pos - 1) / 2;
  801. if (clause_num >= static_cast<int>(stmt->GetMatch().clauses->size())) {
  802. frame->todo.Pop(1);
  803. break;
  804. }
  805. auto c = stmt->GetMatch().clauses->begin();
  806. std::advance(c, clause_num);
  807. if (act->pos % 2 == 1) {
  808. // start interpreting the pattern of the clause
  809. // { {v :: (match ([]) ...) :: C, E, F} :: S, H}
  810. // -> { {pi :: (match ([]) ...) :: C, E, F} :: S, H}
  811. frame->todo.Push(Action::MakeExpressionAction(c->first));
  812. act->pos++;
  813. } else { // try to match
  814. auto v = act->results[0];
  815. auto pat = act->results[clause_num + 1];
  816. auto values = CurrentEnv(state);
  817. std::list<std::string> vars;
  818. std::optional<Env> matches =
  819. PatternMatch(pat, v, values, &vars, stmt->line_num);
  820. if (matches) { // we have a match, start the body
  821. auto* new_scope = new Scope(*matches, vars);
  822. frame->scopes.Push(new_scope);
  823. const Statement* body_block =
  824. Statement::MakeBlock(stmt->line_num, c->second);
  825. Action* body_act = Action::MakeStatementAction(body_block);
  826. body_act->pos = 1;
  827. frame->todo.Pop(1);
  828. frame->todo.Push(body_act);
  829. frame->todo.Push(Action::MakeStatementAction(c->second));
  830. } else {
  831. // this case did not match, moving on
  832. act->pos++;
  833. clause_num = (act->pos - 1) / 2;
  834. if (clause_num ==
  835. static_cast<int>(stmt->GetMatch().clauses->size())) {
  836. frame->todo.Pop(2);
  837. }
  838. }
  839. }
  840. }
  841. break;
  842. case StatementKind::While:
  843. if (act->pos == 0) {
  844. // { { (while (e) s) :: C, E, F} :: S, H}
  845. // -> { { e :: (while ([]) s) :: C, E, F} :: S, H}
  846. frame->todo.Push(Action::MakeExpressionAction(stmt->GetWhile().cond));
  847. act->pos++;
  848. } else if (act->results[0]->GetBoolValue()) {
  849. // { {true :: (while ([]) s) :: C, E, F} :: S, H}
  850. // -> { { s :: (while (e) s) :: C, E, F } :: S, H}
  851. frame->todo.Top()->pos = 0;
  852. frame->todo.Top()->results.clear();
  853. frame->todo.Push(Action::MakeStatementAction(stmt->GetWhile().body));
  854. } else {
  855. // { {false :: (while ([]) s) :: C, E, F} :: S, H}
  856. // -> { { C, E, F } :: S, H}
  857. frame->todo.Top()->pos = 0;
  858. frame->todo.Top()->results.clear();
  859. frame->todo.Pop(1);
  860. }
  861. break;
  862. case StatementKind::Break:
  863. CHECK(act->pos == 0);
  864. // { { break; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  865. // -> { { C, E', F} :: S, H}
  866. frame->todo.Pop(1);
  867. while (!frame->todo.IsEmpty() && !IsWhileAct(frame->todo.Top())) {
  868. if (IsBlockAct(frame->todo.Top())) {
  869. DeallocateScope(stmt->line_num, frame->scopes.Top());
  870. frame->scopes.Pop(1);
  871. }
  872. frame->todo.Pop(1);
  873. }
  874. frame->todo.Pop(1);
  875. break;
  876. case StatementKind::Continue:
  877. CHECK(act->pos == 0);
  878. // { { continue; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  879. // -> { { (while (e) s) :: C, E', F} :: S, H}
  880. frame->todo.Pop(1);
  881. while (!frame->todo.IsEmpty() && !IsWhileAct(frame->todo.Top())) {
  882. if (IsBlockAct(frame->todo.Top())) {
  883. DeallocateScope(stmt->line_num, frame->scopes.Top());
  884. frame->scopes.Pop(1);
  885. }
  886. frame->todo.Pop(1);
  887. }
  888. break;
  889. case StatementKind::Block: {
  890. if (act->pos == 0) {
  891. if (stmt->GetBlock().stmt) {
  892. auto* scope = new Scope(CurrentEnv(state), {});
  893. frame->scopes.Push(scope);
  894. frame->todo.Push(Action::MakeStatementAction(stmt->GetBlock().stmt));
  895. act->pos++;
  896. act->pos++;
  897. } else {
  898. frame->todo.Pop();
  899. }
  900. } else {
  901. Scope* scope = frame->scopes.Top();
  902. DeallocateScope(stmt->line_num, scope);
  903. frame->scopes.Pop(1);
  904. frame->todo.Pop(1);
  905. }
  906. break;
  907. }
  908. case StatementKind::VariableDefinition:
  909. if (act->pos == 0) {
  910. // { {(var x = e) :: C, E, F} :: S, H}
  911. // -> { {e :: (var x = []) :: C, E, F} :: S, H}
  912. frame->todo.Push(
  913. Action::MakeExpressionAction(stmt->GetVariableDefinition().init));
  914. act->pos++;
  915. } else if (act->pos == 1) {
  916. frame->todo.Push(
  917. Action::MakeExpressionAction(stmt->GetVariableDefinition().pat));
  918. act->pos++;
  919. } else if (act->pos == 2) {
  920. // { { v :: (x = []) :: C, E, F} :: S, H}
  921. // -> { { C, E(x := a), F} :: S, H(a := copy(v))}
  922. const Value* v = act->results[0];
  923. const Value* p = act->results[1];
  924. std::optional<Env> matches =
  925. PatternMatch(p, v, frame->scopes.Top()->values,
  926. &frame->scopes.Top()->locals, stmt->line_num);
  927. if (!matches) {
  928. std::cerr << stmt->line_num
  929. << ": internal error in variable definition, match failed"
  930. << std::endl;
  931. exit(-1);
  932. }
  933. frame->scopes.Top()->values = *matches;
  934. frame->todo.Pop(1);
  935. }
  936. break;
  937. case StatementKind::ExpressionStatement:
  938. if (act->pos == 0) {
  939. // { {e :: C, E, F} :: S, H}
  940. // -> { {e :: C, E, F} :: S, H}
  941. frame->todo.Push(
  942. Action::MakeExpressionAction(stmt->GetExpressionStatement().exp));
  943. act->pos++;
  944. } else {
  945. frame->todo.Pop(1);
  946. }
  947. break;
  948. case StatementKind::Assign:
  949. if (act->pos == 0) {
  950. // { {(lv = e) :: C, E, F} :: S, H}
  951. // -> { {lv :: ([] = e) :: C, E, F} :: S, H}
  952. frame->todo.Push(Action::MakeLValAction(stmt->GetAssign().lhs));
  953. act->pos++;
  954. } else if (act->pos == 1) {
  955. // { { a :: ([] = e) :: C, E, F} :: S, H}
  956. // -> { { e :: (a = []) :: C, E, F} :: S, H}
  957. frame->todo.Push(Action::MakeExpressionAction(stmt->GetAssign().rhs));
  958. act->pos++;
  959. } else if (act->pos == 2) {
  960. // { { v :: (a = []) :: C, E, F} :: S, H}
  961. // -> { { C, E, F} :: S, H(a := v)}
  962. auto pat = act->results[0];
  963. auto val = act->results[1];
  964. PatternAssignment(pat, val, stmt->line_num);
  965. frame->todo.Pop(1);
  966. }
  967. break;
  968. case StatementKind::If:
  969. if (act->pos == 0) {
  970. // { {(if (e) then_stmt else else_stmt) :: C, E, F} :: S, H}
  971. // -> { { e :: (if ([]) then_stmt else else_stmt) :: C, E, F} :: S, H}
  972. frame->todo.Push(Action::MakeExpressionAction(stmt->GetIf().cond));
  973. act->pos++;
  974. } else if (act->results[0]->GetBoolValue()) {
  975. // { {true :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  976. // S, H}
  977. // -> { { then_stmt :: C, E, F } :: S, H}
  978. frame->todo.Pop(1);
  979. frame->todo.Push(Action::MakeStatementAction(stmt->GetIf().then_stmt));
  980. } else if (stmt->GetIf().else_stmt) {
  981. // { {false :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  982. // S, H}
  983. // -> { { else_stmt :: C, E, F } :: S, H}
  984. frame->todo.Pop(1);
  985. frame->todo.Push(Action::MakeStatementAction(stmt->GetIf().else_stmt));
  986. } else {
  987. frame->todo.Pop(1);
  988. }
  989. break;
  990. case StatementKind::Return:
  991. if (act->pos == 0) {
  992. // { {return e :: C, E, F} :: S, H}
  993. // -> { {e :: return [] :: C, E, F} :: S, H}
  994. frame->todo.Push(Action::MakeExpressionAction(stmt->GetReturn().exp));
  995. act->pos++;
  996. } else {
  997. // { {v :: return [] :: C, E, F} :: {C', E', F'} :: S, H}
  998. // -> { {v :: C', E', F'} :: S, H}
  999. const Value* ret_val = CopyVal(act->results[0], stmt->line_num);
  1000. DeallocateLocals(stmt->line_num, frame);
  1001. state->stack.Pop(1);
  1002. frame = state->stack.Top();
  1003. frame->todo.Push(Action::MakeValAction(ret_val));
  1004. }
  1005. break;
  1006. case StatementKind::Sequence:
  1007. CHECK(act->pos == 0);
  1008. // { { (s1,s2) :: C, E, F} :: S, H}
  1009. // -> { { s1 :: s2 :: C, E, F} :: S, H}
  1010. frame->todo.Pop(1);
  1011. if (stmt->GetSequence().next) {
  1012. frame->todo.Push(Action::MakeStatementAction(stmt->GetSequence().next));
  1013. }
  1014. frame->todo.Push(Action::MakeStatementAction(stmt->GetSequence().stmt));
  1015. break;
  1016. case StatementKind::Continuation: {
  1017. CHECK(act->pos == 0);
  1018. // Create a continuation object by creating a frame similar the
  1019. // way one is created in a function call.
  1020. Scope* scope = new Scope(CurrentEnv(state), std::list<std::string>());
  1021. Stack<Scope*> scopes;
  1022. scopes.Push(scope);
  1023. Stack<Action*> todo;
  1024. todo.Push(Action::MakeStatementAction(Statement::MakeReturn(
  1025. stmt->line_num, Expression::MakeTupleLiteral(stmt->line_num, {}))));
  1026. todo.Push(Action::MakeStatementAction(stmt->GetContinuation().body));
  1027. Frame* continuation_frame = new Frame("__continuation", scopes, todo);
  1028. Address continuation_address = state->heap.AllocateValue(
  1029. Value::MakeContinuationValue({continuation_frame}));
  1030. // Store the continuation's address in the frame.
  1031. continuation_frame->continuation = continuation_address;
  1032. // Bind the continuation object to the continuation variable
  1033. frame->scopes.Top()->values.Set(
  1034. stmt->GetContinuation().continuation_variable, continuation_address);
  1035. // Pop the continuation statement.
  1036. frame->todo.Pop();
  1037. break;
  1038. }
  1039. case StatementKind::Run:
  1040. if (act->pos == 0) {
  1041. // Evaluate the argument of the run statement.
  1042. frame->todo.Push(Action::MakeExpressionAction(stmt->GetRun().argument));
  1043. act->pos++;
  1044. } else {
  1045. frame->todo.Pop(1);
  1046. // Push an expression statement action to ignore the result
  1047. // value from the continuation.
  1048. Action* ignore_result =
  1049. Action::MakeStatementAction(Statement::MakeExpressionStatement(
  1050. stmt->line_num,
  1051. Expression::MakeTupleLiteral(stmt->line_num, {})));
  1052. ignore_result->pos = 0;
  1053. frame->todo.Push(ignore_result);
  1054. // Push the continuation onto the current stack.
  1055. const std::vector<Frame*>& continuation_vector =
  1056. act->results[0]->GetContinuationValue().stack;
  1057. for (auto frame_iter = continuation_vector.rbegin();
  1058. frame_iter != continuation_vector.rend(); ++frame_iter) {
  1059. state->stack.Push(*frame_iter);
  1060. }
  1061. }
  1062. break;
  1063. case StatementKind::Await:
  1064. CHECK(act->pos == 0);
  1065. // Pause the current continuation
  1066. frame->todo.Pop();
  1067. std::vector<Frame*> paused;
  1068. do {
  1069. paused.push_back(state->stack.Pop());
  1070. } while (paused.back()->continuation == std::nullopt);
  1071. // Update the continuation with the paused stack.
  1072. state->heap.Write(*paused.back()->continuation,
  1073. Value::MakeContinuationValue(paused), stmt->line_num);
  1074. break;
  1075. }
  1076. }
  1077. // State transition.
  1078. void Step() {
  1079. Frame* frame = state->stack.Top();
  1080. if (frame->todo.IsEmpty()) {
  1081. std::cerr << "runtime error: fell off end of function " << frame->name
  1082. << " without `return`" << std::endl;
  1083. exit(-1);
  1084. }
  1085. Action* act = frame->todo.Top();
  1086. switch (act->tag()) {
  1087. case ActionKind::ValAction: {
  1088. Action* val_act = frame->todo.Pop();
  1089. Action* act = frame->todo.Top();
  1090. act->results.push_back(val_act->GetValAction().val);
  1091. break;
  1092. }
  1093. case ActionKind::LValAction:
  1094. StepLvalue();
  1095. break;
  1096. case ActionKind::ExpressionAction:
  1097. StepExp();
  1098. break;
  1099. case ActionKind::StatementAction:
  1100. StepStmt();
  1101. break;
  1102. } // switch
  1103. }
  1104. // Interpret the whole porogram.
  1105. auto InterpProgram(std::list<Declaration>* fs) -> int {
  1106. state = new State(); // Runtime state.
  1107. if (tracing_output) {
  1108. std::cout << "********** initializing globals **********" << std::endl;
  1109. }
  1110. InitGlobals(fs);
  1111. const Expression* arg = Expression::MakeTupleLiteral(0, {});
  1112. const Expression* call_main = Expression::MakeCallExpression(
  1113. 0, Expression::MakeIdentifierExpression(0, "main"), arg);
  1114. auto todo = Stack(Action::MakeExpressionAction(call_main));
  1115. auto* scope = new Scope(globals, std::list<std::string>());
  1116. auto* frame = new Frame("top", Stack(scope), todo);
  1117. state->stack = Stack(frame);
  1118. if (tracing_output) {
  1119. std::cout << "********** calling main function **********" << std::endl;
  1120. PrintState(std::cout);
  1121. }
  1122. while (state->stack.CountExceeds(1) ||
  1123. state->stack.Top()->todo.CountExceeds(1) ||
  1124. state->stack.Top()->todo.Top()->tag() != ActionKind::ValAction) {
  1125. Step();
  1126. if (tracing_output) {
  1127. PrintState(std::cout);
  1128. }
  1129. }
  1130. const Value* v = state->stack.Top()->todo.Top()->GetValAction().val;
  1131. return v->GetIntValue();
  1132. }
  1133. // Interpret an expression at compile-time.
  1134. auto InterpExp(Env values, const Expression* e) -> const Value* {
  1135. auto todo = Stack(Action::MakeExpressionAction(e));
  1136. auto* scope = new Scope(values, std::list<std::string>());
  1137. auto* frame = new Frame("InterpExp", Stack(scope), todo);
  1138. state->stack = Stack(frame);
  1139. while (state->stack.CountExceeds(1) ||
  1140. state->stack.Top()->todo.CountExceeds(1) ||
  1141. state->stack.Top()->todo.Top()->tag() != ActionKind::ValAction) {
  1142. Step();
  1143. }
  1144. const Value* v = state->stack.Top()->todo.Top()->GetValAction().val;
  1145. return v;
  1146. }
  1147. } // namespace Carbon