interpreter.cpp 87 KB

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