interpreter.cpp 84 KB

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