interpreter.cpp 46 KB

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