interpreter.cpp 49 KB

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