interpreter.cpp 45 KB

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