interpreter.cpp 44 KB

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