interpreter.cpp 44 KB

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