interpreter.cpp 45 KB

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