interpreter.cpp 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251
  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 global_arena->New<IntValue>(-cast<IntValue>(*args[0]).Val());
  66. case Operator::Add:
  67. return global_arena->New<IntValue>(cast<IntValue>(*args[0]).Val() +
  68. cast<IntValue>(*args[1]).Val());
  69. case Operator::Sub:
  70. return global_arena->New<IntValue>(cast<IntValue>(*args[0]).Val() -
  71. cast<IntValue>(*args[1]).Val());
  72. case Operator::Mul:
  73. return global_arena->New<IntValue>(cast<IntValue>(*args[0]).Val() *
  74. cast<IntValue>(*args[1]).Val());
  75. case Operator::Not:
  76. return global_arena->New<BoolValue>(!cast<BoolValue>(*args[0]).Val());
  77. case Operator::And:
  78. return global_arena->New<BoolValue>(cast<BoolValue>(*args[0]).Val() &&
  79. cast<BoolValue>(*args[1]).Val());
  80. case Operator::Or:
  81. return global_arena->New<BoolValue>(cast<BoolValue>(*args[0]).Val() ||
  82. cast<BoolValue>(*args[1]).Val());
  83. case Operator::Eq:
  84. return global_arena->New<BoolValue>(
  85. ValueEqual(args[0], args[1], line_num));
  86. case Operator::Ptr:
  87. return global_arena->New<PointerType>(args[0]);
  88. case Operator::Deref:
  89. llvm::errs() << line_num << ": dereference not implemented yet\n";
  90. exit(-1);
  91. }
  92. }
  93. // Globally-defined entities, such as functions, structs, choices.
  94. static Env globals;
  95. void InitEnv(const Declaration& d, Env* env) {
  96. switch (d.tag()) {
  97. case DeclarationKind::FunctionDeclaration: {
  98. const FunctionDefinition& func_def =
  99. d.GetFunctionDeclaration().definition;
  100. Env new_env = *env;
  101. // Bring the deduced parameters into scope.
  102. for (const auto& deduced : func_def.deduced_parameters) {
  103. Address a = state->heap.AllocateValue(
  104. global_arena->New<VariableType>(deduced.name));
  105. new_env.Set(deduced.name, a);
  106. }
  107. auto pt = InterpPattern(new_env, func_def.param_pattern);
  108. auto f =
  109. global_arena->New<FunctionValue>(func_def.name, pt, func_def.body);
  110. Address a = state->heap.AllocateValue(f);
  111. env->Set(func_def.name, a);
  112. break;
  113. }
  114. case DeclarationKind::StructDeclaration: {
  115. const StructDefinition& struct_def = d.GetStructDeclaration().definition;
  116. VarValues fields;
  117. VarValues methods;
  118. for (const Member* m : struct_def.members) {
  119. switch (m->tag()) {
  120. case MemberKind::FieldMember: {
  121. const BindingPattern* binding = m->GetFieldMember().binding;
  122. const Expression* type_expression =
  123. cast<ExpressionPattern>(binding->Type())->Expression();
  124. auto type = InterpExp(Env(), type_expression);
  125. fields.push_back(make_pair(*binding->Name(), type));
  126. break;
  127. }
  128. }
  129. }
  130. auto st = global_arena->New<StructType>(
  131. struct_def.name, std::move(fields), std::move(methods));
  132. auto a = state->heap.AllocateValue(st);
  133. env->Set(struct_def.name, a);
  134. break;
  135. }
  136. case DeclarationKind::ChoiceDeclaration: {
  137. const auto& choice = d.GetChoiceDeclaration();
  138. VarValues alts;
  139. for (const auto& [name, signature] : choice.alternatives) {
  140. auto t = InterpExp(Env(), signature);
  141. alts.push_back(make_pair(name, t));
  142. }
  143. auto ct = global_arena->New<ChoiceType>(choice.name, std::move(alts));
  144. auto a = state->heap.AllocateValue(ct);
  145. env->Set(choice.name, a);
  146. break;
  147. }
  148. case DeclarationKind::VariableDeclaration: {
  149. const auto& var = d.GetVariableDeclaration();
  150. // Adds an entry in `globals` mapping the variable's name to the
  151. // result of evaluating the initializer.
  152. auto v = InterpExp(*env, var.initializer);
  153. Address a = state->heap.AllocateValue(v);
  154. env->Set(*var.binding->Name(), a);
  155. break;
  156. }
  157. }
  158. }
  159. static void InitGlobals(std::list<Declaration>* fs) {
  160. for (auto const& d : *fs) {
  161. InitEnv(d, &globals);
  162. }
  163. }
  164. // { S, H} -> { { C, E, F} :: S, H}
  165. // where C is the body of the function,
  166. // E is the environment (functions + parameters + locals)
  167. // F is the function
  168. void CallFunction(int line_num, std::vector<const Value*> operas,
  169. State* state) {
  170. switch (operas[0]->Tag()) {
  171. case Value::Kind::FunctionValue: {
  172. const auto& fn = cast<FunctionValue>(*operas[0]);
  173. // Bind arguments to parameters
  174. std::list<std::string> params;
  175. std::optional<Env> matches =
  176. PatternMatch(fn.Param(), operas[1], globals, &params, line_num);
  177. CHECK(matches) << "internal error in call_function, pattern match failed";
  178. // Create the new frame and push it on the stack
  179. auto* scope = global_arena->New<Scope>(*matches, params);
  180. auto* frame = global_arena->New<Frame>(
  181. fn.Name(), Stack(scope),
  182. Stack(Action::MakeStatementAction(fn.Body())));
  183. state->stack.Push(frame);
  184. break;
  185. }
  186. case Value::Kind::StructType: {
  187. const Value* arg = CopyVal(operas[1], line_num);
  188. const Value* sv = global_arena->New<StructValue>(operas[0], arg);
  189. Frame* frame = state->stack.Top();
  190. frame->todo.Push(Action::MakeValAction(sv));
  191. break;
  192. }
  193. case Value::Kind::AlternativeConstructorValue: {
  194. const auto& alt = cast<AlternativeConstructorValue>(*operas[0]);
  195. const Value* arg = CopyVal(operas[1], line_num);
  196. const Value* av = global_arena->New<AlternativeValue>(
  197. alt.AltName(), alt.ChoiceName(), arg);
  198. Frame* frame = state->stack.Top();
  199. frame->todo.Push(Action::MakeValAction(av));
  200. break;
  201. }
  202. default:
  203. FATAL_RUNTIME_ERROR(line_num)
  204. << "in call, expected a function, not " << *operas[0];
  205. }
  206. }
  207. void DeallocateScope(int line_num, Scope* scope) {
  208. for (const auto& l : scope->locals) {
  209. std::optional<Address> a = scope->values.Get(l);
  210. CHECK(a);
  211. state->heap.Deallocate(*a);
  212. }
  213. }
  214. void DeallocateLocals(int line_num, Frame* frame) {
  215. while (!frame->scopes.IsEmpty()) {
  216. DeallocateScope(line_num, frame->scopes.Top());
  217. frame->scopes.Pop();
  218. }
  219. }
  220. void CreateTuple(Frame* frame, Action* act, const Expression* exp) {
  221. // { { (v1,...,vn) :: C, E, F} :: S, H}
  222. // -> { { `(v1,...,vn) :: C, E, F} :: S, H}
  223. std::vector<TupleElement> elements;
  224. auto f = exp->GetTupleLiteral().fields.begin();
  225. for (auto i = act->results.begin(); i != act->results.end(); ++i, ++f) {
  226. elements.push_back({.name = f->name, .value = *i});
  227. }
  228. const Value* tv = global_arena->New<TupleValue>(std::move(elements));
  229. frame->todo.Pop(1);
  230. frame->todo.Push(Action::MakeValAction(tv));
  231. }
  232. // Returns an updated environment that includes the bindings of
  233. // pattern variables to their matched values, if matching succeeds.
  234. //
  235. // The names of the pattern variables are added to the vars parameter.
  236. // Returns nullopt if the value doesn't match the pattern.
  237. auto PatternMatch(const Value* p, const Value* v, Env values,
  238. std::list<std::string>* vars, int line_num)
  239. -> std::optional<Env> {
  240. switch (p->Tag()) {
  241. case Value::Kind::BindingPlaceholderValue: {
  242. const auto& placeholder = cast<BindingPlaceholderValue>(*p);
  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 Value::Kind::TupleValue:
  251. switch (v->Tag()) {
  252. case Value::Kind::TupleValue: {
  253. const auto& p_tup = cast<TupleValue>(*p);
  254. const auto& v_tup = cast<TupleValue>(*v);
  255. if (p_tup.Elements().size() != v_tup.Elements().size()) {
  256. FATAL_RUNTIME_ERROR(line_num)
  257. << "arity mismatch in tuple pattern match:\n pattern: "
  258. << p_tup << "\n value: " << v_tup;
  259. }
  260. for (const TupleElement& pattern_element : p_tup.Elements()) {
  261. const Value* value_field = v_tup.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 Value::Kind::AlternativeValue:
  282. switch (v->Tag()) {
  283. case Value::Kind::AlternativeValue: {
  284. const auto& p_alt = cast<AlternativeValue>(*p);
  285. const auto& v_alt = cast<AlternativeValue>(*v);
  286. if (p_alt.ChoiceName() != v_alt.ChoiceName() ||
  287. p_alt.AltName() != v_alt.AltName()) {
  288. return std::nullopt;
  289. }
  290. std::optional<Env> matches = PatternMatch(
  291. p_alt.Argument(), v_alt.Argument(), values, vars, line_num);
  292. if (!matches) {
  293. return std::nullopt;
  294. }
  295. return *matches;
  296. }
  297. default:
  298. llvm::errs()
  299. << "internal error, expected a choice alternative in pattern, "
  300. "not "
  301. << *v << "\n";
  302. exit(-1);
  303. }
  304. case Value::Kind::FunctionType:
  305. switch (v->Tag()) {
  306. case Value::Kind::FunctionType: {
  307. const auto& p_fn = cast<FunctionType>(*p);
  308. const auto& v_fn = cast<FunctionType>(*v);
  309. std::optional<Env> matches =
  310. PatternMatch(p_fn.Param(), v_fn.Param(), values, vars, line_num);
  311. if (!matches) {
  312. return std::nullopt;
  313. }
  314. return PatternMatch(p_fn.Ret(), v_fn.Ret(), *matches, vars, 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 Value::Kind::PointerValue:
  330. state->heap.Write(cast<PointerValue>(*pat).Val(), CopyVal(val, line_num),
  331. line_num);
  332. break;
  333. case Value::Kind::TupleValue: {
  334. switch (val->Tag()) {
  335. case Value::Kind::TupleValue: {
  336. const auto& pat_tup = cast<TupleValue>(*pat);
  337. const auto& val_tup = cast<TupleValue>(*val);
  338. if (pat_tup.Elements().size() != val_tup.Elements().size()) {
  339. FATAL_RUNTIME_ERROR(line_num)
  340. << "arity mismatch in tuple pattern assignment:\n pattern: "
  341. << pat_tup << "\n value: " << val_tup;
  342. }
  343. for (const TupleElement& pattern_element : pat_tup.Elements()) {
  344. const Value* value_field = val_tup.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 Value::Kind::AlternativeValue: {
  363. switch (val->Tag()) {
  364. case Value::Kind::AlternativeValue: {
  365. const auto& pat_alt = cast<AlternativeValue>(*pat);
  366. const auto& val_alt = cast<AlternativeValue>(*val);
  367. CHECK(val_alt.ChoiceName() == pat_alt.ChoiceName() &&
  368. val_alt.AltName() == pat_alt.AltName())
  369. << "internal error in pattern assignment";
  370. PatternAssignment(pat_alt.Argument(), val_alt.Argument(), line_num);
  371. break;
  372. }
  373. default:
  374. llvm::errs()
  375. << "internal error, expected an alternative in left-hand-side, "
  376. "not "
  377. << *val << "\n";
  378. exit(-1);
  379. }
  380. break;
  381. }
  382. default:
  383. CHECK(ValueEqual(pat, val, line_num))
  384. << "internal error in pattern assignment";
  385. }
  386. }
  387. // State transitions for lvalues.
  388. void StepLvalue() {
  389. Frame* frame = state->stack.Top();
  390. Action* act = frame->todo.Top();
  391. const Expression* exp = act->GetLValAction().exp;
  392. if (tracing_output) {
  393. llvm::outs() << "--- step lvalue " << *exp << " --->\n";
  394. }
  395. switch (exp->tag()) {
  396. case ExpressionKind::IdentifierExpression: {
  397. // { {x :: C, E, F} :: S, H}
  398. // -> { {E(x) :: C, E, F} :: S, H}
  399. std::optional<Address> pointer =
  400. CurrentEnv(state).Get(exp->GetIdentifierExpression().name);
  401. if (!pointer) {
  402. FATAL_RUNTIME_ERROR(exp->line_num)
  403. << ": could not find `" << exp->GetIdentifierExpression().name
  404. << "`";
  405. }
  406. const Value* v = global_arena->New<PointerValue>(*pointer);
  407. frame->todo.Pop();
  408. frame->todo.Push(Action::MakeValAction(v));
  409. break;
  410. }
  411. case ExpressionKind::FieldAccessExpression: {
  412. if (act->pos == 0) {
  413. // { {e.f :: C, E, F} :: S, H}
  414. // -> { e :: [].f :: C, E, F} :: S, H}
  415. frame->todo.Push(
  416. Action::MakeLValAction(exp->GetFieldAccessExpression().aggregate));
  417. act->pos++;
  418. } else {
  419. // { v :: [].f :: C, E, F} :: S, H}
  420. // -> { { &v.f :: C, E, F} :: S, H }
  421. Address aggregate = cast<PointerValue>(*act->results[0]).Val();
  422. Address field =
  423. aggregate.SubobjectAddress(exp->GetFieldAccessExpression().field);
  424. frame->todo.Pop(1);
  425. frame->todo.Push(
  426. Action::MakeValAction(global_arena->New<PointerValue>(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 = cast<PointerValue>(*act->results[0]).Val();
  445. std::string f = std::to_string(cast<IntValue>(*act->results[1]).Val());
  446. Address field = aggregate.SubobjectAddress(f);
  447. frame->todo.Pop(1);
  448. frame->todo.Push(
  449. Action::MakeValAction(global_arena->New<PointerValue>(field)));
  450. }
  451. break;
  452. }
  453. case ExpressionKind::TupleLiteral: {
  454. if (act->pos == 0) {
  455. // { {(f1=e1,...) :: C, E, F} :: S, H}
  456. // -> { {e1 :: (f1=[],...) :: C, E, F} :: S, H}
  457. const Expression* e1 = exp->GetTupleLiteral().fields[0].expression;
  458. frame->todo.Push(Action::MakeLValAction(e1));
  459. act->pos++;
  460. } else if (act->pos !=
  461. static_cast<int>(exp->GetTupleLiteral().fields.size())) {
  462. // { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
  463. // H}
  464. // -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
  465. // H}
  466. const Expression* elt =
  467. exp->GetTupleLiteral().fields[act->pos].expression;
  468. frame->todo.Push(Action::MakeLValAction(elt));
  469. act->pos++;
  470. } else {
  471. CreateTuple(frame, act, exp);
  472. }
  473. break;
  474. }
  475. case ExpressionKind::IntLiteral:
  476. case ExpressionKind::BoolLiteral:
  477. case ExpressionKind::CallExpression:
  478. case ExpressionKind::PrimitiveOperatorExpression:
  479. case ExpressionKind::IntTypeLiteral:
  480. case ExpressionKind::BoolTypeLiteral:
  481. case ExpressionKind::TypeTypeLiteral:
  482. case ExpressionKind::FunctionTypeLiteral:
  483. case ExpressionKind::ContinuationTypeLiteral: {
  484. FATAL_RUNTIME_ERROR_NO_LINE()
  485. << "Can't treat expression as lvalue: " << *exp;
  486. }
  487. }
  488. }
  489. // State transitions for expressions.
  490. void StepExp() {
  491. Frame* frame = state->stack.Top();
  492. Action* act = frame->todo.Top();
  493. const Expression* exp = act->GetExpressionAction().exp;
  494. if (tracing_output) {
  495. llvm::outs() << "--- step exp " << *exp << " --->\n";
  496. }
  497. switch (exp->tag()) {
  498. case ExpressionKind::IndexExpression: {
  499. if (act->pos == 0) {
  500. // { { e[i] :: C, E, F} :: S, H}
  501. // -> { { e :: [][i] :: C, E, F} :: S, H}
  502. frame->todo.Push(
  503. Action::MakeExpressionAction(exp->GetIndexExpression().aggregate));
  504. act->pos++;
  505. } else if (act->pos == 1) {
  506. frame->todo.Push(
  507. Action::MakeExpressionAction(exp->GetIndexExpression().offset));
  508. act->pos++;
  509. } else if (act->pos == 2) {
  510. auto tuple = act->results[0];
  511. switch (tuple->Tag()) {
  512. case Value::Kind::TupleValue: {
  513. // { { v :: [][i] :: C, E, F} :: S, H}
  514. // -> { { v_i :: C, E, F} : S, H}
  515. std::string f =
  516. std::to_string(cast<IntValue>(*act->results[1]).Val());
  517. const Value* field = cast<TupleValue>(*tuple).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(Action::MakeValAction(
  596. global_arena->New<IntValue>(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(Action::MakeValAction(
  603. global_arena->New<BoolValue>(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 = global_arena->New<IntType>();
  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 = global_arena->New<BoolType>();
  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 = global_arena->New<TypeType>();
  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 = global_arena->New<FunctionType>(
  683. std::vector<GenericBinding>(), 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 = global_arena->New<ContinuationType>();
  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 = global_arena->New<AutoType>();
  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 = global_arena->New<BindingPlaceholderValue>(binding.Name(),
  720. 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(
  732. global_arena->New<TupleValue>(std::vector<TupleElement>())));
  733. } else {
  734. const Pattern* p1 = tuple.Fields()[0].pattern;
  735. frame->todo.Push(Action::MakePatternAction(p1));
  736. act->pos++;
  737. }
  738. } else if (act->pos != static_cast<int>(tuple.Fields().size())) {
  739. // { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
  740. // H}
  741. // -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
  742. // H}
  743. const Pattern* elt = tuple.Fields()[act->pos].pattern;
  744. frame->todo.Push(Action::MakePatternAction(elt));
  745. act->pos++;
  746. } else {
  747. std::vector<TupleElement> elements;
  748. for (size_t i = 0; i < tuple.Fields().size(); ++i) {
  749. elements.push_back(
  750. {.name = tuple.Fields()[i].name, .value = act->results[i]});
  751. }
  752. const Value* tuple_value =
  753. global_arena->New<TupleValue>(std::move(elements));
  754. frame->todo.Pop(1);
  755. frame->todo.Push(Action::MakeValAction(tuple_value));
  756. }
  757. break;
  758. }
  759. case Pattern::Kind::AlternativePattern: {
  760. const auto& alternative = cast<AlternativePattern>(*pattern);
  761. if (act->pos == 0) {
  762. frame->todo.Push(
  763. Action::MakeExpressionAction(alternative.ChoiceType()));
  764. act->pos++;
  765. } else if (act->pos == 1) {
  766. frame->todo.Push(Action::MakePatternAction(alternative.Arguments()));
  767. act->pos++;
  768. } else {
  769. CHECK(act->pos == 2);
  770. const auto& choice_type = cast<ChoiceType>(*act->results[0]);
  771. frame->todo.Pop(1);
  772. frame->todo.Push(
  773. Action::MakeValAction(global_arena->New<AlternativeValue>(
  774. alternative.AlternativeName(), choice_type.Name(),
  775. act->results[1])));
  776. }
  777. break;
  778. }
  779. case Pattern::Kind::ExpressionPattern:
  780. frame->todo.Pop(1);
  781. frame->todo.Push(Action::MakeExpressionAction(
  782. cast<ExpressionPattern>(pattern)->Expression()));
  783. break;
  784. }
  785. }
  786. auto IsWhileAct(Action* act) -> bool {
  787. switch (act->tag()) {
  788. case ActionKind::StatementAction:
  789. switch (act->GetStatementAction().stmt->tag()) {
  790. case StatementKind::While:
  791. return true;
  792. default:
  793. return false;
  794. }
  795. default:
  796. return false;
  797. }
  798. }
  799. auto IsBlockAct(Action* act) -> bool {
  800. switch (act->tag()) {
  801. case ActionKind::StatementAction:
  802. switch (act->GetStatementAction().stmt->tag()) {
  803. case StatementKind::Block:
  804. return true;
  805. default:
  806. return false;
  807. }
  808. default:
  809. return false;
  810. }
  811. }
  812. // State transitions for statements.
  813. void StepStmt() {
  814. Frame* frame = state->stack.Top();
  815. Action* act = frame->todo.Top();
  816. const Statement* stmt = act->GetStatementAction().stmt;
  817. CHECK(stmt != nullptr) << "null statement!";
  818. if (tracing_output) {
  819. llvm::outs() << "--- step stmt ";
  820. stmt->PrintDepth(1, llvm::outs());
  821. llvm::outs() << " --->\n";
  822. }
  823. switch (stmt->tag()) {
  824. case StatementKind::Match:
  825. if (act->pos == 0) {
  826. // { { (match (e) ...) :: C, E, F} :: S, H}
  827. // -> { { e :: (match ([]) ...) :: C, E, F} :: S, H}
  828. frame->todo.Push(Action::MakeExpressionAction(stmt->GetMatch().exp));
  829. act->pos++;
  830. } else {
  831. // Regarding act->pos:
  832. // * odd: start interpreting the pattern of a clause
  833. // * even: finished interpreting the pattern, now try to match
  834. //
  835. // Regarding act->results:
  836. // * 0: the value that we're matching
  837. // * 1: the pattern for clause 0
  838. // * 2: the pattern for clause 1
  839. // * ...
  840. auto clause_num = (act->pos - 1) / 2;
  841. if (clause_num >= static_cast<int>(stmt->GetMatch().clauses->size())) {
  842. frame->todo.Pop(1);
  843. break;
  844. }
  845. auto c = stmt->GetMatch().clauses->begin();
  846. std::advance(c, clause_num);
  847. if (act->pos % 2 == 1) {
  848. // start interpreting the pattern of the clause
  849. // { {v :: (match ([]) ...) :: C, E, F} :: S, H}
  850. // -> { {pi :: (match ([]) ...) :: C, E, F} :: S, H}
  851. frame->todo.Push(Action::MakePatternAction(c->first));
  852. act->pos++;
  853. } else { // try to match
  854. auto v = act->results[0];
  855. auto pat = act->results[clause_num + 1];
  856. auto values = CurrentEnv(state);
  857. std::list<std::string> vars;
  858. std::optional<Env> matches =
  859. PatternMatch(pat, v, values, &vars, stmt->line_num);
  860. if (matches) { // we have a match, start the body
  861. auto* new_scope = global_arena->New<Scope>(*matches, vars);
  862. frame->scopes.Push(new_scope);
  863. const Statement* body_block =
  864. Statement::MakeBlock(stmt->line_num, c->second);
  865. Action* body_act = Action::MakeStatementAction(body_block);
  866. body_act->pos = 1;
  867. frame->todo.Pop(1);
  868. frame->todo.Push(body_act);
  869. frame->todo.Push(Action::MakeStatementAction(c->second));
  870. } else {
  871. // this case did not match, moving on
  872. act->pos++;
  873. clause_num = (act->pos - 1) / 2;
  874. if (clause_num ==
  875. static_cast<int>(stmt->GetMatch().clauses->size())) {
  876. frame->todo.Pop(1);
  877. }
  878. }
  879. }
  880. }
  881. break;
  882. case StatementKind::While:
  883. if (act->pos == 0) {
  884. // { { (while (e) s) :: C, E, F} :: S, H}
  885. // -> { { e :: (while ([]) s) :: C, E, F} :: S, H}
  886. frame->todo.Push(Action::MakeExpressionAction(stmt->GetWhile().cond));
  887. act->pos++;
  888. } else if (cast<BoolValue>(*act->results[0]).Val()) {
  889. // { {true :: (while ([]) s) :: C, E, F} :: S, H}
  890. // -> { { s :: (while (e) s) :: C, E, F } :: S, H}
  891. frame->todo.Top()->pos = 0;
  892. frame->todo.Top()->results.clear();
  893. frame->todo.Push(Action::MakeStatementAction(stmt->GetWhile().body));
  894. } else {
  895. // { {false :: (while ([]) s) :: C, E, F} :: S, H}
  896. // -> { { C, E, F } :: S, H}
  897. frame->todo.Top()->pos = 0;
  898. frame->todo.Top()->results.clear();
  899. frame->todo.Pop(1);
  900. }
  901. break;
  902. case StatementKind::Break:
  903. CHECK(act->pos == 0);
  904. // { { break; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  905. // -> { { C, E', F} :: S, H}
  906. frame->todo.Pop(1);
  907. while (!frame->todo.IsEmpty() && !IsWhileAct(frame->todo.Top())) {
  908. if (IsBlockAct(frame->todo.Top())) {
  909. DeallocateScope(stmt->line_num, frame->scopes.Top());
  910. frame->scopes.Pop(1);
  911. }
  912. frame->todo.Pop(1);
  913. }
  914. frame->todo.Pop(1);
  915. break;
  916. case StatementKind::Continue:
  917. CHECK(act->pos == 0);
  918. // { { continue; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  919. // -> { { (while (e) s) :: C, E', F} :: S, H}
  920. frame->todo.Pop(1);
  921. while (!frame->todo.IsEmpty() && !IsWhileAct(frame->todo.Top())) {
  922. if (IsBlockAct(frame->todo.Top())) {
  923. DeallocateScope(stmt->line_num, frame->scopes.Top());
  924. frame->scopes.Pop(1);
  925. }
  926. frame->todo.Pop(1);
  927. }
  928. break;
  929. case StatementKind::Block: {
  930. if (act->pos == 0) {
  931. if (stmt->GetBlock().stmt) {
  932. auto* scope = global_arena->New<Scope>(CurrentEnv(state),
  933. std::list<std::string>());
  934. frame->scopes.Push(scope);
  935. frame->todo.Push(Action::MakeStatementAction(stmt->GetBlock().stmt));
  936. act->pos++;
  937. act->pos++;
  938. } else {
  939. frame->todo.Pop();
  940. }
  941. } else {
  942. Scope* scope = frame->scopes.Top();
  943. DeallocateScope(stmt->line_num, scope);
  944. frame->scopes.Pop(1);
  945. frame->todo.Pop(1);
  946. }
  947. break;
  948. }
  949. case StatementKind::VariableDefinition:
  950. if (act->pos == 0) {
  951. // { {(var x = e) :: C, E, F} :: S, H}
  952. // -> { {e :: (var x = []) :: C, E, F} :: S, H}
  953. frame->todo.Push(
  954. Action::MakeExpressionAction(stmt->GetVariableDefinition().init));
  955. act->pos++;
  956. } else if (act->pos == 1) {
  957. frame->todo.Push(
  958. Action::MakePatternAction(stmt->GetVariableDefinition().pat));
  959. act->pos++;
  960. } else if (act->pos == 2) {
  961. // { { v :: (x = []) :: C, E, F} :: S, H}
  962. // -> { { C, E(x := a), F} :: S, H(a := copy(v))}
  963. const Value* v = act->results[0];
  964. const Value* p = act->results[1];
  965. std::optional<Env> matches =
  966. PatternMatch(p, v, frame->scopes.Top()->values,
  967. &frame->scopes.Top()->locals, stmt->line_num);
  968. CHECK(matches)
  969. << stmt->line_num
  970. << ": internal error in variable definition, match failed";
  971. frame->scopes.Top()->values = *matches;
  972. frame->todo.Pop(1);
  973. }
  974. break;
  975. case StatementKind::ExpressionStatement:
  976. if (act->pos == 0) {
  977. // { {e :: C, E, F} :: S, H}
  978. // -> { {e :: C, E, F} :: S, H}
  979. frame->todo.Push(
  980. Action::MakeExpressionAction(stmt->GetExpressionStatement().exp));
  981. act->pos++;
  982. } else {
  983. frame->todo.Pop(1);
  984. }
  985. break;
  986. case StatementKind::Assign:
  987. if (act->pos == 0) {
  988. // { {(lv = e) :: C, E, F} :: S, H}
  989. // -> { {lv :: ([] = e) :: C, E, F} :: S, H}
  990. frame->todo.Push(Action::MakeLValAction(stmt->GetAssign().lhs));
  991. act->pos++;
  992. } else if (act->pos == 1) {
  993. // { { a :: ([] = e) :: C, E, F} :: S, H}
  994. // -> { { e :: (a = []) :: C, E, F} :: S, H}
  995. frame->todo.Push(Action::MakeExpressionAction(stmt->GetAssign().rhs));
  996. act->pos++;
  997. } else if (act->pos == 2) {
  998. // { { v :: (a = []) :: C, E, F} :: S, H}
  999. // -> { { C, E, F} :: S, H(a := v)}
  1000. auto pat = act->results[0];
  1001. auto val = act->results[1];
  1002. PatternAssignment(pat, val, stmt->line_num);
  1003. frame->todo.Pop(1);
  1004. }
  1005. break;
  1006. case StatementKind::If:
  1007. if (act->pos == 0) {
  1008. // { {(if (e) then_stmt else else_stmt) :: C, E, F} :: S, H}
  1009. // -> { { e :: (if ([]) then_stmt else else_stmt) :: C, E, F} :: S, H}
  1010. frame->todo.Push(Action::MakeExpressionAction(stmt->GetIf().cond));
  1011. act->pos++;
  1012. } else if (cast<BoolValue>(*act->results[0]).Val()) {
  1013. // { {true :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  1014. // S, H}
  1015. // -> { { then_stmt :: C, E, F } :: S, H}
  1016. frame->todo.Pop(1);
  1017. frame->todo.Push(Action::MakeStatementAction(stmt->GetIf().then_stmt));
  1018. } else if (stmt->GetIf().else_stmt) {
  1019. // { {false :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  1020. // S, H}
  1021. // -> { { else_stmt :: C, E, F } :: S, H}
  1022. frame->todo.Pop(1);
  1023. frame->todo.Push(Action::MakeStatementAction(stmt->GetIf().else_stmt));
  1024. } else {
  1025. frame->todo.Pop(1);
  1026. }
  1027. break;
  1028. case StatementKind::Return:
  1029. if (act->pos == 0) {
  1030. // { {return e :: C, E, F} :: S, H}
  1031. // -> { {e :: return [] :: C, E, F} :: S, H}
  1032. frame->todo.Push(Action::MakeExpressionAction(stmt->GetReturn().exp));
  1033. act->pos++;
  1034. } else {
  1035. // { {v :: return [] :: C, E, F} :: {C', E', F'} :: S, H}
  1036. // -> { {v :: C', E', F'} :: S, H}
  1037. const Value* ret_val = CopyVal(act->results[0], stmt->line_num);
  1038. DeallocateLocals(stmt->line_num, frame);
  1039. state->stack.Pop(1);
  1040. frame = state->stack.Top();
  1041. frame->todo.Push(Action::MakeValAction(ret_val));
  1042. }
  1043. break;
  1044. case StatementKind::Sequence:
  1045. CHECK(act->pos == 0);
  1046. // { { (s1,s2) :: C, E, F} :: S, H}
  1047. // -> { { s1 :: s2 :: C, E, F} :: S, H}
  1048. frame->todo.Pop(1);
  1049. if (stmt->GetSequence().next) {
  1050. frame->todo.Push(Action::MakeStatementAction(stmt->GetSequence().next));
  1051. }
  1052. frame->todo.Push(Action::MakeStatementAction(stmt->GetSequence().stmt));
  1053. break;
  1054. case StatementKind::Continuation: {
  1055. CHECK(act->pos == 0);
  1056. // Create a continuation object by creating a frame similar the
  1057. // way one is created in a function call.
  1058. Scope* scope =
  1059. global_arena->New<Scope>(CurrentEnv(state), std::list<std::string>());
  1060. Stack<Scope*> scopes;
  1061. scopes.Push(scope);
  1062. Stack<Action*> todo;
  1063. todo.Push(Action::MakeStatementAction(
  1064. Statement::MakeReturn(stmt->line_num, nullptr,
  1065. /*is_omitted_exp=*/true)));
  1066. todo.Push(Action::MakeStatementAction(stmt->GetContinuation().body));
  1067. Frame* continuation_frame =
  1068. global_arena->New<Frame>("__continuation", scopes, todo);
  1069. Address continuation_address =
  1070. state->heap.AllocateValue(global_arena->New<ContinuationValue>(
  1071. std::vector<Frame*>({continuation_frame})));
  1072. // Store the continuation's address in the frame.
  1073. continuation_frame->continuation = continuation_address;
  1074. // Bind the continuation object to the continuation variable
  1075. frame->scopes.Top()->values.Set(
  1076. stmt->GetContinuation().continuation_variable, continuation_address);
  1077. // Pop the continuation statement.
  1078. frame->todo.Pop();
  1079. break;
  1080. }
  1081. case StatementKind::Run:
  1082. if (act->pos == 0) {
  1083. // Evaluate the argument of the run statement.
  1084. frame->todo.Push(Action::MakeExpressionAction(stmt->GetRun().argument));
  1085. act->pos++;
  1086. } else {
  1087. frame->todo.Pop(1);
  1088. // Push an expression statement action to ignore the result
  1089. // value from the continuation.
  1090. Action* ignore_result =
  1091. Action::MakeStatementAction(Statement::MakeExpressionStatement(
  1092. stmt->line_num,
  1093. Expression::MakeTupleLiteral(stmt->line_num, {})));
  1094. ignore_result->pos = 0;
  1095. frame->todo.Push(ignore_result);
  1096. // Push the continuation onto the current stack.
  1097. const std::vector<Frame*>& continuation_vector =
  1098. cast<ContinuationValue>(*act->results[0]).Stack();
  1099. for (auto frame_iter = continuation_vector.rbegin();
  1100. frame_iter != continuation_vector.rend(); ++frame_iter) {
  1101. state->stack.Push(*frame_iter);
  1102. }
  1103. }
  1104. break;
  1105. case StatementKind::Await:
  1106. CHECK(act->pos == 0);
  1107. // Pause the current continuation
  1108. frame->todo.Pop();
  1109. std::vector<Frame*> paused;
  1110. do {
  1111. paused.push_back(state->stack.Pop());
  1112. } while (paused.back()->continuation == std::nullopt);
  1113. // Update the continuation with the paused stack.
  1114. state->heap.Write(*paused.back()->continuation,
  1115. global_arena->New<ContinuationValue>(paused),
  1116. stmt->line_num);
  1117. break;
  1118. }
  1119. }
  1120. // State transition.
  1121. void Step() {
  1122. Frame* frame = state->stack.Top();
  1123. if (frame->todo.IsEmpty()) {
  1124. FATAL_RUNTIME_ERROR_NO_LINE()
  1125. << "fell off end of function " << frame->name << " without `return`";
  1126. }
  1127. Action* act = frame->todo.Top();
  1128. switch (act->tag()) {
  1129. case ActionKind::ValAction: {
  1130. Action* val_act = frame->todo.Pop();
  1131. Action* act = frame->todo.Top();
  1132. act->results.push_back(val_act->GetValAction().val);
  1133. break;
  1134. }
  1135. case ActionKind::LValAction:
  1136. StepLvalue();
  1137. break;
  1138. case ActionKind::ExpressionAction:
  1139. StepExp();
  1140. break;
  1141. case ActionKind::PatternAction:
  1142. StepPattern();
  1143. break;
  1144. case ActionKind::StatementAction:
  1145. StepStmt();
  1146. break;
  1147. } // switch
  1148. }
  1149. // Interpret the whole porogram.
  1150. auto InterpProgram(std::list<Declaration>* fs) -> int {
  1151. state = global_arena->New<State>(); // Runtime state.
  1152. if (tracing_output) {
  1153. llvm::outs() << "********** initializing globals **********\n";
  1154. }
  1155. InitGlobals(fs);
  1156. const Expression* arg = Expression::MakeTupleLiteral(0, {});
  1157. const Expression* call_main = Expression::MakeCallExpression(
  1158. 0, Expression::MakeIdentifierExpression(0, "main"), arg);
  1159. auto todo = Stack(Action::MakeExpressionAction(call_main));
  1160. auto* scope = global_arena->New<Scope>(globals, std::list<std::string>());
  1161. auto* frame = global_arena->New<Frame>("top", Stack(scope), todo);
  1162. state->stack = Stack(frame);
  1163. if (tracing_output) {
  1164. llvm::outs() << "********** calling main function **********\n";
  1165. PrintState(llvm::outs());
  1166. }
  1167. while (state->stack.Count() > 1 || state->stack.Top()->todo.Count() > 1 ||
  1168. state->stack.Top()->todo.Top()->tag() != ActionKind::ValAction) {
  1169. Step();
  1170. if (tracing_output) {
  1171. PrintState(llvm::outs());
  1172. }
  1173. }
  1174. const Value* v = state->stack.Top()->todo.Top()->GetValAction().val;
  1175. return cast<IntValue>(*v).Val();
  1176. }
  1177. // Interpret an expression at compile-time.
  1178. auto InterpExp(Env values, const Expression* e) -> const Value* {
  1179. auto todo = Stack(Action::MakeExpressionAction(e));
  1180. auto* scope = global_arena->New<Scope>(values, std::list<std::string>());
  1181. auto* frame = global_arena->New<Frame>("InterpExp", Stack(scope), todo);
  1182. state->stack = Stack(frame);
  1183. while (state->stack.Count() > 1 || state->stack.Top()->todo.Count() > 1 ||
  1184. state->stack.Top()->todo.Top()->tag() != ActionKind::ValAction) {
  1185. Step();
  1186. }
  1187. const Value* v = state->stack.Top()->todo.Top()->GetValAction().val;
  1188. return v;
  1189. }
  1190. // Interpret a pattern at compile-time.
  1191. auto InterpPattern(Env values, const Pattern* p) -> const Value* {
  1192. auto todo = Stack(Action::MakePatternAction(p));
  1193. auto* scope = global_arena->New<Scope>(values, std::list<std::string>());
  1194. auto* frame = global_arena->New<Frame>("InterpPattern", Stack(scope), todo);
  1195. state->stack = Stack(frame);
  1196. while (state->stack.Count() > 1 || state->stack.Top()->todo.Count() > 1 ||
  1197. state->stack.Top()->todo.Top()->tag() != ActionKind::ValAction) {
  1198. Step();
  1199. }
  1200. const Value* v = state->stack.Top()->todo.Top()->GetValAction().val;
  1201. return v;
  1202. }
  1203. } // namespace Carbon