interpreter.cpp 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179
  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. Nonnull<const FunctionValue*> f = arena_->New<FunctionValue>(&func_def);
  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{arena_->New<ExpressionAction>(
  390. &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{arena_->New<ExpressionAction>(
  448. &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. .function =
  561. &cast<FunctionValue>(*act->results()[0]).declaration(),
  562. .args = act->results()[1],
  563. .source_loc = exp.source_loc()};
  564. default:
  565. FATAL_RUNTIME_ERROR(exp.source_loc())
  566. << "in call, expected a function, not " << *act->results()[0];
  567. }
  568. } else {
  569. FATAL() << "in handle_value with Call pos " << act->pos();
  570. }
  571. case Expression::Kind::IntrinsicExpression:
  572. CHECK(act->pos() == 0);
  573. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  574. switch (cast<IntrinsicExpression>(exp).intrinsic()) {
  575. case IntrinsicExpression::Intrinsic::Print:
  576. Address pointer = GetFromEnv(exp.source_loc(), "format_str");
  577. Nonnull<const Value*> pointee = heap_.Read(pointer, exp.source_loc());
  578. CHECK(pointee->kind() == Value::Kind::StringValue);
  579. // TODO: This could eventually use something like llvm::formatv.
  580. llvm::outs() << cast<StringValue>(*pointee).value();
  581. return Done{TupleValue::Empty()};
  582. }
  583. case Expression::Kind::IntTypeLiteral: {
  584. CHECK(act->pos() == 0);
  585. return Done{arena_->New<IntType>()};
  586. }
  587. case Expression::Kind::BoolTypeLiteral: {
  588. CHECK(act->pos() == 0);
  589. return Done{arena_->New<BoolType>()};
  590. }
  591. case Expression::Kind::TypeTypeLiteral: {
  592. CHECK(act->pos() == 0);
  593. return Done{arena_->New<TypeType>()};
  594. }
  595. case Expression::Kind::FunctionTypeLiteral: {
  596. if (act->pos() == 0) {
  597. return Spawn{arena_->New<ExpressionAction>(
  598. &cast<FunctionTypeLiteral>(exp).parameter())};
  599. } else if (act->pos() == 1) {
  600. // { { pt :: fn [] -> e :: C, E, F} :: S, H}
  601. // -> { { e :: fn pt -> []) :: C, E, F} :: S, H}
  602. return Spawn{arena_->New<ExpressionAction>(
  603. &cast<FunctionTypeLiteral>(exp).return_type())};
  604. } else {
  605. // { { rt :: fn pt -> [] :: C, E, F} :: S, H}
  606. // -> { fn pt -> rt :: {C, E, F} :: S, H}
  607. return Done{arena_->New<FunctionType>(std::vector<GenericBinding>(),
  608. act->results()[0],
  609. act->results()[1])};
  610. }
  611. }
  612. case Expression::Kind::ContinuationTypeLiteral: {
  613. CHECK(act->pos() == 0);
  614. return Done{arena_->New<ContinuationType>()};
  615. }
  616. case Expression::Kind::StringLiteral:
  617. CHECK(act->pos() == 0);
  618. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  619. return Done{arena_->New<StringValue>(cast<StringLiteral>(exp).value())};
  620. case Expression::Kind::StringTypeLiteral: {
  621. CHECK(act->pos() == 0);
  622. return Done{arena_->New<StringType>()};
  623. }
  624. } // switch (exp->kind)
  625. }
  626. auto Interpreter::StepPattern() -> Transition {
  627. Nonnull<Action*> act = stack_.Top()->todo.Top();
  628. const Pattern& pattern = cast<PatternAction>(*act).pattern();
  629. if (trace_) {
  630. llvm::outs() << "--- step pattern " << pattern << " ("
  631. << pattern.source_loc() << ") --->\n";
  632. }
  633. switch (pattern.kind()) {
  634. case Pattern::Kind::AutoPattern: {
  635. CHECK(act->pos() == 0);
  636. return Done{arena_->New<AutoType>()};
  637. }
  638. case Pattern::Kind::BindingPattern: {
  639. const auto& binding = cast<BindingPattern>(pattern);
  640. if (act->pos() == 0) {
  641. return Spawn{arena_->New<PatternAction>(&binding.type())};
  642. } else {
  643. return Done{arena_->New<BindingPlaceholderValue>(binding.name(),
  644. act->results()[0])};
  645. }
  646. }
  647. case Pattern::Kind::TuplePattern: {
  648. const auto& tuple = cast<TuplePattern>(pattern);
  649. if (act->pos() < static_cast<int>(tuple.fields().size())) {
  650. // { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
  651. // H}
  652. // -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
  653. // H}
  654. return Spawn{arena_->New<PatternAction>(tuple.fields()[act->pos()])};
  655. } else {
  656. return Done{arena_->New<TupleValue>(act->results())};
  657. }
  658. }
  659. case Pattern::Kind::AlternativePattern: {
  660. const auto& alternative = cast<AlternativePattern>(pattern);
  661. if (act->pos() == 0) {
  662. return Spawn{arena_->New<ExpressionAction>(&alternative.choice_type())};
  663. } else if (act->pos() == 1) {
  664. return Spawn{arena_->New<PatternAction>(&alternative.arguments())};
  665. } else {
  666. CHECK(act->pos() == 2);
  667. const auto& choice_type = cast<ChoiceType>(*act->results()[0]);
  668. return Done{arena_->New<AlternativeValue>(
  669. alternative.alternative_name(), choice_type.name(),
  670. act->results()[1])};
  671. }
  672. }
  673. case Pattern::Kind::ExpressionPattern:
  674. return Delegate{arena_->New<ExpressionAction>(
  675. &cast<ExpressionPattern>(pattern).expression())};
  676. }
  677. }
  678. static auto IsWhileAct(Nonnull<Action*> act) -> bool {
  679. switch (act->kind()) {
  680. case Action::Kind::StatementAction:
  681. switch (cast<StatementAction>(*act).statement().kind()) {
  682. case Statement::Kind::While:
  683. return true;
  684. default:
  685. return false;
  686. }
  687. default:
  688. return false;
  689. }
  690. }
  691. static auto HasLocalScope(Nonnull<Action*> act) -> bool {
  692. switch (act->kind()) {
  693. case Action::Kind::StatementAction:
  694. switch (cast<StatementAction>(*act).statement().kind()) {
  695. case Statement::Kind::Block:
  696. case Statement::Kind::Match:
  697. return true;
  698. default:
  699. return false;
  700. }
  701. default:
  702. return false;
  703. }
  704. }
  705. auto Interpreter::StepStmt() -> Transition {
  706. Nonnull<Frame*> frame = stack_.Top();
  707. Nonnull<Action*> act = frame->todo.Top();
  708. const Statement& stmt = cast<StatementAction>(*act).statement();
  709. if (trace_) {
  710. llvm::outs() << "--- step stmt ";
  711. stmt.PrintDepth(1, llvm::outs());
  712. llvm::outs() << " (" << stmt.source_loc() << ") --->\n";
  713. }
  714. switch (stmt.kind()) {
  715. case Statement::Kind::Match: {
  716. const auto& match_stmt = cast<Match>(stmt);
  717. if (act->pos() == 0) {
  718. // { { (match (e) ...) :: C, E, F} :: S, H}
  719. // -> { { e :: (match ([]) ...) :: C, E, F} :: S, H}
  720. frame->scopes.Push(arena_->New<Scope>(CurrentEnv()));
  721. return Spawn{arena_->New<ExpressionAction>(&match_stmt.expression())};
  722. } else {
  723. int clause_num = act->pos() - 1;
  724. if (clause_num >= static_cast<int>(match_stmt.clauses().size())) {
  725. DeallocateScope(frame->scopes.Top());
  726. frame->scopes.Pop();
  727. return Done{};
  728. }
  729. auto c = match_stmt.clauses()[clause_num];
  730. std::optional<Env> matches = PatternMatch(
  731. &c.pattern().value(), act->results()[0], stmt.source_loc());
  732. if (matches) { // We have a match, start the body.
  733. // Ensure we don't process any more clauses.
  734. act->set_pos(match_stmt.clauses().size() + 1);
  735. for (const auto& [name, value] : *matches) {
  736. frame->scopes.Top()->values.Set(name, value);
  737. frame->scopes.Top()->locals.push_back(name);
  738. }
  739. return Spawn{arena_->New<StatementAction>(&c.statement())};
  740. } else {
  741. return RunAgain{};
  742. }
  743. }
  744. }
  745. case Statement::Kind::While:
  746. if (act->pos() % 2 == 0) {
  747. // { { (while (e) s) :: C, E, F} :: S, H}
  748. // -> { { e :: (while ([]) s) :: C, E, F} :: S, H}
  749. act->Clear();
  750. return Spawn{
  751. arena_->New<ExpressionAction>(&cast<While>(stmt).condition())};
  752. } else if (cast<BoolValue>(*act->results().back()).value()) {
  753. // { {true :: (while ([]) s) :: C, E, F} :: S, H}
  754. // -> { { s :: (while (e) s) :: C, E, F } :: S, H}
  755. return Spawn{arena_->New<StatementAction>(&cast<While>(stmt).body())};
  756. } else {
  757. // { {false :: (while ([]) s) :: C, E, F} :: S, H}
  758. // -> { { C, E, F } :: S, H}
  759. return Done{};
  760. }
  761. case Statement::Kind::Break: {
  762. CHECK(act->pos() == 0);
  763. // { { break; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  764. // -> { { C, E', F} :: S, H}
  765. auto it =
  766. std::find_if(frame->todo.begin(), frame->todo.end(), &IsWhileAct);
  767. if (it == frame->todo.end()) {
  768. FATAL_RUNTIME_ERROR(stmt.source_loc())
  769. << "`break` not inside `while` statement";
  770. }
  771. ++it;
  772. return UnwindTo{*it};
  773. }
  774. case Statement::Kind::Continue: {
  775. CHECK(act->pos() == 0);
  776. // { { continue; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  777. // -> { { (while (e) s) :: C, E', F} :: S, H}
  778. auto it =
  779. std::find_if(frame->todo.begin(), frame->todo.end(), &IsWhileAct);
  780. if (it == frame->todo.end()) {
  781. FATAL_RUNTIME_ERROR(stmt.source_loc())
  782. << "`continue` not inside `while` statement";
  783. }
  784. return UnwindTo{*it};
  785. }
  786. case Statement::Kind::Block: {
  787. if (act->pos() == 0) {
  788. const auto& block = cast<Block>(stmt);
  789. if (block.statement()) {
  790. frame->scopes.Push(arena_->New<Scope>(CurrentEnv()));
  791. return Spawn{arena_->New<StatementAction>(*block.statement())};
  792. } else {
  793. return Done{};
  794. }
  795. } else {
  796. Nonnull<Scope*> scope = frame->scopes.Top();
  797. DeallocateScope(scope);
  798. frame->scopes.Pop(1);
  799. return Done{};
  800. }
  801. }
  802. case Statement::Kind::VariableDefinition:
  803. if (act->pos() == 0) {
  804. // { {(var x = e) :: C, E, F} :: S, H}
  805. // -> { {e :: (var x = []) :: C, E, F} :: S, H}
  806. return Spawn{arena_->New<ExpressionAction>(
  807. &cast<VariableDefinition>(stmt).init())};
  808. } else {
  809. // { { v :: (x = []) :: C, E, F} :: S, H}
  810. // -> { { C, E(x := a), F} :: S, H(a := copy(v))}
  811. Nonnull<const Value*> v = act->results()[0];
  812. Nonnull<const Value*> p =
  813. &cast<VariableDefinition>(stmt).pattern().value();
  814. std::optional<Env> matches = PatternMatch(p, v, stmt.source_loc());
  815. CHECK(matches)
  816. << stmt.source_loc()
  817. << ": internal error in variable definition, match failed";
  818. for (const auto& [name, value] : *matches) {
  819. frame->scopes.Top()->values.Set(name, value);
  820. frame->scopes.Top()->locals.push_back(name);
  821. }
  822. return Done{};
  823. }
  824. case Statement::Kind::ExpressionStatement:
  825. if (act->pos() == 0) {
  826. // { {e :: C, E, F} :: S, H}
  827. // -> { {e :: C, E, F} :: S, H}
  828. return Spawn{arena_->New<ExpressionAction>(
  829. &cast<ExpressionStatement>(stmt).expression())};
  830. } else {
  831. return Done{};
  832. }
  833. case Statement::Kind::Assign:
  834. if (act->pos() == 0) {
  835. // { {(lv = e) :: C, E, F} :: S, H}
  836. // -> { {lv :: ([] = e) :: C, E, F} :: S, H}
  837. return Spawn{arena_->New<LValAction>(&cast<Assign>(stmt).lhs())};
  838. } else if (act->pos() == 1) {
  839. // { { a :: ([] = e) :: C, E, F} :: S, H}
  840. // -> { { e :: (a = []) :: C, E, F} :: S, H}
  841. return Spawn{arena_->New<ExpressionAction>(&cast<Assign>(stmt).rhs())};
  842. } else {
  843. // { { v :: (a = []) :: C, E, F} :: S, H}
  844. // -> { { C, E, F} :: S, H(a := v)}
  845. auto pat = act->results()[0];
  846. auto val = act->results()[1];
  847. PatternAssignment(pat, val, stmt.source_loc());
  848. return Done{};
  849. }
  850. case Statement::Kind::If:
  851. if (act->pos() == 0) {
  852. // { {(if (e) then_stmt else else_stmt) :: C, E, F} :: S, H}
  853. // -> { { e :: (if ([]) then_stmt else else_stmt) :: C, E, F} :: S, H}
  854. return Spawn{
  855. arena_->New<ExpressionAction>(&cast<If>(stmt).condition())};
  856. } else if (cast<BoolValue>(*act->results()[0]).value()) {
  857. // { {true :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  858. // S, H}
  859. // -> { { then_stmt :: C, E, F } :: S, H}
  860. return Delegate{
  861. arena_->New<StatementAction>(&cast<If>(stmt).then_statement())};
  862. } else if (cast<If>(stmt).else_statement()) {
  863. // { {false :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  864. // S, H}
  865. // -> { { else_stmt :: C, E, F } :: S, H}
  866. return Delegate{
  867. arena_->New<StatementAction>(*cast<If>(stmt).else_statement())};
  868. } else {
  869. return Done{};
  870. }
  871. case Statement::Kind::Return:
  872. if (act->pos() == 0) {
  873. // { {return e :: C, E, F} :: S, H}
  874. // -> { {e :: return [] :: C, E, F} :: S, H}
  875. return Spawn{
  876. arena_->New<ExpressionAction>(&cast<Return>(stmt).expression())};
  877. } else {
  878. // { {v :: return [] :: C, E, F} :: {C', E', F'} :: S, H}
  879. // -> { {v :: C', E', F'} :: S, H}
  880. return UnwindFunctionCall{act->results()[0]};
  881. }
  882. case Statement::Kind::Sequence: {
  883. // { { (s1,s2) :: C, E, F} :: S, H}
  884. // -> { { s1 :: s2 :: C, E, F} :: S, H}
  885. const auto& seq = cast<Sequence>(stmt);
  886. if (act->pos() == 0) {
  887. return Spawn{arena_->New<StatementAction>(&seq.statement())};
  888. } else {
  889. if (seq.next()) {
  890. return Delegate{
  891. arena_->New<StatementAction>(*cast<Sequence>(stmt).next())};
  892. } else {
  893. return Done{};
  894. }
  895. }
  896. }
  897. case Statement::Kind::Continuation: {
  898. CHECK(act->pos() == 0);
  899. // Create a continuation object by creating a frame similar the
  900. // way one is created in a function call.
  901. auto scopes = Stack<Nonnull<Scope*>>(arena_->New<Scope>(CurrentEnv()));
  902. Stack<Nonnull<Action*>> todo;
  903. todo.Push(arena_->New<StatementAction>(
  904. arena_->New<Return>(arena_, stmt.source_loc())));
  905. todo.Push(arena_->New<StatementAction>(&cast<Continuation>(stmt).body()));
  906. auto continuation_stack = arena_->New<std::vector<Nonnull<Frame*>>>();
  907. auto continuation_frame =
  908. arena_->New<Frame>("__continuation", scopes, todo);
  909. continuation_stack->push_back(continuation_frame);
  910. Address continuation_address = heap_.AllocateValue(
  911. arena_->New<ContinuationValue>(continuation_stack));
  912. // Store the continuation's address in the frame.
  913. continuation_frame->continuation = continuation_address;
  914. // Bind the continuation object to the continuation variable
  915. frame->scopes.Top()->values.Set(
  916. cast<Continuation>(stmt).continuation_variable(),
  917. continuation_address);
  918. // Pop the continuation statement.
  919. frame->todo.Pop();
  920. return ManualTransition{};
  921. }
  922. case Statement::Kind::Run:
  923. if (act->pos() == 0) {
  924. // Evaluate the argument of the run statement.
  925. return Spawn{
  926. arena_->New<ExpressionAction>(&cast<Run>(stmt).argument())};
  927. } else {
  928. frame->todo.Pop(1);
  929. // Push an expression statement action to ignore the result
  930. // value from the continuation.
  931. auto ignore_result =
  932. arena_->New<StatementAction>(arena_->New<ExpressionStatement>(
  933. stmt.source_loc(),
  934. arena_->New<TupleLiteral>(stmt.source_loc())));
  935. frame->todo.Push(ignore_result);
  936. // Push the continuation onto the current stack_.
  937. std::vector<Nonnull<Frame*>>& continuation_vector =
  938. cast<ContinuationValue>(*act->results()[0]).stack();
  939. while (!continuation_vector.empty()) {
  940. stack_.Push(continuation_vector.back());
  941. continuation_vector.pop_back();
  942. }
  943. return ManualTransition{};
  944. }
  945. case Statement::Kind::Await:
  946. CHECK(act->pos() == 0);
  947. // Pause the current continuation
  948. frame->todo.Pop();
  949. std::vector<Nonnull<Frame*>> paused;
  950. do {
  951. paused.push_back(stack_.Pop());
  952. } while (paused.back()->continuation == std::nullopt);
  953. // Update the continuation with the paused stack_.
  954. const auto& continuation = cast<ContinuationValue>(
  955. *heap_.Read(*paused.back()->continuation, stmt.source_loc()));
  956. CHECK(continuation.stack().empty());
  957. continuation.stack() = std::move(paused);
  958. return ManualTransition{};
  959. }
  960. }
  961. class Interpreter::DoTransition {
  962. public:
  963. // Does not take ownership of interpreter.
  964. explicit DoTransition(Interpreter* interpreter) : interpreter(interpreter) {}
  965. void operator()(const Done& done) {
  966. Nonnull<Frame*> frame = interpreter->stack_.Top();
  967. if (frame->todo.Top()->kind() != Action::Kind::StatementAction) {
  968. CHECK(done.result);
  969. frame->todo.Pop();
  970. if (frame->todo.IsEmpty()) {
  971. interpreter->program_value_ = *done.result;
  972. } else {
  973. frame->todo.Top()->AddResult(*done.result);
  974. }
  975. } else {
  976. CHECK(!done.result);
  977. frame->todo.Pop();
  978. }
  979. }
  980. void operator()(const Spawn& spawn) {
  981. Nonnull<Frame*> frame = interpreter->stack_.Top();
  982. Nonnull<Action*> action = frame->todo.Top();
  983. action->set_pos(action->pos() + 1);
  984. frame->todo.Push(spawn.child);
  985. }
  986. void operator()(const Delegate& delegate) {
  987. Nonnull<Frame*> frame = interpreter->stack_.Top();
  988. frame->todo.Pop();
  989. frame->todo.Push(delegate.delegate);
  990. }
  991. void operator()(const RunAgain&) {
  992. Nonnull<Action*> action = interpreter->stack_.Top()->todo.Top();
  993. action->set_pos(action->pos() + 1);
  994. }
  995. void operator()(const UnwindTo& unwind_to) {
  996. Nonnull<Frame*> frame = interpreter->stack_.Top();
  997. while (frame->todo.Top() != unwind_to.new_top) {
  998. if (HasLocalScope(frame->todo.Top())) {
  999. interpreter->DeallocateScope(frame->scopes.Top());
  1000. frame->scopes.Pop();
  1001. }
  1002. frame->todo.Pop();
  1003. }
  1004. }
  1005. void operator()(const UnwindFunctionCall& unwind) {
  1006. interpreter->DeallocateLocals(interpreter->stack_.Top());
  1007. interpreter->stack_.Pop();
  1008. if (interpreter->stack_.Top()->todo.IsEmpty()) {
  1009. interpreter->program_value_ = unwind.return_val;
  1010. } else {
  1011. interpreter->stack_.Top()->todo.Top()->AddResult(unwind.return_val);
  1012. }
  1013. }
  1014. void operator()(const CallFunction& call) {
  1015. interpreter->stack_.Top()->todo.Pop();
  1016. std::optional<Env> matches = interpreter->PatternMatch(
  1017. &call.function->param_pattern().value(), call.args, call.source_loc);
  1018. CHECK(matches.has_value())
  1019. << "internal error in call_function, pattern match failed";
  1020. // Create the new frame and push it on the stack
  1021. Env values = interpreter->globals_;
  1022. std::vector<std::string> params;
  1023. for (const auto& [name, value] : *matches) {
  1024. values.Set(name, value);
  1025. params.push_back(name);
  1026. }
  1027. auto scopes =
  1028. Stack<Nonnull<Scope*>>(interpreter->arena_->New<Scope>(values, params));
  1029. CHECK(call.function->body()) << "Calling a function that's missing a body";
  1030. auto todo = Stack<Nonnull<Action*>>(
  1031. interpreter->arena_->New<StatementAction>(*call.function->body()));
  1032. auto frame =
  1033. interpreter->arena_->New<Frame>(call.function->name(), scopes, todo);
  1034. interpreter->stack_.Push(frame);
  1035. }
  1036. void operator()(const ManualTransition&) {}
  1037. private:
  1038. Nonnull<Interpreter*> interpreter;
  1039. };
  1040. // State transition.
  1041. void Interpreter::Step() {
  1042. Nonnull<Frame*> frame = stack_.Top();
  1043. if (frame->todo.IsEmpty()) {
  1044. std::visit(DoTransition(this),
  1045. Transition{UnwindFunctionCall{TupleValue::Empty()}});
  1046. return;
  1047. }
  1048. Nonnull<Action*> act = frame->todo.Top();
  1049. switch (act->kind()) {
  1050. case Action::Kind::LValAction:
  1051. std::visit(DoTransition(this), StepLvalue());
  1052. break;
  1053. case Action::Kind::ExpressionAction:
  1054. std::visit(DoTransition(this), StepExp());
  1055. break;
  1056. case Action::Kind::PatternAction:
  1057. std::visit(DoTransition(this), StepPattern());
  1058. break;
  1059. case Action::Kind::StatementAction:
  1060. std::visit(DoTransition(this), StepStmt());
  1061. break;
  1062. } // switch
  1063. }
  1064. auto Interpreter::InterpProgram(llvm::ArrayRef<Nonnull<Declaration*>> fs,
  1065. Nonnull<const Expression*> call_main) -> int {
  1066. // Check that the interpreter is in a clean state.
  1067. CHECK(globals_.IsEmpty());
  1068. CHECK(stack_.IsEmpty());
  1069. CHECK(program_value_ == std::nullopt);
  1070. if (trace_) {
  1071. llvm::outs() << "********** initializing globals **********\n";
  1072. }
  1073. InitGlobals(fs);
  1074. auto todo = Stack<Nonnull<Action*>>(arena_->New<ExpressionAction>(call_main));
  1075. auto scopes = Stack<Nonnull<Scope*>>(arena_->New<Scope>(globals_));
  1076. stack_ = Stack<Nonnull<Frame*>>(arena_->New<Frame>("top", scopes, todo));
  1077. if (trace_) {
  1078. llvm::outs() << "********** calling main function **********\n";
  1079. PrintState(llvm::outs());
  1080. }
  1081. while (stack_.Count() > 1 || !stack_.Top()->todo.IsEmpty()) {
  1082. if (!stack_.Top()->todo.IsEmpty()) {
  1083. CHECK(stack_.Top()->todo.Top()->kind() != Action::Kind::PatternAction)
  1084. << "Pattern evaluation must happen before run-time.";
  1085. }
  1086. Step();
  1087. if (trace_) {
  1088. PrintState(llvm::outs());
  1089. }
  1090. }
  1091. return cast<IntValue>(**program_value_).value();
  1092. }
  1093. auto Interpreter::InterpExp(Env values, Nonnull<const Expression*> e)
  1094. -> Nonnull<const Value*> {
  1095. CHECK(program_value_ == std::nullopt);
  1096. auto program_value_guard =
  1097. llvm::make_scope_exit([&] { program_value_ = std::nullopt; });
  1098. auto todo = Stack<Nonnull<Action*>>(arena_->New<ExpressionAction>(e));
  1099. auto scopes = Stack<Nonnull<Scope*>>(arena_->New<Scope>(values));
  1100. stack_ =
  1101. Stack<Nonnull<Frame*>>(arena_->New<Frame>("InterpExp", scopes, todo));
  1102. while (stack_.Count() > 1 || !stack_.Top()->todo.IsEmpty()) {
  1103. Step();
  1104. }
  1105. CHECK(program_value_ != std::nullopt);
  1106. return *program_value_;
  1107. }
  1108. auto Interpreter::InterpPattern(Env values, Nonnull<const Pattern*> p)
  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<PatternAction>(p));
  1114. auto scopes = Stack<Nonnull<Scope*>>(arena_->New<Scope>(values));
  1115. stack_ =
  1116. Stack<Nonnull<Frame*>>(arena_->New<Frame>("InterpPattern", scopes, todo));
  1117. while (stack_.Count() > 1 || !stack_.Top()->todo.IsEmpty()) {
  1118. Step();
  1119. }
  1120. CHECK(program_value_ != std::nullopt);
  1121. return *program_value_;
  1122. }
  1123. } // namespace Carbon