interpreter.cpp 75 KB

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