interpreter.cpp 41 KB

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