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