interpreter.cpp 49 KB

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