interpreter.cpp 45 KB

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