interpreter.cpp 46 KB

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