interpreter.cpp 45 KB

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