interpreter.cpp 45 KB

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