interpreter.cpp 44 KB

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