interpreter.cpp 87 KB

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