interpreter.cpp 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421
  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(Action::MakeExpressionAction(stmt->GetExpression()));
  1117. act->pos++;
  1118. } else {
  1119. frame->todo.Pop(1);
  1120. }
  1121. break;
  1122. case StatementKind::Assign:
  1123. if (act->pos == 0) {
  1124. // { {(lv = e) :: C, E, F} :: S, H}
  1125. // -> { {lv :: ([] = e) :: C, E, F} :: S, H}
  1126. frame->todo.Push(Action::MakeLValAction(stmt->GetAssign().lhs));
  1127. act->pos++;
  1128. } else if (act->pos == 1) {
  1129. // { { a :: ([] = e) :: C, E, F} :: S, H}
  1130. // -> { { e :: (a = []) :: C, E, F} :: S, H}
  1131. frame->todo.Push(Action::MakeExpressionAction(stmt->GetAssign().rhs));
  1132. act->pos++;
  1133. } else if (act->pos == 2) {
  1134. // { { v :: (a = []) :: C, E, F} :: S, H}
  1135. // -> { { C, E, F} :: S, H(a := v)}
  1136. auto pat = act->results[0];
  1137. auto val = act->results[1];
  1138. PatternAssignment(pat, val, stmt->line_num);
  1139. frame->todo.Pop(1);
  1140. }
  1141. break;
  1142. case StatementKind::If:
  1143. if (act->pos == 0) {
  1144. // { {(if (e) then_stmt else else_stmt) :: C, E, F} :: S, H}
  1145. // -> { { e :: (if ([]) then_stmt else else_stmt) :: C, E, F} :: S, H}
  1146. frame->todo.Push(Action::MakeExpressionAction(stmt->GetIf().cond));
  1147. act->pos++;
  1148. } else if (ValToBool(act->results[0], stmt->line_num)) {
  1149. // { {true :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  1150. // S, H}
  1151. // -> { { then_stmt :: C, E, F } :: S, H}
  1152. frame->todo.Pop(1);
  1153. frame->todo.Push(Action::MakeStatementAction(stmt->GetIf().then_stmt));
  1154. } else if (stmt->GetIf().else_stmt) {
  1155. // { {false :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  1156. // S, H}
  1157. // -> { { else_stmt :: C, E, F } :: S, H}
  1158. frame->todo.Pop(1);
  1159. frame->todo.Push(Action::MakeStatementAction(stmt->GetIf().else_stmt));
  1160. } else {
  1161. frame->todo.Pop(1);
  1162. }
  1163. break;
  1164. case StatementKind::Return:
  1165. if (act->pos == 0) {
  1166. // { {return e :: C, E, F} :: S, H}
  1167. // -> { {e :: return [] :: C, E, F} :: S, H}
  1168. frame->todo.Push(Action::MakeExpressionAction(stmt->GetReturn()));
  1169. act->pos++;
  1170. } else {
  1171. // { {v :: return [] :: C, E, F} :: {C', E', F'} :: S, H}
  1172. // -> { {v :: C', E', F'} :: S, H}
  1173. const Value* ret_val = CopyVal(act->results[0], stmt->line_num);
  1174. DeallocateLocals(stmt->line_num, frame);
  1175. state->stack.Pop(1);
  1176. frame = state->stack.Top();
  1177. frame->todo.Push(Action::MakeValAction(ret_val));
  1178. }
  1179. break;
  1180. case StatementKind::Sequence:
  1181. CHECK(act->pos == 0);
  1182. // { { (s1,s2) :: C, E, F} :: S, H}
  1183. // -> { { s1 :: s2 :: C, E, F} :: S, H}
  1184. frame->todo.Pop(1);
  1185. if (stmt->GetSequence().next) {
  1186. frame->todo.Push(Action::MakeStatementAction(stmt->GetSequence().next));
  1187. }
  1188. frame->todo.Push(Action::MakeStatementAction(stmt->GetSequence().stmt));
  1189. break;
  1190. case StatementKind::Continuation: {
  1191. CHECK(act->pos == 0);
  1192. // Create a continuation object by creating a frame similar the
  1193. // way one is created in a function call.
  1194. Scope* scope = new Scope(CurrentEnv(state), std::list<std::string>());
  1195. Stack<Scope*> scopes;
  1196. scopes.Push(scope);
  1197. Stack<Action*> todo;
  1198. todo.Push(Action::MakeStatementAction(Statement::MakeReturn(
  1199. stmt->line_num, Expression::MakeTupleLiteral(stmt->line_num, {}))));
  1200. todo.Push(Action::MakeStatementAction(stmt->GetContinuation().body));
  1201. Frame* continuation_frame = new Frame("__continuation", scopes, todo);
  1202. Address continuation_address = state->heap.AllocateValue(
  1203. Value::MakeContinuationValue({continuation_frame}));
  1204. // Store the continuation's address in the frame.
  1205. continuation_frame->continuation = continuation_address;
  1206. // Bind the continuation object to the continuation variable
  1207. frame->scopes.Top()->values.Set(
  1208. *stmt->GetContinuation().continuation_variable, continuation_address);
  1209. // Pop the continuation statement.
  1210. frame->todo.Pop();
  1211. break;
  1212. }
  1213. case StatementKind::Run:
  1214. if (act->pos == 0) {
  1215. // Evaluate the argument of the run statement.
  1216. frame->todo.Push(Action::MakeExpressionAction(stmt->GetRun().argument));
  1217. act->pos++;
  1218. } else {
  1219. frame->todo.Pop(1);
  1220. // Push an expression statement action to ignore the result
  1221. // value from the continuation.
  1222. Action* ignore_result = Action::MakeStatementAction(
  1223. Statement::MakeExpStmt(stmt->line_num, Expression::MakeTupleLiteral(
  1224. stmt->line_num, {})));
  1225. ignore_result->pos = 0;
  1226. frame->todo.Push(ignore_result);
  1227. // Push the continuation onto the current stack.
  1228. std::vector<Frame*> continuation_vector =
  1229. ContinuationToVector(act->results[0], stmt->line_num);
  1230. for (auto frame_iter = continuation_vector.rbegin();
  1231. frame_iter != continuation_vector.rend(); ++frame_iter) {
  1232. state->stack.Push(*frame_iter);
  1233. }
  1234. }
  1235. break;
  1236. case StatementKind::Await:
  1237. CHECK(act->pos == 0);
  1238. // Pause the current continuation
  1239. frame->todo.Pop();
  1240. std::vector<Frame*> paused;
  1241. do {
  1242. paused.push_back(state->stack.Pop());
  1243. } while (!paused.back()->IsContinuation());
  1244. // Update the continuation with the paused stack.
  1245. state->heap.Write(paused.back()->continuation,
  1246. Value::MakeContinuationValue(paused), stmt->line_num);
  1247. break;
  1248. }
  1249. }
  1250. auto GetMember(const Value* v, const std::string& f, int line_num) -> Address {
  1251. switch (v->tag()) {
  1252. case ValKind::StructValue: {
  1253. auto a = FindTupleField(f, v->GetStructValue().inits);
  1254. if (a == std::nullopt) {
  1255. std::cerr << "runtime error, member " << f << " not in ";
  1256. PrintValue(v, std::cerr);
  1257. std::cerr << std::endl;
  1258. exit(-1);
  1259. }
  1260. return *a;
  1261. }
  1262. case ValKind::TupleValue: {
  1263. auto a = FindTupleField(f, v);
  1264. if (a == std::nullopt) {
  1265. std::cerr << "field " << f << " not in ";
  1266. PrintValue(v, std::cerr);
  1267. std::cerr << std::endl;
  1268. exit(-1);
  1269. }
  1270. return *a;
  1271. }
  1272. case ValKind::ChoiceType: {
  1273. if (FindInVarValues(f, v->GetChoiceType().alternatives) == nullptr) {
  1274. std::cerr << "alternative " << f << " not in ";
  1275. PrintValue(v, std::cerr);
  1276. std::cerr << std::endl;
  1277. exit(-1);
  1278. }
  1279. auto ac =
  1280. Value::MakeAlternativeConstructorValue(f, v->GetChoiceType().name);
  1281. return state->heap.AllocateValue(ac);
  1282. }
  1283. default:
  1284. std::cerr << "field access not allowed for value ";
  1285. PrintValue(v, std::cerr);
  1286. std::cerr << std::endl;
  1287. exit(-1);
  1288. }
  1289. }
  1290. // State transition.
  1291. void Step() {
  1292. Frame* frame = state->stack.Top();
  1293. if (frame->todo.IsEmpty()) {
  1294. std::cerr << "runtime error: fell off end of function " << frame->name
  1295. << " without `return`" << std::endl;
  1296. exit(-1);
  1297. }
  1298. Action* act = frame->todo.Top();
  1299. switch (act->tag()) {
  1300. case ActionKind::ValAction: {
  1301. Action* val_act = frame->todo.Pop();
  1302. Action* act = frame->todo.Top();
  1303. act->results.push_back(val_act->GetValAction().val);
  1304. break;
  1305. }
  1306. case ActionKind::LValAction:
  1307. StepLvalue();
  1308. break;
  1309. case ActionKind::ExpressionAction:
  1310. StepExp();
  1311. break;
  1312. case ActionKind::StatementAction:
  1313. StepStmt();
  1314. break;
  1315. } // switch
  1316. }
  1317. // Interpret the whole porogram.
  1318. auto InterpProgram(std::list<Declaration>* fs) -> int {
  1319. state = new State(); // Runtime state.
  1320. if (tracing_output) {
  1321. std::cout << "********** initializing globals **********" << std::endl;
  1322. }
  1323. InitGlobals(fs);
  1324. const Expression* arg = Expression::MakeTupleLiteral(0, {});
  1325. const Expression* call_main = Expression::MakeCallExpression(
  1326. 0, Expression::MakeIdentifierExpression(0, "main"), arg);
  1327. auto todo = Stack(Action::MakeExpressionAction(call_main));
  1328. auto* scope = new Scope(globals, std::list<std::string>());
  1329. auto* frame = new Frame("top", Stack(scope), todo);
  1330. state->stack = Stack(frame);
  1331. if (tracing_output) {
  1332. std::cout << "********** calling main function **********" << std::endl;
  1333. PrintState(std::cout);
  1334. }
  1335. while (state->stack.CountExceeds(1) ||
  1336. state->stack.Top()->todo.CountExceeds(1) ||
  1337. state->stack.Top()->todo.Top()->tag() != ActionKind::ValAction) {
  1338. Step();
  1339. if (tracing_output) {
  1340. PrintState(std::cout);
  1341. }
  1342. }
  1343. const Value* v = state->stack.Top()->todo.Top()->GetValAction().val;
  1344. return ValToInt(v, 0);
  1345. }
  1346. // Interpret an expression at compile-time.
  1347. auto InterpExp(Env values, const Expression* e) -> const Value* {
  1348. auto todo = Stack(Action::MakeExpressionAction(e));
  1349. auto* scope = new Scope(values, std::list<std::string>());
  1350. auto* frame = new Frame("InterpExp", Stack(scope), todo);
  1351. state->stack = Stack(frame);
  1352. while (state->stack.CountExceeds(1) ||
  1353. state->stack.Top()->todo.CountExceeds(1) ||
  1354. state->stack.Top()->todo.Top()->tag() != ActionKind::ValAction) {
  1355. Step();
  1356. }
  1357. const Value* v = state->stack.Top()->todo.Top()->GetValAction().val;
  1358. return v;
  1359. }
  1360. } // namespace Carbon