interpreter.cpp 48 KB

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