interpreter.cpp 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275
  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. Ptr<const Statement> stmt = cast<StatementAction>(*act).Stmt();
  772. if (tracing_output) {
  773. llvm::outs() << "--- step stmt ";
  774. stmt->PrintDepth(1, llvm::outs());
  775. llvm::outs() << " --->\n";
  776. }
  777. switch (stmt->Tag()) {
  778. case Statement::Kind::Match:
  779. if (act->Pos() == 0) {
  780. // { { (match (e) ...) :: C, E, F} :: S, H}
  781. // -> { { e :: (match ([]) ...) :: C, E, F} :: S, H}
  782. return Spawn{
  783. global_arena->New<ExpressionAction>(cast<Match>(*stmt).Exp())};
  784. } else {
  785. // Regarding act->Pos():
  786. // * odd: start interpreting the pattern of a clause
  787. // * even: finished interpreting the pattern, now try to match
  788. //
  789. // Regarding act->Results():
  790. // * 0: the value that we're matching
  791. // * 1: the pattern for clause 0
  792. // * 2: the pattern for clause 1
  793. // * ...
  794. auto clause_num = (act->Pos() - 1) / 2;
  795. if (clause_num >=
  796. static_cast<int>(cast<Match>(*stmt).Clauses()->size())) {
  797. return Done{};
  798. }
  799. auto c = cast<Match>(*stmt).Clauses()->begin();
  800. std::advance(c, clause_num);
  801. if (act->Pos() % 2 == 1) {
  802. // start interpreting the pattern of the clause
  803. // { {v :: (match ([]) ...) :: C, E, F} :: S, H}
  804. // -> { {pi :: (match ([]) ...) :: C, E, F} :: S, H}
  805. return Spawn{global_arena->New<PatternAction>(c->first)};
  806. } else { // try to match
  807. auto v = act->Results()[0];
  808. auto pat = act->Results()[clause_num + 1];
  809. std::optional<Env> matches = PatternMatch(pat, v, stmt->SourceLoc());
  810. if (matches) { // we have a match, start the body
  811. Env values = CurrentEnv(state);
  812. std::list<std::string> vars;
  813. for (const auto& [name, value] : *matches) {
  814. values.Set(name, value);
  815. vars.push_back(name);
  816. }
  817. frame->scopes.Push(global_arena->New<Scope>(values, vars));
  818. auto body_act = global_arena->New<StatementAction>(
  819. global_arena->New<Block>(stmt->SourceLoc(), c->second));
  820. body_act->IncrementPos();
  821. frame->todo.Pop(1);
  822. frame->todo.Push(body_act);
  823. frame->todo.Push(global_arena->New<StatementAction>(c->second));
  824. return ManualTransition{};
  825. } else {
  826. // this case did not match, moving on
  827. int next_clause_num = act->Pos() / 2;
  828. if (next_clause_num ==
  829. static_cast<int>(cast<Match>(*stmt).Clauses()->size())) {
  830. return Done{};
  831. }
  832. return RunAgain{};
  833. }
  834. }
  835. }
  836. case Statement::Kind::While:
  837. if (act->Pos() % 2 == 0) {
  838. // { { (while (e) s) :: C, E, F} :: S, H}
  839. // -> { { e :: (while ([]) s) :: C, E, F} :: S, H}
  840. act->Clear();
  841. return Spawn{
  842. global_arena->New<ExpressionAction>(cast<While>(*stmt).Cond())};
  843. } else if (cast<BoolValue>(*act->Results().back()).Val()) {
  844. // { {true :: (while ([]) s) :: C, E, F} :: S, H}
  845. // -> { { s :: (while (e) s) :: C, E, F } :: S, H}
  846. return Spawn{
  847. global_arena->New<StatementAction>(cast<While>(*stmt).Body())};
  848. } else {
  849. // { {false :: (while ([]) s) :: C, E, F} :: S, H}
  850. // -> { { C, E, F } :: S, H}
  851. return Done{};
  852. }
  853. case Statement::Kind::Break: {
  854. CHECK(act->Pos() == 0);
  855. // { { break; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  856. // -> { { C, E', F} :: S, H}
  857. auto it =
  858. std::find_if(frame->todo.begin(), frame->todo.end(), &IsWhileAct);
  859. if (it == frame->todo.end()) {
  860. FATAL_RUNTIME_ERROR(stmt->SourceLoc())
  861. << "`break` not inside `while` statement";
  862. }
  863. ++it;
  864. return UnwindTo{*it};
  865. }
  866. case Statement::Kind::Continue: {
  867. CHECK(act->Pos() == 0);
  868. // { { continue; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  869. // -> { { (while (e) s) :: C, E', F} :: S, H}
  870. auto it =
  871. std::find_if(frame->todo.begin(), frame->todo.end(), &IsWhileAct);
  872. if (it == frame->todo.end()) {
  873. FATAL_RUNTIME_ERROR(stmt->SourceLoc())
  874. << "`continue` not inside `while` statement";
  875. }
  876. return UnwindTo{*it};
  877. }
  878. case Statement::Kind::Block: {
  879. if (act->Pos() == 0) {
  880. const Block& block = cast<Block>(*stmt);
  881. if (block.Stmt()) {
  882. frame->scopes.Push(global_arena->New<Scope>(CurrentEnv(state)));
  883. return Spawn{global_arena->New<StatementAction>(*block.Stmt())};
  884. } else {
  885. return Done{};
  886. }
  887. } else {
  888. Ptr<Scope> scope = frame->scopes.Top();
  889. DeallocateScope(scope);
  890. frame->scopes.Pop(1);
  891. return Done{};
  892. }
  893. }
  894. case Statement::Kind::VariableDefinition:
  895. if (act->Pos() == 0) {
  896. // { {(var x = e) :: C, E, F} :: S, H}
  897. // -> { {e :: (var x = []) :: C, E, F} :: S, H}
  898. return Spawn{global_arena->New<ExpressionAction>(
  899. cast<VariableDefinition>(*stmt).Init())};
  900. } else if (act->Pos() == 1) {
  901. return Spawn{global_arena->New<PatternAction>(
  902. cast<VariableDefinition>(*stmt).Pat())};
  903. } else {
  904. // { { v :: (x = []) :: C, E, F} :: S, H}
  905. // -> { { C, E(x := a), F} :: S, H(a := copy(v))}
  906. const Value* v = act->Results()[0];
  907. const Value* p = act->Results()[1];
  908. std::optional<Env> matches = PatternMatch(p, v, stmt->SourceLoc());
  909. CHECK(matches)
  910. << stmt->SourceLoc()
  911. << ": internal error in variable definition, match failed";
  912. for (const auto& [name, value] : *matches) {
  913. frame->scopes.Top()->values.Set(name, value);
  914. frame->scopes.Top()->locals.push_back(name);
  915. }
  916. return Done{};
  917. }
  918. case Statement::Kind::ExpressionStatement:
  919. if (act->Pos() == 0) {
  920. // { {e :: C, E, F} :: S, H}
  921. // -> { {e :: C, E, F} :: S, H}
  922. return Spawn{global_arena->New<ExpressionAction>(
  923. cast<ExpressionStatement>(*stmt).Exp())};
  924. } else {
  925. return Done{};
  926. }
  927. case Statement::Kind::Assign:
  928. if (act->Pos() == 0) {
  929. // { {(lv = e) :: C, E, F} :: S, H}
  930. // -> { {lv :: ([] = e) :: C, E, F} :: S, H}
  931. return Spawn{global_arena->New<LValAction>(cast<Assign>(*stmt).Lhs())};
  932. } else if (act->Pos() == 1) {
  933. // { { a :: ([] = e) :: C, E, F} :: S, H}
  934. // -> { { e :: (a = []) :: C, E, F} :: S, H}
  935. return Spawn{
  936. global_arena->New<ExpressionAction>(cast<Assign>(*stmt).Rhs())};
  937. } else {
  938. // { { v :: (a = []) :: C, E, F} :: S, H}
  939. // -> { { C, E, F} :: S, H(a := v)}
  940. auto pat = act->Results()[0];
  941. auto val = act->Results()[1];
  942. PatternAssignment(pat, val, stmt->SourceLoc());
  943. return Done{};
  944. }
  945. case Statement::Kind::If:
  946. if (act->Pos() == 0) {
  947. // { {(if (e) then_stmt else else_stmt) :: C, E, F} :: S, H}
  948. // -> { { e :: (if ([]) then_stmt else else_stmt) :: C, E, F} :: S, H}
  949. return Spawn{
  950. global_arena->New<ExpressionAction>(cast<If>(*stmt).Cond())};
  951. } else if (cast<BoolValue>(*act->Results()[0]).Val()) {
  952. // { {true :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  953. // S, H}
  954. // -> { { then_stmt :: C, E, F } :: S, H}
  955. return Delegate{
  956. global_arena->New<StatementAction>(cast<If>(*stmt).ThenStmt())};
  957. } else if (cast<If>(*stmt).ElseStmt()) {
  958. // { {false :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  959. // S, H}
  960. // -> { { else_stmt :: C, E, F } :: S, H}
  961. return Delegate{
  962. global_arena->New<StatementAction>(*cast<If>(*stmt).ElseStmt())};
  963. } else {
  964. return Done{};
  965. }
  966. case Statement::Kind::Return:
  967. if (act->Pos() == 0) {
  968. // { {return e :: C, E, F} :: S, H}
  969. // -> { {e :: return [] :: C, E, F} :: S, H}
  970. return Spawn{
  971. global_arena->New<ExpressionAction>(cast<Return>(*stmt).Exp())};
  972. } else {
  973. // { {v :: return [] :: C, E, F} :: {C', E', F'} :: S, H}
  974. // -> { {v :: C', E', F'} :: S, H}
  975. const Value* ret_val = CopyVal(act->Results()[0], stmt->SourceLoc());
  976. return UnwindFunctionCall{ret_val};
  977. }
  978. case Statement::Kind::Sequence: {
  979. // { { (s1,s2) :: C, E, F} :: S, H}
  980. // -> { { s1 :: s2 :: C, E, F} :: S, H}
  981. const Sequence& seq = cast<Sequence>(*stmt);
  982. if (act->Pos() == 0) {
  983. return Spawn{global_arena->New<StatementAction>(seq.Stmt())};
  984. } else {
  985. if (seq.Next()) {
  986. return Delegate{global_arena->New<StatementAction>(
  987. *cast<Sequence>(*stmt).Next())};
  988. } else {
  989. return Done{};
  990. }
  991. }
  992. }
  993. case Statement::Kind::Continuation: {
  994. CHECK(act->Pos() == 0);
  995. // Create a continuation object by creating a frame similar the
  996. // way one is created in a function call.
  997. auto scopes =
  998. Stack<Ptr<Scope>>(global_arena->New<Scope>(CurrentEnv(state)));
  999. Stack<Ptr<Action>> todo;
  1000. todo.Push(global_arena->New<StatementAction>(
  1001. global_arena->New<Return>(stmt->SourceLoc())));
  1002. todo.Push(
  1003. global_arena->New<StatementAction>(cast<Continuation>(*stmt).Body()));
  1004. auto continuation_frame =
  1005. global_arena->New<Frame>("__continuation", scopes, todo);
  1006. Address continuation_address =
  1007. state->heap.AllocateValue(global_arena->RawNew<ContinuationValue>(
  1008. std::vector<Ptr<Frame>>({continuation_frame})));
  1009. // Store the continuation's address in the frame.
  1010. continuation_frame->continuation = continuation_address;
  1011. // Bind the continuation object to the continuation variable
  1012. frame->scopes.Top()->values.Set(
  1013. cast<Continuation>(*stmt).ContinuationVariable(),
  1014. continuation_address);
  1015. // Pop the continuation statement.
  1016. frame->todo.Pop();
  1017. return ManualTransition{};
  1018. }
  1019. case Statement::Kind::Run:
  1020. if (act->Pos() == 0) {
  1021. // Evaluate the argument of the run statement.
  1022. return Spawn{
  1023. global_arena->New<ExpressionAction>(cast<Run>(*stmt).Argument())};
  1024. } else {
  1025. frame->todo.Pop(1);
  1026. // Push an expression statement action to ignore the result
  1027. // value from the continuation.
  1028. auto ignore_result = global_arena->New<StatementAction>(
  1029. global_arena->New<ExpressionStatement>(
  1030. stmt->SourceLoc(),
  1031. global_arena->New<TupleLiteral>(stmt->SourceLoc())));
  1032. frame->todo.Push(ignore_result);
  1033. // Push the continuation onto the current stack.
  1034. const std::vector<Ptr<Frame>>& continuation_vector =
  1035. cast<ContinuationValue>(*act->Results()[0]).Stack();
  1036. for (auto frame_iter = continuation_vector.rbegin();
  1037. frame_iter != continuation_vector.rend(); ++frame_iter) {
  1038. state->stack.Push(*frame_iter);
  1039. }
  1040. return ManualTransition{};
  1041. }
  1042. case Statement::Kind::Await:
  1043. CHECK(act->Pos() == 0);
  1044. // Pause the current continuation
  1045. frame->todo.Pop();
  1046. std::vector<Ptr<Frame>> paused;
  1047. do {
  1048. paused.push_back(state->stack.Pop());
  1049. } while (paused.back()->continuation == std::nullopt);
  1050. // Update the continuation with the paused stack.
  1051. state->heap.Write(*paused.back()->continuation,
  1052. global_arena->RawNew<ContinuationValue>(paused),
  1053. stmt->SourceLoc());
  1054. return ManualTransition{};
  1055. }
  1056. }
  1057. // Visitor which implements the behavior associated with each transition type.
  1058. struct DoTransition {
  1059. void operator()(const Done& done) {
  1060. Ptr<Frame> frame = state->stack.Top();
  1061. if (frame->todo.Top()->Tag() != Action::Kind::StatementAction) {
  1062. CHECK(done.result != nullptr);
  1063. frame->todo.Pop();
  1064. if (frame->todo.IsEmpty()) {
  1065. state->program_value = done.result;
  1066. } else {
  1067. frame->todo.Top()->AddResult(done.result);
  1068. }
  1069. } else {
  1070. CHECK(done.result == nullptr);
  1071. frame->todo.Pop();
  1072. }
  1073. }
  1074. void operator()(const Spawn& spawn) {
  1075. Ptr<Frame> frame = state->stack.Top();
  1076. frame->todo.Top()->IncrementPos();
  1077. frame->todo.Push(spawn.child);
  1078. }
  1079. void operator()(const Delegate& delegate) {
  1080. Ptr<Frame> frame = state->stack.Top();
  1081. frame->todo.Pop();
  1082. frame->todo.Push(delegate.delegate);
  1083. }
  1084. void operator()(const RunAgain&) {
  1085. state->stack.Top()->todo.Top()->IncrementPos();
  1086. }
  1087. void operator()(const UnwindTo& unwind_to) {
  1088. Ptr<Frame> frame = state->stack.Top();
  1089. while (frame->todo.Top() != unwind_to.new_top) {
  1090. if (IsBlockAct(frame->todo.Top())) {
  1091. DeallocateScope(frame->scopes.Top());
  1092. frame->scopes.Pop();
  1093. }
  1094. frame->todo.Pop();
  1095. }
  1096. }
  1097. void operator()(const UnwindFunctionCall& unwind) {
  1098. DeallocateLocals(state->stack.Top());
  1099. state->stack.Pop();
  1100. if (state->stack.Top()->todo.IsEmpty()) {
  1101. state->program_value = unwind.return_val;
  1102. } else {
  1103. state->stack.Top()->todo.Top()->AddResult(unwind.return_val);
  1104. }
  1105. }
  1106. void operator()(const CallFunction& call) {
  1107. state->stack.Top()->todo.Pop();
  1108. std::optional<Env> matches =
  1109. PatternMatch(call.function->Param(), call.args, call.loc);
  1110. CHECK(matches.has_value())
  1111. << "internal error in call_function, pattern match failed";
  1112. // Create the new frame and push it on the stack
  1113. Env values = globals;
  1114. std::list<std::string> params;
  1115. for (const auto& [name, value] : *matches) {
  1116. values.Set(name, value);
  1117. params.push_back(name);
  1118. }
  1119. auto scopes = Stack<Ptr<Scope>>(global_arena->New<Scope>(values, params));
  1120. CHECK(call.function->Body()) << "Calling a function that's missing a body";
  1121. auto todo = Stack<Ptr<Action>>(
  1122. global_arena->New<StatementAction>(*call.function->Body()));
  1123. auto frame = global_arena->New<Frame>(call.function->Name(), scopes, todo);
  1124. state->stack.Push(frame);
  1125. }
  1126. void operator()(const ManualTransition&) {}
  1127. };
  1128. // State transition.
  1129. void Step() {
  1130. Ptr<Frame> frame = state->stack.Top();
  1131. if (frame->todo.IsEmpty()) {
  1132. FATAL_RUNTIME_ERROR_NO_LINE()
  1133. << "fell off end of function " << frame->name << " without `return`";
  1134. }
  1135. Ptr<Action> act = frame->todo.Top();
  1136. switch (act->Tag()) {
  1137. case Action::Kind::LValAction:
  1138. std::visit(DoTransition(), StepLvalue());
  1139. break;
  1140. case Action::Kind::ExpressionAction:
  1141. std::visit(DoTransition(), StepExp());
  1142. break;
  1143. case Action::Kind::PatternAction:
  1144. std::visit(DoTransition(), StepPattern());
  1145. break;
  1146. case Action::Kind::StatementAction:
  1147. std::visit(DoTransition(), StepStmt());
  1148. break;
  1149. } // switch
  1150. }
  1151. // Interpret the whole porogram.
  1152. auto InterpProgram(const std::list<Ptr<const Declaration>>& fs) -> int {
  1153. state = global_arena->RawNew<State>(); // Runtime state.
  1154. if (tracing_output) {
  1155. llvm::outs() << "********** initializing globals **********\n";
  1156. }
  1157. InitGlobals(fs);
  1158. SourceLocation loc("<InterpProgram()>", 0);
  1159. Ptr<const Expression> arg = global_arena->New<TupleLiteral>(loc);
  1160. Ptr<const Expression> call_main = global_arena->New<CallExpression>(
  1161. loc, global_arena->New<IdentifierExpression>(loc, "main"), arg);
  1162. auto todo =
  1163. Stack<Ptr<Action>>(global_arena->New<ExpressionAction>(call_main));
  1164. auto scopes = Stack<Ptr<Scope>>(global_arena->New<Scope>(globals));
  1165. state->stack =
  1166. Stack<Ptr<Frame>>(global_arena->New<Frame>("top", scopes, todo));
  1167. if (tracing_output) {
  1168. llvm::outs() << "********** calling main function **********\n";
  1169. PrintState(llvm::outs());
  1170. }
  1171. while (state->stack.Count() > 1 || !state->stack.Top()->todo.IsEmpty()) {
  1172. Step();
  1173. if (tracing_output) {
  1174. PrintState(llvm::outs());
  1175. }
  1176. }
  1177. return cast<IntValue>(**state->program_value).Val();
  1178. }
  1179. // Interpret an expression at compile-time.
  1180. auto InterpExp(Env values, Ptr<const Expression> e) -> const Value* {
  1181. CHECK(state->program_value == std::nullopt);
  1182. auto program_value_guard =
  1183. llvm::make_scope_exit([] { state->program_value = std::nullopt; });
  1184. auto todo = Stack<Ptr<Action>>(global_arena->New<ExpressionAction>(e));
  1185. auto scopes = Stack<Ptr<Scope>>(global_arena->New<Scope>(values));
  1186. state->stack =
  1187. Stack<Ptr<Frame>>(global_arena->New<Frame>("InterpExp", scopes, todo));
  1188. while (state->stack.Count() > 1 || !state->stack.Top()->todo.IsEmpty()) {
  1189. Step();
  1190. }
  1191. CHECK(state->program_value != std::nullopt);
  1192. return *state->program_value;
  1193. }
  1194. // Interpret a pattern at compile-time.
  1195. auto InterpPattern(Env values, Ptr<const Pattern> p) -> const Value* {
  1196. CHECK(state->program_value == std::nullopt);
  1197. auto program_value_guard =
  1198. llvm::make_scope_exit([] { state->program_value = std::nullopt; });
  1199. auto todo = Stack<Ptr<Action>>(global_arena->New<PatternAction>(p));
  1200. auto scopes = Stack<Ptr<Scope>>(global_arena->New<Scope>(values));
  1201. state->stack = Stack<Ptr<Frame>>(
  1202. global_arena->New<Frame>("InterpPattern", scopes, todo));
  1203. while (state->stack.Count() > 1 || !state->stack.Top()->todo.IsEmpty()) {
  1204. Step();
  1205. }
  1206. CHECK(state->program_value != std::nullopt);
  1207. return *state->program_value;
  1208. }
  1209. } // namespace Carbon