interpreter.cpp 44 KB

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