interpreter.cpp 45 KB

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