interpreter.cpp 41 KB

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