interpreter.cpp 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366
  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 {
  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. }
  1137. break;
  1138. case StatementKind::While:
  1139. if (ValToBool(act->results[0], stmt->line_num)) {
  1140. // { {true :: (while ([]) s) :: C, E, F} :: S, H}
  1141. // -> { { s :: (while (e) s) :: C, E, F } :: S, H}
  1142. frame->todo.Pop(1);
  1143. frame->todo.Top()->pos = -1;
  1144. frame->todo.Top()->results.clear();
  1145. frame->todo.Push(MakeStmtAct(stmt->u.while_stmt.body));
  1146. } else {
  1147. // { {false :: (while ([]) s) :: C, E, F} :: S, H}
  1148. // -> { { C, E, F } :: S, H}
  1149. frame->todo.Pop(1);
  1150. frame->todo.Top()->pos = -1;
  1151. frame->todo.Top()->results.clear();
  1152. frame->todo.Pop(1);
  1153. }
  1154. break;
  1155. case StatementKind::Match: {
  1156. // Regarding act->pos:
  1157. // * odd: start interpreting the pattern of a clause
  1158. // * even: finished interpreting the pattern, now try to match
  1159. //
  1160. // Regarding act->results:
  1161. // * 0: the value that we're matching
  1162. // * 1: the pattern for clause 0
  1163. // * 2: the pattern for clause 1
  1164. // * ...
  1165. auto clause_num = (act->pos - 1) / 2;
  1166. if (clause_num >=
  1167. static_cast<int>(stmt->u.match_stmt.clauses->size())) {
  1168. frame->todo.Pop(2);
  1169. break;
  1170. }
  1171. auto c = stmt->u.match_stmt.clauses->begin();
  1172. std::advance(c, clause_num);
  1173. if (act->pos % 2 == 1) {
  1174. // start interpreting the pattern of the clause
  1175. // { {v :: (match ([]) ...) :: C, E, F} :: S, H}
  1176. // -> { {pi :: (match ([]) ...) :: C, E, F} :: S, H}
  1177. frame->todo.Pop(1);
  1178. frame->todo.Push(MakeExpAct(c->first));
  1179. } else { // try to match
  1180. auto v = act->results[0];
  1181. auto pat = act->results[clause_num + 1];
  1182. auto env = CurrentEnv(state);
  1183. std::list<std::string> vars;
  1184. Env* new_env = PatternMatch(pat, v, env, &vars, stmt->line_num);
  1185. if (new_env) { // we have a match, start the body
  1186. auto* new_scope = new Scope(new_env, vars);
  1187. frame->scopes.Push(new_scope);
  1188. Statement* body_block = MakeBlock(stmt->line_num, c->second);
  1189. Action* body_act = MakeStmtAct(body_block);
  1190. body_act->pos = 0;
  1191. frame->todo.Pop(2);
  1192. frame->todo.Push(body_act);
  1193. frame->todo.Push(MakeStmtAct(c->second));
  1194. } else {
  1195. act->pos++;
  1196. clause_num = (act->pos - 1) / 2;
  1197. if (clause_num <
  1198. static_cast<int>(stmt->u.match_stmt.clauses->size())) {
  1199. // move on to the next clause
  1200. c = stmt->u.match_stmt.clauses->begin();
  1201. std::advance(c, clause_num);
  1202. frame->todo.Pop(1);
  1203. frame->todo.Push(MakeExpAct(c->first));
  1204. } else { // No more clauses in match
  1205. frame->todo.Pop(2);
  1206. }
  1207. }
  1208. }
  1209. break;
  1210. }
  1211. case StatementKind::Return: {
  1212. // { {v :: return [] :: C, E, F} :: {C', E', F'} :: S, H}
  1213. // -> { {v :: C', E', F'} :: S, H}
  1214. Value* ret_val = CopyVal(val_act->u.val, stmt->line_num);
  1215. KillLocals(stmt->line_num, frame);
  1216. state->stack.Pop(1);
  1217. frame = state->stack.Top();
  1218. frame->todo.Push(MakeValAct(ret_val));
  1219. break;
  1220. }
  1221. case StatementKind::Block:
  1222. case StatementKind::Sequence:
  1223. case StatementKind::Break:
  1224. case StatementKind::Continue:
  1225. std::cerr << "internal error in handle_value, unhandled statement ";
  1226. PrintStatement(stmt, 1);
  1227. std::cerr << std::endl;
  1228. exit(-1);
  1229. } // switch stmt
  1230. break;
  1231. }
  1232. case ActionKind::ValAction:
  1233. std::cerr << "internal error, ValAction in handle_value" << std::endl;
  1234. exit(-1);
  1235. } // switch act
  1236. }
  1237. // State transition.
  1238. void Step() {
  1239. Frame* frame = state->stack.Top();
  1240. if (frame->todo.IsEmpty()) {
  1241. std::cerr << "runtime error: fell off end of function " << frame->name
  1242. << " without `return`" << std::endl;
  1243. exit(-1);
  1244. }
  1245. Action* act = frame->todo.Top();
  1246. switch (act->tag) {
  1247. case ActionKind::DeleteTmpAction:
  1248. std::cerr << "internal error in step, did not expect DeleteTmpAction"
  1249. << std::endl;
  1250. break;
  1251. case ActionKind::ExpToLValAction:
  1252. std::cerr << "internal error in step, did not expect ExpToLValAction"
  1253. << std::endl;
  1254. break;
  1255. case ActionKind::ValAction:
  1256. HandleValue();
  1257. break;
  1258. case ActionKind::LValAction:
  1259. StepLvalue();
  1260. break;
  1261. case ActionKind::ExpressionAction:
  1262. StepExp();
  1263. break;
  1264. case ActionKind::StatementAction:
  1265. StepStmt();
  1266. break;
  1267. } // switch
  1268. }
  1269. // Interpret the whole porogram.
  1270. auto InterpProgram(std::list<Declaration>* fs) -> int {
  1271. state = new State(); // Runtime state.
  1272. std::cout << "********** initializing globals **********" << std::endl;
  1273. InitGlobals(fs);
  1274. Expression* arg =
  1275. MakeTuple(0, new std::vector<std::pair<std::string, Expression*>>());
  1276. Expression* call_main = MakeCall(0, MakeVar(0, "main"), arg);
  1277. auto todo = Stack(MakeExpAct(call_main));
  1278. auto* scope = new Scope(globals, std::list<std::string>());
  1279. auto* frame = new Frame("top", Stack(scope), todo);
  1280. state->stack = Stack(frame);
  1281. std::cout << "********** calling main function **********" << std::endl;
  1282. PrintState(std::cout);
  1283. while (state->stack.CountExceeds(1) ||
  1284. state->stack.Top()->todo.CountExceeds(1) ||
  1285. state->stack.Top()->todo.Top()->tag != ActionKind::ValAction) {
  1286. Step();
  1287. PrintState(std::cout);
  1288. }
  1289. Value* v = state->stack.Top()->todo.Top()->u.val;
  1290. return ValToInt(v, 0);
  1291. }
  1292. // Interpret an expression at compile-time.
  1293. auto InterpExp(Env* env, Expression* e) -> Value* {
  1294. auto todo = Stack(MakeExpAct(e));
  1295. auto* scope = new Scope(env, std::list<std::string>());
  1296. auto* frame = new Frame("InterpExp", Stack(scope), todo);
  1297. state->stack = Stack(frame);
  1298. while (state->stack.CountExceeds(1) ||
  1299. state->stack.Top()->todo.CountExceeds(1) ||
  1300. state->stack.Top()->todo.Top()->tag != ActionKind::ValAction) {
  1301. Step();
  1302. }
  1303. Value* v = state->stack.Top()->todo.Top()->u.val;
  1304. return v;
  1305. }
  1306. } // namespace Carbon