interpreter.cpp 44 KB

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