interpreter.cpp 44 KB

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