interpreter.cpp 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208
  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 <iterator>
  6. #include <map>
  7. #include <optional>
  8. #include <utility>
  9. #include <variant>
  10. #include <vector>
  11. #include "common/check.h"
  12. #include "executable_semantics/ast/expression.h"
  13. #include "executable_semantics/ast/function_definition.h"
  14. #include "executable_semantics/common/arena.h"
  15. #include "executable_semantics/common/error.h"
  16. #include "executable_semantics/common/tracing_flag.h"
  17. #include "executable_semantics/interpreter/action.h"
  18. #include "executable_semantics/interpreter/frame.h"
  19. #include "executable_semantics/interpreter/stack.h"
  20. #include "llvm/ADT/ScopeExit.h"
  21. #include "llvm/ADT/StringExtras.h"
  22. #include "llvm/Support/Casting.h"
  23. using llvm::cast;
  24. using llvm::dyn_cast;
  25. namespace Carbon {
  26. //
  27. // Auxiliary Functions
  28. //
  29. void Interpreter::PrintEnv(Env values, llvm::raw_ostream& out) {
  30. llvm::ListSeparator sep;
  31. for (const auto& [name, address] : values) {
  32. out << sep << name << ": ";
  33. heap.PrintAddress(address, out);
  34. }
  35. }
  36. //
  37. // State Operations
  38. //
  39. auto Interpreter::CurrentEnv() -> Env {
  40. Ptr<Frame> frame = stack.Top();
  41. return frame->scopes.Top()->values;
  42. }
  43. // Returns the given name from the environment, printing an error if not found.
  44. auto Interpreter::GetFromEnv(SourceLocation loc, const std::string& name)
  45. -> Address {
  46. std::optional<Address> pointer = CurrentEnv().Get(name);
  47. if (!pointer) {
  48. FATAL_RUNTIME_ERROR(loc) << "could not find `" << name << "`";
  49. }
  50. return *pointer;
  51. }
  52. void Interpreter::PrintState(llvm::raw_ostream& out) {
  53. out << "{\nstack: ";
  54. llvm::ListSeparator sep(" :: ");
  55. for (const auto& frame : stack) {
  56. out << sep << *frame;
  57. }
  58. out << "\nheap: " << heap;
  59. if (!stack.IsEmpty() && !stack.Top()->scopes.IsEmpty()) {
  60. out << "\nvalues: ";
  61. PrintEnv(CurrentEnv(), out);
  62. }
  63. out << "\n}\n";
  64. }
  65. static auto EvalPrim(Operator op, const std::vector<Ptr<const Value>>& args,
  66. SourceLocation loc) -> Ptr<const Value> {
  67. switch (op) {
  68. case Operator::Neg:
  69. return global_arena->New<IntValue>(-cast<IntValue>(*args[0]).Val());
  70. case Operator::Add:
  71. return global_arena->New<IntValue>(cast<IntValue>(*args[0]).Val() +
  72. cast<IntValue>(*args[1]).Val());
  73. case Operator::Sub:
  74. return global_arena->New<IntValue>(cast<IntValue>(*args[0]).Val() -
  75. cast<IntValue>(*args[1]).Val());
  76. case Operator::Mul:
  77. return global_arena->New<IntValue>(cast<IntValue>(*args[0]).Val() *
  78. cast<IntValue>(*args[1]).Val());
  79. case Operator::Not:
  80. return global_arena->New<BoolValue>(!cast<BoolValue>(*args[0]).Val());
  81. case Operator::And:
  82. return global_arena->New<BoolValue>(cast<BoolValue>(*args[0]).Val() &&
  83. cast<BoolValue>(*args[1]).Val());
  84. case Operator::Or:
  85. return global_arena->New<BoolValue>(cast<BoolValue>(*args[0]).Val() ||
  86. cast<BoolValue>(*args[1]).Val());
  87. case Operator::Eq:
  88. return global_arena->New<BoolValue>(ValueEqual(args[0], args[1], loc));
  89. case Operator::Ptr:
  90. return global_arena->New<PointerType>(args[0]);
  91. case Operator::Deref:
  92. FATAL() << "dereference not implemented yet";
  93. }
  94. }
  95. void Interpreter::InitEnv(const Declaration& d, Env* env) {
  96. switch (d.Tag()) {
  97. case Declaration::Kind::FunctionDeclaration: {
  98. const FunctionDefinition& func_def =
  99. cast<FunctionDeclaration>(d).Definition();
  100. Env new_env = *env;
  101. // Bring the deduced parameters into scope.
  102. for (const auto& deduced : func_def.deduced_parameters) {
  103. Address a =
  104. heap.AllocateValue(global_arena->New<VariableType>(deduced.name));
  105. new_env.Set(deduced.name, a);
  106. }
  107. auto pt = InterpPattern(new_env, func_def.param_pattern);
  108. auto f =
  109. global_arena->New<FunctionValue>(func_def.name, pt, func_def.body);
  110. Address a = heap.AllocateValue(f);
  111. env->Set(func_def.name, a);
  112. break;
  113. }
  114. case Declaration::Kind::ClassDeclaration: {
  115. const ClassDefinition& class_def = cast<ClassDeclaration>(d).Definition();
  116. VarValues fields;
  117. VarValues methods;
  118. for (Ptr<const Member> m : class_def.members) {
  119. switch (m->Tag()) {
  120. case Member::Kind::FieldMember: {
  121. Ptr<const BindingPattern> binding = cast<FieldMember>(*m).Binding();
  122. Ptr<const Expression> type_expression =
  123. cast<ExpressionPattern>(*binding->Type()).Expression();
  124. auto type = InterpExp(Env(), type_expression);
  125. fields.push_back(make_pair(*binding->Name(), type));
  126. break;
  127. }
  128. }
  129. }
  130. auto st = global_arena->New<ClassType>(class_def.name, std::move(fields),
  131. std::move(methods));
  132. auto a = heap.AllocateValue(st);
  133. env->Set(class_def.name, a);
  134. break;
  135. }
  136. case Declaration::Kind::ChoiceDeclaration: {
  137. const auto& choice = cast<ChoiceDeclaration>(d);
  138. VarValues alts;
  139. for (const auto& [name, signature] : choice.Alternatives()) {
  140. auto t = InterpExp(Env(), signature);
  141. alts.push_back(make_pair(name, t));
  142. }
  143. auto ct = global_arena->New<ChoiceType>(choice.Name(), std::move(alts));
  144. auto a = heap.AllocateValue(ct);
  145. env->Set(choice.Name(), a);
  146. break;
  147. }
  148. case Declaration::Kind::VariableDeclaration: {
  149. const auto& var = cast<VariableDeclaration>(d);
  150. // Adds an entry in `globals` mapping the variable's name to the
  151. // result of evaluating the initializer.
  152. auto v = InterpExp(*env, var.Initializer());
  153. Address a = heap.AllocateValue(v);
  154. env->Set(*var.Binding()->Name(), a);
  155. break;
  156. }
  157. }
  158. }
  159. void Interpreter::InitGlobals(const std::vector<Ptr<const Declaration>>& fs) {
  160. for (const auto d : fs) {
  161. InitEnv(*d, &globals);
  162. }
  163. }
  164. void Interpreter::DeallocateScope(Ptr<Scope> scope) {
  165. for (const auto& l : scope->locals) {
  166. std::optional<Address> a = scope->values.Get(l);
  167. CHECK(a);
  168. heap.Deallocate(*a);
  169. }
  170. }
  171. void Interpreter::DeallocateLocals(Ptr<Frame> frame) {
  172. while (!frame->scopes.IsEmpty()) {
  173. DeallocateScope(frame->scopes.Top());
  174. frame->scopes.Pop();
  175. }
  176. }
  177. static Ptr<const Value> CreateTuple(Ptr<Action> act,
  178. Ptr<const Expression> exp) {
  179. // { { (v1,...,vn) :: C, E, F} :: S, H}
  180. // -> { { `(v1,...,vn) :: C, E, F} :: S, H}
  181. const auto& tup_lit = cast<TupleLiteral>(*exp);
  182. CHECK(act->Results().size() == tup_lit.Fields().size());
  183. std::vector<TupleElement> elements;
  184. for (size_t i = 0; i < act->Results().size(); ++i) {
  185. elements.push_back(
  186. {.name = tup_lit.Fields()[i].name, .value = act->Results()[i]});
  187. }
  188. return global_arena->New<TupleValue>(std::move(elements));
  189. }
  190. auto Interpreter::PatternMatch(Ptr<const Value> p, Ptr<const Value> v,
  191. SourceLocation loc) -> std::optional<Env> {
  192. switch (p->Tag()) {
  193. case Value::Kind::BindingPlaceholderValue: {
  194. const auto& placeholder = cast<BindingPlaceholderValue>(*p);
  195. Env values;
  196. if (placeholder.Name().has_value()) {
  197. Address a = heap.AllocateValue(CopyVal(v, loc));
  198. values.Set(*placeholder.Name(), a);
  199. }
  200. return values;
  201. }
  202. case Value::Kind::TupleValue:
  203. switch (v->Tag()) {
  204. case Value::Kind::TupleValue: {
  205. const auto& p_tup = cast<TupleValue>(*p);
  206. const auto& v_tup = cast<TupleValue>(*v);
  207. if (p_tup.Elements().size() != v_tup.Elements().size()) {
  208. FATAL_PROGRAM_ERROR(loc)
  209. << "arity mismatch in tuple pattern match:\n pattern: "
  210. << p_tup << "\n value: " << v_tup;
  211. }
  212. Env values;
  213. for (size_t i = 0; i < p_tup.Elements().size(); ++i) {
  214. if (p_tup.Elements()[i].name != v_tup.Elements()[i].name) {
  215. FATAL_PROGRAM_ERROR(loc)
  216. << "Tuple field name '" << v_tup.Elements()[i].name
  217. << "' does not match pattern field name '"
  218. << p_tup.Elements()[i].name << "'";
  219. }
  220. std::optional<Env> matches = PatternMatch(
  221. p_tup.Elements()[i].value, v_tup.Elements()[i].value, loc);
  222. if (!matches) {
  223. return std::nullopt;
  224. }
  225. for (const auto& [name, value] : *matches) {
  226. values.Set(name, value);
  227. }
  228. } // for
  229. return values;
  230. }
  231. default:
  232. FATAL() << "expected a tuple value in pattern, not " << *v;
  233. }
  234. case Value::Kind::AlternativeValue:
  235. switch (v->Tag()) {
  236. case Value::Kind::AlternativeValue: {
  237. const auto& p_alt = cast<AlternativeValue>(*p);
  238. const auto& v_alt = cast<AlternativeValue>(*v);
  239. if (p_alt.ChoiceName() != v_alt.ChoiceName() ||
  240. p_alt.AltName() != v_alt.AltName()) {
  241. return std::nullopt;
  242. }
  243. return PatternMatch(p_alt.Argument(), v_alt.Argument(), loc);
  244. }
  245. default:
  246. FATAL() << "expected a choice alternative in pattern, not " << *v;
  247. }
  248. case Value::Kind::FunctionType:
  249. switch (v->Tag()) {
  250. case Value::Kind::FunctionType: {
  251. const auto& p_fn = cast<FunctionType>(*p);
  252. const auto& v_fn = cast<FunctionType>(*v);
  253. std::optional<Env> param_matches =
  254. PatternMatch(p_fn.Param(), v_fn.Param(), loc);
  255. if (!param_matches) {
  256. return std::nullopt;
  257. }
  258. std::optional<Env> ret_matches =
  259. PatternMatch(p_fn.Ret(), v_fn.Ret(), loc);
  260. if (!ret_matches) {
  261. return std::nullopt;
  262. }
  263. Env values = *param_matches;
  264. for (const auto& [name, value] : *ret_matches) {
  265. values.Set(name, value);
  266. }
  267. return values;
  268. }
  269. default:
  270. return std::nullopt;
  271. }
  272. case Value::Kind::AutoType:
  273. // `auto` matches any type, without binding any new names. We rely
  274. // on the typechecker to ensure that `v` is a type.
  275. return Env();
  276. default:
  277. if (ValueEqual(p, v, loc)) {
  278. return Env();
  279. } else {
  280. return std::nullopt;
  281. }
  282. }
  283. }
  284. void Interpreter::PatternAssignment(Ptr<const Value> pat, Ptr<const Value> val,
  285. SourceLocation loc) {
  286. switch (pat->Tag()) {
  287. case Value::Kind::PointerValue:
  288. heap.Write(cast<PointerValue>(*pat).Val(), CopyVal(val, loc), loc);
  289. break;
  290. case Value::Kind::TupleValue: {
  291. switch (val->Tag()) {
  292. case Value::Kind::TupleValue: {
  293. const auto& pat_tup = cast<TupleValue>(*pat);
  294. const auto& val_tup = cast<TupleValue>(*val);
  295. if (pat_tup.Elements().size() != val_tup.Elements().size()) {
  296. FATAL_RUNTIME_ERROR(loc)
  297. << "arity mismatch in tuple pattern assignment:\n pattern: "
  298. << pat_tup << "\n value: " << val_tup;
  299. }
  300. for (const TupleElement& pattern_element : pat_tup.Elements()) {
  301. std::optional<Ptr<const Value>> value_field =
  302. val_tup.FindField(pattern_element.name);
  303. if (!value_field) {
  304. FATAL_RUNTIME_ERROR(loc)
  305. << "field " << pattern_element.name << "not in " << *val;
  306. }
  307. PatternAssignment(pattern_element.value, *value_field, loc);
  308. }
  309. break;
  310. }
  311. default:
  312. FATAL() << "expected a tuple value on right-hand-side, not " << *val;
  313. }
  314. break;
  315. }
  316. case Value::Kind::AlternativeValue: {
  317. switch (val->Tag()) {
  318. case Value::Kind::AlternativeValue: {
  319. const auto& pat_alt = cast<AlternativeValue>(*pat);
  320. const auto& val_alt = cast<AlternativeValue>(*val);
  321. CHECK(val_alt.ChoiceName() == pat_alt.ChoiceName() &&
  322. val_alt.AltName() == pat_alt.AltName())
  323. << "internal error in pattern assignment";
  324. PatternAssignment(pat_alt.Argument(), val_alt.Argument(), loc);
  325. break;
  326. }
  327. default:
  328. FATAL() << "expected an alternative in left-hand-side, not " << *val;
  329. }
  330. break;
  331. }
  332. default:
  333. CHECK(ValueEqual(pat, val, loc))
  334. << "internal error in pattern assignment";
  335. }
  336. }
  337. auto Interpreter::StepLvalue() -> Transition {
  338. Ptr<Action> act = stack.Top()->todo.Top();
  339. Ptr<const Expression> exp = cast<LValAction>(*act).Exp();
  340. if (tracing_output) {
  341. llvm::outs() << "--- step lvalue " << *exp << " (" << exp->SourceLoc()
  342. << ") --->\n";
  343. }
  344. switch (exp->Tag()) {
  345. case Expression::Kind::IdentifierExpression: {
  346. // { {x :: C, E, F} :: S, H}
  347. // -> { {E(x) :: C, E, F} :: S, H}
  348. Address pointer =
  349. GetFromEnv(exp->SourceLoc(), cast<IdentifierExpression>(*exp).Name());
  350. Ptr<const Value> v = global_arena->New<PointerValue>(pointer);
  351. return Done{v};
  352. }
  353. case Expression::Kind::FieldAccessExpression: {
  354. if (act->Pos() == 0) {
  355. // { {e.f :: C, E, F} :: S, H}
  356. // -> { e :: [].f :: C, E, F} :: S, H}
  357. return Spawn{global_arena->New<LValAction>(
  358. cast<FieldAccessExpression>(*exp).Aggregate())};
  359. } else {
  360. // { v :: [].f :: C, E, F} :: S, H}
  361. // -> { { &v.f :: C, E, F} :: S, H }
  362. Address aggregate = cast<PointerValue>(*act->Results()[0]).Val();
  363. Address field = aggregate.SubobjectAddress(
  364. cast<FieldAccessExpression>(*exp).Field());
  365. return Done{global_arena->New<PointerValue>(field)};
  366. }
  367. }
  368. case Expression::Kind::IndexExpression: {
  369. if (act->Pos() == 0) {
  370. // { {e[i] :: C, E, F} :: S, H}
  371. // -> { e :: [][i] :: C, E, F} :: S, H}
  372. return Spawn{global_arena->New<LValAction>(
  373. cast<IndexExpression>(*exp).Aggregate())};
  374. } else if (act->Pos() == 1) {
  375. return Spawn{global_arena->New<ExpressionAction>(
  376. cast<IndexExpression>(*exp).Offset())};
  377. } else {
  378. // { v :: [][i] :: C, E, F} :: S, H}
  379. // -> { { &v[i] :: C, E, F} :: S, H }
  380. Address aggregate = cast<PointerValue>(*act->Results()[0]).Val();
  381. std::string f =
  382. std::to_string(cast<IntValue>(*act->Results()[1]).Val());
  383. Address field = aggregate.SubobjectAddress(f);
  384. return Done{global_arena->New<PointerValue>(field)};
  385. }
  386. }
  387. case Expression::Kind::TupleLiteral: {
  388. if (act->Pos() == 0) {
  389. // { {(f1=e1,...) :: C, E, F} :: S, H}
  390. // -> { {e1 :: (f1=[],...) :: C, E, F} :: S, H}
  391. Ptr<const Expression> e1 =
  392. cast<TupleLiteral>(*exp).Fields()[0].expression;
  393. return Spawn{global_arena->New<LValAction>(e1)};
  394. } else if (act->Pos() !=
  395. static_cast<int>(cast<TupleLiteral>(*exp).Fields().size())) {
  396. // { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
  397. // H}
  398. // -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
  399. // H}
  400. Ptr<const Expression> elt =
  401. cast<TupleLiteral>(*exp).Fields()[act->Pos()].expression;
  402. return Spawn{global_arena->New<LValAction>(elt)};
  403. } else {
  404. return Done{CreateTuple(act, exp)};
  405. }
  406. }
  407. case Expression::Kind::IntLiteral:
  408. case Expression::Kind::BoolLiteral:
  409. case Expression::Kind::CallExpression:
  410. case Expression::Kind::PrimitiveOperatorExpression:
  411. case Expression::Kind::IntTypeLiteral:
  412. case Expression::Kind::BoolTypeLiteral:
  413. case Expression::Kind::TypeTypeLiteral:
  414. case Expression::Kind::FunctionTypeLiteral:
  415. case Expression::Kind::ContinuationTypeLiteral:
  416. case Expression::Kind::StringLiteral:
  417. case Expression::Kind::StringTypeLiteral:
  418. case Expression::Kind::IntrinsicExpression:
  419. FATAL_RUNTIME_ERROR_NO_LINE()
  420. << "Can't treat expression as lvalue: " << *exp;
  421. }
  422. }
  423. auto Interpreter::StepExp() -> Transition {
  424. Ptr<Action> act = stack.Top()->todo.Top();
  425. Ptr<const Expression> exp = cast<ExpressionAction>(*act).Exp();
  426. if (tracing_output) {
  427. llvm::outs() << "--- step exp " << *exp << " (" << exp->SourceLoc()
  428. << ") --->\n";
  429. }
  430. switch (exp->Tag()) {
  431. case Expression::Kind::IndexExpression: {
  432. if (act->Pos() == 0) {
  433. // { { e[i] :: C, E, F} :: S, H}
  434. // -> { { e :: [][i] :: C, E, F} :: S, H}
  435. return Spawn{global_arena->New<ExpressionAction>(
  436. cast<IndexExpression>(*exp).Aggregate())};
  437. } else if (act->Pos() == 1) {
  438. return Spawn{global_arena->New<ExpressionAction>(
  439. cast<IndexExpression>(*exp).Offset())};
  440. } else {
  441. // { { v :: [][i] :: C, E, F} :: S, H}
  442. // -> { { v_i :: C, E, F} : S, H}
  443. auto* tuple = dyn_cast<TupleValue>(act->Results()[0].Get());
  444. if (tuple == nullptr) {
  445. FATAL_RUNTIME_ERROR_NO_LINE()
  446. << "expected a tuple in field access, not " << *act->Results()[0];
  447. }
  448. std::string f =
  449. std::to_string(cast<IntValue>(*act->Results()[1]).Val());
  450. std::optional<Ptr<const Value>> field = tuple->FindField(f);
  451. if (!field) {
  452. FATAL_RUNTIME_ERROR_NO_LINE()
  453. << "field " << f << " not in " << *tuple;
  454. }
  455. return Done{*field};
  456. }
  457. }
  458. case Expression::Kind::TupleLiteral: {
  459. if (act->Pos() == 0) {
  460. if (cast<TupleLiteral>(*exp).Fields().size() > 0) {
  461. // { {(f1=e1,...) :: C, E, F} :: S, H}
  462. // -> { {e1 :: (f1=[],...) :: C, E, F} :: S, H}
  463. Ptr<const Expression> e1 =
  464. cast<TupleLiteral>(*exp).Fields()[0].expression;
  465. return Spawn{global_arena->New<ExpressionAction>(e1)};
  466. } else {
  467. return Done{CreateTuple(act, exp)};
  468. }
  469. } else if (act->Pos() !=
  470. static_cast<int>(cast<TupleLiteral>(*exp).Fields().size())) {
  471. // { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
  472. // H}
  473. // -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
  474. // H}
  475. Ptr<const Expression> elt =
  476. cast<TupleLiteral>(*exp).Fields()[act->Pos()].expression;
  477. return Spawn{global_arena->New<ExpressionAction>(elt)};
  478. } else {
  479. return Done{CreateTuple(act, exp)};
  480. }
  481. }
  482. case Expression::Kind::FieldAccessExpression: {
  483. const auto& access = cast<FieldAccessExpression>(*exp);
  484. if (act->Pos() == 0) {
  485. // { { e.f :: C, E, F} :: S, H}
  486. // -> { { e :: [].f :: C, E, F} :: S, H}
  487. return Spawn{global_arena->New<ExpressionAction>(access.Aggregate())};
  488. } else {
  489. // { { v :: [].f :: C, E, F} :: S, H}
  490. // -> { { v_f :: C, E, F} : S, H}
  491. return Done{act->Results()[0]->GetField(FieldPath(access.Field()),
  492. exp->SourceLoc())};
  493. }
  494. }
  495. case Expression::Kind::IdentifierExpression: {
  496. CHECK(act->Pos() == 0);
  497. const auto& ident = cast<IdentifierExpression>(*exp);
  498. // { {x :: C, E, F} :: S, H} -> { {H(E(x)) :: C, E, F} :: S, H}
  499. Address pointer = GetFromEnv(exp->SourceLoc(), ident.Name());
  500. return Done{heap.Read(pointer, exp->SourceLoc())};
  501. }
  502. case Expression::Kind::IntLiteral:
  503. CHECK(act->Pos() == 0);
  504. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  505. return Done{global_arena->New<IntValue>(cast<IntLiteral>(*exp).Val())};
  506. case Expression::Kind::BoolLiteral:
  507. CHECK(act->Pos() == 0);
  508. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  509. return Done{global_arena->New<BoolValue>(cast<BoolLiteral>(*exp).Val())};
  510. case Expression::Kind::PrimitiveOperatorExpression: {
  511. const auto& op = cast<PrimitiveOperatorExpression>(*exp);
  512. if (act->Pos() != static_cast<int>(op.Arguments().size())) {
  513. // { {v :: op(vs,[],e,es) :: C, E, F} :: S, H}
  514. // -> { {e :: op(vs,v,[],es) :: C, E, F} :: S, H}
  515. Ptr<const Expression> arg = op.Arguments()[act->Pos()];
  516. return Spawn{global_arena->New<ExpressionAction>(arg)};
  517. } else {
  518. // { {v :: op(vs,[]) :: C, E, F} :: S, H}
  519. // -> { {eval_prim(op, (vs,v)) :: C, E, F} :: S, H}
  520. return Done{EvalPrim(op.Op(), act->Results(), exp->SourceLoc())};
  521. }
  522. }
  523. case Expression::Kind::CallExpression:
  524. if (act->Pos() == 0) {
  525. // { {e1(e2) :: C, E, F} :: S, H}
  526. // -> { {e1 :: [](e2) :: C, E, F} :: S, H}
  527. return Spawn{global_arena->New<ExpressionAction>(
  528. cast<CallExpression>(*exp).Function())};
  529. } else if (act->Pos() == 1) {
  530. // { { v :: [](e) :: C, E, F} :: S, H}
  531. // -> { { e :: v([]) :: C, E, F} :: S, H}
  532. return Spawn{global_arena->New<ExpressionAction>(
  533. cast<CallExpression>(*exp).Argument())};
  534. } else if (act->Pos() == 2) {
  535. // { { v2 :: v1([]) :: C, E, F} :: S, H}
  536. // -> { {C',E',F'} :: {C, E, F} :: S, H}
  537. switch (act->Results()[0]->Tag()) {
  538. case Value::Kind::ClassType: {
  539. Ptr<const Value> arg = CopyVal(act->Results()[1], exp->SourceLoc());
  540. return Done{global_arena->New<StructValue>(act->Results()[0], arg)};
  541. }
  542. case Value::Kind::AlternativeConstructorValue: {
  543. const auto& alt =
  544. cast<AlternativeConstructorValue>(*act->Results()[0]);
  545. Ptr<const Value> arg = CopyVal(act->Results()[1], exp->SourceLoc());
  546. return Done{global_arena->New<AlternativeValue>(
  547. alt.AltName(), alt.ChoiceName(), arg)};
  548. }
  549. case Value::Kind::FunctionValue:
  550. return CallFunction{
  551. // TODO: Think about a cleaner way to cast between Ptr types.
  552. // (multiple TODOs)
  553. .function = Ptr<const FunctionValue>(
  554. cast<FunctionValue>(act->Results()[0].Get())),
  555. .args = act->Results()[1],
  556. .loc = exp->SourceLoc()};
  557. default:
  558. FATAL_RUNTIME_ERROR(exp->SourceLoc())
  559. << "in call, expected a function, not " << *act->Results()[0];
  560. }
  561. } else {
  562. FATAL() << "in handle_value with Call pos " << act->Pos();
  563. }
  564. case Expression::Kind::IntrinsicExpression:
  565. CHECK(act->Pos() == 0);
  566. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  567. switch (cast<IntrinsicExpression>(*exp).Intrinsic()) {
  568. case IntrinsicExpression::IntrinsicKind::Print:
  569. Address pointer = GetFromEnv(exp->SourceLoc(), "format_str");
  570. Ptr<const Value> pointee = heap.Read(pointer, exp->SourceLoc());
  571. CHECK(pointee->Tag() == Value::Kind::StringValue);
  572. // TODO: This could eventually use something like llvm::formatv.
  573. llvm::outs() << cast<StringValue>(*pointee).Val();
  574. return Done{TupleValue::Empty()};
  575. }
  576. case Expression::Kind::IntTypeLiteral: {
  577. CHECK(act->Pos() == 0);
  578. return Done{global_arena->New<IntType>()};
  579. }
  580. case Expression::Kind::BoolTypeLiteral: {
  581. CHECK(act->Pos() == 0);
  582. return Done{global_arena->New<BoolType>()};
  583. }
  584. case Expression::Kind::TypeTypeLiteral: {
  585. CHECK(act->Pos() == 0);
  586. return Done{global_arena->New<TypeType>()};
  587. }
  588. case Expression::Kind::FunctionTypeLiteral: {
  589. if (act->Pos() == 0) {
  590. return Spawn{global_arena->New<ExpressionAction>(
  591. cast<FunctionTypeLiteral>(*exp).Parameter())};
  592. } else if (act->Pos() == 1) {
  593. // { { pt :: fn [] -> e :: C, E, F} :: S, H}
  594. // -> { { e :: fn pt -> []) :: C, E, F} :: S, H}
  595. return Spawn{global_arena->New<ExpressionAction>(
  596. cast<FunctionTypeLiteral>(*exp).ReturnType())};
  597. } else {
  598. // { { rt :: fn pt -> [] :: C, E, F} :: S, H}
  599. // -> { fn pt -> rt :: {C, E, F} :: S, H}
  600. return Done{global_arena->New<FunctionType>(
  601. std::vector<GenericBinding>(), act->Results()[0],
  602. act->Results()[1])};
  603. }
  604. }
  605. case Expression::Kind::ContinuationTypeLiteral: {
  606. CHECK(act->Pos() == 0);
  607. return Done{global_arena->New<ContinuationType>()};
  608. }
  609. case Expression::Kind::StringLiteral:
  610. CHECK(act->Pos() == 0);
  611. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  612. return Done{
  613. global_arena->New<StringValue>(cast<StringLiteral>(*exp).Val())};
  614. case Expression::Kind::StringTypeLiteral: {
  615. CHECK(act->Pos() == 0);
  616. return Done{global_arena->New<StringType>()};
  617. }
  618. } // switch (exp->Tag)
  619. }
  620. auto Interpreter::StepPattern() -> Transition {
  621. Ptr<Action> act = stack.Top()->todo.Top();
  622. Ptr<const Pattern> pattern = cast<PatternAction>(*act).Pat();
  623. if (tracing_output) {
  624. llvm::outs() << "--- step pattern " << *pattern << " ("
  625. << pattern->SourceLoc() << ") --->\n";
  626. }
  627. switch (pattern->Tag()) {
  628. case Pattern::Kind::AutoPattern: {
  629. CHECK(act->Pos() == 0);
  630. return Done{global_arena->New<AutoType>()};
  631. }
  632. case Pattern::Kind::BindingPattern: {
  633. const auto& binding = cast<BindingPattern>(*pattern);
  634. if (act->Pos() == 0) {
  635. return Spawn{global_arena->New<PatternAction>(binding.Type())};
  636. } else {
  637. return Done{global_arena->New<BindingPlaceholderValue>(
  638. binding.Name(), act->Results()[0])};
  639. }
  640. }
  641. case Pattern::Kind::TuplePattern: {
  642. const auto& tuple = cast<TuplePattern>(*pattern);
  643. if (act->Pos() == 0) {
  644. if (tuple.Fields().empty()) {
  645. return Done{TupleValue::Empty()};
  646. } else {
  647. Ptr<const Pattern> p1 = tuple.Fields()[0].pattern;
  648. return Spawn{(global_arena->New<PatternAction>(p1))};
  649. }
  650. } else if (act->Pos() != static_cast<int>(tuple.Fields().size())) {
  651. // { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
  652. // H}
  653. // -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
  654. // H}
  655. Ptr<const Pattern> elt = tuple.Fields()[act->Pos()].pattern;
  656. return Spawn{global_arena->New<PatternAction>(elt)};
  657. } else {
  658. std::vector<TupleElement> elements;
  659. for (size_t i = 0; i < tuple.Fields().size(); ++i) {
  660. elements.push_back(
  661. {.name = tuple.Fields()[i].name, .value = act->Results()[i]});
  662. }
  663. return Done{global_arena->New<TupleValue>(std::move(elements))};
  664. }
  665. }
  666. case Pattern::Kind::AlternativePattern: {
  667. const auto& alternative = cast<AlternativePattern>(*pattern);
  668. if (act->Pos() == 0) {
  669. return Spawn{
  670. global_arena->New<ExpressionAction>(alternative.ChoiceType())};
  671. } else if (act->Pos() == 1) {
  672. return Spawn{global_arena->New<PatternAction>(alternative.Arguments())};
  673. } else {
  674. CHECK(act->Pos() == 2);
  675. const auto& choice_type = cast<ChoiceType>(*act->Results()[0]);
  676. return Done{global_arena->New<AlternativeValue>(
  677. alternative.AlternativeName(), choice_type.Name(),
  678. act->Results()[1])};
  679. }
  680. }
  681. case Pattern::Kind::ExpressionPattern:
  682. return Delegate{global_arena->New<ExpressionAction>(
  683. cast<ExpressionPattern>(*pattern).Expression())};
  684. }
  685. }
  686. static auto IsWhileAct(Ptr<Action> act) -> bool {
  687. switch (act->Tag()) {
  688. case Action::Kind::StatementAction:
  689. switch (cast<StatementAction>(*act).Stmt()->Tag()) {
  690. case Statement::Kind::While:
  691. return true;
  692. default:
  693. return false;
  694. }
  695. default:
  696. return false;
  697. }
  698. }
  699. static auto HasLocalScope(Ptr<Action> act) -> bool {
  700. switch (act->Tag()) {
  701. case Action::Kind::StatementAction:
  702. switch (cast<StatementAction>(*act).Stmt()->Tag()) {
  703. case Statement::Kind::Block:
  704. case Statement::Kind::Match:
  705. return true;
  706. default:
  707. return false;
  708. }
  709. default:
  710. return false;
  711. }
  712. }
  713. auto Interpreter::StepStmt() -> Transition {
  714. Ptr<Frame> frame = stack.Top();
  715. Ptr<Action> act = frame->todo.Top();
  716. Ptr<const Statement> stmt = cast<StatementAction>(*act).Stmt();
  717. if (tracing_output) {
  718. llvm::outs() << "--- step stmt ";
  719. stmt->PrintDepth(1, llvm::outs());
  720. llvm::outs() << " (" << stmt->SourceLoc() << ") --->\n";
  721. }
  722. switch (stmt->Tag()) {
  723. case Statement::Kind::Match: {
  724. const auto& match_stmt = cast<Match>(*stmt);
  725. if (act->Pos() == 0) {
  726. // { { (match (e) ...) :: C, E, F} :: S, H}
  727. // -> { { e :: (match ([]) ...) :: C, E, F} :: S, H}
  728. frame->scopes.Push(global_arena->New<Scope>(CurrentEnv()));
  729. return Spawn{global_arena->New<ExpressionAction>(match_stmt.Exp())};
  730. } else {
  731. // Regarding act->Pos():
  732. // * odd: start interpreting the pattern of a clause
  733. // * even: finished interpreting the pattern, now try to match
  734. //
  735. // Regarding act->Results():
  736. // * 0: the value that we're matching
  737. // * 1: the pattern for clause 0
  738. // * 2: the pattern for clause 1
  739. // * ...
  740. auto clause_num = (act->Pos() - 1) / 2;
  741. if (clause_num >= static_cast<int>(match_stmt.Clauses().size())) {
  742. DeallocateScope(frame->scopes.Top());
  743. frame->scopes.Pop();
  744. return Done{};
  745. }
  746. auto c = match_stmt.Clauses()[clause_num];
  747. if (act->Pos() % 2 == 1) {
  748. // start interpreting the pattern of the clause
  749. // { {v :: (match ([]) ...) :: C, E, F} :: S, H}
  750. // -> { {pi :: (match ([]) ...) :: C, E, F} :: S, H}
  751. return Spawn{global_arena->New<PatternAction>(c.first)};
  752. } else { // try to match
  753. auto v = act->Results()[0];
  754. auto pat = act->Results()[clause_num + 1];
  755. std::optional<Env> matches = PatternMatch(pat, v, stmt->SourceLoc());
  756. if (matches) { // we have a match, start the body
  757. // Ensure we don't process any more clauses.
  758. act->SetPos(2 * match_stmt.Clauses().size() + 1);
  759. for (const auto& [name, value] : *matches) {
  760. frame->scopes.Top()->values.Set(name, value);
  761. frame->scopes.Top()->locals.push_back(name);
  762. }
  763. return Spawn{global_arena->New<StatementAction>(c.second)};
  764. } else {
  765. return RunAgain{};
  766. }
  767. }
  768. }
  769. }
  770. case Statement::Kind::While:
  771. if (act->Pos() % 2 == 0) {
  772. // { { (while (e) s) :: C, E, F} :: S, H}
  773. // -> { { e :: (while ([]) s) :: C, E, F} :: S, H}
  774. act->Clear();
  775. return Spawn{
  776. global_arena->New<ExpressionAction>(cast<While>(*stmt).Cond())};
  777. } else if (cast<BoolValue>(*act->Results().back()).Val()) {
  778. // { {true :: (while ([]) s) :: C, E, F} :: S, H}
  779. // -> { { s :: (while (e) s) :: C, E, F } :: S, H}
  780. return Spawn{
  781. global_arena->New<StatementAction>(cast<While>(*stmt).Body())};
  782. } else {
  783. // { {false :: (while ([]) s) :: C, E, F} :: S, H}
  784. // -> { { C, E, F } :: S, H}
  785. return Done{};
  786. }
  787. case Statement::Kind::Break: {
  788. CHECK(act->Pos() == 0);
  789. // { { break; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  790. // -> { { C, E', F} :: S, H}
  791. auto it =
  792. std::find_if(frame->todo.begin(), frame->todo.end(), &IsWhileAct);
  793. if (it == frame->todo.end()) {
  794. FATAL_RUNTIME_ERROR(stmt->SourceLoc())
  795. << "`break` not inside `while` statement";
  796. }
  797. ++it;
  798. return UnwindTo{*it};
  799. }
  800. case Statement::Kind::Continue: {
  801. CHECK(act->Pos() == 0);
  802. // { { continue; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  803. // -> { { (while (e) s) :: C, E', F} :: S, H}
  804. auto it =
  805. std::find_if(frame->todo.begin(), frame->todo.end(), &IsWhileAct);
  806. if (it == frame->todo.end()) {
  807. FATAL_RUNTIME_ERROR(stmt->SourceLoc())
  808. << "`continue` not inside `while` statement";
  809. }
  810. return UnwindTo{*it};
  811. }
  812. case Statement::Kind::Block: {
  813. if (act->Pos() == 0) {
  814. const Block& block = cast<Block>(*stmt);
  815. if (block.Stmt()) {
  816. frame->scopes.Push(global_arena->New<Scope>(CurrentEnv()));
  817. return Spawn{global_arena->New<StatementAction>(*block.Stmt())};
  818. } else {
  819. return Done{};
  820. }
  821. } else {
  822. Ptr<Scope> scope = frame->scopes.Top();
  823. DeallocateScope(scope);
  824. frame->scopes.Pop(1);
  825. return Done{};
  826. }
  827. }
  828. case Statement::Kind::VariableDefinition:
  829. if (act->Pos() == 0) {
  830. // { {(var x = e) :: C, E, F} :: S, H}
  831. // -> { {e :: (var x = []) :: C, E, F} :: S, H}
  832. return Spawn{global_arena->New<ExpressionAction>(
  833. cast<VariableDefinition>(*stmt).Init())};
  834. } else if (act->Pos() == 1) {
  835. return Spawn{global_arena->New<PatternAction>(
  836. cast<VariableDefinition>(*stmt).Pat())};
  837. } else {
  838. // { { v :: (x = []) :: C, E, F} :: S, H}
  839. // -> { { C, E(x := a), F} :: S, H(a := copy(v))}
  840. Ptr<const Value> v = act->Results()[0];
  841. Ptr<const Value> p = act->Results()[1];
  842. std::optional<Env> matches = PatternMatch(p, v, stmt->SourceLoc());
  843. CHECK(matches)
  844. << stmt->SourceLoc()
  845. << ": internal error in variable definition, match failed";
  846. for (const auto& [name, value] : *matches) {
  847. frame->scopes.Top()->values.Set(name, value);
  848. frame->scopes.Top()->locals.push_back(name);
  849. }
  850. return Done{};
  851. }
  852. case Statement::Kind::ExpressionStatement:
  853. if (act->Pos() == 0) {
  854. // { {e :: C, E, F} :: S, H}
  855. // -> { {e :: C, E, F} :: S, H}
  856. return Spawn{global_arena->New<ExpressionAction>(
  857. cast<ExpressionStatement>(*stmt).Exp())};
  858. } else {
  859. return Done{};
  860. }
  861. case Statement::Kind::Assign:
  862. if (act->Pos() == 0) {
  863. // { {(lv = e) :: C, E, F} :: S, H}
  864. // -> { {lv :: ([] = e) :: C, E, F} :: S, H}
  865. return Spawn{global_arena->New<LValAction>(cast<Assign>(*stmt).Lhs())};
  866. } else if (act->Pos() == 1) {
  867. // { { a :: ([] = e) :: C, E, F} :: S, H}
  868. // -> { { e :: (a = []) :: C, E, F} :: S, H}
  869. return Spawn{
  870. global_arena->New<ExpressionAction>(cast<Assign>(*stmt).Rhs())};
  871. } else {
  872. // { { v :: (a = []) :: C, E, F} :: S, H}
  873. // -> { { C, E, F} :: S, H(a := v)}
  874. auto pat = act->Results()[0];
  875. auto val = act->Results()[1];
  876. PatternAssignment(pat, val, stmt->SourceLoc());
  877. return Done{};
  878. }
  879. case Statement::Kind::If:
  880. if (act->Pos() == 0) {
  881. // { {(if (e) then_stmt else else_stmt) :: C, E, F} :: S, H}
  882. // -> { { e :: (if ([]) then_stmt else else_stmt) :: C, E, F} :: S, H}
  883. return Spawn{
  884. global_arena->New<ExpressionAction>(cast<If>(*stmt).Cond())};
  885. } else if (cast<BoolValue>(*act->Results()[0]).Val()) {
  886. // { {true :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  887. // S, H}
  888. // -> { { then_stmt :: C, E, F } :: S, H}
  889. return Delegate{
  890. global_arena->New<StatementAction>(cast<If>(*stmt).ThenStmt())};
  891. } else if (cast<If>(*stmt).ElseStmt()) {
  892. // { {false :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  893. // S, H}
  894. // -> { { else_stmt :: C, E, F } :: S, H}
  895. return Delegate{
  896. global_arena->New<StatementAction>(*cast<If>(*stmt).ElseStmt())};
  897. } else {
  898. return Done{};
  899. }
  900. case Statement::Kind::Return:
  901. if (act->Pos() == 0) {
  902. // { {return e :: C, E, F} :: S, H}
  903. // -> { {e :: return [] :: C, E, F} :: S, H}
  904. return Spawn{
  905. global_arena->New<ExpressionAction>(cast<Return>(*stmt).Exp())};
  906. } else {
  907. // { {v :: return [] :: C, E, F} :: {C', E', F'} :: S, H}
  908. // -> { {v :: C', E', F'} :: S, H}
  909. Ptr<const Value> ret_val =
  910. CopyVal(act->Results()[0], stmt->SourceLoc());
  911. return UnwindFunctionCall{ret_val};
  912. }
  913. case Statement::Kind::Sequence: {
  914. // { { (s1,s2) :: C, E, F} :: S, H}
  915. // -> { { s1 :: s2 :: C, E, F} :: S, H}
  916. const Sequence& seq = cast<Sequence>(*stmt);
  917. if (act->Pos() == 0) {
  918. return Spawn{global_arena->New<StatementAction>(seq.Stmt())};
  919. } else {
  920. if (seq.Next()) {
  921. return Delegate{global_arena->New<StatementAction>(
  922. *cast<Sequence>(*stmt).Next())};
  923. } else {
  924. return Done{};
  925. }
  926. }
  927. }
  928. case Statement::Kind::Continuation: {
  929. CHECK(act->Pos() == 0);
  930. // Create a continuation object by creating a frame similar the
  931. // way one is created in a function call.
  932. auto scopes = Stack<Ptr<Scope>>(global_arena->New<Scope>(CurrentEnv()));
  933. Stack<Ptr<Action>> todo;
  934. todo.Push(global_arena->New<StatementAction>(
  935. global_arena->New<Return>(stmt->SourceLoc())));
  936. todo.Push(
  937. global_arena->New<StatementAction>(cast<Continuation>(*stmt).Body()));
  938. auto continuation_frame =
  939. global_arena->New<Frame>("__continuation", scopes, todo);
  940. Address continuation_address =
  941. heap.AllocateValue(global_arena->New<ContinuationValue>(
  942. std::vector<Ptr<Frame>>({continuation_frame})));
  943. // Store the continuation's address in the frame.
  944. continuation_frame->continuation = continuation_address;
  945. // Bind the continuation object to the continuation variable
  946. frame->scopes.Top()->values.Set(
  947. cast<Continuation>(*stmt).ContinuationVariable(),
  948. continuation_address);
  949. // Pop the continuation statement.
  950. frame->todo.Pop();
  951. return ManualTransition{};
  952. }
  953. case Statement::Kind::Run:
  954. if (act->Pos() == 0) {
  955. // Evaluate the argument of the run statement.
  956. return Spawn{
  957. global_arena->New<ExpressionAction>(cast<Run>(*stmt).Argument())};
  958. } else {
  959. frame->todo.Pop(1);
  960. // Push an expression statement action to ignore the result
  961. // value from the continuation.
  962. auto ignore_result = global_arena->New<StatementAction>(
  963. global_arena->New<ExpressionStatement>(
  964. stmt->SourceLoc(),
  965. global_arena->New<TupleLiteral>(stmt->SourceLoc())));
  966. frame->todo.Push(ignore_result);
  967. // Push the continuation onto the current stack.
  968. const std::vector<Ptr<Frame>>& continuation_vector =
  969. cast<ContinuationValue>(*act->Results()[0]).Stack();
  970. for (auto frame_iter = continuation_vector.rbegin();
  971. frame_iter != continuation_vector.rend(); ++frame_iter) {
  972. stack.Push(*frame_iter);
  973. }
  974. return ManualTransition{};
  975. }
  976. case Statement::Kind::Await:
  977. CHECK(act->Pos() == 0);
  978. // Pause the current continuation
  979. frame->todo.Pop();
  980. std::vector<Ptr<Frame>> paused;
  981. do {
  982. paused.push_back(stack.Pop());
  983. } while (paused.back()->continuation == std::nullopt);
  984. // Update the continuation with the paused stack.
  985. heap.Write(*paused.back()->continuation,
  986. global_arena->New<ContinuationValue>(paused),
  987. stmt->SourceLoc());
  988. return ManualTransition{};
  989. }
  990. }
  991. class Interpreter::DoTransition {
  992. public:
  993. // Does not take ownership of interpreter.
  994. DoTransition(Interpreter* interpreter) : interpreter(interpreter) {}
  995. void operator()(const Done& done) {
  996. Ptr<Frame> frame = interpreter->stack.Top();
  997. if (frame->todo.Top()->Tag() != Action::Kind::StatementAction) {
  998. CHECK(done.result);
  999. frame->todo.Pop();
  1000. if (frame->todo.IsEmpty()) {
  1001. interpreter->program_value = *done.result;
  1002. } else {
  1003. frame->todo.Top()->AddResult(*done.result);
  1004. }
  1005. } else {
  1006. CHECK(!done.result);
  1007. frame->todo.Pop();
  1008. }
  1009. }
  1010. void operator()(const Spawn& spawn) {
  1011. Ptr<Frame> frame = interpreter->stack.Top();
  1012. Ptr<Action> action = frame->todo.Top();
  1013. action->SetPos(action->Pos() + 1);
  1014. frame->todo.Push(spawn.child);
  1015. }
  1016. void operator()(const Delegate& delegate) {
  1017. Ptr<Frame> frame = interpreter->stack.Top();
  1018. frame->todo.Pop();
  1019. frame->todo.Push(delegate.delegate);
  1020. }
  1021. void operator()(const RunAgain&) {
  1022. Ptr<Action> action = interpreter->stack.Top()->todo.Top();
  1023. action->SetPos(action->Pos() + 1);
  1024. }
  1025. void operator()(const UnwindTo& unwind_to) {
  1026. Ptr<Frame> frame = interpreter->stack.Top();
  1027. while (frame->todo.Top() != unwind_to.new_top) {
  1028. if (HasLocalScope(frame->todo.Top())) {
  1029. interpreter->DeallocateScope(frame->scopes.Top());
  1030. frame->scopes.Pop();
  1031. }
  1032. frame->todo.Pop();
  1033. }
  1034. }
  1035. void operator()(const UnwindFunctionCall& unwind) {
  1036. interpreter->DeallocateLocals(interpreter->stack.Top());
  1037. interpreter->stack.Pop();
  1038. if (interpreter->stack.Top()->todo.IsEmpty()) {
  1039. interpreter->program_value = unwind.return_val;
  1040. } else {
  1041. interpreter->stack.Top()->todo.Top()->AddResult(unwind.return_val);
  1042. }
  1043. }
  1044. void operator()(const CallFunction& call) {
  1045. interpreter->stack.Top()->todo.Pop();
  1046. std::optional<Env> matches =
  1047. interpreter->PatternMatch(call.function->Param(), call.args, call.loc);
  1048. CHECK(matches.has_value())
  1049. << "internal error in call_function, pattern match failed";
  1050. // Create the new frame and push it on the stack
  1051. Env values = interpreter->globals;
  1052. std::vector<std::string> params;
  1053. for (const auto& [name, value] : *matches) {
  1054. values.Set(name, value);
  1055. params.push_back(name);
  1056. }
  1057. auto scopes = Stack<Ptr<Scope>>(global_arena->New<Scope>(values, params));
  1058. CHECK(call.function->Body()) << "Calling a function that's missing a body";
  1059. auto todo = Stack<Ptr<Action>>(
  1060. global_arena->New<StatementAction>(*call.function->Body()));
  1061. auto frame = global_arena->New<Frame>(call.function->Name(), scopes, todo);
  1062. interpreter->stack.Push(frame);
  1063. }
  1064. void operator()(const ManualTransition&) {}
  1065. private:
  1066. Ptr<Interpreter> interpreter;
  1067. };
  1068. // State transition.
  1069. void Interpreter::Step() {
  1070. Ptr<Frame> frame = stack.Top();
  1071. if (frame->todo.IsEmpty()) {
  1072. FATAL_RUNTIME_ERROR_NO_LINE()
  1073. << "fell off end of function " << frame->name << " without `return`";
  1074. }
  1075. Ptr<Action> act = frame->todo.Top();
  1076. switch (act->Tag()) {
  1077. case Action::Kind::LValAction:
  1078. std::visit(DoTransition(this), StepLvalue());
  1079. break;
  1080. case Action::Kind::ExpressionAction:
  1081. std::visit(DoTransition(this), StepExp());
  1082. break;
  1083. case Action::Kind::PatternAction:
  1084. std::visit(DoTransition(this), StepPattern());
  1085. break;
  1086. case Action::Kind::StatementAction:
  1087. std::visit(DoTransition(this), StepStmt());
  1088. break;
  1089. } // switch
  1090. }
  1091. auto Interpreter::InterpProgram(const std::vector<Ptr<const Declaration>>& fs)
  1092. -> int {
  1093. // Check that the interpreter is in a clean state.
  1094. CHECK(globals.IsEmpty());
  1095. CHECK(stack.IsEmpty());
  1096. CHECK(program_value == std::nullopt);
  1097. if (tracing_output) {
  1098. llvm::outs() << "********** initializing globals **********\n";
  1099. }
  1100. InitGlobals(fs);
  1101. SourceLocation loc("<InterpProgram()>", 0);
  1102. Ptr<const Expression> arg = global_arena->New<TupleLiteral>(loc);
  1103. Ptr<const Expression> call_main = global_arena->New<CallExpression>(
  1104. loc, global_arena->New<IdentifierExpression>(loc, "main"), arg);
  1105. auto todo =
  1106. Stack<Ptr<Action>>(global_arena->New<ExpressionAction>(call_main));
  1107. auto scopes = Stack<Ptr<Scope>>(global_arena->New<Scope>(globals));
  1108. stack = Stack<Ptr<Frame>>(global_arena->New<Frame>("top", scopes, todo));
  1109. if (tracing_output) {
  1110. llvm::outs() << "********** calling main function **********\n";
  1111. PrintState(llvm::outs());
  1112. }
  1113. while (stack.Count() > 1 || !stack.Top()->todo.IsEmpty()) {
  1114. Step();
  1115. if (tracing_output) {
  1116. PrintState(llvm::outs());
  1117. }
  1118. }
  1119. return cast<IntValue>(**program_value).Val();
  1120. }
  1121. auto Interpreter::InterpExp(Env values, Ptr<const Expression> e)
  1122. -> Ptr<const Value> {
  1123. CHECK(program_value == std::nullopt);
  1124. auto program_value_guard =
  1125. llvm::make_scope_exit([&] { program_value = std::nullopt; });
  1126. auto todo = Stack<Ptr<Action>>(global_arena->New<ExpressionAction>(e));
  1127. auto scopes = Stack<Ptr<Scope>>(global_arena->New<Scope>(values));
  1128. stack =
  1129. Stack<Ptr<Frame>>(global_arena->New<Frame>("InterpExp", scopes, todo));
  1130. while (stack.Count() > 1 || !stack.Top()->todo.IsEmpty()) {
  1131. Step();
  1132. }
  1133. CHECK(program_value != std::nullopt);
  1134. return *program_value;
  1135. }
  1136. auto Interpreter::InterpPattern(Env values, Ptr<const Pattern> p)
  1137. -> Ptr<const Value> {
  1138. CHECK(program_value == std::nullopt);
  1139. auto program_value_guard =
  1140. llvm::make_scope_exit([&] { program_value = std::nullopt; });
  1141. auto todo = Stack<Ptr<Action>>(global_arena->New<PatternAction>(p));
  1142. auto scopes = Stack<Ptr<Scope>>(global_arena->New<Scope>(values));
  1143. stack = Stack<Ptr<Frame>>(
  1144. global_arena->New<Frame>("InterpPattern", scopes, todo));
  1145. while (stack.Count() > 1 || !stack.Top()->todo.IsEmpty()) {
  1146. Step();
  1147. }
  1148. CHECK(program_value != std::nullopt);
  1149. return *program_value;
  1150. }
  1151. } // namespace Carbon