interpreter.cpp 51 KB

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