interpreter.cpp 45 KB

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