interpreter.cpp 47 KB

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