interpreter.cpp 47 KB

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