interpreter.cpp 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423
  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(const Value* v, 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::TupleValue: {
  58. std::vector<TupleElement> elements;
  59. for (const TupleElement& element : val->GetTupleValue().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::MakeTupleValue(std::move(elements));
  66. }
  67. case ValKind::AlternativeValue: {
  68. const Value* arg = CopyVal(
  69. state->heap.Read(val->GetAlternativeValue().argument, line_num),
  70. line_num);
  71. Address argument_address = state->heap.AllocateValue(arg);
  72. return Value::MakeAlternativeValue(val->GetAlternativeValue().alt_name,
  73. val->GetAlternativeValue().choice_name,
  74. argument_address);
  75. }
  76. case ValKind::StructValue: {
  77. const Value* inits = CopyVal(val->GetStructValue().inits, line_num);
  78. return Value::MakeStructValue(val->GetStructValue().type, inits);
  79. }
  80. case ValKind::IntValue:
  81. return Value::MakeIntValue(val->GetIntValue());
  82. case ValKind::BoolValue:
  83. return Value::MakeBoolValue(val->GetBoolValue());
  84. case ValKind::FunctionValue:
  85. return Value::MakeFunctionValue(val->GetFunctionValue().name,
  86. val->GetFunctionValue().param,
  87. val->GetFunctionValue().body);
  88. case ValKind::PointerValue:
  89. return Value::MakePointerValue(val->GetPointerValue());
  90. case ValKind::ContinuationValue:
  91. // Copying a continuation is "shallow".
  92. return val;
  93. case ValKind::FunctionType:
  94. return Value::MakeFunctionType(
  95. CopyVal(val->GetFunctionType().param, line_num),
  96. CopyVal(val->GetFunctionType().ret, line_num));
  97. case ValKind::PointerType:
  98. return Value::MakePointerType(
  99. CopyVal(val->GetPointerType().type, line_num));
  100. case ValKind::IntType:
  101. return Value::MakeIntType();
  102. case ValKind::BoolType:
  103. return Value::MakeBoolType();
  104. case ValKind::TypeType:
  105. return Value::MakeTypeType();
  106. case ValKind::AutoType:
  107. return Value::MakeAutoType();
  108. case ValKind::ContinuationType:
  109. return Value::MakeContinuationType();
  110. case ValKind::StructType:
  111. case ValKind::ChoiceType:
  112. case ValKind::BindingPlaceholderValue:
  113. case ValKind::AlternativeConstructorValue:
  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::AlternativeValue:
  121. Deallocate(val->GetAlternativeValue().argument);
  122. break;
  123. case ValKind::StructValue:
  124. DeallocateSubObjects(val->GetStructValue().inits);
  125. break;
  126. case ValKind::TupleValue:
  127. for (const TupleElement& element : val->GetTupleValue().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. Action::PrintList(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::IntValue:
  204. return v->GetIntValue();
  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::BoolValue:
  214. return v->GetBoolValue();
  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::PointerValue:
  223. return v->GetPointerValue();
  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::ContinuationValue) {
  237. return continuation->GetContinuationValue().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::MakeIntValue(-ValToInt(args[0], line_num));
  249. case Operator::Add:
  250. return Value::MakeIntValue(ValToInt(args[0], line_num) +
  251. ValToInt(args[1], line_num));
  252. case Operator::Sub:
  253. return Value::MakeIntValue(ValToInt(args[0], line_num) -
  254. ValToInt(args[1], line_num));
  255. case Operator::Mul:
  256. return Value::MakeIntValue(ValToInt(args[0], line_num) *
  257. ValToInt(args[1], line_num));
  258. case Operator::Not:
  259. return Value::MakeBoolValue(!ValToBool(args[0], line_num));
  260. case Operator::And:
  261. return Value::MakeBoolValue(ValToBool(args[0], line_num) &&
  262. ValToBool(args[1], line_num));
  263. case Operator::Or:
  264. return Value::MakeBoolValue(ValToBool(args[0], line_num) ||
  265. ValToBool(args[1], line_num));
  266. case Operator::Eq:
  267. return Value::MakeBoolValue(ValueEqual(args[0], args[1], line_num));
  268. case Operator::Ptr:
  269. return Value::MakePointerType(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. VarValues alts;
  284. for (const auto& [name, signature] : alternatives) {
  285. auto t = InterpExp(Env(), signature);
  286. alts.push_back(make_pair(name, t));
  287. }
  288. auto ct = Value::MakeChoiceType(name, std::move(alts));
  289. auto a = state->heap.AllocateValue(ct);
  290. globals.Set(name, a);
  291. }
  292. auto StructDeclaration::InitGlobals(Env& globals) const -> void {
  293. VarValues fields;
  294. VarValues methods;
  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::MakeStructType(*definition.name, std::move(fields),
  306. std::move(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::MakeFunctionValue(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::FunctionValue: {
  331. // Bind arguments to parameters
  332. std::list<std::string> params;
  333. std::optional<Env> matches =
  334. PatternMatch(operas[0]->GetFunctionValue().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 = new Frame(operas[0]->GetFunctionValue().name, Stack(scope),
  344. Stack(Action::MakeStatementAction(
  345. operas[0]->GetFunctionValue().body)));
  346. state->stack.Push(frame);
  347. break;
  348. }
  349. case ValKind::StructType: {
  350. const Value* arg = CopyVal(operas[1], line_num);
  351. const Value* sv = Value::MakeStructValue(operas[0], arg);
  352. Frame* frame = state->stack.Top();
  353. frame->todo.Push(Action::MakeValAction(sv));
  354. break;
  355. }
  356. case ValKind::AlternativeConstructorValue: {
  357. const Value* arg = CopyVal(operas[1], line_num);
  358. const Value* av = Value::MakeAlternativeValue(
  359. operas[0]->GetAlternativeConstructorValue().alt_name,
  360. operas[0]->GetAlternativeConstructorValue().choice_name,
  361. state->heap.AllocateValue(arg));
  362. Frame* frame = state->stack.Top();
  363. frame->todo.Push(Action::MakeValAction(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. std::vector<TupleElement> elements;
  392. auto f = exp->GetTupleLiteral().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::MakeTupleValue(std::move(elements));
  398. frame->todo.Pop(1);
  399. frame->todo.Push(Action::MakeValAction(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::BindingPlaceholderValue: {
  411. Address a = state->heap.AllocateValue(CopyVal(v, line_num));
  412. vars->push_back(p->GetBindingPlaceholderValue().name);
  413. values.Set(p->GetBindingPlaceholderValue().name, a);
  414. return values;
  415. }
  416. case ValKind::TupleValue:
  417. switch (v->tag()) {
  418. case ValKind::TupleValue: {
  419. if (p->GetTupleValue().elements.size() !=
  420. v->GetTupleValue().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->GetTupleValue().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::AlternativeValue:
  451. switch (v->tag()) {
  452. case ValKind::AlternativeValue: {
  453. if (p->GetAlternativeValue().choice_name !=
  454. v->GetAlternativeValue().choice_name ||
  455. p->GetAlternativeValue().alt_name !=
  456. v->GetAlternativeValue().alt_name) {
  457. return std::nullopt;
  458. }
  459. std::optional<Env> matches = PatternMatch(
  460. state->heap.Read(p->GetAlternativeValue().argument, line_num),
  461. state->heap.Read(v->GetAlternativeValue().argument, line_num),
  462. values, vars, line_num);
  463. if (!matches) {
  464. return std::nullopt;
  465. }
  466. return *matches;
  467. }
  468. default:
  469. std::cerr
  470. << "internal error, expected a choice alternative in pattern, "
  471. "not ";
  472. PrintValue(v, std::cerr);
  473. std::cerr << std::endl;
  474. exit(-1);
  475. }
  476. case ValKind::FunctionType:
  477. switch (v->tag()) {
  478. case ValKind::FunctionType: {
  479. std::optional<Env> matches =
  480. PatternMatch(p->GetFunctionType().param,
  481. v->GetFunctionType().param, values, vars, line_num);
  482. if (!matches) {
  483. return std::nullopt;
  484. }
  485. return PatternMatch(p->GetFunctionType().ret,
  486. v->GetFunctionType().ret, *matches, vars,
  487. line_num);
  488. }
  489. default:
  490. return std::nullopt;
  491. }
  492. default:
  493. if (ValueEqual(p, v, line_num)) {
  494. return values;
  495. } else {
  496. return std::nullopt;
  497. }
  498. }
  499. }
  500. void PatternAssignment(const Value* pat, const Value* val, int line_num) {
  501. switch (pat->tag()) {
  502. case ValKind::PointerValue:
  503. state->heap.Write(ValToPtr(pat, line_num), CopyVal(val, line_num),
  504. line_num);
  505. break;
  506. case ValKind::TupleValue: {
  507. switch (val->tag()) {
  508. case ValKind::TupleValue: {
  509. if (pat->GetTupleValue().elements.size() !=
  510. val->GetTupleValue().elements.size()) {
  511. std::cerr << "runtime error: arity mismatch in tuple pattern match"
  512. << std::endl;
  513. exit(-1);
  514. }
  515. for (const TupleElement& element : pat->GetTupleValue().elements) {
  516. auto a = FindTupleField(element.name, val);
  517. if (a == std::nullopt) {
  518. std::cerr << "runtime error: field " << element.name << "not in ";
  519. PrintValue(val, std::cerr);
  520. std::cerr << std::endl;
  521. exit(-1);
  522. }
  523. PatternAssignment(state->heap.Read(element.address, line_num),
  524. state->heap.Read(*a, line_num), line_num);
  525. }
  526. break;
  527. }
  528. default:
  529. std::cerr
  530. << "internal error, expected a tuple value on right-hand-side, "
  531. "not ";
  532. PrintValue(val, std::cerr);
  533. std::cerr << std::endl;
  534. exit(-1);
  535. }
  536. break;
  537. }
  538. case ValKind::AlternativeValue: {
  539. switch (val->tag()) {
  540. case ValKind::AlternativeValue: {
  541. if (pat->GetAlternativeValue().choice_name !=
  542. val->GetAlternativeValue().choice_name ||
  543. pat->GetAlternativeValue().alt_name !=
  544. val->GetAlternativeValue().alt_name) {
  545. std::cerr << "internal error in pattern assignment" << std::endl;
  546. exit(-1);
  547. }
  548. PatternAssignment(
  549. state->heap.Read(pat->GetAlternativeValue().argument, line_num),
  550. state->heap.Read(val->GetAlternativeValue().argument, line_num),
  551. line_num);
  552. break;
  553. }
  554. default:
  555. std::cerr
  556. << "internal error, expected an alternative in left-hand-side, "
  557. "not ";
  558. PrintValue(val, std::cerr);
  559. std::cerr << std::endl;
  560. exit(-1);
  561. }
  562. break;
  563. }
  564. default:
  565. if (!ValueEqual(pat, val, line_num)) {
  566. std::cerr << "internal error in pattern assignment" << std::endl;
  567. exit(-1);
  568. }
  569. }
  570. }
  571. // State transitions for lvalues.
  572. void StepLvalue() {
  573. Frame* frame = state->stack.Top();
  574. Action* act = frame->todo.Top();
  575. const Expression* exp = act->GetLValAction().exp;
  576. if (tracing_output) {
  577. std::cout << "--- step lvalue ";
  578. PrintExp(exp);
  579. std::cout << " --->" << std::endl;
  580. }
  581. switch (exp->tag()) {
  582. case ExpressionKind::IdentifierExpression: {
  583. // { {x :: C, E, F} :: S, H}
  584. // -> { {E(x) :: C, E, F} :: S, H}
  585. std::optional<Address> pointer =
  586. CurrentEnv(state).Get(exp->GetIdentifierExpression().name);
  587. if (!pointer) {
  588. std::cerr << exp->line_num << ": could not find `"
  589. << exp->GetIdentifierExpression().name << "`" << std::endl;
  590. exit(-1);
  591. }
  592. const Value* v = Value::MakePointerValue(*pointer);
  593. frame->todo.Pop();
  594. frame->todo.Push(Action::MakeValAction(v));
  595. break;
  596. }
  597. case ExpressionKind::FieldAccessExpression: {
  598. if (act->pos == 0) {
  599. // { {e.f :: C, E, F} :: S, H}
  600. // -> { e :: [].f :: C, E, F} :: S, H}
  601. frame->todo.Push(Action::MakeExpressionAction(
  602. exp->GetFieldAccessExpression().aggregate));
  603. act->pos++;
  604. } else {
  605. // { v :: [].f :: C, E, F} :: S, H}
  606. // -> { { &v.f :: C, E, F} :: S, H }
  607. const Value* str = act->results[0];
  608. Address a = GetMember(str, exp->GetFieldAccessExpression().field,
  609. exp->line_num);
  610. frame->todo.Pop(1);
  611. frame->todo.Push(Action::MakeValAction(Value::MakePointerValue(a)));
  612. }
  613. break;
  614. }
  615. case ExpressionKind::IndexExpression: {
  616. if (act->pos == 0) {
  617. // { {e[i] :: C, E, F} :: S, H}
  618. // -> { e :: [][i] :: C, E, F} :: S, H}
  619. frame->todo.Push(
  620. Action::MakeExpressionAction(exp->GetIndexExpression().aggregate));
  621. act->pos++;
  622. } else if (act->pos == 1) {
  623. frame->todo.Push(
  624. Action::MakeExpressionAction(exp->GetIndexExpression().offset));
  625. act->pos++;
  626. } else if (act->pos == 2) {
  627. // { v :: [][i] :: C, E, F} :: S, H}
  628. // -> { { &v[i] :: C, E, F} :: S, H }
  629. const Value* tuple = act->results[0];
  630. std::string f = std::to_string(ToInteger(act->results[1]));
  631. auto a = FindTupleField(f, tuple);
  632. if (a == std::nullopt) {
  633. std::cerr << "runtime error: field " << f << "not in ";
  634. PrintValue(tuple, std::cerr);
  635. std::cerr << std::endl;
  636. exit(-1);
  637. }
  638. frame->todo.Pop(1);
  639. frame->todo.Push(Action::MakeValAction(Value::MakePointerValue(*a)));
  640. }
  641. break;
  642. }
  643. case ExpressionKind::TupleLiteral: {
  644. if (act->pos == 0) {
  645. // { {(f1=e1,...) :: C, E, F} :: S, H}
  646. // -> { {e1 :: (f1=[],...) :: C, E, F} :: S, H}
  647. const Expression* e1 = exp->GetTupleLiteral().fields[0].expression;
  648. frame->todo.Push(Action::MakeLValAction(e1));
  649. act->pos++;
  650. } else if (act->pos !=
  651. static_cast<int>(exp->GetTupleLiteral().fields.size())) {
  652. // { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
  653. // H}
  654. // -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
  655. // H}
  656. const Expression* elt =
  657. exp->GetTupleLiteral().fields[act->pos].expression;
  658. frame->todo.Push(Action::MakeLValAction(elt));
  659. act->pos++;
  660. } else {
  661. CreateTuple(frame, act, exp);
  662. }
  663. break;
  664. }
  665. case ExpressionKind::IntLiteral:
  666. case ExpressionKind::BoolLiteral:
  667. case ExpressionKind::CallExpression:
  668. case ExpressionKind::PrimitiveOperatorExpression:
  669. case ExpressionKind::IntTypeLiteral:
  670. case ExpressionKind::BoolTypeLiteral:
  671. case ExpressionKind::TypeTypeLiteral:
  672. case ExpressionKind::FunctionTypeLiteral:
  673. case ExpressionKind::AutoTypeLiteral:
  674. case ExpressionKind::ContinuationTypeLiteral:
  675. case ExpressionKind::BindingExpression: {
  676. std::cerr << "Can't treat expression as lvalue: ";
  677. PrintExp(exp);
  678. std::cerr << std::endl;
  679. exit(-1);
  680. }
  681. }
  682. }
  683. // State transitions for expressions.
  684. void StepExp() {
  685. Frame* frame = state->stack.Top();
  686. Action* act = frame->todo.Top();
  687. const Expression* exp = act->GetExpressionAction().exp;
  688. if (tracing_output) {
  689. std::cout << "--- step exp ";
  690. PrintExp(exp);
  691. std::cout << " --->" << std::endl;
  692. }
  693. switch (exp->tag()) {
  694. case ExpressionKind::BindingExpression: {
  695. if (act->pos == 0) {
  696. frame->todo.Push(
  697. Action::MakeExpressionAction(exp->GetBindingExpression().type));
  698. act->pos++;
  699. } else {
  700. auto v = Value::MakeBindingPlaceholderValue(
  701. exp->GetBindingExpression().name, act->results[0]);
  702. frame->todo.Pop(1);
  703. frame->todo.Push(Action::MakeValAction(v));
  704. }
  705. break;
  706. }
  707. case ExpressionKind::IndexExpression: {
  708. if (act->pos == 0) {
  709. // { { e[i] :: C, E, F} :: S, H}
  710. // -> { { e :: [][i] :: C, E, F} :: S, H}
  711. frame->todo.Push(
  712. Action::MakeExpressionAction(exp->GetIndexExpression().aggregate));
  713. act->pos++;
  714. } else if (act->pos == 1) {
  715. frame->todo.Push(
  716. Action::MakeExpressionAction(exp->GetIndexExpression().offset));
  717. act->pos++;
  718. } else if (act->pos == 2) {
  719. auto tuple = act->results[0];
  720. switch (tuple->tag()) {
  721. case ValKind::TupleValue: {
  722. // { { v :: [][i] :: C, E, F} :: S, H}
  723. // -> { { v_i :: C, E, F} : S, H}
  724. std::string f = std::to_string(ToInteger(act->results[1]));
  725. auto a = FindTupleField(f, tuple);
  726. if (a == std::nullopt) {
  727. std::cerr << "runtime error, field " << f << " not in ";
  728. PrintValue(tuple, std::cerr);
  729. std::cerr << std::endl;
  730. exit(-1);
  731. }
  732. frame->todo.Pop(1);
  733. const Value* element = state->heap.Read(*a, exp->line_num);
  734. frame->todo.Push(Action::MakeValAction(element));
  735. break;
  736. }
  737. default:
  738. std::cerr
  739. << "runtime type error, expected a tuple in field access, "
  740. "not ";
  741. PrintValue(tuple, std::cerr);
  742. exit(-1);
  743. }
  744. }
  745. break;
  746. }
  747. case ExpressionKind::TupleLiteral: {
  748. if (act->pos == 0) {
  749. if (exp->GetTupleLiteral().fields.size() > 0) {
  750. // { {(f1=e1,...) :: C, E, F} :: S, H}
  751. // -> { {e1 :: (f1=[],...) :: C, E, F} :: S, H}
  752. const Expression* e1 = exp->GetTupleLiteral().fields[0].expression;
  753. frame->todo.Push(Action::MakeExpressionAction(e1));
  754. act->pos++;
  755. } else {
  756. CreateTuple(frame, act, exp);
  757. }
  758. } else if (act->pos !=
  759. static_cast<int>(exp->GetTupleLiteral().fields.size())) {
  760. // { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
  761. // H}
  762. // -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
  763. // H}
  764. const Expression* elt =
  765. exp->GetTupleLiteral().fields[act->pos].expression;
  766. frame->todo.Push(Action::MakeExpressionAction(elt));
  767. act->pos++;
  768. } else {
  769. CreateTuple(frame, act, exp);
  770. }
  771. break;
  772. }
  773. case ExpressionKind::FieldAccessExpression: {
  774. if (act->pos == 0) {
  775. // { { e.f :: C, E, F} :: S, H}
  776. // -> { { e :: [].f :: C, E, F} :: S, H}
  777. frame->todo.Push(Action::MakeExpressionAction(
  778. exp->GetFieldAccessExpression().aggregate));
  779. act->pos++;
  780. } else {
  781. // { { v :: [].f :: C, E, F} :: S, H}
  782. // -> { { v_f :: C, E, F} : S, H}
  783. Address element =
  784. GetMember(act->results[0], exp->GetFieldAccessExpression().field,
  785. exp->line_num);
  786. frame->todo.Pop(1);
  787. frame->todo.Push(
  788. Action::MakeValAction(state->heap.Read(element, exp->line_num)));
  789. }
  790. break;
  791. }
  792. case ExpressionKind::IdentifierExpression: {
  793. CHECK(act->pos == 0);
  794. // { {x :: C, E, F} :: S, H} -> { {H(E(x)) :: C, E, F} :: S, H}
  795. std::optional<Address> pointer =
  796. CurrentEnv(state).Get(exp->GetIdentifierExpression().name);
  797. if (!pointer) {
  798. std::cerr << exp->line_num << ": could not find `"
  799. << exp->GetIdentifierExpression().name << "`" << std::endl;
  800. exit(-1);
  801. }
  802. const Value* pointee = state->heap.Read(*pointer, exp->line_num);
  803. frame->todo.Pop(1);
  804. frame->todo.Push(Action::MakeValAction(pointee));
  805. break;
  806. }
  807. case ExpressionKind::IntLiteral:
  808. CHECK(act->pos == 0);
  809. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  810. frame->todo.Pop(1);
  811. frame->todo.Push(
  812. Action::MakeValAction(Value::MakeIntValue(exp->GetIntLiteral())));
  813. break;
  814. case ExpressionKind::BoolLiteral:
  815. CHECK(act->pos == 0);
  816. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  817. frame->todo.Pop(1);
  818. frame->todo.Push(
  819. Action::MakeValAction(Value::MakeBoolValue(exp->GetBoolLiteral())));
  820. break;
  821. case ExpressionKind::PrimitiveOperatorExpression:
  822. if (act->pos !=
  823. static_cast<int>(
  824. exp->GetPrimitiveOperatorExpression().arguments.size())) {
  825. // { {v :: op(vs,[],e,es) :: C, E, F} :: S, H}
  826. // -> { {e :: op(vs,v,[],es) :: C, E, F} :: S, H}
  827. const Expression* arg =
  828. exp->GetPrimitiveOperatorExpression().arguments[act->pos];
  829. frame->todo.Push(Action::MakeExpressionAction(arg));
  830. act->pos++;
  831. } else {
  832. // { {v :: op(vs,[]) :: C, E, F} :: S, H}
  833. // -> { {eval_prim(op, (vs,v)) :: C, E, F} :: S, H}
  834. const Value* v = EvalPrim(exp->GetPrimitiveOperatorExpression().op,
  835. act->results, exp->line_num);
  836. frame->todo.Pop(1);
  837. frame->todo.Push(Action::MakeValAction(v));
  838. }
  839. break;
  840. case ExpressionKind::CallExpression:
  841. if (act->pos == 0) {
  842. // { {e1(e2) :: C, E, F} :: S, H}
  843. // -> { {e1 :: [](e2) :: C, E, F} :: S, H}
  844. frame->todo.Push(
  845. Action::MakeExpressionAction(exp->GetCallExpression().function));
  846. act->pos++;
  847. } else if (act->pos == 1) {
  848. // { { v :: [](e) :: C, E, F} :: S, H}
  849. // -> { { e :: v([]) :: C, E, F} :: S, H}
  850. frame->todo.Push(
  851. Action::MakeExpressionAction(exp->GetCallExpression().argument));
  852. act->pos++;
  853. } else if (act->pos == 2) {
  854. // { { v2 :: v1([]) :: C, E, F} :: S, H}
  855. // -> { {C',E',F'} :: {C, E, F} :: S, H}
  856. frame->todo.Pop(1);
  857. CallFunction(exp->line_num, act->results, state);
  858. } else {
  859. std::cerr << "internal error in handle_value with Call" << std::endl;
  860. exit(-1);
  861. }
  862. break;
  863. case ExpressionKind::IntTypeLiteral: {
  864. CHECK(act->pos == 0);
  865. const Value* v = Value::MakeIntType();
  866. frame->todo.Pop(1);
  867. frame->todo.Push(Action::MakeValAction(v));
  868. break;
  869. }
  870. case ExpressionKind::BoolTypeLiteral: {
  871. CHECK(act->pos == 0);
  872. const Value* v = Value::MakeBoolType();
  873. frame->todo.Pop(1);
  874. frame->todo.Push(Action::MakeValAction(v));
  875. break;
  876. }
  877. case ExpressionKind::AutoTypeLiteral: {
  878. CHECK(act->pos == 0);
  879. const Value* v = Value::MakeAutoType();
  880. frame->todo.Pop(1);
  881. frame->todo.Push(Action::MakeValAction(v));
  882. break;
  883. }
  884. case ExpressionKind::TypeTypeLiteral: {
  885. CHECK(act->pos == 0);
  886. const Value* v = Value::MakeTypeType();
  887. frame->todo.Pop(1);
  888. frame->todo.Push(Action::MakeValAction(v));
  889. break;
  890. }
  891. case ExpressionKind::FunctionTypeLiteral: {
  892. if (act->pos == 0) {
  893. frame->todo.Push(Action::MakeExpressionAction(
  894. exp->GetFunctionTypeLiteral().parameter));
  895. act->pos++;
  896. } else if (act->pos == 1) {
  897. // { { pt :: fn [] -> e :: C, E, F} :: S, H}
  898. // -> { { e :: fn pt -> []) :: C, E, F} :: S, H}
  899. frame->todo.Push(Action::MakeExpressionAction(
  900. exp->GetFunctionTypeLiteral().return_type));
  901. act->pos++;
  902. } else if (act->pos == 2) {
  903. // { { rt :: fn pt -> [] :: C, E, F} :: S, H}
  904. // -> { fn pt -> rt :: {C, E, F} :: S, H}
  905. const Value* v =
  906. Value::MakeFunctionType(act->results[0], act->results[1]);
  907. frame->todo.Pop(1);
  908. frame->todo.Push(Action::MakeValAction(v));
  909. }
  910. break;
  911. }
  912. case ExpressionKind::ContinuationTypeLiteral: {
  913. CHECK(act->pos == 0);
  914. const Value* v = Value::MakeContinuationType();
  915. frame->todo.Pop(1);
  916. frame->todo.Push(Action::MakeValAction(v));
  917. break;
  918. }
  919. } // switch (exp->tag)
  920. }
  921. auto IsWhileAct(Action* act) -> bool {
  922. switch (act->tag()) {
  923. case ActionKind::StatementAction:
  924. switch (act->GetStatementAction().stmt->tag()) {
  925. case StatementKind::While:
  926. return true;
  927. default:
  928. return false;
  929. }
  930. default:
  931. return false;
  932. }
  933. }
  934. auto IsBlockAct(Action* act) -> bool {
  935. switch (act->tag()) {
  936. case ActionKind::StatementAction:
  937. switch (act->GetStatementAction().stmt->tag()) {
  938. case StatementKind::Block:
  939. return true;
  940. default:
  941. return false;
  942. }
  943. default:
  944. return false;
  945. }
  946. }
  947. // State transitions for statements.
  948. void StepStmt() {
  949. Frame* frame = state->stack.Top();
  950. Action* act = frame->todo.Top();
  951. const Statement* stmt = act->GetStatementAction().stmt;
  952. CHECK(stmt != nullptr && "null statement!");
  953. if (tracing_output) {
  954. std::cout << "--- step stmt ";
  955. PrintStatement(stmt, 1);
  956. std::cout << " --->" << std::endl;
  957. }
  958. switch (stmt->tag()) {
  959. case StatementKind::Match:
  960. if (act->pos == 0) {
  961. // { { (match (e) ...) :: C, E, F} :: S, H}
  962. // -> { { e :: (match ([]) ...) :: C, E, F} :: S, H}
  963. frame->todo.Push(Action::MakeExpressionAction(stmt->GetMatch().exp));
  964. act->pos++;
  965. } else {
  966. // Regarding act->pos:
  967. // * odd: start interpreting the pattern of a clause
  968. // * even: finished interpreting the pattern, now try to match
  969. //
  970. // Regarding act->results:
  971. // * 0: the value that we're matching
  972. // * 1: the pattern for clause 0
  973. // * 2: the pattern for clause 1
  974. // * ...
  975. auto clause_num = (act->pos - 1) / 2;
  976. if (clause_num >= static_cast<int>(stmt->GetMatch().clauses->size())) {
  977. frame->todo.Pop(1);
  978. break;
  979. }
  980. auto c = stmt->GetMatch().clauses->begin();
  981. std::advance(c, clause_num);
  982. if (act->pos % 2 == 1) {
  983. // start interpreting the pattern of the clause
  984. // { {v :: (match ([]) ...) :: C, E, F} :: S, H}
  985. // -> { {pi :: (match ([]) ...) :: C, E, F} :: S, H}
  986. frame->todo.Push(Action::MakeExpressionAction(c->first));
  987. act->pos++;
  988. } else { // try to match
  989. auto v = act->results[0];
  990. auto pat = act->results[clause_num + 1];
  991. auto values = CurrentEnv(state);
  992. std::list<std::string> vars;
  993. std::optional<Env> matches =
  994. PatternMatch(pat, v, values, &vars, stmt->line_num);
  995. if (matches) { // we have a match, start the body
  996. auto* new_scope = new Scope(*matches, vars);
  997. frame->scopes.Push(new_scope);
  998. const Statement* body_block =
  999. Statement::MakeBlock(stmt->line_num, c->second);
  1000. Action* body_act = Action::MakeStatementAction(body_block);
  1001. body_act->pos = 1;
  1002. frame->todo.Pop(1);
  1003. frame->todo.Push(body_act);
  1004. frame->todo.Push(Action::MakeStatementAction(c->second));
  1005. } else {
  1006. // this case did not match, moving on
  1007. act->pos++;
  1008. clause_num = (act->pos - 1) / 2;
  1009. if (clause_num ==
  1010. static_cast<int>(stmt->GetMatch().clauses->size())) {
  1011. frame->todo.Pop(2);
  1012. }
  1013. }
  1014. }
  1015. }
  1016. break;
  1017. case StatementKind::While:
  1018. if (act->pos == 0) {
  1019. // { { (while (e) s) :: C, E, F} :: S, H}
  1020. // -> { { e :: (while ([]) s) :: C, E, F} :: S, H}
  1021. frame->todo.Push(Action::MakeExpressionAction(stmt->GetWhile().cond));
  1022. act->pos++;
  1023. } else if (ValToBool(act->results[0], stmt->line_num)) {
  1024. // { {true :: (while ([]) s) :: C, E, F} :: S, H}
  1025. // -> { { s :: (while (e) s) :: C, E, F } :: S, H}
  1026. frame->todo.Top()->pos = 0;
  1027. frame->todo.Top()->results.clear();
  1028. frame->todo.Push(Action::MakeStatementAction(stmt->GetWhile().body));
  1029. } else {
  1030. // { {false :: (while ([]) s) :: C, E, F} :: S, H}
  1031. // -> { { C, E, F } :: S, H}
  1032. frame->todo.Top()->pos = 0;
  1033. frame->todo.Top()->results.clear();
  1034. frame->todo.Pop(1);
  1035. }
  1036. break;
  1037. case StatementKind::Break:
  1038. CHECK(act->pos == 0);
  1039. // { { break; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  1040. // -> { { C, E', F} :: S, H}
  1041. frame->todo.Pop(1);
  1042. while (!frame->todo.IsEmpty() && !IsWhileAct(frame->todo.Top())) {
  1043. if (IsBlockAct(frame->todo.Top())) {
  1044. DeallocateScope(stmt->line_num, frame->scopes.Top());
  1045. frame->scopes.Pop(1);
  1046. }
  1047. frame->todo.Pop(1);
  1048. }
  1049. frame->todo.Pop(1);
  1050. break;
  1051. case StatementKind::Continue:
  1052. CHECK(act->pos == 0);
  1053. // { { continue; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  1054. // -> { { (while (e) s) :: C, E', F} :: S, H}
  1055. frame->todo.Pop(1);
  1056. while (!frame->todo.IsEmpty() && !IsWhileAct(frame->todo.Top())) {
  1057. if (IsBlockAct(frame->todo.Top())) {
  1058. DeallocateScope(stmt->line_num, frame->scopes.Top());
  1059. frame->scopes.Pop(1);
  1060. }
  1061. frame->todo.Pop(1);
  1062. }
  1063. break;
  1064. case StatementKind::Block: {
  1065. if (act->pos == 0) {
  1066. if (stmt->GetBlock().stmt) {
  1067. auto* scope = new Scope(CurrentEnv(state), {});
  1068. frame->scopes.Push(scope);
  1069. frame->todo.Push(Action::MakeStatementAction(stmt->GetBlock().stmt));
  1070. act->pos++;
  1071. act->pos++;
  1072. } else {
  1073. frame->todo.Pop();
  1074. }
  1075. } else {
  1076. Scope* scope = frame->scopes.Top();
  1077. DeallocateScope(stmt->line_num, scope);
  1078. frame->scopes.Pop(1);
  1079. frame->todo.Pop(1);
  1080. }
  1081. break;
  1082. }
  1083. case StatementKind::VariableDefinition:
  1084. if (act->pos == 0) {
  1085. // { {(var x = e) :: C, E, F} :: S, H}
  1086. // -> { {e :: (var x = []) :: C, E, F} :: S, H}
  1087. frame->todo.Push(
  1088. Action::MakeExpressionAction(stmt->GetVariableDefinition().init));
  1089. act->pos++;
  1090. } else if (act->pos == 1) {
  1091. frame->todo.Push(
  1092. Action::MakeExpressionAction(stmt->GetVariableDefinition().pat));
  1093. act->pos++;
  1094. } else if (act->pos == 2) {
  1095. // { { v :: (x = []) :: C, E, F} :: S, H}
  1096. // -> { { C, E(x := a), F} :: S, H(a := copy(v))}
  1097. const Value* v = act->results[0];
  1098. const Value* p = act->results[1];
  1099. std::optional<Env> matches =
  1100. PatternMatch(p, v, frame->scopes.Top()->values,
  1101. &frame->scopes.Top()->locals, stmt->line_num);
  1102. if (!matches) {
  1103. std::cerr << stmt->line_num
  1104. << ": internal error in variable definition, match failed"
  1105. << std::endl;
  1106. exit(-1);
  1107. }
  1108. frame->scopes.Top()->values = *matches;
  1109. frame->todo.Pop(1);
  1110. }
  1111. break;
  1112. case StatementKind::ExpressionStatement:
  1113. if (act->pos == 0) {
  1114. // { {e :: C, E, F} :: S, H}
  1115. // -> { {e :: C, E, F} :: S, H}
  1116. frame->todo.Push(
  1117. Action::MakeExpressionAction(stmt->GetExpressionStatement().exp));
  1118. act->pos++;
  1119. } else {
  1120. frame->todo.Pop(1);
  1121. }
  1122. break;
  1123. case StatementKind::Assign:
  1124. if (act->pos == 0) {
  1125. // { {(lv = e) :: C, E, F} :: S, H}
  1126. // -> { {lv :: ([] = e) :: C, E, F} :: S, H}
  1127. frame->todo.Push(Action::MakeLValAction(stmt->GetAssign().lhs));
  1128. act->pos++;
  1129. } else if (act->pos == 1) {
  1130. // { { a :: ([] = e) :: C, E, F} :: S, H}
  1131. // -> { { e :: (a = []) :: C, E, F} :: S, H}
  1132. frame->todo.Push(Action::MakeExpressionAction(stmt->GetAssign().rhs));
  1133. act->pos++;
  1134. } else if (act->pos == 2) {
  1135. // { { v :: (a = []) :: C, E, F} :: S, H}
  1136. // -> { { C, E, F} :: S, H(a := v)}
  1137. auto pat = act->results[0];
  1138. auto val = act->results[1];
  1139. PatternAssignment(pat, val, stmt->line_num);
  1140. frame->todo.Pop(1);
  1141. }
  1142. break;
  1143. case StatementKind::If:
  1144. if (act->pos == 0) {
  1145. // { {(if (e) then_stmt else else_stmt) :: C, E, F} :: S, H}
  1146. // -> { { e :: (if ([]) then_stmt else else_stmt) :: C, E, F} :: S, H}
  1147. frame->todo.Push(Action::MakeExpressionAction(stmt->GetIf().cond));
  1148. act->pos++;
  1149. } else if (ValToBool(act->results[0], stmt->line_num)) {
  1150. // { {true :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  1151. // S, H}
  1152. // -> { { then_stmt :: C, E, F } :: S, H}
  1153. frame->todo.Pop(1);
  1154. frame->todo.Push(Action::MakeStatementAction(stmt->GetIf().then_stmt));
  1155. } else if (stmt->GetIf().else_stmt) {
  1156. // { {false :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  1157. // S, H}
  1158. // -> { { else_stmt :: C, E, F } :: S, H}
  1159. frame->todo.Pop(1);
  1160. frame->todo.Push(Action::MakeStatementAction(stmt->GetIf().else_stmt));
  1161. } else {
  1162. frame->todo.Pop(1);
  1163. }
  1164. break;
  1165. case StatementKind::Return:
  1166. if (act->pos == 0) {
  1167. // { {return e :: C, E, F} :: S, H}
  1168. // -> { {e :: return [] :: C, E, F} :: S, H}
  1169. frame->todo.Push(Action::MakeExpressionAction(stmt->GetReturn().exp));
  1170. act->pos++;
  1171. } else {
  1172. // { {v :: return [] :: C, E, F} :: {C', E', F'} :: S, H}
  1173. // -> { {v :: C', E', F'} :: S, H}
  1174. const Value* ret_val = CopyVal(act->results[0], stmt->line_num);
  1175. DeallocateLocals(stmt->line_num, frame);
  1176. state->stack.Pop(1);
  1177. frame = state->stack.Top();
  1178. frame->todo.Push(Action::MakeValAction(ret_val));
  1179. }
  1180. break;
  1181. case StatementKind::Sequence:
  1182. CHECK(act->pos == 0);
  1183. // { { (s1,s2) :: C, E, F} :: S, H}
  1184. // -> { { s1 :: s2 :: C, E, F} :: S, H}
  1185. frame->todo.Pop(1);
  1186. if (stmt->GetSequence().next) {
  1187. frame->todo.Push(Action::MakeStatementAction(stmt->GetSequence().next));
  1188. }
  1189. frame->todo.Push(Action::MakeStatementAction(stmt->GetSequence().stmt));
  1190. break;
  1191. case StatementKind::Continuation: {
  1192. CHECK(act->pos == 0);
  1193. // Create a continuation object by creating a frame similar the
  1194. // way one is created in a function call.
  1195. Scope* scope = new Scope(CurrentEnv(state), std::list<std::string>());
  1196. Stack<Scope*> scopes;
  1197. scopes.Push(scope);
  1198. Stack<Action*> todo;
  1199. todo.Push(Action::MakeStatementAction(Statement::MakeReturn(
  1200. stmt->line_num, Expression::MakeTupleLiteral(stmt->line_num, {}))));
  1201. todo.Push(Action::MakeStatementAction(stmt->GetContinuation().body));
  1202. Frame* continuation_frame = new Frame("__continuation", scopes, todo);
  1203. Address continuation_address = state->heap.AllocateValue(
  1204. Value::MakeContinuationValue({continuation_frame}));
  1205. // Store the continuation's address in the frame.
  1206. continuation_frame->continuation = continuation_address;
  1207. // Bind the continuation object to the continuation variable
  1208. frame->scopes.Top()->values.Set(
  1209. stmt->GetContinuation().continuation_variable, continuation_address);
  1210. // Pop the continuation statement.
  1211. frame->todo.Pop();
  1212. break;
  1213. }
  1214. case StatementKind::Run:
  1215. if (act->pos == 0) {
  1216. // Evaluate the argument of the run statement.
  1217. frame->todo.Push(Action::MakeExpressionAction(stmt->GetRun().argument));
  1218. act->pos++;
  1219. } else {
  1220. frame->todo.Pop(1);
  1221. // Push an expression statement action to ignore the result
  1222. // value from the continuation.
  1223. Action* ignore_result =
  1224. Action::MakeStatementAction(Statement::MakeExpressionStatement(
  1225. stmt->line_num,
  1226. Expression::MakeTupleLiteral(stmt->line_num, {})));
  1227. ignore_result->pos = 0;
  1228. frame->todo.Push(ignore_result);
  1229. // Push the continuation onto the current stack.
  1230. std::vector<Frame*> continuation_vector =
  1231. ContinuationToVector(act->results[0], stmt->line_num);
  1232. for (auto frame_iter = continuation_vector.rbegin();
  1233. frame_iter != continuation_vector.rend(); ++frame_iter) {
  1234. state->stack.Push(*frame_iter);
  1235. }
  1236. }
  1237. break;
  1238. case StatementKind::Await:
  1239. CHECK(act->pos == 0);
  1240. // Pause the current continuation
  1241. frame->todo.Pop();
  1242. std::vector<Frame*> paused;
  1243. do {
  1244. paused.push_back(state->stack.Pop());
  1245. } while (!paused.back()->IsContinuation());
  1246. // Update the continuation with the paused stack.
  1247. state->heap.Write(paused.back()->continuation,
  1248. Value::MakeContinuationValue(paused), stmt->line_num);
  1249. break;
  1250. }
  1251. }
  1252. auto GetMember(const Value* v, const std::string& f, int line_num) -> Address {
  1253. switch (v->tag()) {
  1254. case ValKind::StructValue: {
  1255. auto a = FindTupleField(f, v->GetStructValue().inits);
  1256. if (a == std::nullopt) {
  1257. std::cerr << "runtime error, member " << f << " not in ";
  1258. PrintValue(v, std::cerr);
  1259. std::cerr << std::endl;
  1260. exit(-1);
  1261. }
  1262. return *a;
  1263. }
  1264. case ValKind::TupleValue: {
  1265. auto a = FindTupleField(f, v);
  1266. if (a == std::nullopt) {
  1267. std::cerr << "field " << f << " not in ";
  1268. PrintValue(v, std::cerr);
  1269. std::cerr << std::endl;
  1270. exit(-1);
  1271. }
  1272. return *a;
  1273. }
  1274. case ValKind::ChoiceType: {
  1275. if (FindInVarValues(f, v->GetChoiceType().alternatives) == nullptr) {
  1276. std::cerr << "alternative " << f << " not in ";
  1277. PrintValue(v, std::cerr);
  1278. std::cerr << std::endl;
  1279. exit(-1);
  1280. }
  1281. auto ac =
  1282. Value::MakeAlternativeConstructorValue(f, v->GetChoiceType().name);
  1283. return state->heap.AllocateValue(ac);
  1284. }
  1285. default:
  1286. std::cerr << "field access not allowed for value ";
  1287. PrintValue(v, std::cerr);
  1288. std::cerr << std::endl;
  1289. exit(-1);
  1290. }
  1291. }
  1292. // State transition.
  1293. void Step() {
  1294. Frame* frame = state->stack.Top();
  1295. if (frame->todo.IsEmpty()) {
  1296. std::cerr << "runtime error: fell off end of function " << frame->name
  1297. << " without `return`" << std::endl;
  1298. exit(-1);
  1299. }
  1300. Action* act = frame->todo.Top();
  1301. switch (act->tag()) {
  1302. case ActionKind::ValAction: {
  1303. Action* val_act = frame->todo.Pop();
  1304. Action* act = frame->todo.Top();
  1305. act->results.push_back(val_act->GetValAction().val);
  1306. break;
  1307. }
  1308. case ActionKind::LValAction:
  1309. StepLvalue();
  1310. break;
  1311. case ActionKind::ExpressionAction:
  1312. StepExp();
  1313. break;
  1314. case ActionKind::StatementAction:
  1315. StepStmt();
  1316. break;
  1317. } // switch
  1318. }
  1319. // Interpret the whole porogram.
  1320. auto InterpProgram(std::list<Declaration>* fs) -> int {
  1321. state = new State(); // Runtime state.
  1322. if (tracing_output) {
  1323. std::cout << "********** initializing globals **********" << std::endl;
  1324. }
  1325. InitGlobals(fs);
  1326. const Expression* arg = Expression::MakeTupleLiteral(0, {});
  1327. const Expression* call_main = Expression::MakeCallExpression(
  1328. 0, Expression::MakeIdentifierExpression(0, "main"), arg);
  1329. auto todo = Stack(Action::MakeExpressionAction(call_main));
  1330. auto* scope = new Scope(globals, std::list<std::string>());
  1331. auto* frame = new Frame("top", Stack(scope), todo);
  1332. state->stack = Stack(frame);
  1333. if (tracing_output) {
  1334. std::cout << "********** calling main function **********" << std::endl;
  1335. PrintState(std::cout);
  1336. }
  1337. while (state->stack.CountExceeds(1) ||
  1338. state->stack.Top()->todo.CountExceeds(1) ||
  1339. state->stack.Top()->todo.Top()->tag() != ActionKind::ValAction) {
  1340. Step();
  1341. if (tracing_output) {
  1342. PrintState(std::cout);
  1343. }
  1344. }
  1345. const Value* v = state->stack.Top()->todo.Top()->GetValAction().val;
  1346. return ValToInt(v, 0);
  1347. }
  1348. // Interpret an expression at compile-time.
  1349. auto InterpExp(Env values, const Expression* e) -> const Value* {
  1350. auto todo = Stack(Action::MakeExpressionAction(e));
  1351. auto* scope = new Scope(values, std::list<std::string>());
  1352. auto* frame = new Frame("InterpExp", Stack(scope), todo);
  1353. state->stack = Stack(frame);
  1354. while (state->stack.CountExceeds(1) ||
  1355. state->stack.Top()->todo.CountExceeds(1) ||
  1356. state->stack.Top()->todo.Top()->tag() != ActionKind::ValAction) {
  1357. Step();
  1358. }
  1359. const Value* v = state->stack.Top()->todo.Top()->GetValAction().val;
  1360. return v;
  1361. }
  1362. } // namespace Carbon