interpreter.cpp 43 KB

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