interpreter.cpp 44 KB

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