interpreter.cpp 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540
  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::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(MakeLvalAct(exp->GetFieldAccess().aggregate));
  599. act->pos++;
  600. break;
  601. }
  602. case ExpressionKind::Index: {
  603. // { {e[i] :: C, E, F} :: S, H}
  604. // -> { e :: [][i] :: C, E, F} :: S, H}
  605. frame->todo.Push(MakeExpAct(exp->GetIndex().aggregate));
  606. act->pos++;
  607. break;
  608. }
  609. case ExpressionKind::Tuple: {
  610. // { {(f1=e1,...) :: C, E, F} :: S, H}
  611. // -> { {e1 :: (f1=[],...) :: C, E, F} :: S, H}
  612. const Expression* e1 = (*exp->GetTuple().fields)[0].expression;
  613. frame->todo.Push(MakeLvalAct(e1));
  614. act->pos++;
  615. break;
  616. }
  617. case ExpressionKind::Integer:
  618. case ExpressionKind::Boolean:
  619. case ExpressionKind::Call:
  620. case ExpressionKind::PrimitiveOp:
  621. case ExpressionKind::IntT:
  622. case ExpressionKind::BoolT:
  623. case ExpressionKind::TypeT:
  624. case ExpressionKind::FunctionT:
  625. case ExpressionKind::AutoT:
  626. case ExpressionKind::ContinuationT:
  627. case ExpressionKind::PatternVariable: {
  628. frame->todo.Pop();
  629. frame->todo.Push(MakeExpToLvalAct());
  630. frame->todo.Push(MakeExpAct(exp));
  631. }
  632. }
  633. }
  634. // State transitions for expressions.
  635. void StepExp() {
  636. Frame* frame = state->stack.Top();
  637. Action* act = frame->todo.Top();
  638. const Expression* exp = act->u.exp;
  639. if (tracing_output) {
  640. std::cout << "--- step exp ";
  641. PrintExp(exp);
  642. std::cout << " --->" << std::endl;
  643. }
  644. switch (exp->tag()) {
  645. case ExpressionKind::PatternVariable: {
  646. frame->todo.Push(MakeExpAct(exp->GetPatternVariable().type));
  647. act->pos++;
  648. break;
  649. }
  650. case ExpressionKind::Index: {
  651. // { { e[i] :: C, E, F} :: S, H}
  652. // -> { { e :: [][i] :: C, E, F} :: S, H}
  653. frame->todo.Push(MakeExpAct(exp->GetIndex().aggregate));
  654. act->pos++;
  655. break;
  656. }
  657. case ExpressionKind::Tuple: {
  658. if (exp->GetTuple().fields->size() > 0) {
  659. // { {(f1=e1,...) :: C, E, F} :: S, H}
  660. // -> { {e1 :: (f1=[],...) :: C, E, F} :: S, H}
  661. const Expression* e1 = (*exp->GetTuple().fields)[0].expression;
  662. frame->todo.Push(MakeExpAct(e1));
  663. act->pos++;
  664. } else {
  665. CreateTuple(frame, act, exp);
  666. }
  667. break;
  668. }
  669. case ExpressionKind::GetField: {
  670. // { { e.f :: C, E, F} :: S, H}
  671. // -> { { e :: [].f :: C, E, F} :: S, H}
  672. frame->todo.Push(MakeLvalAct(exp->GetFieldAccess().aggregate));
  673. act->pos++;
  674. break;
  675. }
  676. case ExpressionKind::Variable: {
  677. // { {x :: C, E, F} :: S, H} -> { {H(E(x)) :: C, E, F} :: S, H}
  678. std::optional<Address> pointer =
  679. CurrentEnv(state).Get(exp->GetVariable().name);
  680. if (!pointer) {
  681. std::cerr << exp->line_num << ": could not find `"
  682. << exp->GetVariable().name << "`" << std::endl;
  683. exit(-1);
  684. }
  685. const Value* pointee = state->heap.Read(*pointer, exp->line_num);
  686. frame->todo.Pop(1);
  687. frame->todo.Push(MakeValAct(pointee));
  688. break;
  689. }
  690. case ExpressionKind::Integer:
  691. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  692. frame->todo.Pop(1);
  693. frame->todo.Push(MakeValAct(Value::MakeIntVal(exp->GetInteger())));
  694. break;
  695. case ExpressionKind::Boolean:
  696. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  697. frame->todo.Pop(1);
  698. frame->todo.Push(MakeValAct(Value::MakeBoolVal(exp->GetBoolean())));
  699. break;
  700. case ExpressionKind::PrimitiveOp:
  701. if (exp->GetPrimitiveOperator().arguments->size() > 0) {
  702. // { {op(e :: es) :: C, E, F} :: S, H}
  703. // -> { e :: op([] :: es) :: C, E, F} :: S, H}
  704. frame->todo.Push(
  705. MakeExpAct(exp->GetPrimitiveOperator().arguments->front()));
  706. act->pos++;
  707. } else {
  708. // { {v :: op(]) :: C, E, F} :: S, H}
  709. // -> { {eval_prim(op, ()) :: C, E, F} :: S, H}
  710. const Value* v = EvalPrim(exp->GetPrimitiveOperator().op, act->results,
  711. exp->line_num);
  712. frame->todo.Pop(2);
  713. frame->todo.Push(MakeValAct(v));
  714. }
  715. break;
  716. case ExpressionKind::Call:
  717. // { {e1(e2) :: C, E, F} :: S, H}
  718. // -> { {e1 :: [](e2) :: C, E, F} :: S, H}
  719. frame->todo.Push(MakeExpAct(exp->GetCall().function));
  720. act->pos++;
  721. break;
  722. case ExpressionKind::IntT: {
  723. const Value* v = Value::MakeIntTypeVal();
  724. frame->todo.Pop(1);
  725. frame->todo.Push(MakeValAct(v));
  726. break;
  727. }
  728. case ExpressionKind::BoolT: {
  729. const Value* v = Value::MakeBoolTypeVal();
  730. frame->todo.Pop(1);
  731. frame->todo.Push(MakeValAct(v));
  732. break;
  733. }
  734. case ExpressionKind::AutoT: {
  735. const Value* v = Value::MakeAutoTypeVal();
  736. frame->todo.Pop(1);
  737. frame->todo.Push(MakeValAct(v));
  738. break;
  739. }
  740. case ExpressionKind::TypeT: {
  741. const Value* v = Value::MakeTypeTypeVal();
  742. frame->todo.Pop(1);
  743. frame->todo.Push(MakeValAct(v));
  744. break;
  745. }
  746. case ExpressionKind::FunctionT: {
  747. frame->todo.Push(MakeExpAct(exp->GetFunctionType().parameter));
  748. act->pos++;
  749. break;
  750. }
  751. case ExpressionKind::ContinuationT: {
  752. const Value* v = Value::MakeContinuationTypeVal();
  753. frame->todo.Pop(1);
  754. frame->todo.Push(MakeValAct(v));
  755. break;
  756. }
  757. } // switch (exp->tag)
  758. }
  759. auto IsWhileAct(Action* act) -> bool {
  760. switch (act->tag) {
  761. case ActionKind::StatementAction:
  762. switch (act->u.stmt->tag) {
  763. case StatementKind::While:
  764. return true;
  765. default:
  766. return false;
  767. }
  768. default:
  769. return false;
  770. }
  771. }
  772. auto IsBlockAct(Action* act) -> bool {
  773. switch (act->tag) {
  774. case ActionKind::StatementAction:
  775. switch (act->u.stmt->tag) {
  776. case StatementKind::Block:
  777. return true;
  778. default:
  779. return false;
  780. }
  781. default:
  782. return false;
  783. }
  784. }
  785. // State transitions for statements.
  786. void StepStmt() {
  787. Frame* frame = state->stack.Top();
  788. Action* act = frame->todo.Top();
  789. const Statement* stmt = act->u.stmt;
  790. assert(stmt != nullptr && "null statement!");
  791. if (tracing_output) {
  792. std::cout << "--- step stmt ";
  793. PrintStatement(stmt, 1);
  794. std::cout << " --->" << std::endl;
  795. }
  796. switch (stmt->tag) {
  797. case StatementKind::Match:
  798. // { { (match (e) ...) :: C, E, F} :: S, H}
  799. // -> { { e :: (match ([]) ...) :: C, E, F} :: S, H}
  800. frame->todo.Push(MakeExpAct(stmt->GetMatch().exp));
  801. act->pos++;
  802. break;
  803. case StatementKind::While:
  804. // { { (while (e) s) :: C, E, F} :: S, H}
  805. // -> { { e :: (while ([]) s) :: C, E, F} :: S, H}
  806. frame->todo.Push(MakeExpAct(stmt->GetWhile().cond));
  807. act->pos++;
  808. break;
  809. case StatementKind::Break:
  810. // { { break; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  811. // -> { { C, E', F} :: S, H}
  812. frame->todo.Pop(1);
  813. while (!frame->todo.IsEmpty() && !IsWhileAct(frame->todo.Top())) {
  814. if (IsBlockAct(frame->todo.Top())) {
  815. DeallocateScope(stmt->line_num, frame->scopes.Top());
  816. frame->scopes.Pop(1);
  817. }
  818. frame->todo.Pop(1);
  819. }
  820. frame->todo.Pop(1);
  821. break;
  822. case StatementKind::Continue:
  823. // { { continue; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  824. // -> { { (while (e) s) :: C, E', F} :: S, H}
  825. frame->todo.Pop(1);
  826. while (!frame->todo.IsEmpty() && !IsWhileAct(frame->todo.Top())) {
  827. if (IsBlockAct(frame->todo.Top())) {
  828. DeallocateScope(stmt->line_num, frame->scopes.Top());
  829. frame->scopes.Pop(1);
  830. }
  831. frame->todo.Pop(1);
  832. }
  833. break;
  834. case StatementKind::Block: {
  835. if (act->pos == -1) {
  836. if (stmt->GetBlock().stmt) {
  837. auto* scope = new Scope(CurrentEnv(state), {});
  838. frame->scopes.Push(scope);
  839. frame->todo.Push(MakeStmtAct(stmt->GetBlock().stmt));
  840. act->pos++;
  841. } else {
  842. frame->todo.Pop();
  843. }
  844. } else {
  845. Scope* scope = frame->scopes.Top();
  846. DeallocateScope(stmt->line_num, scope);
  847. frame->scopes.Pop(1);
  848. frame->todo.Pop(1);
  849. }
  850. break;
  851. }
  852. case StatementKind::VariableDefinition:
  853. // { {(var x = e) :: C, E, F} :: S, H}
  854. // -> { {e :: (var x = []) :: C, E, F} :: S, H}
  855. frame->todo.Push(MakeExpAct(stmt->GetVariableDefinition().init));
  856. act->pos++;
  857. break;
  858. case StatementKind::ExpressionStatement:
  859. // { {e :: C, E, F} :: S, H}
  860. // -> { {e :: C, E, F} :: S, H}
  861. frame->todo.Push(MakeExpAct(stmt->GetExpression()));
  862. break;
  863. case StatementKind::Assign:
  864. // { {(lv = e) :: C, E, F} :: S, H}
  865. // -> { {lv :: ([] = e) :: C, E, F} :: S, H}
  866. frame->todo.Push(MakeLvalAct(stmt->GetAssign().lhs));
  867. act->pos++;
  868. break;
  869. case StatementKind::If:
  870. // { {(if (e) then_stmt else else_stmt) :: C, E, F} :: S, H}
  871. // -> { { e :: (if ([]) then_stmt else else_stmt) :: C, E, F} :: S, H}
  872. frame->todo.Push(MakeExpAct(stmt->GetIf().cond));
  873. act->pos++;
  874. break;
  875. case StatementKind::Return:
  876. // { {return e :: C, E, F} :: S, H}
  877. // -> { {e :: return [] :: C, E, F} :: S, H}
  878. frame->todo.Push(MakeExpAct(stmt->GetReturn()));
  879. act->pos++;
  880. break;
  881. case StatementKind::Sequence:
  882. // { { (s1,s2) :: C, E, F} :: S, H}
  883. // -> { { s1 :: s2 :: C, E, F} :: S, H}
  884. frame->todo.Pop(1);
  885. if (stmt->GetSequence().next) {
  886. frame->todo.Push(MakeStmtAct(stmt->GetSequence().next));
  887. }
  888. frame->todo.Push(MakeStmtAct(stmt->GetSequence().stmt));
  889. break;
  890. case StatementKind::Continuation: {
  891. // Create a continuation object by creating a frame similar the
  892. // way one is created in a function call.
  893. Scope* scope = new Scope(CurrentEnv(state), std::list<std::string>());
  894. Stack<Scope*> scopes;
  895. scopes.Push(scope);
  896. Stack<Action*> todo;
  897. todo.Push(MakeStmtAct(Statement::MakeReturn(
  898. stmt->line_num, Expression::MakeUnit(stmt->line_num))));
  899. todo.Push(MakeStmtAct(stmt->GetContinuation().body));
  900. Frame* continuation_frame = new Frame("__continuation", scopes, todo);
  901. Address continuation_address = state->heap.AllocateValue(
  902. Value::MakeContinuation({continuation_frame}));
  903. // Store the continuation's address in the frame.
  904. continuation_frame->continuation = continuation_address;
  905. // Bind the continuation object to the continuation variable
  906. frame->scopes.Top()->values.Set(
  907. *stmt->GetContinuation().continuation_variable, continuation_address);
  908. // Pop the continuation statement.
  909. frame->todo.Pop();
  910. break;
  911. }
  912. case StatementKind::Run:
  913. // Evaluate the argument of the run statement.
  914. frame->todo.Push(MakeExpAct(stmt->GetRun().argument));
  915. act->pos++;
  916. break;
  917. case StatementKind::Await:
  918. // Pause the current continuation
  919. frame->todo.Pop();
  920. std::vector<Frame*> paused;
  921. do {
  922. paused.push_back(state->stack.Pop());
  923. } while (!paused.back()->IsContinuation());
  924. // Update the continuation with the paused stack.
  925. state->heap.Write(paused.back()->continuation,
  926. Value::MakeContinuation(paused), stmt->line_num);
  927. break;
  928. }
  929. }
  930. auto GetMember(Address a, const std::string& f, int line_num) -> Address {
  931. const Value* v = state->heap.Read(a, line_num);
  932. switch (v->tag) {
  933. case ValKind::StructV: {
  934. auto a = FindTupleField(f, v->GetStruct().inits);
  935. if (a == std::nullopt) {
  936. std::cerr << "runtime error, member " << f << " not in ";
  937. PrintValue(v, std::cerr);
  938. std::cerr << std::endl;
  939. exit(-1);
  940. }
  941. return *a;
  942. }
  943. case ValKind::TupleV: {
  944. auto a = FindTupleField(f, v);
  945. if (a == std::nullopt) {
  946. std::cerr << "field " << f << " not in ";
  947. PrintValue(v, std::cerr);
  948. std::cerr << std::endl;
  949. exit(-1);
  950. }
  951. return *a;
  952. }
  953. case ValKind::ChoiceTV: {
  954. if (FindInVarValues(f, v->GetChoiceType().alternatives) == nullptr) {
  955. std::cerr << "alternative " << f << " not in ";
  956. PrintValue(v, std::cerr);
  957. std::cerr << std::endl;
  958. exit(-1);
  959. }
  960. auto ac = Value::MakeAltCons(f, *v->GetChoiceType().name);
  961. return state->heap.AllocateValue(ac);
  962. }
  963. default:
  964. std::cerr << "field access not allowed for value ";
  965. PrintValue(v, std::cerr);
  966. std::cerr << std::endl;
  967. exit(-1);
  968. }
  969. }
  970. void InsertDelete(Action* del, Stack<Action*>& todo) {
  971. if (!todo.IsEmpty()) {
  972. switch (todo.Top()->tag) {
  973. case ActionKind::StatementAction: {
  974. // This places the delete before the enclosing statement.
  975. // Not sure if that is OK. Conceptually it should go after
  976. // but that is tricky for some statements, like 'return'. -Jeremy
  977. todo.Push(del);
  978. break;
  979. }
  980. case ActionKind::LValAction:
  981. case ActionKind::ExpressionAction:
  982. case ActionKind::ValAction:
  983. case ActionKind::ExpToLValAction:
  984. case ActionKind::DeleteTmpAction:
  985. auto top = todo.Pop();
  986. InsertDelete(del, todo);
  987. todo.Push(top);
  988. break;
  989. }
  990. } else {
  991. todo.Push(del);
  992. }
  993. }
  994. // State transition for handling a value.
  995. void HandleValue() {
  996. Frame* frame = state->stack.Top();
  997. Action* val_act = frame->todo.Top();
  998. Action* act = frame->todo.Popped().Top();
  999. act->results.push_back(val_act->u.val);
  1000. act->pos++;
  1001. if (tracing_output) {
  1002. std::cout << "--- handle value ";
  1003. PrintValue(val_act->u.val, std::cout);
  1004. std::cout << " with ";
  1005. PrintAct(act, std::cout);
  1006. std::cout << " --->" << std::endl;
  1007. }
  1008. switch (act->tag) {
  1009. case ActionKind::DeleteTmpAction: {
  1010. state->heap.Deallocate(act->u.delete_tmp);
  1011. frame->todo.Pop(2);
  1012. frame->todo.Push(val_act);
  1013. break;
  1014. }
  1015. case ActionKind::ExpToLValAction: {
  1016. Address a = state->heap.AllocateValue(act->results[0]);
  1017. auto del = MakeDeleteAct(a);
  1018. frame->todo.Pop(2);
  1019. InsertDelete(del, frame->todo);
  1020. frame->todo.Push(MakeValAct(Value::MakePtrVal(a)));
  1021. break;
  1022. }
  1023. case ActionKind::LValAction: {
  1024. const Expression* exp = act->u.exp;
  1025. switch (exp->tag()) {
  1026. case ExpressionKind::GetField: {
  1027. // { v :: [].f :: C, E, F} :: S, H}
  1028. // -> { { &v.f :: C, E, F} :: S, H }
  1029. const Value* str = act->results[0];
  1030. Address a = GetMember(ValToPtr(str, exp->line_num),
  1031. exp->GetFieldAccess().field, exp->line_num);
  1032. frame->todo.Pop(2);
  1033. frame->todo.Push(MakeValAct(Value::MakePtrVal(a)));
  1034. break;
  1035. }
  1036. case ExpressionKind::Index: {
  1037. if (act->pos == 1) {
  1038. frame->todo.Pop(1);
  1039. frame->todo.Push(MakeExpAct(exp->GetIndex().offset));
  1040. } else if (act->pos == 2) {
  1041. // { v :: [][i] :: C, E, F} :: S, H}
  1042. // -> { { &v[i] :: C, E, F} :: S, H }
  1043. const Value* tuple = act->results[0];
  1044. std::string f = std::to_string(ToInteger(act->results[1]));
  1045. auto a = FindTupleField(f, tuple);
  1046. if (a == std::nullopt) {
  1047. std::cerr << "runtime error: field " << f << "not in ";
  1048. PrintValue(tuple, std::cerr);
  1049. std::cerr << std::endl;
  1050. exit(-1);
  1051. }
  1052. frame->todo.Pop(2);
  1053. frame->todo.Push(MakeValAct(Value::MakePtrVal(*a)));
  1054. }
  1055. break;
  1056. }
  1057. case ExpressionKind::Tuple: {
  1058. if (act->pos != static_cast<int>(exp->GetTuple().fields->size())) {
  1059. // { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
  1060. // H}
  1061. // -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
  1062. // H}
  1063. const Expression* elt =
  1064. (*exp->GetTuple().fields)[act->pos].expression;
  1065. frame->todo.Pop(1);
  1066. frame->todo.Push(MakeLvalAct(elt));
  1067. } else {
  1068. frame->todo.Pop(1);
  1069. CreateTuple(frame, act, exp);
  1070. }
  1071. break;
  1072. }
  1073. default:
  1074. std::cerr << "internal error in handle_value, LValAction"
  1075. << std::endl;
  1076. exit(-1);
  1077. }
  1078. break;
  1079. }
  1080. case ActionKind::ExpressionAction: {
  1081. const Expression* exp = act->u.exp;
  1082. switch (exp->tag()) {
  1083. case ExpressionKind::PatternVariable: {
  1084. auto v = Value::MakeVarPatVal(exp->GetPatternVariable().name,
  1085. act->results[0]);
  1086. frame->todo.Pop(2);
  1087. frame->todo.Push(MakeValAct(v));
  1088. break;
  1089. }
  1090. case ExpressionKind::Tuple: {
  1091. if (act->pos != static_cast<int>(exp->GetTuple().fields->size())) {
  1092. // { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
  1093. // H}
  1094. // -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
  1095. // H}
  1096. const Expression* elt =
  1097. (*exp->GetTuple().fields)[act->pos].expression;
  1098. frame->todo.Pop(1);
  1099. frame->todo.Push(MakeExpAct(elt));
  1100. } else {
  1101. frame->todo.Pop(1);
  1102. CreateTuple(frame, act, exp);
  1103. }
  1104. break;
  1105. }
  1106. case ExpressionKind::Index: {
  1107. if (act->pos == 1) {
  1108. frame->todo.Pop(1);
  1109. frame->todo.Push(MakeExpAct(exp->GetIndex().offset));
  1110. } else if (act->pos == 2) {
  1111. auto tuple = act->results[0];
  1112. switch (tuple->tag) {
  1113. case ValKind::TupleV: {
  1114. // { { v :: [][i] :: C, E, F} :: S, H}
  1115. // -> { { v_i :: C, E, F} : S, H}
  1116. std::string f = std::to_string(ToInteger(act->results[1]));
  1117. auto a = FindTupleField(f, tuple);
  1118. if (a == std::nullopt) {
  1119. std::cerr << "runtime error, field " << f << " not in ";
  1120. PrintValue(tuple, std::cerr);
  1121. std::cerr << std::endl;
  1122. exit(-1);
  1123. }
  1124. frame->todo.Pop(2);
  1125. const Value* element = state->heap.Read(*a, exp->line_num);
  1126. frame->todo.Push(MakeValAct(element));
  1127. break;
  1128. }
  1129. default:
  1130. std::cerr
  1131. << "runtime type error, expected a tuple in field access, "
  1132. "not ";
  1133. PrintValue(tuple, std::cerr);
  1134. exit(-1);
  1135. }
  1136. }
  1137. break;
  1138. }
  1139. case ExpressionKind::GetField: {
  1140. // { { v :: [].f :: C, E, F} :: S, H}
  1141. // -> { { v_f :: C, E, F} : S, H}
  1142. auto a = GetMember(ValToPtr(act->results[0], exp->line_num),
  1143. exp->GetFieldAccess().field, exp->line_num);
  1144. const Value* element = state->heap.Read(a, exp->line_num);
  1145. frame->todo.Pop(2);
  1146. frame->todo.Push(MakeValAct(element));
  1147. break;
  1148. }
  1149. case ExpressionKind::PrimitiveOp: {
  1150. if (act->pos !=
  1151. static_cast<int>(exp->GetPrimitiveOperator().arguments->size())) {
  1152. // { {v :: op(vs,[],e,es) :: C, E, F} :: S, H}
  1153. // -> { {e :: op(vs,v,[],es) :: C, E, F} :: S, H}
  1154. const Expression* arg =
  1155. (*exp->GetPrimitiveOperator().arguments)[act->pos];
  1156. frame->todo.Pop(1);
  1157. frame->todo.Push(MakeExpAct(arg));
  1158. } else {
  1159. // { {v :: op(vs,[]) :: C, E, F} :: S, H}
  1160. // -> { {eval_prim(op, (vs,v)) :: C, E, F} :: S, H}
  1161. const Value* v = EvalPrim(exp->GetPrimitiveOperator().op,
  1162. act->results, exp->line_num);
  1163. frame->todo.Pop(2);
  1164. frame->todo.Push(MakeValAct(v));
  1165. }
  1166. break;
  1167. }
  1168. case ExpressionKind::Call: {
  1169. if (act->pos == 1) {
  1170. // { { v :: [](e) :: C, E, F} :: S, H}
  1171. // -> { { e :: v([]) :: C, E, F} :: S, H}
  1172. frame->todo.Pop(1);
  1173. frame->todo.Push(MakeExpAct(exp->GetCall().argument));
  1174. } else if (act->pos == 2) {
  1175. // { { v2 :: v1([]) :: C, E, F} :: S, H}
  1176. // -> { {C',E',F'} :: {C, E, F} :: S, H}
  1177. frame->todo.Pop(2);
  1178. CallFunction(exp->line_num, act->results, state);
  1179. } else {
  1180. std::cerr << "internal error in handle_value with Call"
  1181. << std::endl;
  1182. exit(-1);
  1183. }
  1184. break;
  1185. }
  1186. case ExpressionKind::FunctionT: {
  1187. if (act->pos == 2) {
  1188. // { { rt :: fn pt -> [] :: C, E, F} :: S, H}
  1189. // -> { fn pt -> rt :: {C, E, F} :: S, H}
  1190. const Value* v =
  1191. Value::MakeFunTypeVal(act->results[0], act->results[1]);
  1192. frame->todo.Pop(2);
  1193. frame->todo.Push(MakeValAct(v));
  1194. } else {
  1195. // { { pt :: fn [] -> e :: C, E, F} :: S, H}
  1196. // -> { { e :: fn pt -> []) :: C, E, F} :: S, H}
  1197. frame->todo.Pop(1);
  1198. frame->todo.Push(MakeExpAct(exp->GetFunctionType().return_type));
  1199. }
  1200. break;
  1201. }
  1202. case ExpressionKind::Variable:
  1203. case ExpressionKind::Integer:
  1204. case ExpressionKind::Boolean:
  1205. case ExpressionKind::IntT:
  1206. case ExpressionKind::BoolT:
  1207. case ExpressionKind::TypeT:
  1208. case ExpressionKind::AutoT:
  1209. case ExpressionKind::ContinuationT:
  1210. std::cerr << "internal error, bad expression context in handle_value"
  1211. << std::endl;
  1212. exit(-1);
  1213. }
  1214. break;
  1215. }
  1216. case ActionKind::StatementAction: {
  1217. const Statement* stmt = act->u.stmt;
  1218. switch (stmt->tag) {
  1219. case StatementKind::ExpressionStatement:
  1220. frame->todo.Pop(2);
  1221. break;
  1222. case StatementKind::VariableDefinition: {
  1223. if (act->pos == 1) {
  1224. frame->todo.Pop(1);
  1225. frame->todo.Push(MakeExpAct(stmt->GetVariableDefinition().pat));
  1226. } else if (act->pos == 2) {
  1227. // { { v :: (x = []) :: C, E, F} :: S, H}
  1228. // -> { { C, E(x := a), F} :: S, H(a := copy(v))}
  1229. const Value* v = act->results[0];
  1230. const Value* p = act->results[1];
  1231. std::optional<Env> matches =
  1232. PatternMatch(p, v, frame->scopes.Top()->values,
  1233. &frame->scopes.Top()->locals, stmt->line_num);
  1234. if (!matches) {
  1235. std::cerr
  1236. << stmt->line_num
  1237. << ": internal error in variable definition, match failed"
  1238. << std::endl;
  1239. exit(-1);
  1240. }
  1241. frame->scopes.Top()->values = *matches;
  1242. frame->todo.Pop(2);
  1243. }
  1244. break;
  1245. }
  1246. case StatementKind::Assign:
  1247. if (act->pos == 1) {
  1248. // { { a :: ([] = e) :: C, E, F} :: S, H}
  1249. // -> { { e :: (a = []) :: C, E, F} :: S, H}
  1250. frame->todo.Pop(1);
  1251. frame->todo.Push(MakeExpAct(stmt->GetAssign().rhs));
  1252. } else if (act->pos == 2) {
  1253. // { { v :: (a = []) :: C, E, F} :: S, H}
  1254. // -> { { C, E, F} :: S, H(a := v)}
  1255. auto pat = act->results[0];
  1256. auto val = act->results[1];
  1257. PatternAssignment(pat, val, stmt->line_num);
  1258. frame->todo.Pop(2);
  1259. }
  1260. break;
  1261. case StatementKind::If:
  1262. if (ValToBool(act->results[0], stmt->line_num)) {
  1263. // { {true :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  1264. // S, H}
  1265. // -> { { then_stmt :: C, E, F } :: S, H}
  1266. frame->todo.Pop(2);
  1267. frame->todo.Push(MakeStmtAct(stmt->GetIf().then_stmt));
  1268. } else if (stmt->GetIf().else_stmt) {
  1269. // { {false :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  1270. // S, H}
  1271. // -> { { else_stmt :: C, E, F } :: S, H}
  1272. frame->todo.Pop(2);
  1273. frame->todo.Push(MakeStmtAct(stmt->GetIf().else_stmt));
  1274. } else {
  1275. frame->todo.Pop(2);
  1276. }
  1277. break;
  1278. case StatementKind::While:
  1279. if (ValToBool(act->results[0], stmt->line_num)) {
  1280. // { {true :: (while ([]) s) :: C, E, F} :: S, H}
  1281. // -> { { s :: (while (e) s) :: C, E, F } :: S, H}
  1282. frame->todo.Pop(1);
  1283. frame->todo.Top()->pos = -1;
  1284. frame->todo.Top()->results.clear();
  1285. frame->todo.Push(MakeStmtAct(stmt->GetWhile().body));
  1286. } else {
  1287. // { {false :: (while ([]) s) :: C, E, F} :: S, H}
  1288. // -> { { C, E, F } :: S, H}
  1289. frame->todo.Pop(1);
  1290. frame->todo.Top()->pos = -1;
  1291. frame->todo.Top()->results.clear();
  1292. frame->todo.Pop(1);
  1293. }
  1294. break;
  1295. case StatementKind::Match: {
  1296. // Regarding act->pos:
  1297. // * odd: start interpreting the pattern of a clause
  1298. // * even: finished interpreting the pattern, now try to match
  1299. //
  1300. // Regarding act->results:
  1301. // * 0: the value that we're matching
  1302. // * 1: the pattern for clause 0
  1303. // * 2: the pattern for clause 1
  1304. // * ...
  1305. auto clause_num = (act->pos - 1) / 2;
  1306. if (clause_num >=
  1307. static_cast<int>(stmt->GetMatch().clauses->size())) {
  1308. frame->todo.Pop(2);
  1309. break;
  1310. }
  1311. auto c = stmt->GetMatch().clauses->begin();
  1312. std::advance(c, clause_num);
  1313. if (act->pos % 2 == 1) {
  1314. // start interpreting the pattern of the clause
  1315. // { {v :: (match ([]) ...) :: C, E, F} :: S, H}
  1316. // -> { {pi :: (match ([]) ...) :: C, E, F} :: S, H}
  1317. frame->todo.Pop(1);
  1318. frame->todo.Push(MakeExpAct(c->first));
  1319. } else { // try to match
  1320. auto v = act->results[0];
  1321. auto pat = act->results[clause_num + 1];
  1322. auto values = CurrentEnv(state);
  1323. std::list<std::string> vars;
  1324. std::optional<Env> matches =
  1325. PatternMatch(pat, v, values, &vars, stmt->line_num);
  1326. if (matches) { // we have a match, start the body
  1327. auto* new_scope = new Scope(*matches, vars);
  1328. frame->scopes.Push(new_scope);
  1329. const Statement* body_block =
  1330. Statement::MakeBlock(stmt->line_num, c->second);
  1331. Action* body_act = MakeStmtAct(body_block);
  1332. body_act->pos = 0;
  1333. frame->todo.Pop(2);
  1334. frame->todo.Push(body_act);
  1335. frame->todo.Push(MakeStmtAct(c->second));
  1336. } else {
  1337. // this case did not match, moving on
  1338. act->pos++;
  1339. clause_num = (act->pos - 1) / 2;
  1340. if (clause_num <
  1341. static_cast<int>(stmt->GetMatch().clauses->size())) {
  1342. // interpret the next clause
  1343. c = stmt->GetMatch().clauses->begin();
  1344. std::advance(c, clause_num);
  1345. frame->todo.Pop(1);
  1346. frame->todo.Push(MakeExpAct(c->first));
  1347. } else { // No more clauses in match
  1348. frame->todo.Pop(2);
  1349. }
  1350. }
  1351. }
  1352. break;
  1353. }
  1354. case StatementKind::Return: {
  1355. // { {v :: return [] :: C, E, F} :: {C', E', F'} :: S, H}
  1356. // -> { {v :: C', E', F'} :: S, H}
  1357. const Value* ret_val = CopyVal(val_act->u.val, stmt->line_num);
  1358. DeallocateLocals(stmt->line_num, frame);
  1359. state->stack.Pop(1);
  1360. frame = state->stack.Top();
  1361. frame->todo.Push(MakeValAct(ret_val));
  1362. break;
  1363. }
  1364. case StatementKind::Run: {
  1365. frame->todo.Pop(2);
  1366. // Push an expression statement action to ignore the result
  1367. // value from the continuation.
  1368. Action* ignore_result = MakeStmtAct(Statement::MakeExpStmt(
  1369. stmt->line_num, Expression::MakeUnit(stmt->line_num)));
  1370. ignore_result->pos = 0;
  1371. frame->todo.Push(ignore_result);
  1372. // Push the continuation onto the current stack.
  1373. std::vector<Frame*> continuation_vector =
  1374. ContinuationToVector(val_act->u.val, stmt->line_num);
  1375. for (auto frame_iter = continuation_vector.rbegin();
  1376. frame_iter != continuation_vector.rend(); ++frame_iter) {
  1377. state->stack.Push(*frame_iter);
  1378. }
  1379. break;
  1380. }
  1381. case StatementKind::Continuation:
  1382. case StatementKind::Await:
  1383. case StatementKind::Block:
  1384. case StatementKind::Sequence:
  1385. case StatementKind::Break:
  1386. case StatementKind::Continue:
  1387. std::cerr << "internal error in handle_value, unhandled statement ";
  1388. PrintStatement(stmt, 1);
  1389. std::cerr << std::endl;
  1390. exit(-1);
  1391. } // switch stmt
  1392. break;
  1393. }
  1394. case ActionKind::ValAction:
  1395. std::cerr << "internal error, ValAction in handle_value" << std::endl;
  1396. exit(-1);
  1397. } // switch act
  1398. }
  1399. // State transition.
  1400. void Step() {
  1401. Frame* frame = state->stack.Top();
  1402. if (frame->todo.IsEmpty()) {
  1403. std::cerr << "runtime error: fell off end of function " << frame->name
  1404. << " without `return`" << std::endl;
  1405. exit(-1);
  1406. }
  1407. Action* act = frame->todo.Top();
  1408. switch (act->tag) {
  1409. case ActionKind::DeleteTmpAction:
  1410. std::cerr << "internal error in step, did not expect DeleteTmpAction"
  1411. << std::endl;
  1412. break;
  1413. case ActionKind::ExpToLValAction:
  1414. std::cerr << "internal error in step, did not expect ExpToLValAction"
  1415. << std::endl;
  1416. break;
  1417. case ActionKind::ValAction:
  1418. HandleValue();
  1419. break;
  1420. case ActionKind::LValAction:
  1421. StepLvalue();
  1422. break;
  1423. case ActionKind::ExpressionAction:
  1424. StepExp();
  1425. break;
  1426. case ActionKind::StatementAction:
  1427. StepStmt();
  1428. break;
  1429. } // switch
  1430. }
  1431. // Interpret the whole porogram.
  1432. auto InterpProgram(std::list<Declaration>* fs) -> int {
  1433. state = new State(); // Runtime state.
  1434. if (tracing_output) {
  1435. std::cout << "********** initializing globals **********" << std::endl;
  1436. }
  1437. InitGlobals(fs);
  1438. const Expression* arg =
  1439. Expression::MakeTuple(0, new std::vector<FieldInitializer>());
  1440. const Expression* call_main =
  1441. Expression::MakeCall(0, Expression::MakeVar(0, "main"), arg);
  1442. auto todo = Stack(MakeExpAct(call_main));
  1443. auto* scope = new Scope(globals, std::list<std::string>());
  1444. auto* frame = new Frame("top", Stack(scope), todo);
  1445. state->stack = Stack(frame);
  1446. if (tracing_output) {
  1447. std::cout << "********** calling main function **********" << std::endl;
  1448. PrintState(std::cout);
  1449. }
  1450. while (state->stack.CountExceeds(1) ||
  1451. state->stack.Top()->todo.CountExceeds(1) ||
  1452. state->stack.Top()->todo.Top()->tag != ActionKind::ValAction) {
  1453. Step();
  1454. if (tracing_output) {
  1455. PrintState(std::cout);
  1456. }
  1457. }
  1458. const Value* v = state->stack.Top()->todo.Top()->u.val;
  1459. return ValToInt(v, 0);
  1460. }
  1461. // Interpret an expression at compile-time.
  1462. auto InterpExp(Env values, const Expression* e) -> const Value* {
  1463. auto todo = Stack(MakeExpAct(e));
  1464. auto* scope = new Scope(values, std::list<std::string>());
  1465. auto* frame = new Frame("InterpExp", Stack(scope), todo);
  1466. state->stack = Stack(frame);
  1467. while (state->stack.CountExceeds(1) ||
  1468. state->stack.Top()->todo.CountExceeds(1) ||
  1469. state->stack.Top()->todo.Top()->tag != ActionKind::ValAction) {
  1470. Step();
  1471. }
  1472. const Value* v = state->stack.Top()->todo.Top()->u.val;
  1473. return v;
  1474. }
  1475. } // namespace Carbon