interpreter.cpp 49 KB

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