interpreter.cpp 52 KB

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