interpreter.cpp 46 KB

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