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