interpreter.cpp 44 KB

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