interpreter.cpp 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249
  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 Declaration::Kind::FunctionDeclaration: {
  97. const FunctionDefinition& func_def =
  98. cast<FunctionDeclaration>(d).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 Declaration::Kind::StructDeclaration: {
  114. const StructDefinition& struct_def =
  115. cast<StructDeclaration>(d).Definition();
  116. VarValues fields;
  117. VarValues methods;
  118. for (const Member* m : struct_def.members) {
  119. switch (m->Tag()) {
  120. case Member::Kind::FieldMember: {
  121. const BindingPattern* binding = cast<FieldMember>(*m).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 Declaration::Kind::ChoiceDeclaration: {
  137. const auto& choice = cast<ChoiceDeclaration>(d);
  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 Declaration::Kind::VariableDeclaration: {
  149. const auto& var = cast<VariableDeclaration>(d);
  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(const std::list<const Declaration*>& fs) {
  160. for (const auto* 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*>(global_arena->New<StatementAction>(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(global_arena->New<ValAction>(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(global_arena->New<ValAction>(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. const auto& tup_lit = cast<TupleLiteral>(*exp);
  224. CHECK(act->Results().size() == tup_lit.Fields().size());
  225. std::vector<TupleElement> elements;
  226. for (size_t i = 0; i < act->Results().size(); ++i) {
  227. elements.push_back(
  228. {.name = tup_lit.Fields()[i].name, .value = act->Results()[i]});
  229. }
  230. const Value* tv = global_arena->New<TupleValue>(std::move(elements));
  231. frame->todo.Pop(1);
  232. frame->todo.Push(global_arena->New<ValAction>(tv));
  233. }
  234. // Returns an updated environment that includes the bindings of
  235. // pattern variables to their matched values, if matching succeeds.
  236. //
  237. // The names of the pattern variables are added to the vars parameter.
  238. // Returns nullopt if the value doesn't match the pattern.
  239. auto PatternMatch(const Value* p, const Value* v, Env values,
  240. std::list<std::string>* vars, int line_num)
  241. -> std::optional<Env> {
  242. switch (p->Tag()) {
  243. case Value::Kind::BindingPlaceholderValue: {
  244. const auto& placeholder = cast<BindingPlaceholderValue>(*p);
  245. if (placeholder.Name().has_value()) {
  246. Address a = state->heap.AllocateValue(CopyVal(v, line_num));
  247. vars->push_back(*placeholder.Name());
  248. values.Set(*placeholder.Name(), a);
  249. }
  250. return values;
  251. }
  252. case Value::Kind::TupleValue:
  253. switch (v->Tag()) {
  254. case Value::Kind::TupleValue: {
  255. const auto& p_tup = cast<TupleValue>(*p);
  256. const auto& v_tup = cast<TupleValue>(*v);
  257. if (p_tup.Elements().size() != v_tup.Elements().size()) {
  258. FATAL_RUNTIME_ERROR(line_num)
  259. << "arity mismatch in tuple pattern match:\n pattern: "
  260. << p_tup << "\n value: " << v_tup;
  261. }
  262. for (const TupleElement& pattern_element : p_tup.Elements()) {
  263. const Value* value_field = v_tup.FindField(pattern_element.name);
  264. if (value_field == nullptr) {
  265. FATAL_RUNTIME_ERROR(line_num)
  266. << "field " << pattern_element.name << "not in " << *v;
  267. }
  268. std::optional<Env> matches = PatternMatch(
  269. pattern_element.value, value_field, values, vars, line_num);
  270. if (!matches) {
  271. return std::nullopt;
  272. }
  273. values = *matches;
  274. } // for
  275. return values;
  276. }
  277. default:
  278. FATAL() << "expected a tuple value in pattern, not " << *v;
  279. }
  280. case Value::Kind::AlternativeValue:
  281. switch (v->Tag()) {
  282. case Value::Kind::AlternativeValue: {
  283. const auto& p_alt = cast<AlternativeValue>(*p);
  284. const auto& v_alt = cast<AlternativeValue>(*v);
  285. if (p_alt.ChoiceName() != v_alt.ChoiceName() ||
  286. p_alt.AltName() != v_alt.AltName()) {
  287. return std::nullopt;
  288. }
  289. std::optional<Env> matches = PatternMatch(
  290. p_alt.Argument(), v_alt.Argument(), values, vars, line_num);
  291. if (!matches) {
  292. return std::nullopt;
  293. }
  294. return *matches;
  295. }
  296. default:
  297. FATAL() << "expected a choice alternative in pattern, not " << *v;
  298. }
  299. case Value::Kind::FunctionType:
  300. switch (v->Tag()) {
  301. case Value::Kind::FunctionType: {
  302. const auto& p_fn = cast<FunctionType>(*p);
  303. const auto& v_fn = cast<FunctionType>(*v);
  304. std::optional<Env> matches =
  305. PatternMatch(p_fn.Param(), v_fn.Param(), values, vars, line_num);
  306. if (!matches) {
  307. return std::nullopt;
  308. }
  309. return PatternMatch(p_fn.Ret(), v_fn.Ret(), *matches, vars, line_num);
  310. }
  311. default:
  312. return std::nullopt;
  313. }
  314. default:
  315. if (ValueEqual(p, v, line_num)) {
  316. return values;
  317. } else {
  318. return std::nullopt;
  319. }
  320. }
  321. }
  322. void PatternAssignment(const Value* pat, const Value* val, int line_num) {
  323. switch (pat->Tag()) {
  324. case Value::Kind::PointerValue:
  325. state->heap.Write(cast<PointerValue>(*pat).Val(), CopyVal(val, line_num),
  326. line_num);
  327. break;
  328. case Value::Kind::TupleValue: {
  329. switch (val->Tag()) {
  330. case Value::Kind::TupleValue: {
  331. const auto& pat_tup = cast<TupleValue>(*pat);
  332. const auto& val_tup = cast<TupleValue>(*val);
  333. if (pat_tup.Elements().size() != val_tup.Elements().size()) {
  334. FATAL_RUNTIME_ERROR(line_num)
  335. << "arity mismatch in tuple pattern assignment:\n pattern: "
  336. << pat_tup << "\n value: " << val_tup;
  337. }
  338. for (const TupleElement& pattern_element : pat_tup.Elements()) {
  339. const Value* value_field = val_tup.FindField(pattern_element.name);
  340. if (value_field == nullptr) {
  341. FATAL_RUNTIME_ERROR(line_num)
  342. << "field " << pattern_element.name << "not in " << *val;
  343. }
  344. PatternAssignment(pattern_element.value, value_field, line_num);
  345. }
  346. break;
  347. }
  348. default:
  349. FATAL() << "expected a tuple value on right-hand-side, not " << *val;
  350. }
  351. break;
  352. }
  353. case Value::Kind::AlternativeValue: {
  354. switch (val->Tag()) {
  355. case Value::Kind::AlternativeValue: {
  356. const auto& pat_alt = cast<AlternativeValue>(*pat);
  357. const auto& val_alt = cast<AlternativeValue>(*val);
  358. CHECK(val_alt.ChoiceName() == pat_alt.ChoiceName() &&
  359. val_alt.AltName() == pat_alt.AltName())
  360. << "internal error in pattern assignment";
  361. PatternAssignment(pat_alt.Argument(), val_alt.Argument(), line_num);
  362. break;
  363. }
  364. default:
  365. FATAL() << "expected an alternative in left-hand-side, not " << *val;
  366. }
  367. break;
  368. }
  369. default:
  370. CHECK(ValueEqual(pat, val, line_num))
  371. << "internal error in pattern assignment";
  372. }
  373. }
  374. // State transitions for lvalues.
  375. void StepLvalue() {
  376. Frame* frame = state->stack.Top();
  377. Action* act = frame->todo.Top();
  378. const Expression* exp = cast<LValAction>(*act).Exp();
  379. if (tracing_output) {
  380. llvm::outs() << "--- step lvalue " << *exp << " --->\n";
  381. }
  382. switch (exp->Tag()) {
  383. case Expression::Kind::IdentifierExpression: {
  384. // { {x :: C, E, F} :: S, H}
  385. // -> { {E(x) :: C, E, F} :: S, H}
  386. std::optional<Address> pointer =
  387. CurrentEnv(state).Get(cast<IdentifierExpression>(*exp).Name());
  388. if (!pointer) {
  389. FATAL_RUNTIME_ERROR(exp->LineNumber())
  390. << "could not find `" << cast<IdentifierExpression>(*exp).Name()
  391. << "`";
  392. }
  393. const Value* v = global_arena->New<PointerValue>(*pointer);
  394. frame->todo.Pop();
  395. frame->todo.Push(global_arena->New<ValAction>(v));
  396. break;
  397. }
  398. case Expression::Kind::FieldAccessExpression: {
  399. if (act->Pos() == 0) {
  400. // { {e.f :: C, E, F} :: S, H}
  401. // -> { e :: [].f :: C, E, F} :: S, H}
  402. frame->todo.Push(global_arena->New<LValAction>(
  403. cast<FieldAccessExpression>(*exp).Aggregate()));
  404. act->IncrementPos();
  405. } else {
  406. // { v :: [].f :: C, E, F} :: S, H}
  407. // -> { { &v.f :: C, E, F} :: S, H }
  408. Address aggregate = cast<PointerValue>(*act->Results()[0]).Val();
  409. Address field = aggregate.SubobjectAddress(
  410. cast<FieldAccessExpression>(*exp).Field());
  411. frame->todo.Pop(1);
  412. frame->todo.Push(global_arena->New<ValAction>(
  413. global_arena->New<PointerValue>(field)));
  414. }
  415. break;
  416. }
  417. case Expression::Kind::IndexExpression: {
  418. if (act->Pos() == 0) {
  419. // { {e[i] :: C, E, F} :: S, H}
  420. // -> { e :: [][i] :: C, E, F} :: S, H}
  421. frame->todo.Push(global_arena->New<LValAction>(
  422. cast<IndexExpression>(*exp).Aggregate()));
  423. act->IncrementPos();
  424. } else if (act->Pos() == 1) {
  425. frame->todo.Push(global_arena->New<ExpressionAction>(
  426. cast<IndexExpression>(*exp).Offset()));
  427. act->IncrementPos();
  428. } else if (act->Pos() == 2) {
  429. // { v :: [][i] :: C, E, F} :: S, H}
  430. // -> { { &v[i] :: C, E, F} :: S, H }
  431. Address aggregate = cast<PointerValue>(*act->Results()[0]).Val();
  432. std::string f =
  433. std::to_string(cast<IntValue>(*act->Results()[1]).Val());
  434. Address field = aggregate.SubobjectAddress(f);
  435. frame->todo.Pop(1);
  436. frame->todo.Push(global_arena->New<ValAction>(
  437. global_arena->New<PointerValue>(field)));
  438. }
  439. break;
  440. }
  441. case Expression::Kind::TupleLiteral: {
  442. if (act->Pos() == 0) {
  443. // { {(f1=e1,...) :: C, E, F} :: S, H}
  444. // -> { {e1 :: (f1=[],...) :: C, E, F} :: S, H}
  445. const Expression* e1 = cast<TupleLiteral>(*exp).Fields()[0].expression;
  446. frame->todo.Push(global_arena->New<LValAction>(e1));
  447. act->IncrementPos();
  448. } else if (act->Pos() !=
  449. static_cast<int>(cast<TupleLiteral>(*exp).Fields().size())) {
  450. // { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
  451. // H}
  452. // -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
  453. // H}
  454. const Expression* elt =
  455. cast<TupleLiteral>(*exp).Fields()[act->Pos()].expression;
  456. frame->todo.Push(global_arena->New<LValAction>(elt));
  457. act->IncrementPos();
  458. } else {
  459. CreateTuple(frame, act, exp);
  460. }
  461. break;
  462. }
  463. case Expression::Kind::IntLiteral:
  464. case Expression::Kind::BoolLiteral:
  465. case Expression::Kind::CallExpression:
  466. case Expression::Kind::PrimitiveOperatorExpression:
  467. case Expression::Kind::IntTypeLiteral:
  468. case Expression::Kind::BoolTypeLiteral:
  469. case Expression::Kind::TypeTypeLiteral:
  470. case Expression::Kind::FunctionTypeLiteral:
  471. case Expression::Kind::ContinuationTypeLiteral: {
  472. FATAL_RUNTIME_ERROR_NO_LINE()
  473. << "Can't treat expression as lvalue: " << *exp;
  474. }
  475. }
  476. }
  477. // State transitions for expressions.
  478. void StepExp() {
  479. Frame* frame = state->stack.Top();
  480. Action* act = frame->todo.Top();
  481. const Expression* exp = cast<ExpressionAction>(*act).Exp();
  482. if (tracing_output) {
  483. llvm::outs() << "--- step exp " << *exp << " --->\n";
  484. }
  485. switch (exp->Tag()) {
  486. case Expression::Kind::IndexExpression: {
  487. if (act->Pos() == 0) {
  488. // { { e[i] :: C, E, F} :: S, H}
  489. // -> { { e :: [][i] :: C, E, F} :: S, H}
  490. frame->todo.Push(global_arena->New<ExpressionAction>(
  491. cast<IndexExpression>(*exp).Aggregate()));
  492. act->IncrementPos();
  493. } else if (act->Pos() == 1) {
  494. frame->todo.Push(global_arena->New<ExpressionAction>(
  495. cast<IndexExpression>(*exp).Offset()));
  496. act->IncrementPos();
  497. } else if (act->Pos() == 2) {
  498. auto tuple = act->Results()[0];
  499. switch (tuple->Tag()) {
  500. case Value::Kind::TupleValue: {
  501. // { { v :: [][i] :: C, E, F} :: S, H}
  502. // -> { { v_i :: C, E, F} : S, H}
  503. std::string f =
  504. std::to_string(cast<IntValue>(*act->Results()[1]).Val());
  505. const Value* field = cast<TupleValue>(*tuple).FindField(f);
  506. if (field == nullptr) {
  507. FATAL_RUNTIME_ERROR_NO_LINE()
  508. << "field " << f << " not in " << *tuple;
  509. }
  510. frame->todo.Pop(1);
  511. frame->todo.Push(global_arena->New<ValAction>(field));
  512. break;
  513. }
  514. default:
  515. FATAL_RUNTIME_ERROR_NO_LINE()
  516. << "expected a tuple in field access, not " << *tuple;
  517. }
  518. }
  519. break;
  520. }
  521. case Expression::Kind::TupleLiteral: {
  522. if (act->Pos() == 0) {
  523. if (cast<TupleLiteral>(*exp).Fields().size() > 0) {
  524. // { {(f1=e1,...) :: C, E, F} :: S, H}
  525. // -> { {e1 :: (f1=[],...) :: C, E, F} :: S, H}
  526. const Expression* e1 =
  527. cast<TupleLiteral>(*exp).Fields()[0].expression;
  528. frame->todo.Push(global_arena->New<ExpressionAction>(e1));
  529. act->IncrementPos();
  530. } else {
  531. CreateTuple(frame, act, exp);
  532. }
  533. } else if (act->Pos() !=
  534. static_cast<int>(cast<TupleLiteral>(*exp).Fields().size())) {
  535. // { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
  536. // H}
  537. // -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
  538. // H}
  539. const Expression* elt =
  540. cast<TupleLiteral>(*exp).Fields()[act->Pos()].expression;
  541. frame->todo.Push(global_arena->New<ExpressionAction>(elt));
  542. act->IncrementPos();
  543. } else {
  544. CreateTuple(frame, act, exp);
  545. }
  546. break;
  547. }
  548. case Expression::Kind::FieldAccessExpression: {
  549. const auto& access = cast<FieldAccessExpression>(*exp);
  550. if (act->Pos() == 0) {
  551. // { { e.f :: C, E, F} :: S, H}
  552. // -> { { e :: [].f :: C, E, F} :: S, H}
  553. frame->todo.Push(
  554. global_arena->New<ExpressionAction>(access.Aggregate()));
  555. act->IncrementPos();
  556. } else {
  557. // { { v :: [].f :: C, E, F} :: S, H}
  558. // -> { { v_f :: C, E, F} : S, H}
  559. const Value* element = act->Results()[0]->GetField(
  560. FieldPath(access.Field()), exp->LineNumber());
  561. frame->todo.Pop(1);
  562. frame->todo.Push(global_arena->New<ValAction>(element));
  563. }
  564. break;
  565. }
  566. case Expression::Kind::IdentifierExpression: {
  567. CHECK(act->Pos() == 0);
  568. const auto& ident = cast<IdentifierExpression>(*exp);
  569. // { {x :: C, E, F} :: S, H} -> { {H(E(x)) :: C, E, F} :: S, H}
  570. std::optional<Address> pointer = CurrentEnv(state).Get(ident.Name());
  571. if (!pointer) {
  572. FATAL_RUNTIME_ERROR(exp->LineNumber())
  573. << "could not find `" << ident.Name() << "`";
  574. }
  575. const Value* pointee = state->heap.Read(*pointer, exp->LineNumber());
  576. frame->todo.Pop(1);
  577. frame->todo.Push(global_arena->New<ValAction>(pointee));
  578. break;
  579. }
  580. case Expression::Kind::IntLiteral:
  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(global_arena->New<ValAction>(
  585. global_arena->New<IntValue>(cast<IntLiteral>(*exp).Val())));
  586. break;
  587. case Expression::Kind::BoolLiteral:
  588. CHECK(act->Pos() == 0);
  589. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  590. frame->todo.Pop(1);
  591. frame->todo.Push(global_arena->New<ValAction>(
  592. global_arena->New<BoolValue>(cast<BoolLiteral>(*exp).Val())));
  593. break;
  594. case Expression::Kind::PrimitiveOperatorExpression: {
  595. const auto& op = cast<PrimitiveOperatorExpression>(*exp);
  596. if (act->Pos() != static_cast<int>(op.Arguments().size())) {
  597. // { {v :: op(vs,[],e,es) :: C, E, F} :: S, H}
  598. // -> { {e :: op(vs,v,[],es) :: C, E, F} :: S, H}
  599. const Expression* arg = op.Arguments()[act->Pos()];
  600. frame->todo.Push(global_arena->New<ExpressionAction>(arg));
  601. act->IncrementPos();
  602. } else {
  603. // { {v :: op(vs,[]) :: C, E, F} :: S, H}
  604. // -> { {eval_prim(op, (vs,v)) :: C, E, F} :: S, H}
  605. const Value* v = EvalPrim(op.Op(), act->Results(), exp->LineNumber());
  606. frame->todo.Pop(1);
  607. frame->todo.Push(global_arena->New<ValAction>(v));
  608. }
  609. break;
  610. }
  611. case Expression::Kind::CallExpression:
  612. if (act->Pos() == 0) {
  613. // { {e1(e2) :: C, E, F} :: S, H}
  614. // -> { {e1 :: [](e2) :: C, E, F} :: S, H}
  615. frame->todo.Push(global_arena->New<ExpressionAction>(
  616. cast<CallExpression>(*exp).Function()));
  617. act->IncrementPos();
  618. } else if (act->Pos() == 1) {
  619. // { { v :: [](e) :: C, E, F} :: S, H}
  620. // -> { { e :: v([]) :: C, E, F} :: S, H}
  621. frame->todo.Push(global_arena->New<ExpressionAction>(
  622. cast<CallExpression>(*exp).Argument()));
  623. act->IncrementPos();
  624. } else if (act->Pos() == 2) {
  625. // { { v2 :: v1([]) :: C, E, F} :: S, H}
  626. // -> { {C',E',F'} :: {C, E, F} :: S, H}
  627. frame->todo.Pop(1);
  628. CallFunction(exp->LineNumber(), act->Results(), state);
  629. } else {
  630. FATAL() << "in handle_value with Call pos " << act->Pos();
  631. }
  632. break;
  633. case Expression::Kind::IntTypeLiteral: {
  634. CHECK(act->Pos() == 0);
  635. const Value* v = global_arena->New<IntType>();
  636. frame->todo.Pop(1);
  637. frame->todo.Push(global_arena->New<ValAction>(v));
  638. break;
  639. }
  640. case Expression::Kind::BoolTypeLiteral: {
  641. CHECK(act->Pos() == 0);
  642. const Value* v = global_arena->New<BoolType>();
  643. frame->todo.Pop(1);
  644. frame->todo.Push(global_arena->New<ValAction>(v));
  645. break;
  646. }
  647. case Expression::Kind::TypeTypeLiteral: {
  648. CHECK(act->Pos() == 0);
  649. const Value* v = global_arena->New<TypeType>();
  650. frame->todo.Pop(1);
  651. frame->todo.Push(global_arena->New<ValAction>(v));
  652. break;
  653. }
  654. case Expression::Kind::FunctionTypeLiteral: {
  655. if (act->Pos() == 0) {
  656. frame->todo.Push(global_arena->New<ExpressionAction>(
  657. cast<FunctionTypeLiteral>(*exp).Parameter()));
  658. act->IncrementPos();
  659. } else if (act->Pos() == 1) {
  660. // { { pt :: fn [] -> e :: C, E, F} :: S, H}
  661. // -> { { e :: fn pt -> []) :: C, E, F} :: S, H}
  662. frame->todo.Push(global_arena->New<ExpressionAction>(
  663. cast<FunctionTypeLiteral>(*exp).ReturnType()));
  664. act->IncrementPos();
  665. } else if (act->Pos() == 2) {
  666. // { { rt :: fn pt -> [] :: C, E, F} :: S, H}
  667. // -> { fn pt -> rt :: {C, E, F} :: S, H}
  668. const Value* v = global_arena->New<FunctionType>(
  669. std::vector<GenericBinding>(), act->Results()[0],
  670. act->Results()[1]);
  671. frame->todo.Pop(1);
  672. frame->todo.Push(global_arena->New<ValAction>(v));
  673. }
  674. break;
  675. }
  676. case Expression::Kind::ContinuationTypeLiteral: {
  677. CHECK(act->Pos() == 0);
  678. const Value* v = global_arena->New<ContinuationType>();
  679. frame->todo.Pop(1);
  680. frame->todo.Push(global_arena->New<ValAction>(v));
  681. break;
  682. }
  683. } // switch (exp->Tag)
  684. }
  685. void StepPattern() {
  686. Frame* frame = state->stack.Top();
  687. Action* act = frame->todo.Top();
  688. const Pattern* pattern = cast<PatternAction>(*act).Pat();
  689. if (tracing_output) {
  690. llvm::outs() << "--- step pattern " << *pattern << " --->\n";
  691. }
  692. switch (pattern->Tag()) {
  693. case Pattern::Kind::AutoPattern: {
  694. CHECK(act->Pos() == 0);
  695. const Value* v = global_arena->New<AutoType>();
  696. frame->todo.Pop(1);
  697. frame->todo.Push(global_arena->New<ValAction>(v));
  698. break;
  699. }
  700. case Pattern::Kind::BindingPattern: {
  701. const auto& binding = cast<BindingPattern>(*pattern);
  702. if (act->Pos() == 0) {
  703. frame->todo.Push(global_arena->New<PatternAction>(binding.Type()));
  704. act->IncrementPos();
  705. } else {
  706. auto v = global_arena->New<BindingPlaceholderValue>(binding.Name(),
  707. act->Results()[0]);
  708. frame->todo.Pop(1);
  709. frame->todo.Push(global_arena->New<ValAction>(v));
  710. }
  711. break;
  712. }
  713. case Pattern::Kind::TuplePattern: {
  714. const auto& tuple = cast<TuplePattern>(*pattern);
  715. if (act->Pos() == 0) {
  716. if (tuple.Fields().empty()) {
  717. frame->todo.Pop(1);
  718. frame->todo.Push(global_arena->New<ValAction>(&TupleValue::Empty()));
  719. } else {
  720. const Pattern* p1 = tuple.Fields()[0].pattern;
  721. frame->todo.Push(global_arena->New<PatternAction>(p1));
  722. act->IncrementPos();
  723. }
  724. } else if (act->Pos() != static_cast<int>(tuple.Fields().size())) {
  725. // { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
  726. // H}
  727. // -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
  728. // H}
  729. const Pattern* elt = tuple.Fields()[act->Pos()].pattern;
  730. frame->todo.Push(global_arena->New<PatternAction>(elt));
  731. act->IncrementPos();
  732. } else {
  733. std::vector<TupleElement> elements;
  734. for (size_t i = 0; i < tuple.Fields().size(); ++i) {
  735. elements.push_back(
  736. {.name = tuple.Fields()[i].name, .value = act->Results()[i]});
  737. }
  738. const Value* tuple_value =
  739. global_arena->New<TupleValue>(std::move(elements));
  740. frame->todo.Pop(1);
  741. frame->todo.Push(global_arena->New<ValAction>(tuple_value));
  742. }
  743. break;
  744. }
  745. case Pattern::Kind::AlternativePattern: {
  746. const auto& alternative = cast<AlternativePattern>(*pattern);
  747. if (act->Pos() == 0) {
  748. frame->todo.Push(
  749. global_arena->New<ExpressionAction>(alternative.ChoiceType()));
  750. act->IncrementPos();
  751. } else if (act->Pos() == 1) {
  752. frame->todo.Push(
  753. global_arena->New<PatternAction>(alternative.Arguments()));
  754. act->IncrementPos();
  755. } else {
  756. CHECK(act->Pos() == 2);
  757. const auto& choice_type = cast<ChoiceType>(*act->Results()[0]);
  758. frame->todo.Pop(1);
  759. frame->todo.Push(
  760. global_arena->New<ValAction>(global_arena->New<AlternativeValue>(
  761. alternative.AlternativeName(), choice_type.Name(),
  762. act->Results()[1])));
  763. }
  764. break;
  765. }
  766. case Pattern::Kind::ExpressionPattern:
  767. frame->todo.Pop(1);
  768. frame->todo.Push(global_arena->New<ExpressionAction>(
  769. cast<ExpressionPattern>(pattern)->Expression()));
  770. break;
  771. }
  772. }
  773. auto IsWhileAct(Action* act) -> bool {
  774. switch (act->Tag()) {
  775. case Action::Kind::StatementAction:
  776. switch (cast<StatementAction>(*act).Stmt()->Tag()) {
  777. case Statement::Kind::While:
  778. return true;
  779. default:
  780. return false;
  781. }
  782. default:
  783. return false;
  784. }
  785. }
  786. auto IsBlockAct(Action* act) -> bool {
  787. switch (act->Tag()) {
  788. case Action::Kind::StatementAction:
  789. switch (cast<StatementAction>(*act).Stmt()->Tag()) {
  790. case Statement::Kind::Block:
  791. return true;
  792. default:
  793. return false;
  794. }
  795. default:
  796. return false;
  797. }
  798. }
  799. // State transitions for statements.
  800. void StepStmt() {
  801. Frame* frame = state->stack.Top();
  802. Action* act = frame->todo.Top();
  803. const Statement* stmt = cast<StatementAction>(*act).Stmt();
  804. CHECK(stmt != nullptr) << "null statement!";
  805. if (tracing_output) {
  806. llvm::outs() << "--- step stmt ";
  807. stmt->PrintDepth(1, llvm::outs());
  808. llvm::outs() << " --->\n";
  809. }
  810. switch (stmt->Tag()) {
  811. case Statement::Kind::Match:
  812. if (act->Pos() == 0) {
  813. // { { (match (e) ...) :: C, E, F} :: S, H}
  814. // -> { { e :: (match ([]) ...) :: C, E, F} :: S, H}
  815. frame->todo.Push(
  816. global_arena->New<ExpressionAction>(cast<Match>(*stmt).Exp()));
  817. act->IncrementPos();
  818. } else {
  819. // Regarding act->Pos():
  820. // * odd: start interpreting the pattern of a clause
  821. // * even: finished interpreting the pattern, now try to match
  822. //
  823. // Regarding act->Results():
  824. // * 0: the value that we're matching
  825. // * 1: the pattern for clause 0
  826. // * 2: the pattern for clause 1
  827. // * ...
  828. auto clause_num = (act->Pos() - 1) / 2;
  829. if (clause_num >=
  830. static_cast<int>(cast<Match>(*stmt).Clauses()->size())) {
  831. frame->todo.Pop(1);
  832. break;
  833. }
  834. auto c = cast<Match>(*stmt).Clauses()->begin();
  835. std::advance(c, clause_num);
  836. if (act->Pos() % 2 == 1) {
  837. // start interpreting the pattern of the clause
  838. // { {v :: (match ([]) ...) :: C, E, F} :: S, H}
  839. // -> { {pi :: (match ([]) ...) :: C, E, F} :: S, H}
  840. frame->todo.Push(global_arena->New<PatternAction>(c->first));
  841. act->IncrementPos();
  842. } else { // try to match
  843. auto v = act->Results()[0];
  844. auto pat = act->Results()[clause_num + 1];
  845. auto values = CurrentEnv(state);
  846. std::list<std::string> vars;
  847. std::optional<Env> matches =
  848. PatternMatch(pat, v, values, &vars, stmt->LineNumber());
  849. if (matches) { // we have a match, start the body
  850. auto* new_scope = global_arena->New<Scope>(*matches, vars);
  851. frame->scopes.Push(new_scope);
  852. const Statement* body_block =
  853. global_arena->New<Block>(stmt->LineNumber(), c->second);
  854. Action* body_act = global_arena->New<StatementAction>(body_block);
  855. body_act->IncrementPos();
  856. frame->todo.Pop(1);
  857. frame->todo.Push(body_act);
  858. frame->todo.Push(global_arena->New<StatementAction>(c->second));
  859. } else {
  860. // this case did not match, moving on
  861. act->IncrementPos();
  862. clause_num = (act->Pos() - 1) / 2;
  863. if (clause_num ==
  864. static_cast<int>(cast<Match>(*stmt).Clauses()->size())) {
  865. frame->todo.Pop(1);
  866. }
  867. }
  868. }
  869. }
  870. break;
  871. case Statement::Kind::While:
  872. if (act->Pos() == 0) {
  873. // { { (while (e) s) :: C, E, F} :: S, H}
  874. // -> { { e :: (while ([]) s) :: C, E, F} :: S, H}
  875. frame->todo.Push(
  876. global_arena->New<ExpressionAction>(cast<While>(*stmt).Cond()));
  877. act->IncrementPos();
  878. } else if (cast<BoolValue>(*act->Results()[0]).Val()) {
  879. // { {true :: (while ([]) s) :: C, E, F} :: S, H}
  880. // -> { { s :: (while (e) s) :: C, E, F } :: S, H}
  881. frame->todo.Top()->Clear();
  882. frame->todo.Push(
  883. global_arena->New<StatementAction>(cast<While>(*stmt).Body()));
  884. } else {
  885. // { {false :: (while ([]) s) :: C, E, F} :: S, H}
  886. // -> { { C, E, F } :: S, H}
  887. frame->todo.Top()->Clear();
  888. frame->todo.Pop(1);
  889. }
  890. break;
  891. case Statement::Kind::Break:
  892. CHECK(act->Pos() == 0);
  893. // { { break; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  894. // -> { { C, E', F} :: S, H}
  895. frame->todo.Pop(1);
  896. while (!frame->todo.IsEmpty() && !IsWhileAct(frame->todo.Top())) {
  897. if (IsBlockAct(frame->todo.Top())) {
  898. DeallocateScope(stmt->LineNumber(), frame->scopes.Top());
  899. frame->scopes.Pop(1);
  900. }
  901. frame->todo.Pop(1);
  902. }
  903. frame->todo.Pop(1);
  904. break;
  905. case Statement::Kind::Continue:
  906. CHECK(act->Pos() == 0);
  907. // { { continue; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  908. // -> { { (while (e) s) :: C, E', F} :: S, H}
  909. frame->todo.Pop(1);
  910. while (!frame->todo.IsEmpty() && !IsWhileAct(frame->todo.Top())) {
  911. if (IsBlockAct(frame->todo.Top())) {
  912. DeallocateScope(stmt->LineNumber(), frame->scopes.Top());
  913. frame->scopes.Pop(1);
  914. }
  915. frame->todo.Pop(1);
  916. }
  917. break;
  918. case Statement::Kind::Block: {
  919. if (act->Pos() == 0) {
  920. if (cast<Block>(*stmt).Stmt()) {
  921. auto* scope = global_arena->New<Scope>(CurrentEnv(state),
  922. std::list<std::string>());
  923. frame->scopes.Push(scope);
  924. frame->todo.Push(
  925. global_arena->New<StatementAction>(cast<Block>(*stmt).Stmt()));
  926. act->IncrementPos();
  927. act->IncrementPos();
  928. } else {
  929. frame->todo.Pop();
  930. }
  931. } else {
  932. Scope* scope = frame->scopes.Top();
  933. DeallocateScope(stmt->LineNumber(), scope);
  934. frame->scopes.Pop(1);
  935. frame->todo.Pop(1);
  936. }
  937. break;
  938. }
  939. case Statement::Kind::VariableDefinition:
  940. if (act->Pos() == 0) {
  941. // { {(var x = e) :: C, E, F} :: S, H}
  942. // -> { {e :: (var x = []) :: C, E, F} :: S, H}
  943. frame->todo.Push(global_arena->New<ExpressionAction>(
  944. cast<VariableDefinition>(*stmt).Init()));
  945. act->IncrementPos();
  946. } else if (act->Pos() == 1) {
  947. frame->todo.Push(global_arena->New<PatternAction>(
  948. cast<VariableDefinition>(*stmt).Pat()));
  949. act->IncrementPos();
  950. } else if (act->Pos() == 2) {
  951. // { { v :: (x = []) :: C, E, F} :: S, H}
  952. // -> { { C, E(x := a), F} :: S, H(a := copy(v))}
  953. const Value* v = act->Results()[0];
  954. const Value* p = act->Results()[1];
  955. std::optional<Env> matches =
  956. PatternMatch(p, v, frame->scopes.Top()->values,
  957. &frame->scopes.Top()->locals, stmt->LineNumber());
  958. CHECK(matches)
  959. << stmt->LineNumber()
  960. << ": internal error in variable definition, match failed";
  961. frame->scopes.Top()->values = *matches;
  962. frame->todo.Pop(1);
  963. }
  964. break;
  965. case Statement::Kind::ExpressionStatement:
  966. if (act->Pos() == 0) {
  967. // { {e :: C, E, F} :: S, H}
  968. // -> { {e :: C, E, F} :: S, H}
  969. frame->todo.Push(global_arena->New<ExpressionAction>(
  970. cast<ExpressionStatement>(*stmt).Exp()));
  971. act->IncrementPos();
  972. } else {
  973. frame->todo.Pop(1);
  974. }
  975. break;
  976. case Statement::Kind::Assign:
  977. if (act->Pos() == 0) {
  978. // { {(lv = e) :: C, E, F} :: S, H}
  979. // -> { {lv :: ([] = e) :: C, E, F} :: S, H}
  980. frame->todo.Push(
  981. global_arena->New<LValAction>(cast<Assign>(*stmt).Lhs()));
  982. act->IncrementPos();
  983. } else if (act->Pos() == 1) {
  984. // { { a :: ([] = e) :: C, E, F} :: S, H}
  985. // -> { { e :: (a = []) :: C, E, F} :: S, H}
  986. frame->todo.Push(
  987. global_arena->New<ExpressionAction>(cast<Assign>(*stmt).Rhs()));
  988. act->IncrementPos();
  989. } else if (act->Pos() == 2) {
  990. // { { v :: (a = []) :: C, E, F} :: S, H}
  991. // -> { { C, E, F} :: S, H(a := v)}
  992. auto pat = act->Results()[0];
  993. auto val = act->Results()[1];
  994. PatternAssignment(pat, val, stmt->LineNumber());
  995. frame->todo.Pop(1);
  996. }
  997. break;
  998. case Statement::Kind::If:
  999. if (act->Pos() == 0) {
  1000. // { {(if (e) then_stmt else else_stmt) :: C, E, F} :: S, H}
  1001. // -> { { e :: (if ([]) then_stmt else else_stmt) :: C, E, F} :: S, H}
  1002. frame->todo.Push(
  1003. global_arena->New<ExpressionAction>(cast<If>(*stmt).Cond()));
  1004. act->IncrementPos();
  1005. } else if (cast<BoolValue>(*act->Results()[0]).Val()) {
  1006. // { {true :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  1007. // S, H}
  1008. // -> { { then_stmt :: C, E, F } :: S, H}
  1009. frame->todo.Pop(1);
  1010. frame->todo.Push(
  1011. global_arena->New<StatementAction>(cast<If>(*stmt).ThenStmt()));
  1012. } else if (cast<If>(*stmt).ElseStmt()) {
  1013. // { {false :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  1014. // S, H}
  1015. // -> { { else_stmt :: C, E, F } :: S, H}
  1016. frame->todo.Pop(1);
  1017. frame->todo.Push(
  1018. global_arena->New<StatementAction>(cast<If>(*stmt).ElseStmt()));
  1019. } else {
  1020. frame->todo.Pop(1);
  1021. }
  1022. break;
  1023. case Statement::Kind::Return:
  1024. if (act->Pos() == 0) {
  1025. // { {return e :: C, E, F} :: S, H}
  1026. // -> { {e :: return [] :: C, E, F} :: S, H}
  1027. frame->todo.Push(
  1028. global_arena->New<ExpressionAction>(cast<Return>(*stmt).Exp()));
  1029. act->IncrementPos();
  1030. } else {
  1031. // { {v :: return [] :: C, E, F} :: {C', E', F'} :: S, H}
  1032. // -> { {v :: C', E', F'} :: S, H}
  1033. const Value* ret_val = CopyVal(act->Results()[0], stmt->LineNumber());
  1034. DeallocateLocals(stmt->LineNumber(), frame);
  1035. state->stack.Pop(1);
  1036. frame = state->stack.Top();
  1037. frame->todo.Push(global_arena->New<ValAction>(ret_val));
  1038. }
  1039. break;
  1040. case Statement::Kind::Sequence:
  1041. CHECK(act->Pos() == 0);
  1042. // { { (s1,s2) :: C, E, F} :: S, H}
  1043. // -> { { s1 :: s2 :: C, E, F} :: S, H}
  1044. frame->todo.Pop(1);
  1045. if (cast<Sequence>(*stmt).Next()) {
  1046. frame->todo.Push(
  1047. global_arena->New<StatementAction>(cast<Sequence>(*stmt).Next()));
  1048. }
  1049. frame->todo.Push(
  1050. global_arena->New<StatementAction>(cast<Sequence>(*stmt).Stmt()));
  1051. break;
  1052. case Statement::Kind::Continuation: {
  1053. CHECK(act->Pos() == 0);
  1054. // Create a continuation object by creating a frame similar the
  1055. // way one is created in a function call.
  1056. Scope* scope =
  1057. global_arena->New<Scope>(CurrentEnv(state), std::list<std::string>());
  1058. Stack<Scope*> scopes;
  1059. scopes.Push(scope);
  1060. Stack<Action*> todo;
  1061. todo.Push(global_arena->New<StatementAction>(
  1062. global_arena->New<Return>(stmt->LineNumber(), nullptr,
  1063. /*is_omitted_exp=*/true)));
  1064. todo.Push(
  1065. global_arena->New<StatementAction>(cast<Continuation>(*stmt).Body()));
  1066. Frame* continuation_frame =
  1067. global_arena->New<Frame>("__continuation", scopes, todo);
  1068. Address continuation_address =
  1069. state->heap.AllocateValue(global_arena->New<ContinuationValue>(
  1070. std::vector<Frame*>({continuation_frame})));
  1071. // Store the continuation's address in the frame.
  1072. continuation_frame->continuation = continuation_address;
  1073. // Bind the continuation object to the continuation variable
  1074. frame->scopes.Top()->values.Set(
  1075. cast<Continuation>(*stmt).ContinuationVariable(),
  1076. continuation_address);
  1077. // Pop the continuation statement.
  1078. frame->todo.Pop();
  1079. break;
  1080. }
  1081. case Statement::Kind::Run:
  1082. if (act->Pos() == 0) {
  1083. // Evaluate the argument of the run statement.
  1084. frame->todo.Push(
  1085. global_arena->New<ExpressionAction>(cast<Run>(*stmt).Argument()));
  1086. act->IncrementPos();
  1087. } else {
  1088. frame->todo.Pop(1);
  1089. // Push an expression statement action to ignore the result
  1090. // value from the continuation.
  1091. Action* ignore_result = global_arena->New<StatementAction>(
  1092. global_arena->New<ExpressionStatement>(
  1093. stmt->LineNumber(),
  1094. global_arena->New<TupleLiteral>(stmt->LineNumber())));
  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 Statement::Kind::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->LineNumber());
  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 Action::Kind::ValAction: {
  1130. const ValAction& val_act = cast<ValAction>(*frame->todo.Pop());
  1131. Action* act = frame->todo.Top();
  1132. act->AddResult(val_act.Val());
  1133. break;
  1134. }
  1135. case Action::Kind::LValAction:
  1136. StepLvalue();
  1137. break;
  1138. case Action::Kind::ExpressionAction:
  1139. StepExp();
  1140. break;
  1141. case Action::Kind::PatternAction:
  1142. StepPattern();
  1143. break;
  1144. case Action::Kind::StatementAction:
  1145. StepStmt();
  1146. break;
  1147. } // switch
  1148. }
  1149. // Interpret the whole porogram.
  1150. auto InterpProgram(const std::list<const 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 = global_arena->New<TupleLiteral>(0);
  1157. const Expression* call_main = global_arena->New<CallExpression>(
  1158. 0, global_arena->New<IdentifierExpression>(0, "main"), arg);
  1159. auto todo = Stack<Action*>(global_arena->New<ExpressionAction>(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() != Action::Kind::ValAction) {
  1169. Step();
  1170. if (tracing_output) {
  1171. PrintState(llvm::outs());
  1172. }
  1173. }
  1174. const Value* v = cast<ValAction>(*state->stack.Top()->todo.Top()).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*>(global_arena->New<ExpressionAction>(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() != Action::Kind::ValAction) {
  1185. Step();
  1186. }
  1187. return cast<ValAction>(*state->stack.Top()->todo.Top()).Val();
  1188. }
  1189. // Interpret a pattern at compile-time.
  1190. auto InterpPattern(Env values, const Pattern* p) -> const Value* {
  1191. auto todo = Stack<Action*>(global_arena->New<PatternAction>(p));
  1192. auto* scope = global_arena->New<Scope>(values, std::list<std::string>());
  1193. auto* frame = global_arena->New<Frame>("InterpPattern", Stack(scope), todo);
  1194. state->stack = Stack(frame);
  1195. while (state->stack.Count() > 1 || state->stack.Top()->todo.Count() > 1 ||
  1196. state->stack.Top()->todo.Top()->Tag() != Action::Kind::ValAction) {
  1197. Step();
  1198. }
  1199. return cast<ValAction>(*state->stack.Top()->todo.Top()).Val();
  1200. }
  1201. } // namespace Carbon