interpreter.cpp 46 KB

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