interpreter.cpp 46 KB

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