interpreter.cpp 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689
  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 "explorer/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 "explorer/ast/declaration.h"
  13. #include "explorer/ast/expression.h"
  14. #include "explorer/common/arena.h"
  15. #include "explorer/common/error_builders.h"
  16. #include "explorer/interpreter/action.h"
  17. #include "explorer/interpreter/action_stack.h"
  18. #include "explorer/interpreter/stack.h"
  19. #include "llvm/ADT/StringExtras.h"
  20. #include "llvm/Support/Casting.h"
  21. #include "llvm/Support/Error.h"
  22. using llvm::cast;
  23. using llvm::dyn_cast;
  24. using llvm::isa;
  25. namespace Carbon {
  26. // Constructs an ActionStack suitable for the specified phase.
  27. static auto MakeTodo(Phase phase, Nonnull<Heap*> heap) -> ActionStack {
  28. switch (phase) {
  29. case Phase::CompileTime:
  30. return ActionStack();
  31. case Phase::RunTime:
  32. return ActionStack(heap);
  33. }
  34. }
  35. // An Interpreter represents an instance of the Carbon abstract machine. It
  36. // manages the state of the abstract machine, and executes the steps of Actions
  37. // passed to it.
  38. class Interpreter {
  39. public:
  40. // Constructs an Interpreter which allocates values on `arena`, and prints
  41. // traces if `trace` is true. `phase` indicates whether it executes at
  42. // compile time or run time.
  43. Interpreter(Phase phase, Nonnull<Arena*> arena,
  44. std::optional<Nonnull<llvm::raw_ostream*>> trace_stream)
  45. : arena_(arena),
  46. heap_(arena),
  47. todo_(MakeTodo(phase, &heap_)),
  48. trace_stream_(trace_stream),
  49. phase_(phase) {}
  50. ~Interpreter();
  51. // Runs all the steps of `action`.
  52. // It's not safe to call `RunAllSteps()` or `result()` after an error.
  53. auto RunAllSteps(std::unique_ptr<Action> action) -> ErrorOr<Success>;
  54. // The result produced by the `action` argument of the most recent
  55. // RunAllSteps call. Cannot be called if `action` was an action that doesn't
  56. // produce results.
  57. auto result() const -> Nonnull<const Value*> { return todo_.result(); }
  58. private:
  59. auto Step() -> ErrorOr<Success>;
  60. // State transitions for expressions.
  61. auto StepExp() -> ErrorOr<Success>;
  62. // State transitions for lvalues.
  63. auto StepLvalue() -> ErrorOr<Success>;
  64. // State transitions for patterns.
  65. auto StepPattern() -> ErrorOr<Success>;
  66. // State transition for statements.
  67. auto StepStmt() -> ErrorOr<Success>;
  68. // State transition for declarations.
  69. auto StepDeclaration() -> ErrorOr<Success>;
  70. auto CreateStruct(const std::vector<FieldInitializer>& fields,
  71. const std::vector<Nonnull<const Value*>>& values)
  72. -> Nonnull<const Value*>;
  73. auto EvalPrim(Operator op, Nonnull<const Value*> static_type,
  74. const std::vector<Nonnull<const Value*>>& args,
  75. SourceLocation source_loc) -> ErrorOr<Nonnull<const Value*>>;
  76. // Returns the result of converting `value` to type `destination_type`.
  77. auto Convert(Nonnull<const Value*> value,
  78. Nonnull<const Value*> destination_type,
  79. SourceLocation source_loc) -> ErrorOr<Nonnull<const Value*>>;
  80. // Evaluate an expression immediately, recursively.
  81. //
  82. // TODO: Stop using this.
  83. auto EvalExpRecursively(Nonnull<const Expression*> exp)
  84. -> ErrorOr<Nonnull<const Value*>>;
  85. // Evaluate an associated constant by evaluating its witness and looking
  86. // inside the impl for the corresponding value.
  87. //
  88. // TODO: This approach doesn't provide values that are known because they
  89. // appear in constraints:
  90. //
  91. // interface Iface { let N:! i32; }
  92. // fn PickType(N: i32) -> Type { return i32; }
  93. // fn F[T:! Iface where .N == 5](x: T) {
  94. // var x: PickType(T.N) = 0;
  95. // }
  96. //
  97. // ... will fail because we can't resolve T.N to 5 at compile time.
  98. auto EvalAssociatedConstant(Nonnull<const AssociatedConstant*> assoc,
  99. SourceLocation source_loc)
  100. -> ErrorOr<Nonnull<const Value*>>;
  101. // Instantiate a type by replacing all type variables that occur inside the
  102. // type by the current values of those variables.
  103. //
  104. // For example, suppose T=i32 and U=Bool. Then
  105. // __Fn (Point(T)) -> Point(U)
  106. // becomes
  107. // __Fn (Point(i32)) -> Point(Bool)
  108. auto InstantiateType(Nonnull<const Value*> type, SourceLocation source_loc)
  109. -> ErrorOr<Nonnull<const Value*>>;
  110. // Instantiate a set of bindings by replacing all type variables that occur
  111. // within it by the current values of those variables.
  112. auto InstantiateBindings(Nonnull<const Bindings*> bindings,
  113. SourceLocation source_loc)
  114. -> ErrorOr<Nonnull<const Bindings*>>;
  115. // Call the function `fun` with the given `arg` and the `witnesses`
  116. // for the function's impl bindings.
  117. auto CallFunction(const CallExpression& call, Nonnull<const Value*> fun,
  118. Nonnull<const Value*> arg, ImplWitnessMap&& witnesses)
  119. -> ErrorOr<Success>;
  120. void PrintState(llvm::raw_ostream& out);
  121. Phase phase() const { return phase_; }
  122. Nonnull<Arena*> arena_;
  123. Heap heap_;
  124. ActionStack todo_;
  125. // The underlying states of continuation values. All StackFragments created
  126. // during execution are tracked here, in order to safely deallocate the
  127. // contents of any non-completed continuations at the end of execution.
  128. std::vector<Nonnull<ContinuationValue::StackFragment*>> stack_fragments_;
  129. std::optional<Nonnull<llvm::raw_ostream*>> trace_stream_;
  130. Phase phase_;
  131. };
  132. Interpreter::~Interpreter() {
  133. // Clean up any remaining suspended continuations.
  134. for (Nonnull<ContinuationValue::StackFragment*> fragment : stack_fragments_) {
  135. fragment->Clear();
  136. }
  137. }
  138. //
  139. // State Operations
  140. //
  141. void Interpreter::PrintState(llvm::raw_ostream& out) {
  142. out << "{\nstack: " << todo_;
  143. out << "\nmemory: " << heap_;
  144. out << "\n}\n";
  145. }
  146. auto Interpreter::EvalPrim(Operator op, Nonnull<const Value*> static_type,
  147. const std::vector<Nonnull<const Value*>>& args,
  148. SourceLocation source_loc)
  149. -> ErrorOr<Nonnull<const Value*>> {
  150. switch (op) {
  151. case Operator::Neg:
  152. return arena_->New<IntValue>(-cast<IntValue>(*args[0]).value());
  153. case Operator::Add:
  154. return arena_->New<IntValue>(cast<IntValue>(*args[0]).value() +
  155. cast<IntValue>(*args[1]).value());
  156. case Operator::Sub:
  157. return arena_->New<IntValue>(cast<IntValue>(*args[0]).value() -
  158. cast<IntValue>(*args[1]).value());
  159. case Operator::Mul:
  160. return arena_->New<IntValue>(cast<IntValue>(*args[0]).value() *
  161. cast<IntValue>(*args[1]).value());
  162. case Operator::Not:
  163. return arena_->New<BoolValue>(!cast<BoolValue>(*args[0]).value());
  164. case Operator::And:
  165. return arena_->New<BoolValue>(cast<BoolValue>(*args[0]).value() &&
  166. cast<BoolValue>(*args[1]).value());
  167. case Operator::Or:
  168. return arena_->New<BoolValue>(cast<BoolValue>(*args[0]).value() ||
  169. cast<BoolValue>(*args[1]).value());
  170. case Operator::Eq:
  171. return arena_->New<BoolValue>(ValueEqual(args[0], args[1], std::nullopt));
  172. case Operator::Ptr:
  173. return arena_->New<PointerType>(args[0]);
  174. case Operator::Deref:
  175. return heap_.Read(cast<PointerValue>(*args[0]).address(), source_loc);
  176. case Operator::AddressOf:
  177. return arena_->New<PointerValue>(cast<LValue>(*args[0]).address());
  178. case Operator::Combine:
  179. return &cast<TypeOfConstraintType>(static_type)->constraint_type();
  180. }
  181. }
  182. auto Interpreter::CreateStruct(const std::vector<FieldInitializer>& fields,
  183. const std::vector<Nonnull<const Value*>>& values)
  184. -> Nonnull<const Value*> {
  185. CARBON_CHECK(fields.size() == values.size());
  186. std::vector<NamedValue> elements;
  187. for (size_t i = 0; i < fields.size(); ++i) {
  188. elements.push_back({.name = fields[i].name(), .value = values[i]});
  189. }
  190. return arena_->New<StructValue>(std::move(elements));
  191. }
  192. auto PatternMatch(Nonnull<const Value*> p, Nonnull<const Value*> v,
  193. SourceLocation source_loc,
  194. std::optional<Nonnull<RuntimeScope*>> bindings,
  195. BindingMap& generic_args,
  196. std::optional<Nonnull<llvm::raw_ostream*>> trace_stream,
  197. Nonnull<Arena*> arena) -> bool {
  198. if (trace_stream) {
  199. **trace_stream << "match pattern " << *p << "\nwith value " << *v << "\n";
  200. }
  201. switch (p->kind()) {
  202. case Value::Kind::BindingPlaceholderValue: {
  203. CARBON_CHECK(bindings.has_value());
  204. const auto& placeholder = cast<BindingPlaceholderValue>(*p);
  205. if (placeholder.value_node().has_value()) {
  206. (*bindings)->Initialize(*placeholder.value_node(), v);
  207. }
  208. return true;
  209. }
  210. case Value::Kind::AddrValue: {
  211. const auto& addr = cast<AddrValue>(*p);
  212. CARBON_CHECK(v->kind() == Value::Kind::LValue);
  213. const auto& lvalue = cast<LValue>(*v);
  214. return PatternMatch(
  215. &addr.pattern(), arena->New<PointerValue>(lvalue.address()),
  216. source_loc, bindings, generic_args, trace_stream, arena);
  217. }
  218. case Value::Kind::VariableType: {
  219. const auto& var_type = cast<VariableType>(*p);
  220. generic_args[&var_type.binding()] = v;
  221. return true;
  222. }
  223. case Value::Kind::TupleValue:
  224. switch (v->kind()) {
  225. case Value::Kind::TupleValue: {
  226. const auto& p_tup = cast<TupleValue>(*p);
  227. const auto& v_tup = cast<TupleValue>(*v);
  228. CARBON_CHECK(p_tup.elements().size() == v_tup.elements().size());
  229. for (size_t i = 0; i < p_tup.elements().size(); ++i) {
  230. if (!PatternMatch(p_tup.elements()[i], v_tup.elements()[i],
  231. source_loc, bindings, generic_args, trace_stream,
  232. arena)) {
  233. return false;
  234. }
  235. } // for
  236. return true;
  237. }
  238. default:
  239. CARBON_FATAL() << "expected a tuple value in pattern, not " << *v;
  240. }
  241. case Value::Kind::StructValue: {
  242. const auto& p_struct = cast<StructValue>(*p);
  243. const auto& v_struct = cast<StructValue>(*v);
  244. CARBON_CHECK(p_struct.elements().size() == v_struct.elements().size());
  245. for (size_t i = 0; i < p_struct.elements().size(); ++i) {
  246. CARBON_CHECK(p_struct.elements()[i].name ==
  247. v_struct.elements()[i].name);
  248. if (!PatternMatch(p_struct.elements()[i].value,
  249. v_struct.elements()[i].value, source_loc, bindings,
  250. generic_args, trace_stream, arena)) {
  251. return false;
  252. }
  253. }
  254. return true;
  255. }
  256. case Value::Kind::AlternativeValue:
  257. switch (v->kind()) {
  258. case Value::Kind::AlternativeValue: {
  259. const auto& p_alt = cast<AlternativeValue>(*p);
  260. const auto& v_alt = cast<AlternativeValue>(*v);
  261. if (p_alt.choice_name() != v_alt.choice_name() ||
  262. p_alt.alt_name() != v_alt.alt_name()) {
  263. return false;
  264. }
  265. return PatternMatch(&p_alt.argument(), &v_alt.argument(), source_loc,
  266. bindings, generic_args, trace_stream, arena);
  267. }
  268. default:
  269. CARBON_FATAL() << "expected a choice alternative in pattern, not "
  270. << *v;
  271. }
  272. case Value::Kind::FunctionType:
  273. switch (v->kind()) {
  274. case Value::Kind::FunctionType: {
  275. const auto& p_fn = cast<FunctionType>(*p);
  276. const auto& v_fn = cast<FunctionType>(*v);
  277. if (!PatternMatch(&p_fn.parameters(), &v_fn.parameters(), source_loc,
  278. bindings, generic_args, trace_stream, arena)) {
  279. return false;
  280. }
  281. if (!PatternMatch(&p_fn.return_type(), &v_fn.return_type(),
  282. source_loc, bindings, generic_args, trace_stream,
  283. arena)) {
  284. return false;
  285. }
  286. return true;
  287. }
  288. default:
  289. return false;
  290. }
  291. case Value::Kind::AutoType:
  292. // `auto` matches any type, without binding any new names. We rely
  293. // on the typechecker to ensure that `v` is a type.
  294. return true;
  295. default:
  296. return ValueEqual(p, v, std::nullopt);
  297. }
  298. }
  299. auto Interpreter::StepLvalue() -> ErrorOr<Success> {
  300. Action& act = todo_.CurrentAction();
  301. const Expression& exp = cast<LValAction>(act).expression();
  302. if (trace_stream_) {
  303. **trace_stream_ << "--- step lvalue " << exp << " ." << act.pos() << "."
  304. << " (" << exp.source_loc() << ") --->\n";
  305. }
  306. switch (exp.kind()) {
  307. case ExpressionKind::IdentifierExpression: {
  308. // { {x :: C, E, F} :: S, H}
  309. // -> { {E(x) :: C, E, F} :: S, H}
  310. CARBON_ASSIGN_OR_RETURN(
  311. Nonnull<const Value*> value,
  312. todo_.ValueOfNode(cast<IdentifierExpression>(exp).value_node(),
  313. exp.source_loc()));
  314. CARBON_CHECK(isa<LValue>(value)) << *value;
  315. return todo_.FinishAction(value);
  316. }
  317. case ExpressionKind::SimpleMemberAccessExpression: {
  318. if (act.pos() == 0) {
  319. // { {e.f :: C, E, F} :: S, H}
  320. // -> { e :: [].f :: C, E, F} :: S, H}
  321. return todo_.Spawn(std::make_unique<LValAction>(
  322. &cast<SimpleMemberAccessExpression>(exp).object()));
  323. } else {
  324. // { v :: [].f :: C, E, F} :: S, H}
  325. // -> { { &v.f :: C, E, F} :: S, H }
  326. Address object = cast<LValue>(*act.results()[0]).address();
  327. Address member = object.SubobjectAddress(
  328. cast<SimpleMemberAccessExpression>(exp).member());
  329. return todo_.FinishAction(arena_->New<LValue>(member));
  330. }
  331. }
  332. case ExpressionKind::CompoundMemberAccessExpression: {
  333. const auto& access = cast<CompoundMemberAccessExpression>(exp);
  334. if (act.pos() == 0) {
  335. return todo_.Spawn(std::make_unique<LValAction>(&access.object()));
  336. } else {
  337. CARBON_CHECK(!access.member().interface().has_value())
  338. << "unexpected lvalue interface member";
  339. CARBON_ASSIGN_OR_RETURN(
  340. Nonnull<const Value*> val,
  341. Convert(act.results()[0], *access.member().base_type(),
  342. exp.source_loc()));
  343. Address object = cast<LValue>(*val).address();
  344. Address field = object.SubobjectAddress(access.member().member());
  345. return todo_.FinishAction(arena_->New<LValue>(field));
  346. }
  347. }
  348. case ExpressionKind::IndexExpression: {
  349. if (act.pos() == 0) {
  350. // { {e[i] :: C, E, F} :: S, H}
  351. // -> { e :: [][i] :: C, E, F} :: S, H}
  352. return todo_.Spawn(
  353. std::make_unique<LValAction>(&cast<IndexExpression>(exp).object()));
  354. } else if (act.pos() == 1) {
  355. return todo_.Spawn(std::make_unique<ExpressionAction>(
  356. &cast<IndexExpression>(exp).offset()));
  357. } else {
  358. // { v :: [][i] :: C, E, F} :: S, H}
  359. // -> { { &v[i] :: C, E, F} :: S, H }
  360. Address object = cast<LValue>(*act.results()[0]).address();
  361. // TODO: Add support to `Member` for naming tuple fields rather than
  362. // pretending we have struct fields with numerical names.
  363. std::string f =
  364. std::to_string(cast<IntValue>(*act.results()[1]).value());
  365. auto* tuple_field_as_struct_field =
  366. arena_->New<NamedValue>(NamedValue{f, &exp.static_type()});
  367. Address field =
  368. object.SubobjectAddress(Member(tuple_field_as_struct_field));
  369. return todo_.FinishAction(arena_->New<LValue>(field));
  370. }
  371. }
  372. case ExpressionKind::PrimitiveOperatorExpression: {
  373. const auto& op = cast<PrimitiveOperatorExpression>(exp);
  374. if (op.op() != Operator::Deref) {
  375. CARBON_FATAL()
  376. << "Can't treat primitive operator expression as lvalue: " << exp;
  377. }
  378. if (act.pos() == 0) {
  379. return todo_.Spawn(
  380. std::make_unique<ExpressionAction>(op.arguments()[0]));
  381. } else {
  382. const auto& res = cast<PointerValue>(*act.results()[0]);
  383. return todo_.FinishAction(arena_->New<LValue>(res.address()));
  384. }
  385. break;
  386. }
  387. case ExpressionKind::TupleLiteral:
  388. case ExpressionKind::StructLiteral:
  389. case ExpressionKind::StructTypeLiteral:
  390. case ExpressionKind::IntLiteral:
  391. case ExpressionKind::BoolLiteral:
  392. case ExpressionKind::CallExpression:
  393. case ExpressionKind::IntTypeLiteral:
  394. case ExpressionKind::BoolTypeLiteral:
  395. case ExpressionKind::TypeTypeLiteral:
  396. case ExpressionKind::FunctionTypeLiteral:
  397. case ExpressionKind::ContinuationTypeLiteral:
  398. case ExpressionKind::StringLiteral:
  399. case ExpressionKind::StringTypeLiteral:
  400. case ExpressionKind::ValueLiteral:
  401. case ExpressionKind::IntrinsicExpression:
  402. case ExpressionKind::IfExpression:
  403. case ExpressionKind::WhereExpression:
  404. case ExpressionKind::DotSelfExpression:
  405. case ExpressionKind::ArrayTypeLiteral:
  406. case ExpressionKind::InstantiateImpl:
  407. CARBON_FATAL() << "Can't treat expression as lvalue: " << exp;
  408. case ExpressionKind::UnimplementedExpression:
  409. CARBON_FATAL() << "Unimplemented: " << exp;
  410. }
  411. }
  412. auto Interpreter::EvalExpRecursively(Nonnull<const Expression*> exp)
  413. -> ErrorOr<Nonnull<const Value*>> {
  414. if (trace_stream_) {
  415. **trace_stream_ << "--- recursive eval of " << *exp << "\n";
  416. PrintState(**trace_stream_);
  417. }
  418. todo_.BeginRecursiveAction();
  419. CARBON_RETURN_IF_ERROR(todo_.Spawn(std::make_unique<ExpressionAction>(exp)));
  420. // Note that the only `RecursiveAction` we can encounter here is our own --
  421. // if a nested action begins a recursive action, it will run until that
  422. // action is finished and popped off the queue before returning to us.
  423. while (!isa<RecursiveAction>(todo_.CurrentAction())) {
  424. CARBON_RETURN_IF_ERROR(Step());
  425. if (trace_stream_) {
  426. PrintState(**trace_stream_);
  427. }
  428. }
  429. if (trace_stream_) {
  430. **trace_stream_ << "--- recursive eval done\n";
  431. }
  432. Nonnull<const Value*> result =
  433. cast<RecursiveAction>(todo_.CurrentAction()).results()[0];
  434. CARBON_RETURN_IF_ERROR(todo_.FinishAction());
  435. return result;
  436. }
  437. auto Interpreter::EvalAssociatedConstant(
  438. Nonnull<const AssociatedConstant*> assoc, SourceLocation source_loc)
  439. -> ErrorOr<Nonnull<const Value*>> {
  440. // Find the witness.
  441. Nonnull<const Value*> witness = &assoc->witness();
  442. if (auto* sym = dyn_cast<SymbolicWitness>(witness)) {
  443. CARBON_ASSIGN_OR_RETURN(witness,
  444. EvalExpRecursively(&sym->impl_expression()));
  445. }
  446. if (!isa<ImplWitness>(witness)) {
  447. CARBON_CHECK(phase() == Phase::CompileTime)
  448. << "symbolic witnesses should only be formed at compile time";
  449. return CompilationError(source_loc)
  450. << "value of associated constant " << *assoc << " is not known";
  451. }
  452. auto& impl_witness = cast<ImplWitness>(*witness);
  453. Nonnull<const ConstraintType*> constraint =
  454. impl_witness.declaration().constraint_type();
  455. Nonnull<const Value*> expected = arena_->New<AssociatedConstant>(
  456. &constraint->self_binding()->value(), &assoc->interface(),
  457. &assoc->constant(), &impl_witness);
  458. std::optional<Nonnull<const Value*>> result;
  459. constraint->VisitEqualValues(expected,
  460. [&](Nonnull<const Value*> equal_value) {
  461. // TODO: The value might depend on the
  462. // parameters of the impl. We need to
  463. // substitute impl_witness.type_args() into the
  464. // value.
  465. if (isa<AssociatedConstant>(equal_value)) {
  466. return true;
  467. }
  468. // TODO: This makes an arbitrary choice if
  469. // there's more than one equal value. It's not
  470. // clear how to handle that case.
  471. result = equal_value;
  472. return false;
  473. });
  474. if (!result) {
  475. CARBON_FATAL() << impl_witness.declaration()
  476. << " is missing value for associated constant " << *assoc;
  477. }
  478. return *result;
  479. }
  480. auto Interpreter::InstantiateType(Nonnull<const Value*> type,
  481. SourceLocation source_loc)
  482. -> ErrorOr<Nonnull<const Value*>> {
  483. switch (type->kind()) {
  484. case Value::Kind::VariableType: {
  485. CARBON_ASSIGN_OR_RETURN(
  486. Nonnull<const Value*> value,
  487. todo_.ValueOfNode(&cast<VariableType>(*type).binding(), source_loc));
  488. if (const auto* lvalue = dyn_cast<LValue>(value)) {
  489. CARBON_ASSIGN_OR_RETURN(value,
  490. heap_.Read(lvalue->address(), source_loc));
  491. }
  492. return value;
  493. }
  494. case Value::Kind::NominalClassType: {
  495. const auto& class_type = cast<NominalClassType>(*type);
  496. CARBON_ASSIGN_OR_RETURN(
  497. Nonnull<const Bindings*> bindings,
  498. InstantiateBindings(&class_type.bindings(), source_loc));
  499. return arena_->New<NominalClassType>(&class_type.declaration(), bindings);
  500. }
  501. case Value::Kind::AssociatedConstant: {
  502. CARBON_ASSIGN_OR_RETURN(
  503. Nonnull<const Value*> type_value,
  504. EvalAssociatedConstant(cast<AssociatedConstant>(type), source_loc));
  505. return InstantiateType(type_value, source_loc);
  506. }
  507. default:
  508. return type;
  509. }
  510. }
  511. auto Interpreter::InstantiateBindings(Nonnull<const Bindings*> bindings,
  512. SourceLocation source_loc)
  513. -> ErrorOr<Nonnull<const Bindings*>> {
  514. BindingMap args = bindings->args();
  515. for (auto& [var, arg] : args) {
  516. CARBON_ASSIGN_OR_RETURN(arg, InstantiateType(arg, source_loc));
  517. }
  518. ImplWitnessMap witnesses = bindings->witnesses();
  519. for (auto& [bind, witness] : witnesses) {
  520. if (auto* sym = dyn_cast<SymbolicWitness>(witness)) {
  521. CARBON_ASSIGN_OR_RETURN(witness,
  522. EvalExpRecursively(&sym->impl_expression()));
  523. }
  524. }
  525. if (args == bindings->args() && witnesses == bindings->witnesses()) {
  526. return bindings;
  527. }
  528. return arena_->New<Bindings>(std::move(args), std::move(witnesses));
  529. }
  530. auto Interpreter::Convert(Nonnull<const Value*> value,
  531. Nonnull<const Value*> destination_type,
  532. SourceLocation source_loc)
  533. -> ErrorOr<Nonnull<const Value*>> {
  534. switch (value->kind()) {
  535. case Value::Kind::IntValue:
  536. case Value::Kind::FunctionValue:
  537. case Value::Kind::BoundMethodValue:
  538. case Value::Kind::PointerValue:
  539. case Value::Kind::LValue:
  540. case Value::Kind::BoolValue:
  541. case Value::Kind::NominalClassValue:
  542. case Value::Kind::AlternativeValue:
  543. case Value::Kind::IntType:
  544. case Value::Kind::BoolType:
  545. case Value::Kind::TypeType:
  546. case Value::Kind::FunctionType:
  547. case Value::Kind::PointerType:
  548. case Value::Kind::AutoType:
  549. case Value::Kind::NominalClassType:
  550. case Value::Kind::InterfaceType:
  551. case Value::Kind::ConstraintType:
  552. case Value::Kind::ImplWitness:
  553. case Value::Kind::SymbolicWitness:
  554. case Value::Kind::ParameterizedEntityName:
  555. case Value::Kind::ChoiceType:
  556. case Value::Kind::ContinuationType:
  557. case Value::Kind::VariableType:
  558. case Value::Kind::BindingPlaceholderValue:
  559. case Value::Kind::AddrValue:
  560. case Value::Kind::AlternativeConstructorValue:
  561. case Value::Kind::ContinuationValue:
  562. case Value::Kind::StringType:
  563. case Value::Kind::StringValue:
  564. case Value::Kind::TypeOfClassType:
  565. case Value::Kind::TypeOfInterfaceType:
  566. case Value::Kind::TypeOfConstraintType:
  567. case Value::Kind::TypeOfChoiceType:
  568. case Value::Kind::TypeOfParameterizedEntityName:
  569. case Value::Kind::TypeOfMemberName:
  570. case Value::Kind::StaticArrayType:
  571. case Value::Kind::MemberName:
  572. // TODO: add `CARBON_CHECK(TypeEqual(type, value->dynamic_type()))`, once
  573. // we have Value::dynamic_type.
  574. return value;
  575. case Value::Kind::StructValue: {
  576. const auto& struct_val = cast<StructValue>(*value);
  577. switch (destination_type->kind()) {
  578. case Value::Kind::StructType: {
  579. const auto& destination_struct_type =
  580. cast<StructType>(*destination_type);
  581. std::vector<NamedValue> new_elements;
  582. for (const auto& [field_name, field_type] :
  583. destination_struct_type.fields()) {
  584. std::optional<Nonnull<const Value*>> old_value =
  585. struct_val.FindField(field_name);
  586. CARBON_ASSIGN_OR_RETURN(
  587. Nonnull<const Value*> val,
  588. Convert(*old_value, field_type, source_loc));
  589. new_elements.push_back({.name = field_name, .value = val});
  590. }
  591. return arena_->New<StructValue>(std::move(new_elements));
  592. }
  593. case Value::Kind::NominalClassType: {
  594. // Instantiate the `destination_type` to obtain the runtime
  595. // type of the object.
  596. CARBON_ASSIGN_OR_RETURN(
  597. Nonnull<const Value*> inst_dest,
  598. InstantiateType(destination_type, source_loc));
  599. return arena_->New<NominalClassValue>(inst_dest, value);
  600. }
  601. default:
  602. CARBON_FATAL() << "Can't convert value " << *value << " to type "
  603. << *destination_type;
  604. }
  605. }
  606. case Value::Kind::StructType: {
  607. // The value `{}` has kind `StructType` not `StructValue`. This value can
  608. // be converted to an empty class type.
  609. if (auto* destination_class_type =
  610. dyn_cast<NominalClassType>(destination_type)) {
  611. CARBON_CHECK(cast<StructType>(*value).fields().empty())
  612. << "only an empty struct type value converts to class type";
  613. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> inst_dest,
  614. InstantiateType(destination_type, source_loc));
  615. return arena_->New<NominalClassValue>(inst_dest, value);
  616. }
  617. return value;
  618. }
  619. case Value::Kind::TupleValue: {
  620. const auto& tuple = cast<TupleValue>(value);
  621. std::vector<Nonnull<const Value*>> destination_element_types;
  622. switch (destination_type->kind()) {
  623. case Value::Kind::TupleValue:
  624. destination_element_types =
  625. cast<TupleValue>(destination_type)->elements();
  626. break;
  627. case Value::Kind::StaticArrayType: {
  628. const auto& array_type = cast<StaticArrayType>(*destination_type);
  629. destination_element_types.resize(array_type.size(),
  630. &array_type.element_type());
  631. break;
  632. }
  633. default:
  634. CARBON_FATAL() << "Can't convert value " << *value << " to type "
  635. << *destination_type;
  636. }
  637. CARBON_CHECK(tuple->elements().size() ==
  638. destination_element_types.size());
  639. std::vector<Nonnull<const Value*>> new_elements;
  640. for (size_t i = 0; i < tuple->elements().size(); ++i) {
  641. CARBON_ASSIGN_OR_RETURN(
  642. Nonnull<const Value*> val,
  643. Convert(tuple->elements()[i], destination_element_types[i],
  644. source_loc));
  645. new_elements.push_back(val);
  646. }
  647. return arena_->New<TupleValue>(std::move(new_elements));
  648. }
  649. case Value::Kind::AssociatedConstant: {
  650. CARBON_ASSIGN_OR_RETURN(
  651. Nonnull<const Value*> value,
  652. EvalAssociatedConstant(cast<AssociatedConstant>(value), source_loc));
  653. return Convert(value, destination_type, source_loc);
  654. }
  655. }
  656. }
  657. auto Interpreter::CallFunction(const CallExpression& call,
  658. Nonnull<const Value*> fun,
  659. Nonnull<const Value*> arg,
  660. ImplWitnessMap&& witnesses) -> ErrorOr<Success> {
  661. if (trace_stream_) {
  662. **trace_stream_ << "calling function: " << *fun << "\n";
  663. }
  664. switch (fun->kind()) {
  665. case Value::Kind::AlternativeConstructorValue: {
  666. const auto& alt = cast<AlternativeConstructorValue>(*fun);
  667. return todo_.FinishAction(arena_->New<AlternativeValue>(
  668. alt.alt_name(), alt.choice_name(), arg));
  669. }
  670. case Value::Kind::FunctionValue: {
  671. const FunctionValue& fun_val = cast<FunctionValue>(*fun);
  672. const FunctionDeclaration& function = fun_val.declaration();
  673. RuntimeScope binding_scope(&heap_);
  674. // Bring the class type arguments into scope.
  675. for (const auto& [bind, val] : fun_val.type_args()) {
  676. binding_scope.Initialize(bind, val);
  677. }
  678. // Bring the deduced type arguments into scope.
  679. for (const auto& [bind, val] : call.deduced_args()) {
  680. binding_scope.Initialize(bind, val);
  681. }
  682. // Bring the impl witness tables into scope.
  683. for (const auto& [impl_bind, witness] : witnesses) {
  684. binding_scope.Initialize(impl_bind, witness);
  685. }
  686. for (const auto& [impl_bind, witness] : fun_val.witnesses()) {
  687. binding_scope.Initialize(impl_bind, witness);
  688. }
  689. // Enter the binding scope to make any deduced arguments visible before
  690. // we resolve the parameter type.
  691. todo_.CurrentAction().StartScope(std::move(binding_scope));
  692. CARBON_ASSIGN_OR_RETURN(
  693. Nonnull<const Value*> converted_args,
  694. Convert(arg, &function.param_pattern().static_type(),
  695. call.source_loc()));
  696. RuntimeScope function_scope(&heap_);
  697. BindingMap generic_args;
  698. CARBON_CHECK(PatternMatch(
  699. &function.param_pattern().value(), converted_args, call.source_loc(),
  700. &function_scope, generic_args, trace_stream_, this->arena_));
  701. CARBON_CHECK(function.body().has_value())
  702. << "Calling a function that's missing a body";
  703. return todo_.Spawn(std::make_unique<StatementAction>(*function.body()),
  704. std::move(function_scope));
  705. }
  706. case Value::Kind::BoundMethodValue: {
  707. const auto& m = cast<BoundMethodValue>(*fun);
  708. const FunctionDeclaration& method = m.declaration();
  709. CARBON_CHECK(method.is_method());
  710. CARBON_ASSIGN_OR_RETURN(
  711. Nonnull<const Value*> converted_args,
  712. Convert(arg, &method.param_pattern().static_type(),
  713. call.source_loc()));
  714. RuntimeScope method_scope(&heap_);
  715. BindingMap generic_args;
  716. // Bind the receiver to the `me` parameter.
  717. CARBON_CHECK(PatternMatch(&method.me_pattern().value(), m.receiver(),
  718. call.source_loc(), &method_scope, generic_args,
  719. trace_stream_, this->arena_));
  720. // Bind the arguments to the parameters.
  721. CARBON_CHECK(PatternMatch(&method.param_pattern().value(), converted_args,
  722. call.source_loc(), &method_scope, generic_args,
  723. trace_stream_, this->arena_));
  724. // Bring the class type arguments into scope.
  725. for (const auto& [bind, val] : m.type_args()) {
  726. method_scope.Initialize(bind->original(), val);
  727. }
  728. // Bring the deduced type arguments into scope.
  729. for (const auto& [bind, val] : call.deduced_args()) {
  730. method_scope.Initialize(bind->original(), val);
  731. }
  732. // Bring the impl witness tables into scope.
  733. for (const auto& [impl_bind, witness] : witnesses) {
  734. method_scope.Initialize(impl_bind->original(), witness);
  735. }
  736. for (const auto& [impl_bind, witness] : m.witnesses()) {
  737. method_scope.Initialize(impl_bind->original(), witness);
  738. }
  739. CARBON_CHECK(method.body().has_value())
  740. << "Calling a method that's missing a body";
  741. return todo_.Spawn(std::make_unique<StatementAction>(*method.body()),
  742. std::move(method_scope));
  743. }
  744. case Value::Kind::ParameterizedEntityName: {
  745. const auto& name = cast<ParameterizedEntityName>(*fun);
  746. const Declaration& decl = name.declaration();
  747. RuntimeScope params_scope(&heap_);
  748. BindingMap generic_args;
  749. CARBON_CHECK(PatternMatch(&name.params().value(), arg, call.source_loc(),
  750. &params_scope, generic_args, trace_stream_,
  751. this->arena_));
  752. Nonnull<const Bindings*> bindings =
  753. arena_->New<Bindings>(std::move(generic_args), std::move(witnesses));
  754. switch (decl.kind()) {
  755. case DeclarationKind::ClassDeclaration:
  756. return todo_.FinishAction(arena_->New<NominalClassType>(
  757. &cast<ClassDeclaration>(decl), bindings));
  758. case DeclarationKind::InterfaceDeclaration:
  759. return todo_.FinishAction(arena_->New<InterfaceType>(
  760. &cast<InterfaceDeclaration>(decl), bindings));
  761. default:
  762. CARBON_FATAL() << "unknown kind of ParameterizedEntityName " << decl;
  763. }
  764. }
  765. default:
  766. return RuntimeError(call.source_loc())
  767. << "in call, expected a function, not " << *fun;
  768. }
  769. }
  770. auto Interpreter::StepExp() -> ErrorOr<Success> {
  771. Action& act = todo_.CurrentAction();
  772. const Expression& exp = cast<ExpressionAction>(act).expression();
  773. if (trace_stream_) {
  774. **trace_stream_ << "--- step exp " << exp << " ." << act.pos() << "."
  775. << " (" << exp.source_loc() << ") --->\n";
  776. }
  777. switch (exp.kind()) {
  778. case ExpressionKind::InstantiateImpl: {
  779. const InstantiateImpl& inst_impl = cast<InstantiateImpl>(exp);
  780. if (act.pos() == 0) {
  781. return todo_.Spawn(
  782. std::make_unique<ExpressionAction>(inst_impl.generic_impl()));
  783. }
  784. if (act.pos() == 1 && isa<SymbolicWitness>(act.results()[0])) {
  785. return todo_.FinishAction(arena_->New<SymbolicWitness>(&exp));
  786. }
  787. if (act.pos() - 1 < int(inst_impl.impls().size())) {
  788. auto iter = inst_impl.impls().begin();
  789. std::advance(iter, act.pos() - 1);
  790. return todo_.Spawn(std::make_unique<ExpressionAction>(iter->second));
  791. } else {
  792. Nonnull<const ImplWitness*> generic_witness =
  793. cast<ImplWitness>(act.results()[0]);
  794. ImplWitnessMap witnesses;
  795. int i = 0;
  796. for (const auto& [impl_bind, impl_exp] : inst_impl.impls()) {
  797. witnesses[impl_bind] = cast<Witness>(act.results()[i + 1]);
  798. ++i;
  799. }
  800. return todo_.FinishAction(arena_->New<ImplWitness>(
  801. &generic_witness->declaration(),
  802. arena_->New<Bindings>(inst_impl.type_args(),
  803. std::move(witnesses))));
  804. }
  805. }
  806. case ExpressionKind::IndexExpression: {
  807. if (act.pos() == 0) {
  808. // { { e[i] :: C, E, F} :: S, H}
  809. // -> { { e :: [][i] :: C, E, F} :: S, H}
  810. return todo_.Spawn(std::make_unique<ExpressionAction>(
  811. &cast<IndexExpression>(exp).object()));
  812. } else if (act.pos() == 1) {
  813. if (isa<SymbolicWitness>(act.results()[0])) {
  814. return todo_.FinishAction(arena_->New<SymbolicWitness>(&exp));
  815. }
  816. return todo_.Spawn(std::make_unique<ExpressionAction>(
  817. &cast<IndexExpression>(exp).offset()));
  818. } else {
  819. // { { v :: [][i] :: C, E, F} :: S, H}
  820. // -> { { v_i :: C, E, F} : S, H}
  821. const auto& tuple = cast<TupleValue>(*act.results()[0]);
  822. int i = cast<IntValue>(*act.results()[1]).value();
  823. if (i < 0 || i >= static_cast<int>(tuple.elements().size())) {
  824. return RuntimeError(exp.source_loc())
  825. << "index " << i << " out of range in " << tuple;
  826. }
  827. return todo_.FinishAction(tuple.elements()[i]);
  828. }
  829. }
  830. case ExpressionKind::TupleLiteral: {
  831. if (act.pos() <
  832. static_cast<int>(cast<TupleLiteral>(exp).fields().size())) {
  833. // { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
  834. // H}
  835. // -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
  836. // H}
  837. return todo_.Spawn(std::make_unique<ExpressionAction>(
  838. cast<TupleLiteral>(exp).fields()[act.pos()]));
  839. } else {
  840. return todo_.FinishAction(arena_->New<TupleValue>(act.results()));
  841. }
  842. }
  843. case ExpressionKind::StructLiteral: {
  844. const auto& literal = cast<StructLiteral>(exp);
  845. if (act.pos() < static_cast<int>(literal.fields().size())) {
  846. return todo_.Spawn(std::make_unique<ExpressionAction>(
  847. &literal.fields()[act.pos()].expression()));
  848. } else {
  849. return todo_.FinishAction(
  850. CreateStruct(literal.fields(), act.results()));
  851. }
  852. }
  853. case ExpressionKind::StructTypeLiteral: {
  854. const auto& struct_type = cast<StructTypeLiteral>(exp);
  855. if (act.pos() < static_cast<int>(struct_type.fields().size())) {
  856. return todo_.Spawn(std::make_unique<ExpressionAction>(
  857. &struct_type.fields()[act.pos()].expression()));
  858. } else {
  859. std::vector<NamedValue> fields;
  860. for (size_t i = 0; i < struct_type.fields().size(); ++i) {
  861. fields.push_back({struct_type.fields()[i].name(), act.results()[i]});
  862. }
  863. return todo_.FinishAction(arena_->New<StructType>(std::move(fields)));
  864. }
  865. }
  866. case ExpressionKind::SimpleMemberAccessExpression: {
  867. const auto& access = cast<SimpleMemberAccessExpression>(exp);
  868. bool forming_member_name = isa<TypeOfMemberName>(&access.static_type());
  869. if (act.pos() == 0) {
  870. // First, evaluate the first operand.
  871. if (access.is_field_addr_me_method()) {
  872. return todo_.Spawn(std::make_unique<LValAction>(&access.object()));
  873. } else {
  874. return todo_.Spawn(
  875. std::make_unique<ExpressionAction>(&access.object()));
  876. }
  877. } else if (act.pos() == 1 && access.impl().has_value() &&
  878. !forming_member_name) {
  879. // Next, if we're accessing an interface member, evaluate the `impl`
  880. // expression to find the corresponding witness.
  881. return todo_.Spawn(
  882. std::make_unique<ExpressionAction>(access.impl().value()));
  883. } else {
  884. // Finally, produce the result.
  885. std::optional<Nonnull<const InterfaceType*>> found_in_interface =
  886. access.found_in_interface();
  887. if (found_in_interface) {
  888. CARBON_ASSIGN_OR_RETURN(
  889. Nonnull<const Value*> instantiated,
  890. InstantiateType(*found_in_interface, exp.source_loc()));
  891. found_in_interface = cast<InterfaceType>(instantiated);
  892. }
  893. if (const auto* member_name_type =
  894. dyn_cast<TypeOfMemberName>(&access.static_type())) {
  895. // The result is a member name, such as in `Type.field_name`. Form a
  896. // suitable member name value.
  897. CARBON_CHECK(phase() == Phase::CompileTime)
  898. << "should not form MemberNames at runtime";
  899. std::optional<const Value*> type_result;
  900. if (!isa<InterfaceType, ConstraintType>(act.results()[0])) {
  901. type_result = act.results()[0];
  902. }
  903. MemberName* member_name = arena_->New<MemberName>(
  904. type_result, found_in_interface, member_name_type->member());
  905. return todo_.FinishAction(member_name);
  906. } else {
  907. // The result is the value of the named field, such as in
  908. // `value.field_name`. Extract the value within the given object.
  909. std::optional<Nonnull<const Witness*>> witness;
  910. if (access.impl().has_value()) {
  911. witness = cast<Witness>(act.results()[1]);
  912. }
  913. FieldPath::Component member(access.member(), found_in_interface,
  914. witness);
  915. const Value* aggregate;
  916. if (const auto* lvalue = dyn_cast<LValue>(act.results()[0])) {
  917. CARBON_ASSIGN_OR_RETURN(
  918. aggregate,
  919. this->heap_.Read(lvalue->address(), exp.source_loc()));
  920. } else {
  921. aggregate = act.results()[0];
  922. }
  923. CARBON_ASSIGN_OR_RETURN(
  924. Nonnull<const Value*> member_value,
  925. aggregate->GetMember(arena_, FieldPath(member), exp.source_loc(),
  926. act.results()[0]));
  927. return todo_.FinishAction(member_value);
  928. }
  929. }
  930. }
  931. case ExpressionKind::CompoundMemberAccessExpression: {
  932. const auto& access = cast<CompoundMemberAccessExpression>(exp);
  933. bool forming_member_name = isa<TypeOfMemberName>(&access.static_type());
  934. if (act.pos() == 0) {
  935. // First, evaluate the first operand.
  936. return todo_.Spawn(
  937. std::make_unique<ExpressionAction>(&access.object()));
  938. } else if (act.pos() == 1 && access.impl().has_value() &&
  939. !forming_member_name) {
  940. // Next, if we're accessing an interface member, evaluate the `impl`
  941. // expression to find the corresponding witness.
  942. return todo_.Spawn(
  943. std::make_unique<ExpressionAction>(access.impl().value()));
  944. } else {
  945. // Finally, produce the result.
  946. std::optional<Nonnull<const InterfaceType*>> found_in_interface =
  947. access.member().interface();
  948. if (found_in_interface) {
  949. CARBON_ASSIGN_OR_RETURN(
  950. Nonnull<const Value*> instantiated,
  951. InstantiateType(*found_in_interface, exp.source_loc()));
  952. found_in_interface = cast<InterfaceType>(instantiated);
  953. }
  954. if (forming_member_name) {
  955. // If we're forming a member name, we must be in the outer evaluation
  956. // in `Type.(Interface.method)`. Produce the same method name with
  957. // its `type` field set.
  958. CARBON_CHECK(phase() == Phase::CompileTime)
  959. << "should not form MemberNames at runtime";
  960. CARBON_CHECK(!access.member().base_type().has_value())
  961. << "compound member access forming a member name should be "
  962. "performing impl lookup";
  963. auto* member_name = arena_->New<MemberName>(
  964. act.results()[0], found_in_interface, access.member().member());
  965. return todo_.FinishAction(member_name);
  966. } else {
  967. // Access the object to find the named member.
  968. Nonnull<const Value*> object = act.results()[0];
  969. std::optional<Nonnull<const Witness*>> witness;
  970. if (access.impl().has_value()) {
  971. witness = cast<Witness>(act.results()[1]);
  972. } else {
  973. CARBON_CHECK(access.member().base_type().has_value())
  974. << "compound access should have base type or impl";
  975. CARBON_ASSIGN_OR_RETURN(
  976. object, Convert(object, *access.member().base_type(),
  977. exp.source_loc()));
  978. }
  979. FieldPath::Component field(access.member().member(),
  980. found_in_interface, witness);
  981. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> member,
  982. object->GetMember(arena_, FieldPath(field),
  983. exp.source_loc(), object));
  984. return todo_.FinishAction(member);
  985. }
  986. }
  987. }
  988. case ExpressionKind::IdentifierExpression: {
  989. CARBON_CHECK(act.pos() == 0);
  990. const auto& ident = cast<IdentifierExpression>(exp);
  991. // { {x :: C, E, F} :: S, H} -> { {H(E(x)) :: C, E, F} :: S, H}
  992. CARBON_ASSIGN_OR_RETURN(
  993. Nonnull<const Value*> value,
  994. todo_.ValueOfNode(ident.value_node(), ident.source_loc()));
  995. if (const auto* lvalue = dyn_cast<LValue>(value)) {
  996. CARBON_ASSIGN_OR_RETURN(
  997. value, heap_.Read(lvalue->address(), exp.source_loc()));
  998. }
  999. return todo_.FinishAction(value);
  1000. }
  1001. case ExpressionKind::DotSelfExpression: {
  1002. // `.Self` always symbolically resolves to the self binding, even if it's
  1003. // not yet been type-checked.
  1004. CARBON_CHECK(act.pos() == 0);
  1005. const auto& dot_self = cast<DotSelfExpression>(exp);
  1006. return todo_.FinishAction(
  1007. arena_->New<VariableType>(&dot_self.self_binding()));
  1008. }
  1009. case ExpressionKind::IntLiteral:
  1010. CARBON_CHECK(act.pos() == 0);
  1011. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  1012. return todo_.FinishAction(
  1013. arena_->New<IntValue>(cast<IntLiteral>(exp).value()));
  1014. case ExpressionKind::BoolLiteral:
  1015. CARBON_CHECK(act.pos() == 0);
  1016. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  1017. return todo_.FinishAction(
  1018. arena_->New<BoolValue>(cast<BoolLiteral>(exp).value()));
  1019. case ExpressionKind::PrimitiveOperatorExpression: {
  1020. const auto& op = cast<PrimitiveOperatorExpression>(exp);
  1021. if (act.pos() != static_cast<int>(op.arguments().size())) {
  1022. // { {v :: op(vs,[],e,es) :: C, E, F} :: S, H}
  1023. // -> { {e :: op(vs,v,[],es) :: C, E, F} :: S, H}
  1024. Nonnull<const Expression*> arg = op.arguments()[act.pos()];
  1025. if (op.op() == Operator::AddressOf) {
  1026. return todo_.Spawn(std::make_unique<LValAction>(arg));
  1027. } else {
  1028. return todo_.Spawn(std::make_unique<ExpressionAction>(arg));
  1029. }
  1030. } else {
  1031. // { {v :: op(vs,[]) :: C, E, F} :: S, H}
  1032. // -> { {eval_prim(op, (vs,v)) :: C, E, F} :: S, H}
  1033. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> value,
  1034. EvalPrim(op.op(), &op.static_type(),
  1035. act.results(), exp.source_loc()));
  1036. return todo_.FinishAction(value);
  1037. }
  1038. }
  1039. case ExpressionKind::CallExpression: {
  1040. const CallExpression& call = cast<CallExpression>(exp);
  1041. unsigned int num_impls = call.impls().size();
  1042. if (act.pos() == 0) {
  1043. // { {e1(e2) :: C, E, F} :: S, H}
  1044. // -> { {e1 :: [](e2) :: C, E, F} :: S, H}
  1045. return todo_.Spawn(
  1046. std::make_unique<ExpressionAction>(&call.function()));
  1047. } else if (act.pos() == 1) {
  1048. // { { v :: [](e) :: C, E, F} :: S, H}
  1049. // -> { { e :: v([]) :: C, E, F} :: S, H}
  1050. return todo_.Spawn(
  1051. std::make_unique<ExpressionAction>(&call.argument()));
  1052. } else if (num_impls > 0 && act.pos() < 2 + int(num_impls)) {
  1053. auto iter = call.impls().begin();
  1054. std::advance(iter, act.pos() - 2);
  1055. return todo_.Spawn(std::make_unique<ExpressionAction>(iter->second));
  1056. } else if (act.pos() == 2 + int(num_impls)) {
  1057. // { { v2 :: v1([]) :: C, E, F} :: S, H}
  1058. // -> { {C',E',F'} :: {C, E, F} :: S, H}
  1059. ImplWitnessMap witnesses;
  1060. if (num_impls > 0) {
  1061. int i = 2;
  1062. for (const auto& [impl_bind, impl_exp] : call.impls()) {
  1063. witnesses[impl_bind] = act.results()[i];
  1064. ++i;
  1065. }
  1066. }
  1067. return CallFunction(call, act.results()[0], act.results()[1],
  1068. std::move(witnesses));
  1069. } else if (act.pos() == 3 + int(num_impls)) {
  1070. if (act.results().size() < 3 + num_impls) {
  1071. // Control fell through without explicit return.
  1072. return todo_.FinishAction(TupleValue::Empty());
  1073. } else {
  1074. return todo_.FinishAction(act.results()[2 + int(num_impls)]);
  1075. }
  1076. } else {
  1077. CARBON_FATAL() << "in StepExp with Call pos " << act.pos();
  1078. }
  1079. }
  1080. case ExpressionKind::IntrinsicExpression: {
  1081. const auto& intrinsic = cast<IntrinsicExpression>(exp);
  1082. if (act.pos() == 0) {
  1083. return todo_.Spawn(
  1084. std::make_unique<ExpressionAction>(&intrinsic.args()));
  1085. }
  1086. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  1087. switch (cast<IntrinsicExpression>(exp).intrinsic()) {
  1088. case IntrinsicExpression::Intrinsic::Print: {
  1089. const auto& args = cast<TupleValue>(*act.results()[0]);
  1090. // TODO: This could eventually use something like llvm::formatv.
  1091. llvm::outs() << cast<StringValue>(*args.elements()[0]).value();
  1092. return todo_.FinishAction(TupleValue::Empty());
  1093. }
  1094. case IntrinsicExpression::Intrinsic::Alloc: {
  1095. const auto& args = cast<TupleValue>(*act.results()[0]);
  1096. CARBON_CHECK(args.elements().size() == 1);
  1097. Address addr(heap_.AllocateValue(args.elements()[0]));
  1098. return todo_.FinishAction(arena_->New<PointerValue>(addr));
  1099. }
  1100. case IntrinsicExpression::Intrinsic::Dealloc: {
  1101. const auto& args = cast<TupleValue>(*act.results()[0]);
  1102. CARBON_CHECK(args.elements().size() == 1);
  1103. heap_.Deallocate(cast<PointerValue>(args.elements()[0])->address());
  1104. return todo_.FinishAction(TupleValue::Empty());
  1105. }
  1106. }
  1107. }
  1108. case ExpressionKind::IntTypeLiteral: {
  1109. CARBON_CHECK(act.pos() == 0);
  1110. return todo_.FinishAction(arena_->New<IntType>());
  1111. }
  1112. case ExpressionKind::BoolTypeLiteral: {
  1113. CARBON_CHECK(act.pos() == 0);
  1114. return todo_.FinishAction(arena_->New<BoolType>());
  1115. }
  1116. case ExpressionKind::TypeTypeLiteral: {
  1117. CARBON_CHECK(act.pos() == 0);
  1118. return todo_.FinishAction(arena_->New<TypeType>());
  1119. }
  1120. case ExpressionKind::FunctionTypeLiteral: {
  1121. if (act.pos() == 0) {
  1122. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1123. &cast<FunctionTypeLiteral>(exp).parameter()));
  1124. } else if (act.pos() == 1) {
  1125. // { { pt :: fn [] -> e :: C, E, F} :: S, H}
  1126. // -> { { e :: fn pt -> []) :: C, E, F} :: S, H}
  1127. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1128. &cast<FunctionTypeLiteral>(exp).return_type()));
  1129. } else {
  1130. // { { rt :: fn pt -> [] :: C, E, F} :: S, H}
  1131. // -> { fn pt -> rt :: {C, E, F} :: S, H}
  1132. return todo_.FinishAction(arena_->New<FunctionType>(
  1133. act.results()[0], llvm::None, act.results()[1], llvm::None,
  1134. llvm::None));
  1135. }
  1136. }
  1137. case ExpressionKind::ContinuationTypeLiteral: {
  1138. CARBON_CHECK(act.pos() == 0);
  1139. return todo_.FinishAction(arena_->New<ContinuationType>());
  1140. }
  1141. case ExpressionKind::StringLiteral:
  1142. CARBON_CHECK(act.pos() == 0);
  1143. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  1144. return todo_.FinishAction(
  1145. arena_->New<StringValue>(cast<StringLiteral>(exp).value()));
  1146. case ExpressionKind::StringTypeLiteral: {
  1147. CARBON_CHECK(act.pos() == 0);
  1148. return todo_.FinishAction(arena_->New<StringType>());
  1149. }
  1150. case ExpressionKind::ValueLiteral: {
  1151. CARBON_CHECK(act.pos() == 0);
  1152. return todo_.FinishAction(&cast<ValueLiteral>(exp).value());
  1153. }
  1154. case ExpressionKind::IfExpression: {
  1155. const auto& if_expr = cast<IfExpression>(exp);
  1156. if (act.pos() == 0) {
  1157. return todo_.Spawn(
  1158. std::make_unique<ExpressionAction>(&if_expr.condition()));
  1159. } else if (act.pos() == 1) {
  1160. const auto& condition = cast<BoolValue>(*act.results()[0]);
  1161. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1162. condition.value() ? &if_expr.then_expression()
  1163. : &if_expr.else_expression()));
  1164. } else {
  1165. return todo_.FinishAction(act.results()[1]);
  1166. }
  1167. break;
  1168. }
  1169. case ExpressionKind::WhereExpression: {
  1170. return todo_.FinishAction(
  1171. &cast<TypeOfConstraintType>(exp.static_type()).constraint_type());
  1172. }
  1173. case ExpressionKind::UnimplementedExpression:
  1174. CARBON_FATAL() << "Unimplemented: " << exp;
  1175. case ExpressionKind::ArrayTypeLiteral: {
  1176. const auto& array_literal = cast<ArrayTypeLiteral>(exp);
  1177. if (act.pos() == 0) {
  1178. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1179. &array_literal.element_type_expression()));
  1180. } else if (act.pos() == 1) {
  1181. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1182. &array_literal.size_expression()));
  1183. } else {
  1184. return todo_.FinishAction(arena_->New<StaticArrayType>(
  1185. act.results()[0], cast<IntValue>(act.results()[1])->value()));
  1186. }
  1187. }
  1188. } // switch (exp->kind)
  1189. }
  1190. auto Interpreter::StepPattern() -> ErrorOr<Success> {
  1191. Action& act = todo_.CurrentAction();
  1192. const Pattern& pattern = cast<PatternAction>(act).pattern();
  1193. if (trace_stream_) {
  1194. **trace_stream_ << "--- step pattern " << pattern << " ." << act.pos()
  1195. << ". (" << pattern.source_loc() << ") --->\n";
  1196. }
  1197. switch (pattern.kind()) {
  1198. case PatternKind::AutoPattern: {
  1199. CARBON_CHECK(act.pos() == 0);
  1200. return todo_.FinishAction(arena_->New<AutoType>());
  1201. }
  1202. case PatternKind::BindingPattern: {
  1203. const auto& binding = cast<BindingPattern>(pattern);
  1204. if (binding.name() != AnonymousName) {
  1205. return todo_.FinishAction(
  1206. arena_->New<BindingPlaceholderValue>(&binding));
  1207. } else {
  1208. return todo_.FinishAction(arena_->New<BindingPlaceholderValue>());
  1209. }
  1210. }
  1211. case PatternKind::GenericBinding: {
  1212. const auto& binding = cast<GenericBinding>(pattern);
  1213. return todo_.FinishAction(arena_->New<VariableType>(&binding));
  1214. }
  1215. case PatternKind::TuplePattern: {
  1216. const auto& tuple = cast<TuplePattern>(pattern);
  1217. if (act.pos() < static_cast<int>(tuple.fields().size())) {
  1218. // { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
  1219. // H}
  1220. // -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
  1221. // H}
  1222. return todo_.Spawn(
  1223. std::make_unique<PatternAction>(tuple.fields()[act.pos()]));
  1224. } else {
  1225. return todo_.FinishAction(arena_->New<TupleValue>(act.results()));
  1226. }
  1227. }
  1228. case PatternKind::AlternativePattern: {
  1229. const auto& alternative = cast<AlternativePattern>(pattern);
  1230. if (act.pos() == 0) {
  1231. return todo_.Spawn(
  1232. std::make_unique<ExpressionAction>(&alternative.choice_type()));
  1233. } else if (act.pos() == 1) {
  1234. return todo_.Spawn(
  1235. std::make_unique<PatternAction>(&alternative.arguments()));
  1236. } else {
  1237. CARBON_CHECK(act.pos() == 2);
  1238. const auto& choice_type = cast<ChoiceType>(*act.results()[0]);
  1239. return todo_.FinishAction(arena_->New<AlternativeValue>(
  1240. alternative.alternative_name(), choice_type.name(),
  1241. act.results()[1]));
  1242. }
  1243. }
  1244. case PatternKind::ExpressionPattern:
  1245. if (act.pos() == 0) {
  1246. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1247. &cast<ExpressionPattern>(pattern).expression()));
  1248. } else {
  1249. return todo_.FinishAction(act.results()[0]);
  1250. }
  1251. case PatternKind::VarPattern:
  1252. if (act.pos() == 0) {
  1253. return todo_.Spawn(std::make_unique<PatternAction>(
  1254. &cast<VarPattern>(pattern).pattern()));
  1255. } else {
  1256. return todo_.FinishAction(act.results()[0]);
  1257. }
  1258. case PatternKind::AddrPattern:
  1259. const auto& addr = cast<AddrPattern>(pattern);
  1260. if (act.pos() == 0) {
  1261. return todo_.Spawn(std::make_unique<PatternAction>(&addr.binding()));
  1262. } else {
  1263. return todo_.FinishAction(arena_->New<AddrValue>(act.results()[0]));
  1264. }
  1265. break;
  1266. }
  1267. }
  1268. auto Interpreter::StepStmt() -> ErrorOr<Success> {
  1269. Action& act = todo_.CurrentAction();
  1270. const Statement& stmt = cast<StatementAction>(act).statement();
  1271. if (trace_stream_) {
  1272. **trace_stream_ << "--- step stmt ";
  1273. stmt.PrintDepth(1, **trace_stream_);
  1274. **trace_stream_ << " ." << act.pos() << ". "
  1275. << "(" << stmt.source_loc() << ") --->\n";
  1276. }
  1277. switch (stmt.kind()) {
  1278. case StatementKind::Match: {
  1279. const auto& match_stmt = cast<Match>(stmt);
  1280. if (act.pos() == 0) {
  1281. // { { (match (e) ...) :: C, E, F} :: S, H}
  1282. // -> { { e :: (match ([]) ...) :: C, E, F} :: S, H}
  1283. act.StartScope(RuntimeScope(&heap_));
  1284. return todo_.Spawn(
  1285. std::make_unique<ExpressionAction>(&match_stmt.expression()));
  1286. } else {
  1287. int clause_num = act.pos() - 1;
  1288. if (clause_num >= static_cast<int>(match_stmt.clauses().size())) {
  1289. return todo_.FinishAction();
  1290. }
  1291. auto c = match_stmt.clauses()[clause_num];
  1292. RuntimeScope matches(&heap_);
  1293. BindingMap generic_args;
  1294. CARBON_ASSIGN_OR_RETURN(
  1295. Nonnull<const Value*> val,
  1296. Convert(act.results()[0], &c.pattern().static_type(),
  1297. stmt.source_loc()));
  1298. if (PatternMatch(&c.pattern().value(), val, stmt.source_loc(), &matches,
  1299. generic_args, trace_stream_, this->arena_)) {
  1300. // Ensure we don't process any more clauses.
  1301. act.set_pos(match_stmt.clauses().size() + 1);
  1302. todo_.MergeScope(std::move(matches));
  1303. return todo_.Spawn(std::make_unique<StatementAction>(&c.statement()));
  1304. } else {
  1305. return todo_.RunAgain();
  1306. }
  1307. }
  1308. }
  1309. case StatementKind::While:
  1310. if (act.pos() % 2 == 0) {
  1311. // { { (while (e) s) :: C, E, F} :: S, H}
  1312. // -> { { e :: (while ([]) s) :: C, E, F} :: S, H}
  1313. act.Clear();
  1314. return todo_.Spawn(
  1315. std::make_unique<ExpressionAction>(&cast<While>(stmt).condition()));
  1316. } else {
  1317. CARBON_ASSIGN_OR_RETURN(
  1318. Nonnull<const Value*> condition,
  1319. Convert(act.results().back(), arena_->New<BoolType>(),
  1320. stmt.source_loc()));
  1321. if (cast<BoolValue>(*condition).value()) {
  1322. // { {true :: (while ([]) s) :: C, E, F} :: S, H}
  1323. // -> { { s :: (while (e) s) :: C, E, F } :: S, H}
  1324. return todo_.Spawn(
  1325. std::make_unique<StatementAction>(&cast<While>(stmt).body()));
  1326. } else {
  1327. // { {false :: (while ([]) s) :: C, E, F} :: S, H}
  1328. // -> { { C, E, F } :: S, H}
  1329. return todo_.FinishAction();
  1330. }
  1331. }
  1332. case StatementKind::Break: {
  1333. CARBON_CHECK(act.pos() == 0);
  1334. // { { break; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  1335. // -> { { C, E', F} :: S, H}
  1336. return todo_.UnwindPast(&cast<Break>(stmt).loop());
  1337. }
  1338. case StatementKind::Continue: {
  1339. CARBON_CHECK(act.pos() == 0);
  1340. // { { continue; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  1341. // -> { { (while (e) s) :: C, E', F} :: S, H}
  1342. return todo_.UnwindTo(&cast<Continue>(stmt).loop());
  1343. }
  1344. case StatementKind::Block: {
  1345. const auto& block = cast<Block>(stmt);
  1346. if (act.pos() >= static_cast<int>(block.statements().size())) {
  1347. // If the position is past the end of the block, end processing. Note
  1348. // that empty blocks immediately end.
  1349. return todo_.FinishAction();
  1350. }
  1351. // Initialize a scope when starting a block.
  1352. if (act.pos() == 0) {
  1353. act.StartScope(RuntimeScope(&heap_));
  1354. }
  1355. // Process the next statement in the block. The position will be
  1356. // incremented as part of Spawn.
  1357. return todo_.Spawn(
  1358. std::make_unique<StatementAction>(block.statements()[act.pos()]));
  1359. }
  1360. case StatementKind::VariableDefinition: {
  1361. const auto& definition = cast<VariableDefinition>(stmt);
  1362. if (act.pos() == 0) {
  1363. // { {(var x = e) :: C, E, F} :: S, H}
  1364. // -> { {e :: (var x = []) :: C, E, F} :: S, H}
  1365. return todo_.Spawn(
  1366. std::make_unique<ExpressionAction>(&definition.init()));
  1367. } else {
  1368. // { { v :: (x = []) :: C, E, F} :: S, H}
  1369. // -> { { C, E(x := a), F} :: S, H(a := copy(v))}
  1370. CARBON_ASSIGN_OR_RETURN(
  1371. Nonnull<const Value*> v,
  1372. Convert(act.results()[0], &definition.pattern().static_type(),
  1373. stmt.source_loc()));
  1374. Nonnull<const Value*> p =
  1375. &cast<VariableDefinition>(stmt).pattern().value();
  1376. RuntimeScope matches(&heap_);
  1377. BindingMap generic_args;
  1378. CARBON_CHECK(PatternMatch(p, v, stmt.source_loc(), &matches,
  1379. generic_args, trace_stream_, this->arena_))
  1380. << stmt.source_loc()
  1381. << ": internal error in variable definition, match failed";
  1382. todo_.MergeScope(std::move(matches));
  1383. return todo_.FinishAction();
  1384. }
  1385. }
  1386. case StatementKind::ExpressionStatement:
  1387. if (act.pos() == 0) {
  1388. // { {e :: C, E, F} :: S, H}
  1389. // -> { {e :: C, E, F} :: S, H}
  1390. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1391. &cast<ExpressionStatement>(stmt).expression()));
  1392. } else {
  1393. return todo_.FinishAction();
  1394. }
  1395. case StatementKind::Assign: {
  1396. const auto& assign = cast<Assign>(stmt);
  1397. if (act.pos() == 0) {
  1398. // { {(lv = e) :: C, E, F} :: S, H}
  1399. // -> { {lv :: ([] = e) :: C, E, F} :: S, H}
  1400. return todo_.Spawn(std::make_unique<LValAction>(&assign.lhs()));
  1401. } else if (act.pos() == 1) {
  1402. // { { a :: ([] = e) :: C, E, F} :: S, H}
  1403. // -> { { e :: (a = []) :: C, E, F} :: S, H}
  1404. return todo_.Spawn(std::make_unique<ExpressionAction>(&assign.rhs()));
  1405. } else {
  1406. // { { v :: (a = []) :: C, E, F} :: S, H}
  1407. // -> { { C, E, F} :: S, H(a := v)}
  1408. const auto& lval = cast<LValue>(*act.results()[0]);
  1409. CARBON_ASSIGN_OR_RETURN(
  1410. Nonnull<const Value*> rval,
  1411. Convert(act.results()[1], &assign.lhs().static_type(),
  1412. stmt.source_loc()));
  1413. CARBON_RETURN_IF_ERROR(
  1414. heap_.Write(lval.address(), rval, stmt.source_loc()));
  1415. return todo_.FinishAction();
  1416. }
  1417. }
  1418. case StatementKind::If:
  1419. if (act.pos() == 0) {
  1420. // { {(if (e) then_stmt else else_stmt) :: C, E, F} :: S, H}
  1421. // -> { { e :: (if ([]) then_stmt else else_stmt) :: C, E, F} :: S, H}
  1422. return todo_.Spawn(
  1423. std::make_unique<ExpressionAction>(&cast<If>(stmt).condition()));
  1424. } else if (act.pos() == 1) {
  1425. CARBON_ASSIGN_OR_RETURN(
  1426. Nonnull<const Value*> condition,
  1427. Convert(act.results()[0], arena_->New<BoolType>(),
  1428. stmt.source_loc()));
  1429. if (cast<BoolValue>(*condition).value()) {
  1430. // { {true :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  1431. // S, H}
  1432. // -> { { then_stmt :: C, E, F } :: S, H}
  1433. return todo_.Spawn(
  1434. std::make_unique<StatementAction>(&cast<If>(stmt).then_block()));
  1435. } else if (cast<If>(stmt).else_block()) {
  1436. // { {false :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  1437. // S, H}
  1438. // -> { { else_stmt :: C, E, F } :: S, H}
  1439. return todo_.Spawn(
  1440. std::make_unique<StatementAction>(*cast<If>(stmt).else_block()));
  1441. } else {
  1442. return todo_.FinishAction();
  1443. }
  1444. } else {
  1445. return todo_.FinishAction();
  1446. }
  1447. case StatementKind::ReturnVar: {
  1448. const ValueNodeView& value_node = cast<ReturnVar>(stmt).value_node();
  1449. if (trace_stream_) {
  1450. **trace_stream_ << "--- step returned var "
  1451. << cast<BindingPattern>(value_node.base()).name()
  1452. << " ." << act.pos() << "."
  1453. << " (" << stmt.source_loc() << ") --->\n";
  1454. }
  1455. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> value,
  1456. todo_.ValueOfNode(value_node, stmt.source_loc()));
  1457. if (const auto* lvalue = dyn_cast<LValue>(value)) {
  1458. CARBON_ASSIGN_OR_RETURN(
  1459. value,
  1460. heap_.Read(lvalue->address(), value_node.base().source_loc()));
  1461. }
  1462. const FunctionDeclaration& function = cast<Return>(stmt).function();
  1463. CARBON_ASSIGN_OR_RETURN(
  1464. Nonnull<const Value*> return_value,
  1465. Convert(value, &function.return_term().static_type(),
  1466. stmt.source_loc()));
  1467. return todo_.UnwindPast(*function.body(), return_value);
  1468. }
  1469. case StatementKind::ReturnExpression:
  1470. if (act.pos() == 0) {
  1471. // { {return e :: C, E, F} :: S, H}
  1472. // -> { {e :: return [] :: C, E, F} :: S, H}
  1473. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1474. &cast<ReturnExpression>(stmt).expression()));
  1475. } else {
  1476. // { {v :: return [] :: C, E, F} :: {C', E', F'} :: S, H}
  1477. // -> { {v :: C', E', F'} :: S, H}
  1478. const FunctionDeclaration& function = cast<Return>(stmt).function();
  1479. CARBON_ASSIGN_OR_RETURN(
  1480. Nonnull<const Value*> return_value,
  1481. Convert(act.results()[0], &function.return_term().static_type(),
  1482. stmt.source_loc()));
  1483. return todo_.UnwindPast(*function.body(), return_value);
  1484. }
  1485. case StatementKind::Continuation: {
  1486. CARBON_CHECK(act.pos() == 0);
  1487. const auto& continuation = cast<Continuation>(stmt);
  1488. // Create a continuation object by creating a frame similar the
  1489. // way one is created in a function call.
  1490. auto fragment = arena_->New<ContinuationValue::StackFragment>();
  1491. stack_fragments_.push_back(fragment);
  1492. todo_.InitializeFragment(*fragment, &continuation.body());
  1493. // Bind the continuation object to the continuation variable
  1494. todo_.Initialize(&cast<Continuation>(stmt),
  1495. arena_->New<ContinuationValue>(fragment));
  1496. return todo_.FinishAction();
  1497. }
  1498. case StatementKind::Run: {
  1499. auto& run = cast<Run>(stmt);
  1500. if (act.pos() == 0) {
  1501. // Evaluate the argument of the run statement.
  1502. return todo_.Spawn(std::make_unique<ExpressionAction>(&run.argument()));
  1503. } else if (act.pos() == 1) {
  1504. // Push the continuation onto the current stack.
  1505. return todo_.Resume(cast<const ContinuationValue>(act.results()[0]));
  1506. } else {
  1507. return todo_.FinishAction();
  1508. }
  1509. }
  1510. case StatementKind::Await:
  1511. CARBON_CHECK(act.pos() == 0);
  1512. return todo_.Suspend();
  1513. }
  1514. }
  1515. auto Interpreter::StepDeclaration() -> ErrorOr<Success> {
  1516. Action& act = todo_.CurrentAction();
  1517. const Declaration& decl = cast<DeclarationAction>(act).declaration();
  1518. if (trace_stream_) {
  1519. **trace_stream_ << "--- step decl ";
  1520. decl.PrintID(**trace_stream_);
  1521. **trace_stream_ << " ." << act.pos() << ". "
  1522. << "(" << decl.source_loc() << ") --->\n";
  1523. }
  1524. switch (decl.kind()) {
  1525. case DeclarationKind::VariableDeclaration: {
  1526. const auto& var_decl = cast<VariableDeclaration>(decl);
  1527. if (var_decl.has_initializer()) {
  1528. if (act.pos() == 0) {
  1529. return todo_.Spawn(
  1530. std::make_unique<ExpressionAction>(&var_decl.initializer()));
  1531. } else {
  1532. CARBON_ASSIGN_OR_RETURN(
  1533. Nonnull<const Value*> v,
  1534. Convert(act.results()[0], &var_decl.binding().static_type(),
  1535. var_decl.source_loc()));
  1536. todo_.Initialize(&var_decl.binding(), v);
  1537. return todo_.FinishAction();
  1538. }
  1539. } else {
  1540. return todo_.FinishAction();
  1541. }
  1542. }
  1543. case DeclarationKind::FunctionDeclaration:
  1544. case DeclarationKind::ClassDeclaration:
  1545. case DeclarationKind::ChoiceDeclaration:
  1546. case DeclarationKind::InterfaceDeclaration:
  1547. case DeclarationKind::AssociatedConstantDeclaration:
  1548. case DeclarationKind::ImplDeclaration:
  1549. case DeclarationKind::SelfDeclaration:
  1550. case DeclarationKind::AliasDeclaration:
  1551. // These declarations have no run-time effects.
  1552. return todo_.FinishAction();
  1553. }
  1554. }
  1555. // State transition.
  1556. auto Interpreter::Step() -> ErrorOr<Success> {
  1557. Action& act = todo_.CurrentAction();
  1558. switch (act.kind()) {
  1559. case Action::Kind::LValAction:
  1560. CARBON_RETURN_IF_ERROR(StepLvalue());
  1561. break;
  1562. case Action::Kind::ExpressionAction:
  1563. CARBON_RETURN_IF_ERROR(StepExp());
  1564. break;
  1565. case Action::Kind::PatternAction:
  1566. CARBON_RETURN_IF_ERROR(StepPattern());
  1567. break;
  1568. case Action::Kind::StatementAction:
  1569. CARBON_RETURN_IF_ERROR(StepStmt());
  1570. break;
  1571. case Action::Kind::DeclarationAction:
  1572. CARBON_RETURN_IF_ERROR(StepDeclaration());
  1573. break;
  1574. case Action::Kind::ScopeAction:
  1575. CARBON_FATAL() << "ScopeAction escaped ActionStack";
  1576. case Action::Kind::RecursiveAction:
  1577. CARBON_FATAL() << "Tried to step a RecursiveAction";
  1578. } // switch
  1579. return Success();
  1580. }
  1581. auto Interpreter::RunAllSteps(std::unique_ptr<Action> action)
  1582. -> ErrorOr<Success> {
  1583. if (trace_stream_) {
  1584. PrintState(**trace_stream_);
  1585. }
  1586. todo_.Start(std::move(action));
  1587. while (!todo_.IsEmpty()) {
  1588. CARBON_RETURN_IF_ERROR(Step());
  1589. if (trace_stream_) {
  1590. PrintState(**trace_stream_);
  1591. }
  1592. }
  1593. return Success();
  1594. }
  1595. auto InterpProgram(const AST& ast, Nonnull<Arena*> arena,
  1596. std::optional<Nonnull<llvm::raw_ostream*>> trace_stream)
  1597. -> ErrorOr<int> {
  1598. Interpreter interpreter(Phase::RunTime, arena, trace_stream);
  1599. if (trace_stream) {
  1600. **trace_stream << "********** initializing globals **********\n";
  1601. }
  1602. for (Nonnull<Declaration*> declaration : ast.declarations) {
  1603. CARBON_RETURN_IF_ERROR(interpreter.RunAllSteps(
  1604. std::make_unique<DeclarationAction>(declaration)));
  1605. }
  1606. if (trace_stream) {
  1607. **trace_stream << "********** calling main function **********\n";
  1608. }
  1609. CARBON_RETURN_IF_ERROR(interpreter.RunAllSteps(
  1610. std::make_unique<ExpressionAction>(*ast.main_call)));
  1611. return cast<IntValue>(*interpreter.result()).value();
  1612. }
  1613. auto InterpExp(Nonnull<const Expression*> e, Nonnull<Arena*> arena,
  1614. std::optional<Nonnull<llvm::raw_ostream*>> trace_stream)
  1615. -> ErrorOr<Nonnull<const Value*>> {
  1616. Interpreter interpreter(Phase::CompileTime, arena, trace_stream);
  1617. CARBON_RETURN_IF_ERROR(
  1618. interpreter.RunAllSteps(std::make_unique<ExpressionAction>(e)));
  1619. return interpreter.result();
  1620. }
  1621. auto InterpPattern(Nonnull<const Pattern*> p, Nonnull<Arena*> arena,
  1622. std::optional<Nonnull<llvm::raw_ostream*>> trace_stream)
  1623. -> ErrorOr<Nonnull<const Value*>> {
  1624. Interpreter interpreter(Phase::CompileTime, arena, trace_stream);
  1625. CARBON_RETURN_IF_ERROR(
  1626. interpreter.RunAllSteps(std::make_unique<PatternAction>(p)));
  1627. return interpreter.result();
  1628. }
  1629. } // namespace Carbon