interpreter.cpp 45 KB

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