interpreter.cpp 45 KB

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