interpreter.cpp 44 KB

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