interpreter.cpp 47 KB

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