interpreter.cpp 88 KB

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