interpreter.cpp 48 KB

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