interpreter.cpp 45 KB

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