interpreter.cpp 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176
  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& alternative : choice.Alternatives()) {
  140. auto t = InterpExp(Env(arena), &alternative.signature());
  141. alts.push_back(make_pair(alternative.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() <
  392. static_cast<int>(cast<TupleLiteral>(*exp).Fields().size())) {
  393. // { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
  394. // H}
  395. // -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
  396. // H}
  397. Nonnull<const Expression*> elt =
  398. cast<TupleLiteral>(*exp).Fields()[act->Pos()].expression;
  399. return Spawn{arena->New<LValAction>(elt)};
  400. } else {
  401. return Done{CreateTuple(act, exp)};
  402. }
  403. }
  404. case Expression::Kind::IntLiteral:
  405. case Expression::Kind::BoolLiteral:
  406. case Expression::Kind::CallExpression:
  407. case Expression::Kind::PrimitiveOperatorExpression:
  408. case Expression::Kind::IntTypeLiteral:
  409. case Expression::Kind::BoolTypeLiteral:
  410. case Expression::Kind::TypeTypeLiteral:
  411. case Expression::Kind::FunctionTypeLiteral:
  412. case Expression::Kind::ContinuationTypeLiteral:
  413. case Expression::Kind::StringLiteral:
  414. case Expression::Kind::StringTypeLiteral:
  415. case Expression::Kind::IntrinsicExpression:
  416. FATAL_RUNTIME_ERROR_NO_LINE()
  417. << "Can't treat expression as lvalue: " << *exp;
  418. }
  419. }
  420. auto Interpreter::StepExp() -> Transition {
  421. Nonnull<Action*> act = stack.Top()->todo.Top();
  422. Nonnull<const Expression*> exp = cast<ExpressionAction>(*act).Exp();
  423. if (tracing_output) {
  424. llvm::outs() << "--- step exp " << *exp << " (" << exp->SourceLoc()
  425. << ") --->\n";
  426. }
  427. switch (exp->Tag()) {
  428. case Expression::Kind::IndexExpression: {
  429. if (act->Pos() == 0) {
  430. // { { e[i] :: C, E, F} :: S, H}
  431. // -> { { e :: [][i] :: C, E, F} :: S, H}
  432. return Spawn{arena->New<ExpressionAction>(
  433. cast<IndexExpression>(*exp).Aggregate())};
  434. } else if (act->Pos() == 1) {
  435. return Spawn{
  436. arena->New<ExpressionAction>(cast<IndexExpression>(*exp).Offset())};
  437. } else {
  438. // { { v :: [][i] :: C, E, F} :: S, H}
  439. // -> { { v_i :: C, E, F} : S, H}
  440. auto* tuple = dyn_cast<TupleValue>(act->Results()[0]);
  441. if (tuple == nullptr) {
  442. FATAL_RUNTIME_ERROR_NO_LINE()
  443. << "expected a tuple in field access, not " << *act->Results()[0];
  444. }
  445. std::string f =
  446. std::to_string(cast<IntValue>(*act->Results()[1]).Val());
  447. std::optional<Nonnull<const Value*>> field = tuple->FindField(f);
  448. if (!field) {
  449. FATAL_RUNTIME_ERROR_NO_LINE()
  450. << "field " << f << " not in " << *tuple;
  451. }
  452. return Done{*field};
  453. }
  454. }
  455. case Expression::Kind::TupleLiteral: {
  456. if (act->Pos() <
  457. static_cast<int>(cast<TupleLiteral>(*exp).Fields().size())) {
  458. // { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
  459. // H}
  460. // -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
  461. // H}
  462. Nonnull<const Expression*> elt =
  463. cast<TupleLiteral>(*exp).Fields()[act->Pos()].expression;
  464. return Spawn{arena->New<ExpressionAction>(elt)};
  465. } else {
  466. return Done{CreateTuple(act, exp)};
  467. }
  468. }
  469. case Expression::Kind::FieldAccessExpression: {
  470. const auto& access = cast<FieldAccessExpression>(*exp);
  471. if (act->Pos() == 0) {
  472. // { { e.f :: C, E, F} :: S, H}
  473. // -> { { e :: [].f :: C, E, F} :: S, H}
  474. return Spawn{arena->New<ExpressionAction>(access.Aggregate())};
  475. } else {
  476. // { { v :: [].f :: C, E, F} :: S, H}
  477. // -> { { v_f :: C, E, F} : S, H}
  478. return Done{act->Results()[0]->GetField(
  479. arena, FieldPath(access.Field()), exp->SourceLoc())};
  480. }
  481. }
  482. case Expression::Kind::IdentifierExpression: {
  483. CHECK(act->Pos() == 0);
  484. const auto& ident = cast<IdentifierExpression>(*exp);
  485. // { {x :: C, E, F} :: S, H} -> { {H(E(x)) :: C, E, F} :: S, H}
  486. Address pointer = GetFromEnv(exp->SourceLoc(), ident.Name());
  487. return Done{heap.Read(pointer, exp->SourceLoc())};
  488. }
  489. case Expression::Kind::IntLiteral:
  490. CHECK(act->Pos() == 0);
  491. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  492. return Done{arena->New<IntValue>(cast<IntLiteral>(*exp).Val())};
  493. case Expression::Kind::BoolLiteral:
  494. CHECK(act->Pos() == 0);
  495. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  496. return Done{arena->New<BoolValue>(cast<BoolLiteral>(*exp).Val())};
  497. case Expression::Kind::PrimitiveOperatorExpression: {
  498. const auto& op = cast<PrimitiveOperatorExpression>(*exp);
  499. if (act->Pos() != static_cast<int>(op.Arguments().size())) {
  500. // { {v :: op(vs,[],e,es) :: C, E, F} :: S, H}
  501. // -> { {e :: op(vs,v,[],es) :: C, E, F} :: S, H}
  502. Nonnull<const Expression*> arg = op.Arguments()[act->Pos()];
  503. return Spawn{arena->New<ExpressionAction>(arg)};
  504. } else {
  505. // { {v :: op(vs,[]) :: C, E, F} :: S, H}
  506. // -> { {eval_prim(op, (vs,v)) :: C, E, F} :: S, H}
  507. return Done{EvalPrim(op.Op(), act->Results(), exp->SourceLoc())};
  508. }
  509. }
  510. case Expression::Kind::CallExpression:
  511. if (act->Pos() == 0) {
  512. // { {e1(e2) :: C, E, F} :: S, H}
  513. // -> { {e1 :: [](e2) :: C, E, F} :: S, H}
  514. return Spawn{arena->New<ExpressionAction>(
  515. cast<CallExpression>(*exp).Function())};
  516. } else if (act->Pos() == 1) {
  517. // { { v :: [](e) :: C, E, F} :: S, H}
  518. // -> { { e :: v([]) :: C, E, F} :: S, H}
  519. return Spawn{arena->New<ExpressionAction>(
  520. cast<CallExpression>(*exp).Argument())};
  521. } else if (act->Pos() == 2) {
  522. // { { v2 :: v1([]) :: C, E, F} :: S, H}
  523. // -> { {C',E',F'} :: {C, E, F} :: S, H}
  524. switch (act->Results()[0]->Tag()) {
  525. case Value::Kind::ClassType: {
  526. Nonnull<const Value*> arg =
  527. CopyVal(arena, act->Results()[1], exp->SourceLoc());
  528. return Done{arena->New<StructValue>(act->Results()[0], arg)};
  529. }
  530. case Value::Kind::AlternativeConstructorValue: {
  531. const auto& alt =
  532. cast<AlternativeConstructorValue>(*act->Results()[0]);
  533. Nonnull<const Value*> arg =
  534. CopyVal(arena, act->Results()[1], exp->SourceLoc());
  535. return Done{arena->New<AlternativeValue>(alt.AltName(),
  536. alt.ChoiceName(), arg)};
  537. }
  538. case Value::Kind::FunctionValue:
  539. return CallFunction{
  540. // TODO: Think about a cleaner way to cast between Ptr types.
  541. // (multiple TODOs)
  542. .function = Nonnull<const FunctionValue*>(
  543. cast<FunctionValue>(act->Results()[0])),
  544. .args = act->Results()[1],
  545. .loc = exp->SourceLoc()};
  546. default:
  547. FATAL_RUNTIME_ERROR(exp->SourceLoc())
  548. << "in call, expected a function, not " << *act->Results()[0];
  549. }
  550. } else {
  551. FATAL() << "in handle_value with Call pos " << act->Pos();
  552. }
  553. case Expression::Kind::IntrinsicExpression:
  554. CHECK(act->Pos() == 0);
  555. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  556. switch (cast<IntrinsicExpression>(*exp).Intrinsic()) {
  557. case IntrinsicExpression::IntrinsicKind::Print:
  558. Address pointer = GetFromEnv(exp->SourceLoc(), "format_str");
  559. Nonnull<const Value*> pointee = heap.Read(pointer, exp->SourceLoc());
  560. CHECK(pointee->Tag() == Value::Kind::StringValue);
  561. // TODO: This could eventually use something like llvm::formatv.
  562. llvm::outs() << cast<StringValue>(*pointee).Val();
  563. return Done{TupleValue::Empty()};
  564. }
  565. case Expression::Kind::IntTypeLiteral: {
  566. CHECK(act->Pos() == 0);
  567. return Done{arena->New<IntType>()};
  568. }
  569. case Expression::Kind::BoolTypeLiteral: {
  570. CHECK(act->Pos() == 0);
  571. return Done{arena->New<BoolType>()};
  572. }
  573. case Expression::Kind::TypeTypeLiteral: {
  574. CHECK(act->Pos() == 0);
  575. return Done{arena->New<TypeType>()};
  576. }
  577. case Expression::Kind::FunctionTypeLiteral: {
  578. if (act->Pos() == 0) {
  579. return Spawn{arena->New<ExpressionAction>(
  580. cast<FunctionTypeLiteral>(*exp).Parameter())};
  581. } else if (act->Pos() == 1) {
  582. // { { pt :: fn [] -> e :: C, E, F} :: S, H}
  583. // -> { { e :: fn pt -> []) :: C, E, F} :: S, H}
  584. return Spawn{arena->New<ExpressionAction>(
  585. cast<FunctionTypeLiteral>(*exp).ReturnType())};
  586. } else {
  587. // { { rt :: fn pt -> [] :: C, E, F} :: S, H}
  588. // -> { fn pt -> rt :: {C, E, F} :: S, H}
  589. return Done{arena->New<FunctionType>(std::vector<GenericBinding>(),
  590. act->Results()[0],
  591. act->Results()[1])};
  592. }
  593. }
  594. case Expression::Kind::ContinuationTypeLiteral: {
  595. CHECK(act->Pos() == 0);
  596. return Done{arena->New<ContinuationType>()};
  597. }
  598. case Expression::Kind::StringLiteral:
  599. CHECK(act->Pos() == 0);
  600. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  601. return Done{arena->New<StringValue>(cast<StringLiteral>(*exp).Val())};
  602. case Expression::Kind::StringTypeLiteral: {
  603. CHECK(act->Pos() == 0);
  604. return Done{arena->New<StringType>()};
  605. }
  606. } // switch (exp->Tag)
  607. }
  608. auto Interpreter::StepPattern() -> Transition {
  609. Nonnull<Action*> act = stack.Top()->todo.Top();
  610. Nonnull<const Pattern*> pattern = cast<PatternAction>(*act).Pat();
  611. if (tracing_output) {
  612. llvm::outs() << "--- step pattern " << *pattern << " ("
  613. << pattern->SourceLoc() << ") --->\n";
  614. }
  615. switch (pattern->Tag()) {
  616. case Pattern::Kind::AutoPattern: {
  617. CHECK(act->Pos() == 0);
  618. return Done{arena->New<AutoType>()};
  619. }
  620. case Pattern::Kind::BindingPattern: {
  621. const auto& binding = cast<BindingPattern>(*pattern);
  622. if (act->Pos() == 0) {
  623. return Spawn{arena->New<PatternAction>(binding.Type())};
  624. } else {
  625. return Done{arena->New<BindingPlaceholderValue>(binding.Name(),
  626. act->Results()[0])};
  627. }
  628. }
  629. case Pattern::Kind::TuplePattern: {
  630. const auto& tuple = cast<TuplePattern>(*pattern);
  631. if (act->Pos() < static_cast<int>(tuple.Fields().size())) {
  632. // { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
  633. // H}
  634. // -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
  635. // H}
  636. Nonnull<const Pattern*> elt = tuple.Fields()[act->Pos()].pattern;
  637. return Spawn{arena->New<PatternAction>(elt)};
  638. } else {
  639. std::vector<TupleElement> elements;
  640. for (size_t i = 0; i < tuple.Fields().size(); ++i) {
  641. elements.push_back(
  642. {.name = tuple.Fields()[i].name, .value = act->Results()[i]});
  643. }
  644. return Done{arena->New<TupleValue>(std::move(elements))};
  645. }
  646. }
  647. case Pattern::Kind::AlternativePattern: {
  648. const auto& alternative = cast<AlternativePattern>(*pattern);
  649. if (act->Pos() == 0) {
  650. return Spawn{arena->New<ExpressionAction>(alternative.ChoiceType())};
  651. } else if (act->Pos() == 1) {
  652. return Spawn{arena->New<PatternAction>(alternative.Arguments())};
  653. } else {
  654. CHECK(act->Pos() == 2);
  655. const auto& choice_type = cast<ChoiceType>(*act->Results()[0]);
  656. return Done{arena->New<AlternativeValue>(alternative.AlternativeName(),
  657. choice_type.Name(),
  658. act->Results()[1])};
  659. }
  660. }
  661. case Pattern::Kind::ExpressionPattern:
  662. return Delegate{arena->New<ExpressionAction>(
  663. cast<ExpressionPattern>(*pattern).Expression())};
  664. }
  665. }
  666. static auto IsWhileAct(Nonnull<Action*> act) -> bool {
  667. switch (act->Tag()) {
  668. case Action::Kind::StatementAction:
  669. switch (cast<StatementAction>(*act).Stmt()->Tag()) {
  670. case Statement::Kind::While:
  671. return true;
  672. default:
  673. return false;
  674. }
  675. default:
  676. return false;
  677. }
  678. }
  679. static auto HasLocalScope(Nonnull<Action*> act) -> bool {
  680. switch (act->Tag()) {
  681. case Action::Kind::StatementAction:
  682. switch (cast<StatementAction>(*act).Stmt()->Tag()) {
  683. case Statement::Kind::Block:
  684. case Statement::Kind::Match:
  685. return true;
  686. default:
  687. return false;
  688. }
  689. default:
  690. return false;
  691. }
  692. }
  693. auto Interpreter::StepStmt() -> Transition {
  694. Nonnull<Frame*> frame = stack.Top();
  695. Nonnull<Action*> act = frame->todo.Top();
  696. Nonnull<const Statement*> stmt = cast<StatementAction>(*act).Stmt();
  697. if (tracing_output) {
  698. llvm::outs() << "--- step stmt ";
  699. stmt->PrintDepth(1, llvm::outs());
  700. llvm::outs() << " (" << stmt->SourceLoc() << ") --->\n";
  701. }
  702. switch (stmt->Tag()) {
  703. case Statement::Kind::Match: {
  704. const auto& match_stmt = cast<Match>(*stmt);
  705. if (act->Pos() == 0) {
  706. // { { (match (e) ...) :: C, E, F} :: S, H}
  707. // -> { { e :: (match ([]) ...) :: C, E, F} :: S, H}
  708. frame->scopes.Push(arena->New<Scope>(CurrentEnv()));
  709. return Spawn{arena->New<ExpressionAction>(match_stmt.Exp())};
  710. } else {
  711. // Regarding act->Pos():
  712. // * odd: start interpreting the pattern of a clause
  713. // * even: finished interpreting the pattern, now try to match
  714. //
  715. // Regarding act->Results():
  716. // * 0: the value that we're matching
  717. // * 1: the pattern for clause 0
  718. // * 2: the pattern for clause 1
  719. // * ...
  720. auto clause_num = (act->Pos() - 1) / 2;
  721. if (clause_num >= static_cast<int>(match_stmt.Clauses().size())) {
  722. DeallocateScope(frame->scopes.Top());
  723. frame->scopes.Pop();
  724. return Done{};
  725. }
  726. auto c = match_stmt.Clauses()[clause_num];
  727. if (act->Pos() % 2 == 1) {
  728. // start interpreting the pattern of the clause
  729. // { {v :: (match ([]) ...) :: C, E, F} :: S, H}
  730. // -> { {pi :: (match ([]) ...) :: C, E, F} :: S, H}
  731. return Spawn{arena->New<PatternAction>(c.first)};
  732. } else { // try to match
  733. auto v = act->Results()[0];
  734. auto pat = act->Results()[clause_num + 1];
  735. std::optional<Env> matches = PatternMatch(pat, v, stmt->SourceLoc());
  736. if (matches) { // we have a match, start the body
  737. // Ensure we don't process any more clauses.
  738. act->SetPos(2 * match_stmt.Clauses().size() + 1);
  739. for (const auto& [name, value] : *matches) {
  740. frame->scopes.Top()->values.Set(name, value);
  741. frame->scopes.Top()->locals.push_back(name);
  742. }
  743. return Spawn{arena->New<StatementAction>(c.second)};
  744. } else {
  745. return RunAgain{};
  746. }
  747. }
  748. }
  749. }
  750. case Statement::Kind::While:
  751. if (act->Pos() % 2 == 0) {
  752. // { { (while (e) s) :: C, E, F} :: S, H}
  753. // -> { { e :: (while ([]) s) :: C, E, F} :: S, H}
  754. act->Clear();
  755. return Spawn{arena->New<ExpressionAction>(cast<While>(*stmt).Cond())};
  756. } else if (cast<BoolValue>(*act->Results().back()).Val()) {
  757. // { {true :: (while ([]) s) :: C, E, F} :: S, H}
  758. // -> { { s :: (while (e) s) :: C, E, F } :: S, H}
  759. return Spawn{arena->New<StatementAction>(cast<While>(*stmt).Body())};
  760. } else {
  761. // { {false :: (while ([]) s) :: C, E, F} :: S, H}
  762. // -> { { C, E, F } :: S, H}
  763. return Done{};
  764. }
  765. case Statement::Kind::Break: {
  766. CHECK(act->Pos() == 0);
  767. // { { break; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  768. // -> { { C, E', F} :: S, H}
  769. auto it =
  770. std::find_if(frame->todo.begin(), frame->todo.end(), &IsWhileAct);
  771. if (it == frame->todo.end()) {
  772. FATAL_RUNTIME_ERROR(stmt->SourceLoc())
  773. << "`break` not inside `while` statement";
  774. }
  775. ++it;
  776. return UnwindTo{*it};
  777. }
  778. case Statement::Kind::Continue: {
  779. CHECK(act->Pos() == 0);
  780. // { { continue; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  781. // -> { { (while (e) s) :: C, E', F} :: S, H}
  782. auto it =
  783. std::find_if(frame->todo.begin(), frame->todo.end(), &IsWhileAct);
  784. if (it == frame->todo.end()) {
  785. FATAL_RUNTIME_ERROR(stmt->SourceLoc())
  786. << "`continue` not inside `while` statement";
  787. }
  788. return UnwindTo{*it};
  789. }
  790. case Statement::Kind::Block: {
  791. if (act->Pos() == 0) {
  792. const Block& block = cast<Block>(*stmt);
  793. if (block.Stmt()) {
  794. frame->scopes.Push(arena->New<Scope>(CurrentEnv()));
  795. return Spawn{arena->New<StatementAction>(*block.Stmt())};
  796. } else {
  797. return Done{};
  798. }
  799. } else {
  800. Nonnull<Scope*> scope = frame->scopes.Top();
  801. DeallocateScope(scope);
  802. frame->scopes.Pop(1);
  803. return Done{};
  804. }
  805. }
  806. case Statement::Kind::VariableDefinition:
  807. if (act->Pos() == 0) {
  808. // { {(var x = e) :: C, E, F} :: S, H}
  809. // -> { {e :: (var x = []) :: C, E, F} :: S, H}
  810. return Spawn{arena->New<ExpressionAction>(
  811. cast<VariableDefinition>(*stmt).Init())};
  812. } else if (act->Pos() == 1) {
  813. return Spawn{
  814. arena->New<PatternAction>(cast<VariableDefinition>(*stmt).Pat())};
  815. } else {
  816. // { { v :: (x = []) :: C, E, F} :: S, H}
  817. // -> { { C, E(x := a), F} :: S, H(a := copy(v))}
  818. Nonnull<const Value*> v = act->Results()[0];
  819. Nonnull<const Value*> p = act->Results()[1];
  820. std::optional<Env> matches = PatternMatch(p, v, stmt->SourceLoc());
  821. CHECK(matches)
  822. << stmt->SourceLoc()
  823. << ": internal error in variable definition, match failed";
  824. for (const auto& [name, value] : *matches) {
  825. frame->scopes.Top()->values.Set(name, value);
  826. frame->scopes.Top()->locals.push_back(name);
  827. }
  828. return Done{};
  829. }
  830. case Statement::Kind::ExpressionStatement:
  831. if (act->Pos() == 0) {
  832. // { {e :: C, E, F} :: S, H}
  833. // -> { {e :: C, E, F} :: S, H}
  834. return Spawn{arena->New<ExpressionAction>(
  835. cast<ExpressionStatement>(*stmt).Exp())};
  836. } else {
  837. return Done{};
  838. }
  839. case Statement::Kind::Assign:
  840. if (act->Pos() == 0) {
  841. // { {(lv = e) :: C, E, F} :: S, H}
  842. // -> { {lv :: ([] = e) :: C, E, F} :: S, H}
  843. return Spawn{arena->New<LValAction>(cast<Assign>(*stmt).Lhs())};
  844. } else if (act->Pos() == 1) {
  845. // { { a :: ([] = e) :: C, E, F} :: S, H}
  846. // -> { { e :: (a = []) :: C, E, F} :: S, H}
  847. return Spawn{arena->New<ExpressionAction>(cast<Assign>(*stmt).Rhs())};
  848. } else {
  849. // { { v :: (a = []) :: C, E, F} :: S, H}
  850. // -> { { C, E, F} :: S, H(a := v)}
  851. auto pat = act->Results()[0];
  852. auto val = act->Results()[1];
  853. PatternAssignment(pat, val, stmt->SourceLoc());
  854. return Done{};
  855. }
  856. case Statement::Kind::If:
  857. if (act->Pos() == 0) {
  858. // { {(if (e) then_stmt else else_stmt) :: C, E, F} :: S, H}
  859. // -> { { e :: (if ([]) then_stmt else else_stmt) :: C, E, F} :: S, H}
  860. return Spawn{arena->New<ExpressionAction>(cast<If>(*stmt).Cond())};
  861. } else if (cast<BoolValue>(*act->Results()[0]).Val()) {
  862. // { {true :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  863. // S, H}
  864. // -> { { then_stmt :: C, E, F } :: S, H}
  865. return Delegate{
  866. arena->New<StatementAction>(cast<If>(*stmt).ThenStmt())};
  867. } else if (cast<If>(*stmt).ElseStmt()) {
  868. // { {false :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  869. // S, H}
  870. // -> { { else_stmt :: C, E, F } :: S, H}
  871. return Delegate{
  872. arena->New<StatementAction>(*cast<If>(*stmt).ElseStmt())};
  873. } else {
  874. return Done{};
  875. }
  876. case Statement::Kind::Return:
  877. if (act->Pos() == 0) {
  878. // { {return e :: C, E, F} :: S, H}
  879. // -> { {e :: return [] :: C, E, F} :: S, H}
  880. return Spawn{arena->New<ExpressionAction>(cast<Return>(*stmt).Exp())};
  881. } else {
  882. // { {v :: return [] :: C, E, F} :: {C', E', F'} :: S, H}
  883. // -> { {v :: C', E', F'} :: S, H}
  884. Nonnull<const Value*> ret_val =
  885. CopyVal(arena, act->Results()[0], stmt->SourceLoc());
  886. return UnwindFunctionCall{ret_val};
  887. }
  888. case Statement::Kind::Sequence: {
  889. // { { (s1,s2) :: C, E, F} :: S, H}
  890. // -> { { s1 :: s2 :: C, E, F} :: S, H}
  891. const Sequence& seq = cast<Sequence>(*stmt);
  892. if (act->Pos() == 0) {
  893. return Spawn{arena->New<StatementAction>(seq.Stmt())};
  894. } else {
  895. if (seq.Next()) {
  896. return Delegate{
  897. arena->New<StatementAction>(*cast<Sequence>(*stmt).Next())};
  898. } else {
  899. return Done{};
  900. }
  901. }
  902. }
  903. case Statement::Kind::Continuation: {
  904. CHECK(act->Pos() == 0);
  905. // Create a continuation object by creating a frame similar the
  906. // way one is created in a function call.
  907. auto scopes = Stack<Nonnull<Scope*>>(arena->New<Scope>(CurrentEnv()));
  908. Stack<Nonnull<Action*>> todo;
  909. todo.Push(arena->New<StatementAction>(
  910. arena->New<Return>(arena, stmt->SourceLoc())));
  911. todo.Push(arena->New<StatementAction>(cast<Continuation>(*stmt).Body()));
  912. auto continuation_frame =
  913. arena->New<Frame>("__continuation", scopes, todo);
  914. Address continuation_address =
  915. heap.AllocateValue(arena->New<ContinuationValue>(
  916. std::vector<Nonnull<Frame*>>({continuation_frame})));
  917. // Store the continuation's address in the frame.
  918. continuation_frame->continuation = continuation_address;
  919. // Bind the continuation object to the continuation variable
  920. frame->scopes.Top()->values.Set(
  921. cast<Continuation>(*stmt).ContinuationVariable(),
  922. continuation_address);
  923. // Pop the continuation statement.
  924. frame->todo.Pop();
  925. return ManualTransition{};
  926. }
  927. case Statement::Kind::Run:
  928. if (act->Pos() == 0) {
  929. // Evaluate the argument of the run statement.
  930. return Spawn{arena->New<ExpressionAction>(cast<Run>(*stmt).Argument())};
  931. } else {
  932. frame->todo.Pop(1);
  933. // Push an expression statement action to ignore the result
  934. // value from the continuation.
  935. auto ignore_result =
  936. arena->New<StatementAction>(arena->New<ExpressionStatement>(
  937. stmt->SourceLoc(),
  938. arena->New<TupleLiteral>(stmt->SourceLoc())));
  939. frame->todo.Push(ignore_result);
  940. // Push the continuation onto the current stack.
  941. const std::vector<Nonnull<Frame*>>& continuation_vector =
  942. cast<ContinuationValue>(*act->Results()[0]).Stack();
  943. for (auto frame_iter = continuation_vector.rbegin();
  944. frame_iter != continuation_vector.rend(); ++frame_iter) {
  945. stack.Push(*frame_iter);
  946. }
  947. return ManualTransition{};
  948. }
  949. case Statement::Kind::Await:
  950. CHECK(act->Pos() == 0);
  951. // Pause the current continuation
  952. frame->todo.Pop();
  953. std::vector<Nonnull<Frame*>> paused;
  954. do {
  955. paused.push_back(stack.Pop());
  956. } while (paused.back()->continuation == std::nullopt);
  957. // Update the continuation with the paused stack.
  958. heap.Write(*paused.back()->continuation,
  959. arena->New<ContinuationValue>(paused), stmt->SourceLoc());
  960. return ManualTransition{};
  961. }
  962. }
  963. class Interpreter::DoTransition {
  964. public:
  965. // Does not take ownership of interpreter.
  966. DoTransition(Interpreter* interpreter) : interpreter(interpreter) {}
  967. void operator()(const Done& done) {
  968. Nonnull<Frame*> frame = interpreter->stack.Top();
  969. if (frame->todo.Top()->Tag() != Action::Kind::StatementAction) {
  970. CHECK(done.result);
  971. frame->todo.Pop();
  972. if (frame->todo.IsEmpty()) {
  973. interpreter->program_value = *done.result;
  974. } else {
  975. frame->todo.Top()->AddResult(*done.result);
  976. }
  977. } else {
  978. CHECK(!done.result);
  979. frame->todo.Pop();
  980. }
  981. }
  982. void operator()(const Spawn& spawn) {
  983. Nonnull<Frame*> frame = interpreter->stack.Top();
  984. Nonnull<Action*> action = frame->todo.Top();
  985. action->SetPos(action->Pos() + 1);
  986. frame->todo.Push(spawn.child);
  987. }
  988. void operator()(const Delegate& delegate) {
  989. Nonnull<Frame*> frame = interpreter->stack.Top();
  990. frame->todo.Pop();
  991. frame->todo.Push(delegate.delegate);
  992. }
  993. void operator()(const RunAgain&) {
  994. Nonnull<Action*> action = interpreter->stack.Top()->todo.Top();
  995. action->SetPos(action->Pos() + 1);
  996. }
  997. void operator()(const UnwindTo& unwind_to) {
  998. Nonnull<Frame*> frame = interpreter->stack.Top();
  999. while (frame->todo.Top() != unwind_to.new_top) {
  1000. if (HasLocalScope(frame->todo.Top())) {
  1001. interpreter->DeallocateScope(frame->scopes.Top());
  1002. frame->scopes.Pop();
  1003. }
  1004. frame->todo.Pop();
  1005. }
  1006. }
  1007. void operator()(const UnwindFunctionCall& unwind) {
  1008. interpreter->DeallocateLocals(interpreter->stack.Top());
  1009. interpreter->stack.Pop();
  1010. if (interpreter->stack.Top()->todo.IsEmpty()) {
  1011. interpreter->program_value = unwind.return_val;
  1012. } else {
  1013. interpreter->stack.Top()->todo.Top()->AddResult(unwind.return_val);
  1014. }
  1015. }
  1016. void operator()(const CallFunction& call) {
  1017. interpreter->stack.Top()->todo.Pop();
  1018. std::optional<Env> matches =
  1019. interpreter->PatternMatch(call.function->Param(), call.args, call.loc);
  1020. CHECK(matches.has_value())
  1021. << "internal error in call_function, pattern match failed";
  1022. // Create the new frame and push it on the stack
  1023. Env values = interpreter->globals;
  1024. std::vector<std::string> params;
  1025. for (const auto& [name, value] : *matches) {
  1026. values.Set(name, value);
  1027. params.push_back(name);
  1028. }
  1029. auto scopes =
  1030. Stack<Nonnull<Scope*>>(interpreter->arena->New<Scope>(values, params));
  1031. CHECK(call.function->Body()) << "Calling a function that's missing a body";
  1032. auto todo = Stack<Nonnull<Action*>>(
  1033. interpreter->arena->New<StatementAction>(*call.function->Body()));
  1034. auto frame =
  1035. interpreter->arena->New<Frame>(call.function->Name(), scopes, todo);
  1036. interpreter->stack.Push(frame);
  1037. }
  1038. void operator()(const ManualTransition&) {}
  1039. private:
  1040. Nonnull<Interpreter*> interpreter;
  1041. };
  1042. // State transition.
  1043. void Interpreter::Step() {
  1044. Nonnull<Frame*> frame = stack.Top();
  1045. if (frame->todo.IsEmpty()) {
  1046. FATAL_RUNTIME_ERROR_NO_LINE()
  1047. << "fell off end of function " << frame->name << " without `return`";
  1048. }
  1049. Nonnull<Action*> act = frame->todo.Top();
  1050. switch (act->Tag()) {
  1051. case Action::Kind::LValAction:
  1052. std::visit(DoTransition(this), StepLvalue());
  1053. break;
  1054. case Action::Kind::ExpressionAction:
  1055. std::visit(DoTransition(this), StepExp());
  1056. break;
  1057. case Action::Kind::PatternAction:
  1058. std::visit(DoTransition(this), StepPattern());
  1059. break;
  1060. case Action::Kind::StatementAction:
  1061. std::visit(DoTransition(this), StepStmt());
  1062. break;
  1063. } // switch
  1064. }
  1065. auto Interpreter::InterpProgram(
  1066. const std::vector<Nonnull<const Declaration*>>& fs,
  1067. Nonnull<const Expression*> call_main) -> int {
  1068. // Check that the interpreter is in a clean state.
  1069. CHECK(globals.IsEmpty());
  1070. CHECK(stack.IsEmpty());
  1071. CHECK(program_value == std::nullopt);
  1072. if (tracing_output) {
  1073. llvm::outs() << "********** initializing globals **********\n";
  1074. }
  1075. InitGlobals(fs);
  1076. auto todo = Stack<Nonnull<Action*>>(arena->New<ExpressionAction>(call_main));
  1077. auto scopes = Stack<Nonnull<Scope*>>(arena->New<Scope>(globals));
  1078. stack = Stack<Nonnull<Frame*>>(arena->New<Frame>("top", scopes, todo));
  1079. if (tracing_output) {
  1080. llvm::outs() << "********** calling main function **********\n";
  1081. PrintState(llvm::outs());
  1082. }
  1083. while (stack.Count() > 1 || !stack.Top()->todo.IsEmpty()) {
  1084. Step();
  1085. if (tracing_output) {
  1086. PrintState(llvm::outs());
  1087. }
  1088. }
  1089. return cast<IntValue>(**program_value).Val();
  1090. }
  1091. auto Interpreter::InterpExp(Env values, Nonnull<const Expression*> e)
  1092. -> Nonnull<const Value*> {
  1093. CHECK(program_value == std::nullopt);
  1094. auto program_value_guard =
  1095. llvm::make_scope_exit([&] { program_value = std::nullopt; });
  1096. auto todo = Stack<Nonnull<Action*>>(arena->New<ExpressionAction>(e));
  1097. auto scopes = Stack<Nonnull<Scope*>>(arena->New<Scope>(values));
  1098. stack = Stack<Nonnull<Frame*>>(arena->New<Frame>("InterpExp", scopes, todo));
  1099. while (stack.Count() > 1 || !stack.Top()->todo.IsEmpty()) {
  1100. Step();
  1101. }
  1102. CHECK(program_value != std::nullopt);
  1103. return *program_value;
  1104. }
  1105. auto Interpreter::InterpPattern(Env values, Nonnull<const Pattern*> p)
  1106. -> Nonnull<const Value*> {
  1107. CHECK(program_value == std::nullopt);
  1108. auto program_value_guard =
  1109. llvm::make_scope_exit([&] { program_value = std::nullopt; });
  1110. auto todo = Stack<Nonnull<Action*>>(arena->New<PatternAction>(p));
  1111. auto scopes = Stack<Nonnull<Scope*>>(arena->New<Scope>(values));
  1112. stack =
  1113. Stack<Nonnull<Frame*>>(arena->New<Frame>("InterpPattern", scopes, todo));
  1114. while (stack.Count() > 1 || !stack.Top()->todo.IsEmpty()) {
  1115. Step();
  1116. }
  1117. CHECK(program_value != std::nullopt);
  1118. return *program_value;
  1119. }
  1120. } // namespace Carbon