interpreter.cpp 44 KB

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