interpreter.cpp 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511
  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 Heap::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. assert(v != nullptr);
  32. Address a = values_.size();
  33. values_.push_back(v);
  34. alive_.push_back(true);
  35. return a;
  36. }
  37. auto Heap::Read(Address a, int line_num) -> const Value* {
  38. this->CheckAlive(a, line_num);
  39. return values_[a];
  40. }
  41. auto Heap::Write(Address a, const Value* v, int line_num) -> void {
  42. assert(v != nullptr);
  43. this->CheckAlive(a, line_num);
  44. values_[a] = v;
  45. }
  46. void Heap::CheckAlive(Address address, int line_num) {
  47. if (!alive_[address]) {
  48. std::cerr << line_num << ": undefined behavior: access to dead value ";
  49. PrintValue(values_[address], std::cerr);
  50. std::cerr << std::endl;
  51. exit(-1);
  52. }
  53. }
  54. auto CopyVal(const Value* val, int line_num) -> const Value* {
  55. switch (val->tag) {
  56. case ValKind::TupleV: {
  57. auto elts = new std::vector<std::pair<std::string, Address>>();
  58. for (auto& i : *val->u.tuple.elts) {
  59. const Value* elt =
  60. CopyVal(state->heap.Read(i.second, line_num), line_num);
  61. Address new_address = state->heap.AllocateValue(elt);
  62. elts->push_back(make_pair(i.first, new_address));
  63. }
  64. return MakeTupleVal(elts);
  65. }
  66. case ValKind::AltV: {
  67. const Value* arg =
  68. CopyVal(state->heap.Read(val->u.alt.argument, line_num), line_num);
  69. Address argument_address = state->heap.AllocateValue(arg);
  70. return MakeAltVal(*val->u.alt.alt_name, *val->u.alt.choice_name,
  71. argument_address);
  72. }
  73. case ValKind::StructV: {
  74. const Value* inits = CopyVal(val->u.struct_val.inits, line_num);
  75. return MakeStructVal(val->u.struct_val.type, inits);
  76. }
  77. case ValKind::IntV:
  78. return MakeIntVal(val->u.integer);
  79. case ValKind::BoolV:
  80. return MakeBoolVal(val->u.boolean);
  81. case ValKind::FunV:
  82. return MakeFunVal(*val->u.fun.name, val->u.fun.param, val->u.fun.body);
  83. case ValKind::PtrV:
  84. return MakePtrVal(val->u.ptr);
  85. case ValKind::ContinuationV:
  86. // Copying a continuation is "shallow".
  87. return val;
  88. case ValKind::FunctionTV:
  89. return MakeFunTypeVal(CopyVal(val->u.fun_type.param, line_num),
  90. CopyVal(val->u.fun_type.ret, line_num));
  91. case ValKind::PointerTV:
  92. return MakePtrTypeVal(CopyVal(val->u.ptr_type.type, line_num));
  93. case ValKind::IntTV:
  94. return MakeIntTypeVal();
  95. case ValKind::BoolTV:
  96. return MakeBoolTypeVal();
  97. case ValKind::TypeTV:
  98. return MakeTypeTypeVal();
  99. case ValKind::VarTV:
  100. return MakeVarTypeVal(*val->u.var_type);
  101. case ValKind::AutoTV:
  102. return MakeAutoTypeVal();
  103. case ValKind::ContinuationTV:
  104. return MakeContinuationTypeVal();
  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 Heap::DeallocateSubObjects(const Value* val) {
  114. switch (val->tag) {
  115. case ValKind::AltV:
  116. Deallocate(val->u.alt.argument);
  117. break;
  118. case ValKind::StructV:
  119. DeallocateSubObjects(val->u.struct_val.inits);
  120. break;
  121. case ValKind::TupleV:
  122. for (auto& elt : *val->u.tuple.elts) {
  123. Deallocate(elt.second);
  124. }
  125. break;
  126. default:
  127. break;
  128. }
  129. }
  130. void Heap::Deallocate(Address address) {
  131. if (alive_[address]) {
  132. alive_[address] = false;
  133. DeallocateSubObjects(values_[address]);
  134. } else {
  135. std::cerr << "runtime error, deallocating an already dead value"
  136. << std::endl;
  137. exit(-1);
  138. }
  139. }
  140. void PrintEnv(Env values, std::ostream& out) {
  141. for (const auto& [name, address] : values) {
  142. out << name << ": ";
  143. state->heap.PrintAddress(address, out);
  144. out << ", ";
  145. }
  146. }
  147. //
  148. // Frame and State Operations
  149. //
  150. void PrintFrame(Frame* frame, std::ostream& out) {
  151. out << frame->name;
  152. out << "{";
  153. PrintActList(frame->todo, out);
  154. out << "}";
  155. }
  156. void PrintStack(Stack<Frame*> ls, std::ostream& out) {
  157. if (!ls.IsEmpty()) {
  158. PrintFrame(ls.Pop(), out);
  159. if (!ls.IsEmpty()) {
  160. out << " :: ";
  161. PrintStack(ls, out);
  162. }
  163. }
  164. }
  165. void Heap::PrintHeap(std::ostream& out) {
  166. for (Address i = 0; i < values_.size(); ++i) {
  167. PrintAddress(i, out);
  168. out << ", ";
  169. }
  170. }
  171. auto Heap::PrintAddress(Address a, std::ostream& out) -> void {
  172. if (!alive_[a]) {
  173. out << "!!";
  174. }
  175. PrintValue(values_[a], out);
  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. state->heap.PrintHeap(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. switch (v->tag) {
  217. case ValKind::PtrV:
  218. return v->u.ptr;
  219. default:
  220. std::cerr << "runtime type error: expected a pointer, not ";
  221. PrintValue(v, std::cerr);
  222. std::cerr << std::endl;
  223. exit(-1);
  224. }
  225. }
  226. // Returns *continuation represented as a list of frames.
  227. //
  228. // - Precondition: continuation->tag == ValKind::ContinuationV.
  229. auto ContinuationToVector(const Value* continuation, int sourceLocation)
  230. -> std::vector<Frame*> {
  231. if (continuation->tag == ValKind::ContinuationV) {
  232. return *continuation->u.continuation.stack;
  233. } else {
  234. std::cerr << sourceLocation << ": runtime error: expected an integer"
  235. << std::endl;
  236. exit(-1);
  237. }
  238. }
  239. auto EvalPrim(Operator op, const std::vector<const Value*>& args, int line_num)
  240. -> const Value* {
  241. switch (op) {
  242. case Operator::Neg:
  243. return MakeIntVal(-ValToInt(args[0], line_num));
  244. case Operator::Add:
  245. return MakeIntVal(ValToInt(args[0], line_num) +
  246. ValToInt(args[1], line_num));
  247. case Operator::Sub:
  248. return MakeIntVal(ValToInt(args[0], line_num) -
  249. ValToInt(args[1], line_num));
  250. case Operator::Not:
  251. return MakeBoolVal(!ValToBool(args[0], line_num));
  252. case Operator::And:
  253. return MakeBoolVal(ValToBool(args[0], line_num) &&
  254. ValToBool(args[1], line_num));
  255. case Operator::Or:
  256. return MakeBoolVal(ValToBool(args[0], line_num) ||
  257. ValToBool(args[1], line_num));
  258. case Operator::Eq:
  259. return MakeBoolVal(ValueEqual(args[0], args[1], line_num));
  260. }
  261. }
  262. // Globally-defined entities, such as functions, structs, choices.
  263. Env globals;
  264. void InitGlobals(std::list<Declaration>* fs) {
  265. for (auto const& d : *fs) {
  266. d.InitGlobals(globals);
  267. }
  268. }
  269. auto ChoiceDeclaration::InitGlobals(Env& globals) const -> void {
  270. auto alts = new VarValues();
  271. for (auto kv : alternatives) {
  272. auto t = InterpExp(Env(), kv.second);
  273. alts->push_back(make_pair(kv.first, t));
  274. }
  275. auto ct = MakeChoiceTypeVal(name, alts);
  276. auto a = state->heap.AllocateValue(ct);
  277. globals.Set(name, a);
  278. }
  279. auto StructDeclaration::InitGlobals(Env& globals) const -> void {
  280. auto fields = new VarValues();
  281. auto methods = new VarValues();
  282. for (auto i = definition.members->begin(); i != definition.members->end();
  283. ++i) {
  284. switch ((*i)->tag) {
  285. case MemberKind::FieldMember: {
  286. auto t = InterpExp(Env(), (*i)->u.field.type);
  287. fields->push_back(make_pair(*(*i)->u.field.name, t));
  288. break;
  289. }
  290. }
  291. }
  292. auto st = MakeStructTypeVal(*definition.name, fields, methods);
  293. auto a = state->heap.AllocateValue(st);
  294. globals.Set(*definition.name, a);
  295. }
  296. auto FunctionDeclaration::InitGlobals(Env& globals) const -> void {
  297. Env values;
  298. auto pt = InterpExp(values, definition->param_pattern);
  299. auto f = MakeFunVal(definition->name, pt, definition->body);
  300. Address a = state->heap.AllocateValue(f);
  301. globals.Set(definition->name, a);
  302. }
  303. // Adds an entry in `globals` mapping the variable's name to the
  304. // result of evaluating the initializer.
  305. auto VariableDeclaration::InitGlobals(Env& globals) const -> void {
  306. auto v = InterpExp(globals, initializer);
  307. Address a = state->heap.AllocateValue(v);
  308. globals.Set(name, a);
  309. }
  310. // { S, H} -> { { C, E, F} :: S, H}
  311. // where C is the body of the function,
  312. // E is the environment (functions + parameters + locals)
  313. // F is the function
  314. void CallFunction(int line_num, std::vector<const Value*> operas,
  315. State* state) {
  316. switch (operas[0]->tag) {
  317. case ValKind::FunV: {
  318. // Bind arguments to parameters
  319. std::list<std::string> params;
  320. std::optional<Env> matches = PatternMatch(
  321. operas[0]->u.fun.param, operas[1], globals, &params, line_num);
  322. if (!matches) {
  323. std::cerr << "internal error in call_function, pattern match failed"
  324. << std::endl;
  325. exit(-1);
  326. }
  327. // Create the new frame and push it on the stack
  328. auto* scope = new Scope(*matches, params);
  329. auto* frame = new Frame(*operas[0]->u.fun.name, Stack(scope),
  330. Stack(MakeStmtAct(operas[0]->u.fun.body)));
  331. state->stack.Push(frame);
  332. break;
  333. }
  334. case ValKind::StructTV: {
  335. const Value* arg = CopyVal(operas[1], line_num);
  336. const Value* sv = MakeStructVal(operas[0], arg);
  337. Frame* frame = state->stack.Top();
  338. frame->todo.Push(MakeValAct(sv));
  339. break;
  340. }
  341. case ValKind::AltConsV: {
  342. const Value* arg = CopyVal(operas[1], line_num);
  343. const Value* av = MakeAltVal(*operas[0]->u.alt_cons.alt_name,
  344. *operas[0]->u.alt_cons.choice_name,
  345. state->heap.AllocateValue(arg));
  346. Frame* frame = state->stack.Top();
  347. frame->todo.Push(MakeValAct(av));
  348. break;
  349. }
  350. default:
  351. std::cerr << line_num << ": in call, expected a function, not ";
  352. PrintValue(operas[0], std::cerr);
  353. std::cerr << std::endl;
  354. exit(-1);
  355. }
  356. }
  357. void DeallocateScope(int line_num, Scope* scope) {
  358. for (const auto& l : scope->locals) {
  359. std::optional<Address> a = scope->values.Get(l);
  360. if (!a) {
  361. std::cerr << "internal error in DeallocateScope" << std::endl;
  362. exit(-1);
  363. }
  364. state->heap.Deallocate(*a);
  365. }
  366. }
  367. void DeallocateLocals(int line_num, Frame* frame) {
  368. for (auto scope : frame->scopes) {
  369. DeallocateScope(line_num, scope);
  370. }
  371. }
  372. void CreateTuple(Frame* frame, Action* act, const Expression* /*exp*/) {
  373. // { { (v1,...,vn) :: C, E, F} :: S, H}
  374. // -> { { `(v1,...,vn) :: C, E, F} :: S, H}
  375. auto elts = new std::vector<std::pair<std::string, Address>>();
  376. auto f = act->u.exp->u.tuple.fields->begin();
  377. for (auto i = act->results.begin(); i != act->results.end(); ++i, ++f) {
  378. Address a = state->heap.AllocateValue(*i); // copy?
  379. elts->push_back(make_pair(f->first, a));
  380. }
  381. const Value* tv = MakeTupleVal(elts);
  382. frame->todo.Pop(1);
  383. frame->todo.Push(MakeValAct(tv));
  384. }
  385. // Returns an updated environment that includes the bindings of
  386. // pattern variables to their matched values, if matching succeeds.
  387. //
  388. // The names of the pattern variables are added to the vars parameter.
  389. // Returns nullopt if the value doesn't match the pattern.
  390. auto PatternMatch(const Value* p, const Value* v, Env values,
  391. std::list<std::string>* vars, int line_num)
  392. -> std::optional<Env> {
  393. switch (p->tag) {
  394. case ValKind::VarPatV: {
  395. Address a = state->heap.AllocateValue(CopyVal(v, line_num));
  396. vars->push_back(*p->u.var_pat.name);
  397. values.Set(*p->u.var_pat.name, a);
  398. return values;
  399. }
  400. case ValKind::TupleV:
  401. switch (v->tag) {
  402. case ValKind::TupleV: {
  403. if (p->u.tuple.elts->size() != v->u.tuple.elts->size()) {
  404. std::cerr << "runtime error: arity mismatch in tuple pattern match"
  405. << std::endl;
  406. exit(-1);
  407. }
  408. for (auto& elt : *p->u.tuple.elts) {
  409. auto a = FindTupleField(elt.first, v);
  410. if (a == std::nullopt) {
  411. std::cerr << "runtime error: field " << elt.first << "not in ";
  412. PrintValue(v, std::cerr);
  413. std::cerr << std::endl;
  414. exit(-1);
  415. }
  416. std::optional<Env> matches = PatternMatch(
  417. state->heap.Read(elt.second, line_num),
  418. state->heap.Read(*a, line_num), values, vars, line_num);
  419. if (!matches) {
  420. return std::nullopt;
  421. }
  422. values = *matches;
  423. } // for
  424. return values;
  425. }
  426. default:
  427. std::cerr
  428. << "internal error, expected a tuple value in pattern, not ";
  429. PrintValue(v, std::cerr);
  430. std::cerr << std::endl;
  431. exit(-1);
  432. }
  433. case ValKind::AltV:
  434. switch (v->tag) {
  435. case ValKind::AltV: {
  436. if (*p->u.alt.choice_name != *v->u.alt.choice_name ||
  437. *p->u.alt.alt_name != *v->u.alt.alt_name) {
  438. return std::nullopt;
  439. }
  440. std::optional<Env> matches =
  441. PatternMatch(state->heap.Read(p->u.alt.argument, line_num),
  442. state->heap.Read(v->u.alt.argument, line_num),
  443. values, vars, line_num);
  444. if (!matches) {
  445. return std::nullopt;
  446. }
  447. return *matches;
  448. }
  449. default:
  450. std::cerr
  451. << "internal error, expected a choice alternative in pattern, "
  452. "not ";
  453. PrintValue(v, std::cerr);
  454. std::cerr << std::endl;
  455. exit(-1);
  456. }
  457. case ValKind::FunctionTV:
  458. switch (v->tag) {
  459. case ValKind::FunctionTV: {
  460. std::optional<Env> matches = PatternMatch(
  461. p->u.fun_type.param, v->u.fun_type.param, values, vars, line_num);
  462. if (!matches) {
  463. return std::nullopt;
  464. }
  465. return PatternMatch(p->u.fun_type.ret, v->u.fun_type.ret, *matches,
  466. vars, line_num);
  467. }
  468. default:
  469. return std::nullopt;
  470. }
  471. default:
  472. if (ValueEqual(p, v, line_num)) {
  473. return values;
  474. } else {
  475. return std::nullopt;
  476. }
  477. }
  478. }
  479. void PatternAssignment(const Value* pat, const Value* val, int line_num) {
  480. switch (pat->tag) {
  481. case ValKind::PtrV:
  482. state->heap.Write(ValToPtr(pat, line_num), CopyVal(val, line_num),
  483. 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 = FindTupleField(elt.first, val);
  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.Read(elt.second, line_num),
  502. state->heap.Read(*a, line_num), 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.Read(pat->u.alt.argument, line_num),
  525. state->heap.Read(val->u.alt.argument, line_num),
  526. line_num);
  527. break;
  528. }
  529. default:
  530. std::cerr
  531. << "internal error, expected an alternative in left-hand-side, "
  532. "not ";
  533. PrintValue(val, std::cerr);
  534. std::cerr << std::endl;
  535. exit(-1);
  536. }
  537. break;
  538. }
  539. default:
  540. if (!ValueEqual(pat, val, line_num)) {
  541. std::cerr << "internal error in pattern assignment" << std::endl;
  542. exit(-1);
  543. }
  544. }
  545. }
  546. // State transitions for lvalues.
  547. void StepLvalue() {
  548. Frame* frame = state->stack.Top();
  549. Action* act = frame->todo.Top();
  550. const Expression* exp = act->u.exp;
  551. if (tracing_output) {
  552. std::cout << "--- step lvalue ";
  553. PrintExp(exp);
  554. std::cout << " --->" << std::endl;
  555. }
  556. switch (exp->tag) {
  557. case ExpressionKind::Variable: {
  558. // { {x :: C, E, F} :: S, H}
  559. // -> { {E(x) :: C, E, F} :: S, H}
  560. std::optional<Address> pointer =
  561. CurrentEnv(state).Get(*(exp->u.variable.name));
  562. if (!pointer) {
  563. std::cerr << exp->line_num << ": could not find `"
  564. << *(exp->u.variable.name) << "`" << std::endl;
  565. exit(-1);
  566. }
  567. const Value* v = MakePtrVal(*pointer);
  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. const 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. const 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. const 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.Read(*pointer, exp->line_num);
  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. const Statement* 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. DeallocateScope(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. DeallocateScope(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. DeallocateScope(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. state->heap.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.Write(paused.back()->continuation, MakeContinuation(paused),
  902. stmt->line_num);
  903. break;
  904. }
  905. }
  906. auto GetMember(Address a, const std::string& f, int line_num) -> Address {
  907. const Value* v = state->heap.Read(a, line_num);
  908. switch (v->tag) {
  909. case ValKind::StructV: {
  910. auto a = FindTupleField(f, v->u.struct_val.inits);
  911. if (a == std::nullopt) {
  912. std::cerr << "runtime error, member " << f << " not in ";
  913. PrintValue(v, std::cerr);
  914. std::cerr << std::endl;
  915. exit(-1);
  916. }
  917. return *a;
  918. }
  919. case ValKind::TupleV: {
  920. auto a = FindTupleField(f, v);
  921. if (a == std::nullopt) {
  922. std::cerr << "field " << f << " not in ";
  923. PrintValue(v, std::cerr);
  924. std::cerr << std::endl;
  925. exit(-1);
  926. }
  927. return *a;
  928. }
  929. case ValKind::ChoiceTV: {
  930. if (FindInVarValues(f, v->u.choice_type.alternatives) == nullptr) {
  931. std::cerr << "alternative " << f << " not in ";
  932. PrintValue(v, std::cerr);
  933. std::cerr << std::endl;
  934. exit(-1);
  935. }
  936. auto ac = MakeAltCons(f, *v->u.choice_type.name);
  937. return state->heap.AllocateValue(ac);
  938. }
  939. default:
  940. std::cerr << "field access not allowed for value ";
  941. PrintValue(v, std::cerr);
  942. std::cerr << std::endl;
  943. exit(-1);
  944. }
  945. }
  946. void InsertDelete(Action* del, Stack<Action*>& todo) {
  947. if (!todo.IsEmpty()) {
  948. switch (todo.Top()->tag) {
  949. case ActionKind::StatementAction: {
  950. // This places the delete before the enclosing statement.
  951. // Not sure if that is OK. Conceptually it should go after
  952. // but that is tricky for some statements, like 'return'. -Jeremy
  953. todo.Push(del);
  954. break;
  955. }
  956. case ActionKind::LValAction:
  957. case ActionKind::ExpressionAction:
  958. case ActionKind::ValAction:
  959. case ActionKind::ExpToLValAction:
  960. case ActionKind::DeleteTmpAction:
  961. auto top = todo.Pop();
  962. InsertDelete(del, todo);
  963. todo.Push(top);
  964. break;
  965. }
  966. } else {
  967. todo.Push(del);
  968. }
  969. }
  970. // State transition for handling a value.
  971. void HandleValue() {
  972. Frame* frame = state->stack.Top();
  973. Action* val_act = frame->todo.Top();
  974. Action* act = frame->todo.Popped().Top();
  975. act->results.push_back(val_act->u.val);
  976. act->pos++;
  977. if (tracing_output) {
  978. std::cout << "--- handle value ";
  979. PrintValue(val_act->u.val, std::cout);
  980. std::cout << " with ";
  981. PrintAct(act, std::cout);
  982. std::cout << " --->" << std::endl;
  983. }
  984. switch (act->tag) {
  985. case ActionKind::DeleteTmpAction: {
  986. state->heap.Deallocate(act->u.delete_tmp);
  987. frame->todo.Pop(2);
  988. frame->todo.Push(val_act);
  989. break;
  990. }
  991. case ActionKind::ExpToLValAction: {
  992. Address a = state->heap.AllocateValue(act->results[0]);
  993. auto del = MakeDeleteAct(a);
  994. frame->todo.Pop(2);
  995. InsertDelete(del, frame->todo);
  996. frame->todo.Push(MakeValAct(MakePtrVal(a)));
  997. break;
  998. }
  999. case ActionKind::LValAction: {
  1000. const Expression* exp = act->u.exp;
  1001. switch (exp->tag) {
  1002. case ExpressionKind::GetField: {
  1003. // { v :: [].f :: C, E, F} :: S, H}
  1004. // -> { { &v.f :: C, E, F} :: S, H }
  1005. const Value* str = act->results[0];
  1006. Address a = GetMember(ValToPtr(str, exp->line_num),
  1007. *exp->u.get_field.field, exp->line_num);
  1008. frame->todo.Pop(2);
  1009. frame->todo.Push(MakeValAct(MakePtrVal(a)));
  1010. break;
  1011. }
  1012. case ExpressionKind::Index: {
  1013. if (act->pos == 1) {
  1014. frame->todo.Pop(1);
  1015. frame->todo.Push(MakeExpAct(exp->u.index.offset));
  1016. } else if (act->pos == 2) {
  1017. // { v :: [][i] :: C, E, F} :: S, H}
  1018. // -> { { &v[i] :: C, E, F} :: S, H }
  1019. const Value* tuple = act->results[0];
  1020. std::string f = std::to_string(ToInteger(act->results[1]));
  1021. auto a = FindTupleField(f, tuple);
  1022. if (a == std::nullopt) {
  1023. std::cerr << "runtime error: field " << f << "not in ";
  1024. PrintValue(tuple, std::cerr);
  1025. std::cerr << std::endl;
  1026. exit(-1);
  1027. }
  1028. frame->todo.Pop(2);
  1029. frame->todo.Push(MakeValAct(MakePtrVal(*a)));
  1030. }
  1031. break;
  1032. }
  1033. case ExpressionKind::Tuple: {
  1034. if (act->pos != static_cast<int>(exp->u.tuple.fields->size())) {
  1035. // { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
  1036. // H}
  1037. // -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
  1038. // H}
  1039. const Expression* elt = (*exp->u.tuple.fields)[act->pos].second;
  1040. frame->todo.Pop(1);
  1041. frame->todo.Push(MakeLvalAct(elt));
  1042. } else {
  1043. frame->todo.Pop(1);
  1044. CreateTuple(frame, act, exp);
  1045. }
  1046. break;
  1047. }
  1048. default:
  1049. std::cerr << "internal error in handle_value, LValAction"
  1050. << std::endl;
  1051. exit(-1);
  1052. }
  1053. break;
  1054. }
  1055. case ActionKind::ExpressionAction: {
  1056. const Expression* exp = act->u.exp;
  1057. switch (exp->tag) {
  1058. case ExpressionKind::PatternVariable: {
  1059. auto v =
  1060. MakeVarPatVal(*exp->u.pattern_variable.name, act->results[0]);
  1061. frame->todo.Pop(2);
  1062. frame->todo.Push(MakeValAct(v));
  1063. break;
  1064. }
  1065. case ExpressionKind::Tuple: {
  1066. if (act->pos != static_cast<int>(exp->u.tuple.fields->size())) {
  1067. // { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
  1068. // H}
  1069. // -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
  1070. // H}
  1071. const Expression* elt = (*exp->u.tuple.fields)[act->pos].second;
  1072. frame->todo.Pop(1);
  1073. frame->todo.Push(MakeExpAct(elt));
  1074. } else {
  1075. frame->todo.Pop(1);
  1076. CreateTuple(frame, act, exp);
  1077. }
  1078. break;
  1079. }
  1080. case ExpressionKind::Index: {
  1081. if (act->pos == 1) {
  1082. frame->todo.Pop(1);
  1083. frame->todo.Push(MakeExpAct(exp->u.index.offset));
  1084. } else if (act->pos == 2) {
  1085. auto tuple = act->results[0];
  1086. switch (tuple->tag) {
  1087. case ValKind::TupleV: {
  1088. // { { v :: [][i] :: C, E, F} :: S, H}
  1089. // -> { { v_i :: C, E, F} : S, H}
  1090. std::string f = std::to_string(ToInteger(act->results[1]));
  1091. auto a = FindTupleField(f, tuple);
  1092. if (a == std::nullopt) {
  1093. std::cerr << "runtime error, field " << f << " not in ";
  1094. PrintValue(tuple, std::cerr);
  1095. std::cerr << std::endl;
  1096. exit(-1);
  1097. }
  1098. frame->todo.Pop(2);
  1099. const Value* element = state->heap.Read(*a, exp->line_num);
  1100. frame->todo.Push(MakeValAct(element));
  1101. break;
  1102. }
  1103. default:
  1104. std::cerr
  1105. << "runtime type error, expected a tuple in field access, "
  1106. "not ";
  1107. PrintValue(tuple, std::cerr);
  1108. exit(-1);
  1109. }
  1110. }
  1111. break;
  1112. }
  1113. case ExpressionKind::GetField: {
  1114. // { { v :: [].f :: C, E, F} :: S, H}
  1115. // -> { { v_f :: C, E, F} : S, H}
  1116. auto a = GetMember(ValToPtr(act->results[0], exp->line_num),
  1117. *exp->u.get_field.field, exp->line_num);
  1118. const Value* element = state->heap.Read(a, exp->line_num);
  1119. frame->todo.Pop(2);
  1120. frame->todo.Push(MakeValAct(element));
  1121. break;
  1122. }
  1123. case ExpressionKind::PrimitiveOp: {
  1124. if (act->pos !=
  1125. static_cast<int>(exp->u.primitive_op.arguments->size())) {
  1126. // { {v :: op(vs,[],e,es) :: C, E, F} :: S, H}
  1127. // -> { {e :: op(vs,v,[],es) :: C, E, F} :: S, H}
  1128. const Expression* arg = (*exp->u.primitive_op.arguments)[act->pos];
  1129. frame->todo.Pop(1);
  1130. frame->todo.Push(MakeExpAct(arg));
  1131. } else {
  1132. // { {v :: op(vs,[]) :: C, E, F} :: S, H}
  1133. // -> { {eval_prim(op, (vs,v)) :: C, E, F} :: S, H}
  1134. const Value* v =
  1135. EvalPrim(exp->u.primitive_op.op, act->results, exp->line_num);
  1136. frame->todo.Pop(2);
  1137. frame->todo.Push(MakeValAct(v));
  1138. }
  1139. break;
  1140. }
  1141. case ExpressionKind::Call: {
  1142. if (act->pos == 1) {
  1143. // { { v :: [](e) :: C, E, F} :: S, H}
  1144. // -> { { e :: v([]) :: C, E, F} :: S, H}
  1145. frame->todo.Pop(1);
  1146. frame->todo.Push(MakeExpAct(exp->u.call.argument));
  1147. } else if (act->pos == 2) {
  1148. // { { v2 :: v1([]) :: C, E, F} :: S, H}
  1149. // -> { {C',E',F'} :: {C, E, F} :: S, H}
  1150. frame->todo.Pop(2);
  1151. CallFunction(exp->line_num, act->results, state);
  1152. } else {
  1153. std::cerr << "internal error in handle_value with Call"
  1154. << std::endl;
  1155. exit(-1);
  1156. }
  1157. break;
  1158. }
  1159. case ExpressionKind::FunctionT: {
  1160. if (act->pos == 2) {
  1161. // { { rt :: fn pt -> [] :: C, E, F} :: S, H}
  1162. // -> { fn pt -> rt :: {C, E, F} :: S, H}
  1163. const Value* v = MakeFunTypeVal(act->results[0], act->results[1]);
  1164. frame->todo.Pop(2);
  1165. frame->todo.Push(MakeValAct(v));
  1166. } else {
  1167. // { { pt :: fn [] -> e :: C, E, F} :: S, H}
  1168. // -> { { e :: fn pt -> []) :: C, E, F} :: S, H}
  1169. frame->todo.Pop(1);
  1170. frame->todo.Push(MakeExpAct(exp->u.function_type.return_type));
  1171. }
  1172. break;
  1173. }
  1174. case ExpressionKind::Variable:
  1175. case ExpressionKind::Integer:
  1176. case ExpressionKind::Boolean:
  1177. case ExpressionKind::IntT:
  1178. case ExpressionKind::BoolT:
  1179. case ExpressionKind::TypeT:
  1180. case ExpressionKind::AutoT:
  1181. case ExpressionKind::ContinuationT:
  1182. std::cerr << "internal error, bad expression context in handle_value"
  1183. << std::endl;
  1184. exit(-1);
  1185. }
  1186. break;
  1187. }
  1188. case ActionKind::StatementAction: {
  1189. const Statement* stmt = act->u.stmt;
  1190. switch (stmt->tag) {
  1191. case StatementKind::ExpressionStatement:
  1192. frame->todo.Pop(2);
  1193. break;
  1194. case StatementKind::VariableDefinition: {
  1195. if (act->pos == 1) {
  1196. frame->todo.Pop(1);
  1197. frame->todo.Push(MakeExpAct(stmt->u.variable_definition.pat));
  1198. } else if (act->pos == 2) {
  1199. // { { v :: (x = []) :: C, E, F} :: S, H}
  1200. // -> { { C, E(x := a), F} :: S, H(a := copy(v))}
  1201. const Value* v = act->results[0];
  1202. const Value* p = act->results[1];
  1203. std::optional<Env> matches =
  1204. PatternMatch(p, v, frame->scopes.Top()->values,
  1205. &frame->scopes.Top()->locals, stmt->line_num);
  1206. if (!matches) {
  1207. std::cerr
  1208. << stmt->line_num
  1209. << ": internal error in variable definition, match failed"
  1210. << std::endl;
  1211. exit(-1);
  1212. }
  1213. frame->scopes.Top()->values = *matches;
  1214. frame->todo.Pop(2);
  1215. }
  1216. break;
  1217. }
  1218. case StatementKind::Assign:
  1219. if (act->pos == 1) {
  1220. // { { a :: ([] = e) :: C, E, F} :: S, H}
  1221. // -> { { e :: (a = []) :: C, E, F} :: S, H}
  1222. frame->todo.Pop(1);
  1223. frame->todo.Push(MakeExpAct(stmt->u.assign.rhs));
  1224. } else if (act->pos == 2) {
  1225. // { { v :: (a = []) :: C, E, F} :: S, H}
  1226. // -> { { C, E, F} :: S, H(a := v)}
  1227. auto pat = act->results[0];
  1228. auto val = act->results[1];
  1229. PatternAssignment(pat, val, stmt->line_num);
  1230. frame->todo.Pop(2);
  1231. }
  1232. break;
  1233. case StatementKind::If:
  1234. if (ValToBool(act->results[0], stmt->line_num)) {
  1235. // { {true :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  1236. // S, H}
  1237. // -> { { then_stmt :: C, E, F } :: S, H}
  1238. frame->todo.Pop(2);
  1239. frame->todo.Push(MakeStmtAct(stmt->u.if_stmt.then_stmt));
  1240. } else if (stmt->u.if_stmt.else_stmt) {
  1241. // { {false :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  1242. // S, H}
  1243. // -> { { else_stmt :: C, E, F } :: S, H}
  1244. frame->todo.Pop(2);
  1245. frame->todo.Push(MakeStmtAct(stmt->u.if_stmt.else_stmt));
  1246. } else {
  1247. frame->todo.Pop(2);
  1248. }
  1249. break;
  1250. case StatementKind::While:
  1251. if (ValToBool(act->results[0], stmt->line_num)) {
  1252. // { {true :: (while ([]) s) :: C, E, F} :: S, H}
  1253. // -> { { s :: (while (e) s) :: C, E, F } :: S, H}
  1254. frame->todo.Pop(1);
  1255. frame->todo.Top()->pos = -1;
  1256. frame->todo.Top()->results.clear();
  1257. frame->todo.Push(MakeStmtAct(stmt->u.while_stmt.body));
  1258. } else {
  1259. // { {false :: (while ([]) s) :: C, E, F} :: S, H}
  1260. // -> { { C, E, F } :: S, H}
  1261. frame->todo.Pop(1);
  1262. frame->todo.Top()->pos = -1;
  1263. frame->todo.Top()->results.clear();
  1264. frame->todo.Pop(1);
  1265. }
  1266. break;
  1267. case StatementKind::Match: {
  1268. // Regarding act->pos:
  1269. // * odd: start interpreting the pattern of a clause
  1270. // * even: finished interpreting the pattern, now try to match
  1271. //
  1272. // Regarding act->results:
  1273. // * 0: the value that we're matching
  1274. // * 1: the pattern for clause 0
  1275. // * 2: the pattern for clause 1
  1276. // * ...
  1277. auto clause_num = (act->pos - 1) / 2;
  1278. if (clause_num >=
  1279. static_cast<int>(stmt->u.match_stmt.clauses->size())) {
  1280. frame->todo.Pop(2);
  1281. break;
  1282. }
  1283. auto c = stmt->u.match_stmt.clauses->begin();
  1284. std::advance(c, clause_num);
  1285. if (act->pos % 2 == 1) {
  1286. // start interpreting the pattern of the clause
  1287. // { {v :: (match ([]) ...) :: C, E, F} :: S, H}
  1288. // -> { {pi :: (match ([]) ...) :: C, E, F} :: S, H}
  1289. frame->todo.Pop(1);
  1290. frame->todo.Push(MakeExpAct(c->first));
  1291. } else { // try to match
  1292. auto v = act->results[0];
  1293. auto pat = act->results[clause_num + 1];
  1294. auto values = CurrentEnv(state);
  1295. std::list<std::string> vars;
  1296. std::optional<Env> matches =
  1297. PatternMatch(pat, v, values, &vars, stmt->line_num);
  1298. if (matches) { // we have a match, start the body
  1299. auto* new_scope = new Scope(*matches, vars);
  1300. frame->scopes.Push(new_scope);
  1301. const Statement* body_block =
  1302. MakeBlock(stmt->line_num, c->second);
  1303. Action* body_act = MakeStmtAct(body_block);
  1304. body_act->pos = 0;
  1305. frame->todo.Pop(2);
  1306. frame->todo.Push(body_act);
  1307. frame->todo.Push(MakeStmtAct(c->second));
  1308. } else {
  1309. // this case did not match, moving on
  1310. act->pos++;
  1311. clause_num = (act->pos - 1) / 2;
  1312. if (clause_num <
  1313. static_cast<int>(stmt->u.match_stmt.clauses->size())) {
  1314. // interpret the next clause
  1315. c = stmt->u.match_stmt.clauses->begin();
  1316. std::advance(c, clause_num);
  1317. frame->todo.Pop(1);
  1318. frame->todo.Push(MakeExpAct(c->first));
  1319. } else { // No more clauses in match
  1320. frame->todo.Pop(2);
  1321. }
  1322. }
  1323. }
  1324. break;
  1325. }
  1326. case StatementKind::Return: {
  1327. // { {v :: return [] :: C, E, F} :: {C', E', F'} :: S, H}
  1328. // -> { {v :: C', E', F'} :: S, H}
  1329. const Value* ret_val = CopyVal(val_act->u.val, stmt->line_num);
  1330. DeallocateLocals(stmt->line_num, frame);
  1331. state->stack.Pop(1);
  1332. frame = state->stack.Top();
  1333. frame->todo.Push(MakeValAct(ret_val));
  1334. break;
  1335. }
  1336. case StatementKind::Run: {
  1337. frame->todo.Pop(2);
  1338. // Push an expression statement action to ignore the result
  1339. // value from the continuation.
  1340. Action* ignore_result = MakeStmtAct(
  1341. MakeExpStmt(stmt->line_num, MakeUnit(stmt->line_num)));
  1342. ignore_result->pos = 0;
  1343. frame->todo.Push(ignore_result);
  1344. // Push the continuation onto the current stack.
  1345. std::vector<Frame*> continuation_vector =
  1346. ContinuationToVector(val_act->u.val, stmt->line_num);
  1347. for (auto frame_iter = continuation_vector.rbegin();
  1348. frame_iter != continuation_vector.rend(); ++frame_iter) {
  1349. state->stack.Push(*frame_iter);
  1350. }
  1351. break;
  1352. }
  1353. case StatementKind::Continuation:
  1354. case StatementKind::Await:
  1355. case StatementKind::Block:
  1356. case StatementKind::Sequence:
  1357. case StatementKind::Break:
  1358. case StatementKind::Continue:
  1359. std::cerr << "internal error in handle_value, unhandled statement ";
  1360. PrintStatement(stmt, 1);
  1361. std::cerr << std::endl;
  1362. exit(-1);
  1363. } // switch stmt
  1364. break;
  1365. }
  1366. case ActionKind::ValAction:
  1367. std::cerr << "internal error, ValAction in handle_value" << std::endl;
  1368. exit(-1);
  1369. } // switch act
  1370. }
  1371. // State transition.
  1372. void Step() {
  1373. Frame* frame = state->stack.Top();
  1374. if (frame->todo.IsEmpty()) {
  1375. std::cerr << "runtime error: fell off end of function " << frame->name
  1376. << " without `return`" << std::endl;
  1377. exit(-1);
  1378. }
  1379. Action* act = frame->todo.Top();
  1380. switch (act->tag) {
  1381. case ActionKind::DeleteTmpAction:
  1382. std::cerr << "internal error in step, did not expect DeleteTmpAction"
  1383. << std::endl;
  1384. break;
  1385. case ActionKind::ExpToLValAction:
  1386. std::cerr << "internal error in step, did not expect ExpToLValAction"
  1387. << std::endl;
  1388. break;
  1389. case ActionKind::ValAction:
  1390. HandleValue();
  1391. break;
  1392. case ActionKind::LValAction:
  1393. StepLvalue();
  1394. break;
  1395. case ActionKind::ExpressionAction:
  1396. StepExp();
  1397. break;
  1398. case ActionKind::StatementAction:
  1399. StepStmt();
  1400. break;
  1401. } // switch
  1402. }
  1403. // Interpret the whole porogram.
  1404. auto InterpProgram(std::list<Declaration>* fs) -> int {
  1405. state = new State(); // Runtime state.
  1406. if (tracing_output) {
  1407. std::cout << "********** initializing globals **********" << std::endl;
  1408. }
  1409. InitGlobals(fs);
  1410. const Expression* arg = MakeTuple(
  1411. 0, new std::vector<std::pair<std::string, const Expression*>>());
  1412. const Expression* call_main = MakeCall(0, MakeVar(0, "main"), arg);
  1413. auto todo = Stack(MakeExpAct(call_main));
  1414. auto* scope = new Scope(globals, std::list<std::string>());
  1415. auto* frame = new Frame("top", Stack(scope), todo);
  1416. state->stack = Stack(frame);
  1417. if (tracing_output) {
  1418. std::cout << "********** calling main function **********" << std::endl;
  1419. PrintState(std::cout);
  1420. }
  1421. while (state->stack.CountExceeds(1) ||
  1422. state->stack.Top()->todo.CountExceeds(1) ||
  1423. state->stack.Top()->todo.Top()->tag != ActionKind::ValAction) {
  1424. Step();
  1425. if (tracing_output) {
  1426. PrintState(std::cout);
  1427. }
  1428. }
  1429. const Value* v = state->stack.Top()->todo.Top()->u.val;
  1430. return ValToInt(v, 0);
  1431. }
  1432. // Interpret an expression at compile-time.
  1433. auto InterpExp(Env values, const Expression* e) -> const Value* {
  1434. auto todo = Stack(MakeExpAct(e));
  1435. auto* scope = new Scope(values, std::list<std::string>());
  1436. auto* frame = new Frame("InterpExp", Stack(scope), todo);
  1437. state->stack = Stack(frame);
  1438. while (state->stack.CountExceeds(1) ||
  1439. state->stack.Top()->todo.CountExceeds(1) ||
  1440. state->stack.Top()->todo.Top()->tag != ActionKind::ValAction) {
  1441. Step();
  1442. }
  1443. const Value* v = state->stack.Top()->todo.Top()->u.val;
  1444. return v;
  1445. }
  1446. } // namespace Carbon