interpreter.cpp 49 KB

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