interpreter.cpp 45 KB

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