interpreter.cpp 45 KB

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