interpreter.cpp 46 KB

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