interpreter.cpp 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210
  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<const Value*>& args,
  67. SourceLocation loc) -> const Value* {
  68. switch (op) {
  69. case Operator::Neg:
  70. return global_arena->RawNew<IntValue>(-cast<IntValue>(*args[0]).Val());
  71. case Operator::Add:
  72. return global_arena->RawNew<IntValue>(cast<IntValue>(*args[0]).Val() +
  73. cast<IntValue>(*args[1]).Val());
  74. case Operator::Sub:
  75. return global_arena->RawNew<IntValue>(cast<IntValue>(*args[0]).Val() -
  76. cast<IntValue>(*args[1]).Val());
  77. case Operator::Mul:
  78. return global_arena->RawNew<IntValue>(cast<IntValue>(*args[0]).Val() *
  79. cast<IntValue>(*args[1]).Val());
  80. case Operator::Not:
  81. return global_arena->RawNew<BoolValue>(!cast<BoolValue>(*args[0]).Val());
  82. case Operator::And:
  83. return global_arena->RawNew<BoolValue>(cast<BoolValue>(*args[0]).Val() &&
  84. cast<BoolValue>(*args[1]).Val());
  85. case Operator::Or:
  86. return global_arena->RawNew<BoolValue>(cast<BoolValue>(*args[0]).Val() ||
  87. cast<BoolValue>(*args[1]).Val());
  88. case Operator::Eq:
  89. return global_arena->RawNew<BoolValue>(ValueEqual(args[0], args[1], loc));
  90. case Operator::Ptr:
  91. return global_arena->RawNew<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(
  105. global_arena->RawNew<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->RawNew<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->RawNew<ClassType>(
  132. class_def.name, std::move(fields), 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 =
  145. global_arena->RawNew<ChoiceType>(choice.Name(), std::move(alts));
  146. auto a = heap.AllocateValue(ct);
  147. env->Set(choice.Name(), a);
  148. break;
  149. }
  150. case Declaration::Kind::VariableDeclaration: {
  151. const auto& var = cast<VariableDeclaration>(d);
  152. // Adds an entry in `globals` mapping the variable's name to the
  153. // result of evaluating the initializer.
  154. auto v = InterpExp(*env, var.Initializer());
  155. Address a = heap.AllocateValue(v);
  156. env->Set(*var.Binding()->Name(), a);
  157. break;
  158. }
  159. }
  160. }
  161. void Interpreter::InitGlobals(const std::list<Ptr<const Declaration>>& fs) {
  162. for (const auto d : fs) {
  163. InitEnv(*d, &globals);
  164. }
  165. }
  166. void Interpreter::DeallocateScope(Ptr<Scope> scope) {
  167. for (const auto& l : scope->locals) {
  168. std::optional<Address> a = scope->values.Get(l);
  169. CHECK(a);
  170. heap.Deallocate(*a);
  171. }
  172. }
  173. void Interpreter::DeallocateLocals(Ptr<Frame> frame) {
  174. while (!frame->scopes.IsEmpty()) {
  175. DeallocateScope(frame->scopes.Top());
  176. frame->scopes.Pop();
  177. }
  178. }
  179. static const Value* CreateTuple(Ptr<Action> act, 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->RawNew<TupleValue>(std::move(elements));
  190. }
  191. auto Interpreter::PatternMatch(const Value* p, 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(const Value* pat, 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. const Value* value_field = val_tup.FindField(pattern_element.name);
  303. if (value_field == nullptr) {
  304. FATAL_RUNTIME_ERROR(loc)
  305. << "field " << pattern_element.name << "not in " << *val;
  306. }
  307. PatternAssignment(pattern_element.value, value_field, loc);
  308. }
  309. break;
  310. }
  311. default:
  312. FATAL() << "expected a tuple value on right-hand-side, not " << *val;
  313. }
  314. break;
  315. }
  316. case Value::Kind::AlternativeValue: {
  317. switch (val->Tag()) {
  318. case Value::Kind::AlternativeValue: {
  319. const auto& pat_alt = cast<AlternativeValue>(*pat);
  320. const auto& val_alt = cast<AlternativeValue>(*val);
  321. CHECK(val_alt.ChoiceName() == pat_alt.ChoiceName() &&
  322. val_alt.AltName() == pat_alt.AltName())
  323. << "internal error in pattern assignment";
  324. PatternAssignment(pat_alt.Argument(), val_alt.Argument(), loc);
  325. break;
  326. }
  327. default:
  328. FATAL() << "expected an alternative in left-hand-side, not " << *val;
  329. }
  330. break;
  331. }
  332. default:
  333. CHECK(ValueEqual(pat, val, loc))
  334. << "internal error in pattern assignment";
  335. }
  336. }
  337. auto Interpreter::StepLvalue() -> Transition {
  338. Ptr<Action> act = stack.Top()->todo.Top();
  339. Ptr<const Expression> exp = cast<LValAction>(*act).Exp();
  340. if (tracing_output) {
  341. llvm::outs() << "--- step lvalue " << *exp << " --->\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. const Value* v = global_arena->RawNew<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{global_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{global_arena->RawNew<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{global_arena->New<LValAction>(
  372. cast<IndexExpression>(*exp).Aggregate())};
  373. } else if (act->Pos() == 1) {
  374. return Spawn{global_arena->New<ExpressionAction>(
  375. 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{global_arena->RawNew<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{global_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{global_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 << " --->\n";
  427. }
  428. switch (exp->Tag()) {
  429. case Expression::Kind::IndexExpression: {
  430. if (act->Pos() == 0) {
  431. // { { e[i] :: C, E, F} :: S, H}
  432. // -> { { e :: [][i] :: C, E, F} :: S, H}
  433. return Spawn{global_arena->New<ExpressionAction>(
  434. cast<IndexExpression>(*exp).Aggregate())};
  435. } else if (act->Pos() == 1) {
  436. return Spawn{global_arena->New<ExpressionAction>(
  437. cast<IndexExpression>(*exp).Offset())};
  438. } else {
  439. // { { v :: [][i] :: C, E, F} :: S, H}
  440. // -> { { v_i :: C, E, F} : S, H}
  441. auto* tuple = dyn_cast<TupleValue>(act->Results()[0]);
  442. if (tuple == nullptr) {
  443. FATAL_RUNTIME_ERROR_NO_LINE()
  444. << "expected a tuple in field access, not " << *tuple;
  445. }
  446. std::string f =
  447. std::to_string(cast<IntValue>(*act->Results()[1]).Val());
  448. const Value* field = tuple->FindField(f);
  449. if (field == nullptr) {
  450. FATAL_RUNTIME_ERROR_NO_LINE()
  451. << "field " << f << " not in " << *tuple;
  452. }
  453. return Done{field};
  454. }
  455. }
  456. case Expression::Kind::TupleLiteral: {
  457. if (act->Pos() == 0) {
  458. if (cast<TupleLiteral>(*exp).Fields().size() > 0) {
  459. // { {(f1=e1,...) :: C, E, F} :: S, H}
  460. // -> { {e1 :: (f1=[],...) :: C, E, F} :: S, H}
  461. Ptr<const Expression> e1 =
  462. cast<TupleLiteral>(*exp).Fields()[0].expression;
  463. return Spawn{global_arena->New<ExpressionAction>(e1)};
  464. } else {
  465. return Done{CreateTuple(act, exp)};
  466. }
  467. } else if (act->Pos() !=
  468. static_cast<int>(cast<TupleLiteral>(*exp).Fields().size())) {
  469. // { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
  470. // H}
  471. // -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
  472. // H}
  473. Ptr<const Expression> elt =
  474. cast<TupleLiteral>(*exp).Fields()[act->Pos()].expression;
  475. return Spawn{global_arena->New<ExpressionAction>(elt)};
  476. } else {
  477. return Done{CreateTuple(act, exp)};
  478. }
  479. }
  480. case Expression::Kind::FieldAccessExpression: {
  481. const auto& access = cast<FieldAccessExpression>(*exp);
  482. if (act->Pos() == 0) {
  483. // { { e.f :: C, E, F} :: S, H}
  484. // -> { { e :: [].f :: C, E, F} :: S, H}
  485. return Spawn{global_arena->New<ExpressionAction>(access.Aggregate())};
  486. } else {
  487. // { { v :: [].f :: C, E, F} :: S, H}
  488. // -> { { v_f :: C, E, F} : S, H}
  489. return Done{act->Results()[0]->GetField(FieldPath(access.Field()),
  490. exp->SourceLoc())};
  491. }
  492. }
  493. case Expression::Kind::IdentifierExpression: {
  494. CHECK(act->Pos() == 0);
  495. const auto& ident = cast<IdentifierExpression>(*exp);
  496. // { {x :: C, E, F} :: S, H} -> { {H(E(x)) :: C, E, F} :: S, H}
  497. Address pointer = GetFromEnv(exp->SourceLoc(), ident.Name());
  498. return Done{heap.Read(pointer, exp->SourceLoc())};
  499. }
  500. case Expression::Kind::IntLiteral:
  501. CHECK(act->Pos() == 0);
  502. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  503. return Done{global_arena->RawNew<IntValue>(cast<IntLiteral>(*exp).Val())};
  504. case Expression::Kind::BoolLiteral:
  505. CHECK(act->Pos() == 0);
  506. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  507. return Done{
  508. global_arena->RawNew<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. const Value* arg = CopyVal(act->Results()[1], exp->SourceLoc());
  539. return Done{
  540. global_arena->RawNew<StructValue>(act->Results()[0], arg)};
  541. }
  542. case Value::Kind::AlternativeConstructorValue: {
  543. const auto& alt =
  544. cast<AlternativeConstructorValue>(*act->Results()[0]);
  545. const Value* arg = CopyVal(act->Results()[1], exp->SourceLoc());
  546. return Done{global_arena->RawNew<AlternativeValue>(
  547. alt.AltName(), alt.ChoiceName(), arg)};
  548. }
  549. case Value::Kind::FunctionValue:
  550. return CallFunction{
  551. .function = cast<FunctionValue>(act->Results()[0]),
  552. .args = act->Results()[1],
  553. .loc = exp->SourceLoc()};
  554. default:
  555. FATAL_RUNTIME_ERROR(exp->SourceLoc())
  556. << "in call, expected a function, not " << *act->Results()[0];
  557. }
  558. } else {
  559. FATAL() << "in handle_value with Call pos " << act->Pos();
  560. }
  561. case Expression::Kind::IntrinsicExpression:
  562. CHECK(act->Pos() == 0);
  563. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  564. switch (cast<IntrinsicExpression>(*exp).Intrinsic()) {
  565. case IntrinsicExpression::IntrinsicKind::Print:
  566. Address pointer = GetFromEnv(exp->SourceLoc(), "format_str");
  567. const Value* pointee = heap.Read(pointer, exp->SourceLoc());
  568. CHECK(pointee->Tag() == Value::Kind::StringValue);
  569. // TODO: This could eventually use something like llvm::formatv.
  570. llvm::outs() << cast<StringValue>(*pointee).Val();
  571. return Done{&TupleValue::Empty()};
  572. }
  573. case Expression::Kind::IntTypeLiteral: {
  574. CHECK(act->Pos() == 0);
  575. return Done{global_arena->RawNew<IntType>()};
  576. }
  577. case Expression::Kind::BoolTypeLiteral: {
  578. CHECK(act->Pos() == 0);
  579. return Done{global_arena->RawNew<BoolType>()};
  580. }
  581. case Expression::Kind::TypeTypeLiteral: {
  582. CHECK(act->Pos() == 0);
  583. return Done{global_arena->RawNew<TypeType>()};
  584. }
  585. case Expression::Kind::FunctionTypeLiteral: {
  586. if (act->Pos() == 0) {
  587. return Spawn{global_arena->New<ExpressionAction>(
  588. cast<FunctionTypeLiteral>(*exp).Parameter())};
  589. } else if (act->Pos() == 1) {
  590. // { { pt :: fn [] -> e :: C, E, F} :: S, H}
  591. // -> { { e :: fn pt -> []) :: C, E, F} :: S, H}
  592. return Spawn{global_arena->New<ExpressionAction>(
  593. cast<FunctionTypeLiteral>(*exp).ReturnType())};
  594. } else {
  595. // { { rt :: fn pt -> [] :: C, E, F} :: S, H}
  596. // -> { fn pt -> rt :: {C, E, F} :: S, H}
  597. return Done{global_arena->RawNew<FunctionType>(
  598. std::vector<GenericBinding>(), act->Results()[0],
  599. act->Results()[1])};
  600. }
  601. }
  602. case Expression::Kind::ContinuationTypeLiteral: {
  603. CHECK(act->Pos() == 0);
  604. return Done{global_arena->RawNew<ContinuationType>()};
  605. }
  606. case Expression::Kind::StringLiteral:
  607. CHECK(act->Pos() == 0);
  608. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  609. return Done{
  610. global_arena->RawNew<StringValue>(cast<StringLiteral>(*exp).Val())};
  611. case Expression::Kind::StringTypeLiteral: {
  612. CHECK(act->Pos() == 0);
  613. return Done{global_arena->RawNew<StringType>()};
  614. }
  615. } // switch (exp->Tag)
  616. }
  617. auto Interpreter::StepPattern() -> Transition {
  618. Ptr<Action> act = stack.Top()->todo.Top();
  619. Ptr<const Pattern> pattern = cast<PatternAction>(*act).Pat();
  620. if (tracing_output) {
  621. llvm::outs() << "--- step pattern " << *pattern << " --->\n";
  622. }
  623. switch (pattern->Tag()) {
  624. case Pattern::Kind::AutoPattern: {
  625. CHECK(act->Pos() == 0);
  626. return Done{global_arena->RawNew<AutoType>()};
  627. }
  628. case Pattern::Kind::BindingPattern: {
  629. const auto& binding = cast<BindingPattern>(*pattern);
  630. if (act->Pos() == 0) {
  631. return Spawn{global_arena->New<PatternAction>(binding.Type())};
  632. } else {
  633. return Done{global_arena->RawNew<BindingPlaceholderValue>(
  634. binding.Name(), act->Results()[0])};
  635. }
  636. }
  637. case Pattern::Kind::TuplePattern: {
  638. const auto& tuple = cast<TuplePattern>(*pattern);
  639. if (act->Pos() == 0) {
  640. if (tuple.Fields().empty()) {
  641. return Done{&TupleValue::Empty()};
  642. } else {
  643. Ptr<const Pattern> p1 = tuple.Fields()[0].pattern;
  644. return Spawn{(global_arena->New<PatternAction>(p1))};
  645. }
  646. } else if (act->Pos() != static_cast<int>(tuple.Fields().size())) {
  647. // { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
  648. // H}
  649. // -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
  650. // H}
  651. Ptr<const Pattern> elt = tuple.Fields()[act->Pos()].pattern;
  652. return Spawn{global_arena->New<PatternAction>(elt)};
  653. } else {
  654. std::vector<TupleElement> elements;
  655. for (size_t i = 0; i < tuple.Fields().size(); ++i) {
  656. elements.push_back(
  657. {.name = tuple.Fields()[i].name, .value = act->Results()[i]});
  658. }
  659. return Done{global_arena->RawNew<TupleValue>(std::move(elements))};
  660. }
  661. }
  662. case Pattern::Kind::AlternativePattern: {
  663. const auto& alternative = cast<AlternativePattern>(*pattern);
  664. if (act->Pos() == 0) {
  665. return Spawn{
  666. global_arena->New<ExpressionAction>(alternative.ChoiceType())};
  667. } else if (act->Pos() == 1) {
  668. return Spawn{global_arena->New<PatternAction>(alternative.Arguments())};
  669. } else {
  670. CHECK(act->Pos() == 2);
  671. const auto& choice_type = cast<ChoiceType>(*act->Results()[0]);
  672. return Done{global_arena->RawNew<AlternativeValue>(
  673. alternative.AlternativeName(), choice_type.Name(),
  674. act->Results()[1])};
  675. }
  676. }
  677. case Pattern::Kind::ExpressionPattern:
  678. return Delegate{global_arena->New<ExpressionAction>(
  679. cast<ExpressionPattern>(*pattern).Expression())};
  680. }
  681. }
  682. static auto IsWhileAct(Ptr<Action> act) -> bool {
  683. switch (act->Tag()) {
  684. case Action::Kind::StatementAction:
  685. switch (cast<StatementAction>(*act).Stmt()->Tag()) {
  686. case Statement::Kind::While:
  687. return true;
  688. default:
  689. return false;
  690. }
  691. default:
  692. return false;
  693. }
  694. }
  695. static auto IsBlockAct(Ptr<Action> act) -> bool {
  696. switch (act->Tag()) {
  697. case Action::Kind::StatementAction:
  698. switch (cast<StatementAction>(*act).Stmt()->Tag()) {
  699. case Statement::Kind::Block:
  700. return true;
  701. default:
  702. return false;
  703. }
  704. default:
  705. return false;
  706. }
  707. }
  708. auto Interpreter::StepStmt() -> Transition {
  709. Ptr<Frame> frame = stack.Top();
  710. Ptr<Action> act = frame->todo.Top();
  711. Ptr<const Statement> stmt = cast<StatementAction>(*act).Stmt();
  712. if (tracing_output) {
  713. llvm::outs() << "--- step stmt ";
  714. stmt->PrintDepth(1, llvm::outs());
  715. llvm::outs() << " --->\n";
  716. }
  717. switch (stmt->Tag()) {
  718. case Statement::Kind::Match:
  719. if (act->Pos() == 0) {
  720. // { { (match (e) ...) :: C, E, F} :: S, H}
  721. // -> { { e :: (match ([]) ...) :: C, E, F} :: S, H}
  722. return Spawn{
  723. global_arena->New<ExpressionAction>(cast<Match>(*stmt).Exp())};
  724. } else {
  725. // Regarding act->Pos():
  726. // * odd: start interpreting the pattern of a clause
  727. // * even: finished interpreting the pattern, now try to match
  728. //
  729. // Regarding act->Results():
  730. // * 0: the value that we're matching
  731. // * 1: the pattern for clause 0
  732. // * 2: the pattern for clause 1
  733. // * ...
  734. auto clause_num = (act->Pos() - 1) / 2;
  735. if (clause_num >=
  736. static_cast<int>(cast<Match>(*stmt).Clauses()->size())) {
  737. return Done{};
  738. }
  739. auto c = cast<Match>(*stmt).Clauses()->begin();
  740. std::advance(c, clause_num);
  741. if (act->Pos() % 2 == 1) {
  742. // start interpreting the pattern of the clause
  743. // { {v :: (match ([]) ...) :: C, E, F} :: S, H}
  744. // -> { {pi :: (match ([]) ...) :: C, E, F} :: S, H}
  745. return Spawn{global_arena->New<PatternAction>(c->first)};
  746. } else { // try to match
  747. auto v = act->Results()[0];
  748. auto pat = act->Results()[clause_num + 1];
  749. std::optional<Env> matches = PatternMatch(pat, v, stmt->SourceLoc());
  750. if (matches) { // we have a match, start the body
  751. Env values = CurrentEnv();
  752. std::list<std::string> vars;
  753. for (const auto& [name, value] : *matches) {
  754. values.Set(name, value);
  755. vars.push_back(name);
  756. }
  757. frame->scopes.Push(global_arena->New<Scope>(values, vars));
  758. auto body_act = global_arena->New<StatementAction>(
  759. global_arena->New<Block>(stmt->SourceLoc(), c->second));
  760. body_act->IncrementPos();
  761. frame->todo.Pop(1);
  762. frame->todo.Push(body_act);
  763. frame->todo.Push(global_arena->New<StatementAction>(c->second));
  764. return ManualTransition{};
  765. } else {
  766. // this case did not match, moving on
  767. int next_clause_num = act->Pos() / 2;
  768. if (next_clause_num ==
  769. static_cast<int>(cast<Match>(*stmt).Clauses()->size())) {
  770. return Done{};
  771. }
  772. return RunAgain{};
  773. }
  774. }
  775. }
  776. case Statement::Kind::While:
  777. if (act->Pos() % 2 == 0) {
  778. // { { (while (e) s) :: C, E, F} :: S, H}
  779. // -> { { e :: (while ([]) s) :: C, E, F} :: S, H}
  780. act->Clear();
  781. return Spawn{
  782. global_arena->New<ExpressionAction>(cast<While>(*stmt).Cond())};
  783. } else if (cast<BoolValue>(*act->Results().back()).Val()) {
  784. // { {true :: (while ([]) s) :: C, E, F} :: S, H}
  785. // -> { { s :: (while (e) s) :: C, E, F } :: S, H}
  786. return Spawn{
  787. global_arena->New<StatementAction>(cast<While>(*stmt).Body())};
  788. } else {
  789. // { {false :: (while ([]) s) :: C, E, F} :: S, H}
  790. // -> { { C, E, F } :: S, H}
  791. return Done{};
  792. }
  793. case Statement::Kind::Break: {
  794. CHECK(act->Pos() == 0);
  795. // { { break; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  796. // -> { { C, E', F} :: S, H}
  797. auto it =
  798. std::find_if(frame->todo.begin(), frame->todo.end(), &IsWhileAct);
  799. if (it == frame->todo.end()) {
  800. FATAL_RUNTIME_ERROR(stmt->SourceLoc())
  801. << "`break` not inside `while` statement";
  802. }
  803. ++it;
  804. return UnwindTo{*it};
  805. }
  806. case Statement::Kind::Continue: {
  807. CHECK(act->Pos() == 0);
  808. // { { continue; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  809. // -> { { (while (e) s) :: C, E', F} :: S, H}
  810. auto it =
  811. std::find_if(frame->todo.begin(), frame->todo.end(), &IsWhileAct);
  812. if (it == frame->todo.end()) {
  813. FATAL_RUNTIME_ERROR(stmt->SourceLoc())
  814. << "`continue` not inside `while` statement";
  815. }
  816. return UnwindTo{*it};
  817. }
  818. case Statement::Kind::Block: {
  819. if (act->Pos() == 0) {
  820. const Block& block = cast<Block>(*stmt);
  821. if (block.Stmt()) {
  822. frame->scopes.Push(global_arena->New<Scope>(CurrentEnv()));
  823. return Spawn{global_arena->New<StatementAction>(*block.Stmt())};
  824. } else {
  825. return Done{};
  826. }
  827. } else {
  828. Ptr<Scope> scope = frame->scopes.Top();
  829. DeallocateScope(scope);
  830. frame->scopes.Pop(1);
  831. return Done{};
  832. }
  833. }
  834. case Statement::Kind::VariableDefinition:
  835. if (act->Pos() == 0) {
  836. // { {(var x = e) :: C, E, F} :: S, H}
  837. // -> { {e :: (var x = []) :: C, E, F} :: S, H}
  838. return Spawn{global_arena->New<ExpressionAction>(
  839. cast<VariableDefinition>(*stmt).Init())};
  840. } else if (act->Pos() == 1) {
  841. return Spawn{global_arena->New<PatternAction>(
  842. cast<VariableDefinition>(*stmt).Pat())};
  843. } else {
  844. // { { v :: (x = []) :: C, E, F} :: S, H}
  845. // -> { { C, E(x := a), F} :: S, H(a := copy(v))}
  846. const Value* v = act->Results()[0];
  847. const Value* p = act->Results()[1];
  848. std::optional<Env> matches = PatternMatch(p, v, stmt->SourceLoc());
  849. CHECK(matches)
  850. << stmt->SourceLoc()
  851. << ": internal error in variable definition, match failed";
  852. for (const auto& [name, value] : *matches) {
  853. frame->scopes.Top()->values.Set(name, value);
  854. frame->scopes.Top()->locals.push_back(name);
  855. }
  856. return Done{};
  857. }
  858. case Statement::Kind::ExpressionStatement:
  859. if (act->Pos() == 0) {
  860. // { {e :: C, E, F} :: S, H}
  861. // -> { {e :: C, E, F} :: S, H}
  862. return Spawn{global_arena->New<ExpressionAction>(
  863. cast<ExpressionStatement>(*stmt).Exp())};
  864. } else {
  865. return Done{};
  866. }
  867. case Statement::Kind::Assign:
  868. if (act->Pos() == 0) {
  869. // { {(lv = e) :: C, E, F} :: S, H}
  870. // -> { {lv :: ([] = e) :: C, E, F} :: S, H}
  871. return Spawn{global_arena->New<LValAction>(cast<Assign>(*stmt).Lhs())};
  872. } else if (act->Pos() == 1) {
  873. // { { a :: ([] = e) :: C, E, F} :: S, H}
  874. // -> { { e :: (a = []) :: C, E, F} :: S, H}
  875. return Spawn{
  876. global_arena->New<ExpressionAction>(cast<Assign>(*stmt).Rhs())};
  877. } else {
  878. // { { v :: (a = []) :: C, E, F} :: S, H}
  879. // -> { { C, E, F} :: S, H(a := v)}
  880. auto pat = act->Results()[0];
  881. auto val = act->Results()[1];
  882. PatternAssignment(pat, val, stmt->SourceLoc());
  883. return Done{};
  884. }
  885. case Statement::Kind::If:
  886. if (act->Pos() == 0) {
  887. // { {(if (e) then_stmt else else_stmt) :: C, E, F} :: S, H}
  888. // -> { { e :: (if ([]) then_stmt else else_stmt) :: C, E, F} :: S, H}
  889. return Spawn{
  890. global_arena->New<ExpressionAction>(cast<If>(*stmt).Cond())};
  891. } else if (cast<BoolValue>(*act->Results()[0]).Val()) {
  892. // { {true :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  893. // S, H}
  894. // -> { { then_stmt :: C, E, F } :: S, H}
  895. return Delegate{
  896. global_arena->New<StatementAction>(cast<If>(*stmt).ThenStmt())};
  897. } else if (cast<If>(*stmt).ElseStmt()) {
  898. // { {false :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  899. // S, H}
  900. // -> { { else_stmt :: C, E, F } :: S, H}
  901. return Delegate{
  902. global_arena->New<StatementAction>(*cast<If>(*stmt).ElseStmt())};
  903. } else {
  904. return Done{};
  905. }
  906. case Statement::Kind::Return:
  907. if (act->Pos() == 0) {
  908. // { {return e :: C, E, F} :: S, H}
  909. // -> { {e :: return [] :: C, E, F} :: S, H}
  910. return Spawn{
  911. global_arena->New<ExpressionAction>(cast<Return>(*stmt).Exp())};
  912. } else {
  913. // { {v :: return [] :: C, E, F} :: {C', E', F'} :: S, H}
  914. // -> { {v :: C', E', F'} :: S, H}
  915. const Value* ret_val = CopyVal(act->Results()[0], stmt->SourceLoc());
  916. return UnwindFunctionCall{ret_val};
  917. }
  918. case Statement::Kind::Sequence: {
  919. // { { (s1,s2) :: C, E, F} :: S, H}
  920. // -> { { s1 :: s2 :: C, E, F} :: S, H}
  921. const Sequence& seq = cast<Sequence>(*stmt);
  922. if (act->Pos() == 0) {
  923. return Spawn{global_arena->New<StatementAction>(seq.Stmt())};
  924. } else {
  925. if (seq.Next()) {
  926. return Delegate{global_arena->New<StatementAction>(
  927. *cast<Sequence>(*stmt).Next())};
  928. } else {
  929. return Done{};
  930. }
  931. }
  932. }
  933. case Statement::Kind::Continuation: {
  934. CHECK(act->Pos() == 0);
  935. // Create a continuation object by creating a frame similar the
  936. // way one is created in a function call.
  937. auto scopes = Stack<Ptr<Scope>>(global_arena->New<Scope>(CurrentEnv()));
  938. Stack<Ptr<Action>> todo;
  939. todo.Push(global_arena->New<StatementAction>(
  940. global_arena->New<Return>(stmt->SourceLoc())));
  941. todo.Push(
  942. global_arena->New<StatementAction>(cast<Continuation>(*stmt).Body()));
  943. auto continuation_frame =
  944. global_arena->New<Frame>("__continuation", scopes, todo);
  945. Address continuation_address =
  946. heap.AllocateValue(global_arena->RawNew<ContinuationValue>(
  947. std::vector<Ptr<Frame>>({continuation_frame})));
  948. // Store the continuation's address in the frame.
  949. continuation_frame->continuation = continuation_address;
  950. // Bind the continuation object to the continuation variable
  951. frame->scopes.Top()->values.Set(
  952. cast<Continuation>(*stmt).ContinuationVariable(),
  953. continuation_address);
  954. // Pop the continuation statement.
  955. frame->todo.Pop();
  956. return ManualTransition{};
  957. }
  958. case Statement::Kind::Run:
  959. if (act->Pos() == 0) {
  960. // Evaluate the argument of the run statement.
  961. return Spawn{
  962. global_arena->New<ExpressionAction>(cast<Run>(*stmt).Argument())};
  963. } else {
  964. frame->todo.Pop(1);
  965. // Push an expression statement action to ignore the result
  966. // value from the continuation.
  967. auto ignore_result = global_arena->New<StatementAction>(
  968. global_arena->New<ExpressionStatement>(
  969. stmt->SourceLoc(),
  970. global_arena->New<TupleLiteral>(stmt->SourceLoc())));
  971. frame->todo.Push(ignore_result);
  972. // Push the continuation onto the current stack.
  973. const std::vector<Ptr<Frame>>& continuation_vector =
  974. cast<ContinuationValue>(*act->Results()[0]).Stack();
  975. for (auto frame_iter = continuation_vector.rbegin();
  976. frame_iter != continuation_vector.rend(); ++frame_iter) {
  977. stack.Push(*frame_iter);
  978. }
  979. return ManualTransition{};
  980. }
  981. case Statement::Kind::Await:
  982. CHECK(act->Pos() == 0);
  983. // Pause the current continuation
  984. frame->todo.Pop();
  985. std::vector<Ptr<Frame>> paused;
  986. do {
  987. paused.push_back(stack.Pop());
  988. } while (paused.back()->continuation == std::nullopt);
  989. // Update the continuation with the paused stack.
  990. heap.Write(*paused.back()->continuation,
  991. global_arena->RawNew<ContinuationValue>(paused),
  992. stmt->SourceLoc());
  993. return ManualTransition{};
  994. }
  995. }
  996. class Interpreter::DoTransition {
  997. public:
  998. // Does not take ownership of interpreter.
  999. DoTransition(Interpreter* interpreter) : interpreter(interpreter) {}
  1000. void operator()(const Done& done) {
  1001. Ptr<Frame> frame = interpreter->stack.Top();
  1002. if (frame->todo.Top()->Tag() != Action::Kind::StatementAction) {
  1003. CHECK(done.result != nullptr);
  1004. frame->todo.Pop();
  1005. if (frame->todo.IsEmpty()) {
  1006. interpreter->program_value = done.result;
  1007. } else {
  1008. frame->todo.Top()->AddResult(done.result);
  1009. }
  1010. } else {
  1011. CHECK(done.result == nullptr);
  1012. frame->todo.Pop();
  1013. }
  1014. }
  1015. void operator()(const Spawn& spawn) {
  1016. Ptr<Frame> frame = interpreter->stack.Top();
  1017. frame->todo.Top()->IncrementPos();
  1018. frame->todo.Push(spawn.child);
  1019. }
  1020. void operator()(const Delegate& delegate) {
  1021. Ptr<Frame> frame = interpreter->stack.Top();
  1022. frame->todo.Pop();
  1023. frame->todo.Push(delegate.delegate);
  1024. }
  1025. void operator()(const RunAgain&) {
  1026. interpreter->stack.Top()->todo.Top()->IncrementPos();
  1027. }
  1028. void operator()(const UnwindTo& unwind_to) {
  1029. Ptr<Frame> frame = interpreter->stack.Top();
  1030. while (frame->todo.Top() != unwind_to.new_top) {
  1031. if (IsBlockAct(frame->todo.Top())) {
  1032. interpreter->DeallocateScope(frame->scopes.Top());
  1033. frame->scopes.Pop();
  1034. }
  1035. frame->todo.Pop();
  1036. }
  1037. }
  1038. void operator()(const UnwindFunctionCall& unwind) {
  1039. interpreter->DeallocateLocals(interpreter->stack.Top());
  1040. interpreter->stack.Pop();
  1041. if (interpreter->stack.Top()->todo.IsEmpty()) {
  1042. interpreter->program_value = unwind.return_val;
  1043. } else {
  1044. interpreter->stack.Top()->todo.Top()->AddResult(unwind.return_val);
  1045. }
  1046. }
  1047. void operator()(const CallFunction& call) {
  1048. interpreter->stack.Top()->todo.Pop();
  1049. std::optional<Env> matches =
  1050. interpreter->PatternMatch(call.function->Param(), call.args, call.loc);
  1051. CHECK(matches.has_value())
  1052. << "internal error in call_function, pattern match failed";
  1053. // Create the new frame and push it on the stack
  1054. Env values = interpreter->globals;
  1055. std::list<std::string> params;
  1056. for (const auto& [name, value] : *matches) {
  1057. values.Set(name, value);
  1058. params.push_back(name);
  1059. }
  1060. auto scopes = Stack<Ptr<Scope>>(global_arena->New<Scope>(values, params));
  1061. CHECK(call.function->Body()) << "Calling a function that's missing a body";
  1062. auto todo = Stack<Ptr<Action>>(
  1063. global_arena->New<StatementAction>(*call.function->Body()));
  1064. auto frame = global_arena->New<Frame>(call.function->Name(), scopes, todo);
  1065. interpreter->stack.Push(frame);
  1066. }
  1067. void operator()(const ManualTransition&) {}
  1068. private:
  1069. Ptr<Interpreter> interpreter;
  1070. };
  1071. // State transition.
  1072. void Interpreter::Step() {
  1073. Ptr<Frame> frame = stack.Top();
  1074. if (frame->todo.IsEmpty()) {
  1075. FATAL_RUNTIME_ERROR_NO_LINE()
  1076. << "fell off end of function " << frame->name << " without `return`";
  1077. }
  1078. Ptr<Action> act = frame->todo.Top();
  1079. switch (act->Tag()) {
  1080. case Action::Kind::LValAction:
  1081. std::visit(DoTransition(this), StepLvalue());
  1082. break;
  1083. case Action::Kind::ExpressionAction:
  1084. std::visit(DoTransition(this), StepExp());
  1085. break;
  1086. case Action::Kind::PatternAction:
  1087. std::visit(DoTransition(this), StepPattern());
  1088. break;
  1089. case Action::Kind::StatementAction:
  1090. std::visit(DoTransition(this), StepStmt());
  1091. break;
  1092. } // switch
  1093. }
  1094. auto Interpreter::InterpProgram(const std::list<Ptr<const Declaration>>& fs)
  1095. -> int {
  1096. // Check that the interpreter is in a clean state.
  1097. CHECK(globals.IsEmpty());
  1098. CHECK(stack.IsEmpty());
  1099. CHECK(program_value == std::nullopt);
  1100. if (tracing_output) {
  1101. llvm::outs() << "********** initializing globals **********\n";
  1102. }
  1103. InitGlobals(fs);
  1104. SourceLocation loc("<InterpProgram()>", 0);
  1105. Ptr<const Expression> arg = global_arena->New<TupleLiteral>(loc);
  1106. Ptr<const Expression> call_main = global_arena->New<CallExpression>(
  1107. loc, global_arena->New<IdentifierExpression>(loc, "main"), arg);
  1108. auto todo =
  1109. Stack<Ptr<Action>>(global_arena->New<ExpressionAction>(call_main));
  1110. auto scopes = Stack<Ptr<Scope>>(global_arena->New<Scope>(globals));
  1111. stack = Stack<Ptr<Frame>>(global_arena->New<Frame>("top", scopes, todo));
  1112. if (tracing_output) {
  1113. llvm::outs() << "********** calling main function **********\n";
  1114. PrintState(llvm::outs());
  1115. }
  1116. while (stack.Count() > 1 || !stack.Top()->todo.IsEmpty()) {
  1117. Step();
  1118. if (tracing_output) {
  1119. PrintState(llvm::outs());
  1120. }
  1121. }
  1122. return cast<IntValue>(**program_value).Val();
  1123. }
  1124. auto Interpreter::InterpExp(Env values, Ptr<const Expression> e)
  1125. -> const Value* {
  1126. CHECK(program_value == std::nullopt);
  1127. auto program_value_guard =
  1128. llvm::make_scope_exit([&] { program_value = std::nullopt; });
  1129. auto todo = Stack<Ptr<Action>>(global_arena->New<ExpressionAction>(e));
  1130. auto scopes = Stack<Ptr<Scope>>(global_arena->New<Scope>(values));
  1131. stack =
  1132. Stack<Ptr<Frame>>(global_arena->New<Frame>("InterpExp", scopes, todo));
  1133. while (stack.Count() > 1 || !stack.Top()->todo.IsEmpty()) {
  1134. Step();
  1135. }
  1136. CHECK(program_value != std::nullopt);
  1137. return *program_value;
  1138. }
  1139. auto Interpreter::InterpPattern(Env values, Ptr<const Pattern> p)
  1140. -> const Value* {
  1141. CHECK(program_value == std::nullopt);
  1142. auto program_value_guard =
  1143. llvm::make_scope_exit([&] { program_value = std::nullopt; });
  1144. auto todo = Stack<Ptr<Action>>(global_arena->New<PatternAction>(p));
  1145. auto scopes = Stack<Ptr<Scope>>(global_arena->New<Scope>(values));
  1146. stack = Stack<Ptr<Frame>>(
  1147. global_arena->New<Frame>("InterpPattern", scopes, todo));
  1148. while (stack.Count() > 1 || !stack.Top()->todo.IsEmpty()) {
  1149. Step();
  1150. }
  1151. CHECK(program_value != std::nullopt);
  1152. return *program_value;
  1153. }
  1154. } // namespace Carbon