interpreter.cpp 51 KB

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