interpreter.cpp 48 KB

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