interpreter.cpp 44 KB

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