interpreter.cpp 46 KB

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