interpreter.cpp 40 KB

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