interpreter.cpp 109 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "explorer/interpreter/interpreter.h"
  5. #include <iterator>
  6. #include <limits>
  7. #include <map>
  8. #include <memory>
  9. #include <optional>
  10. #include <random>
  11. #include <utility>
  12. #include <vector>
  13. #include "common/check.h"
  14. #include "common/error.h"
  15. #include "explorer/ast/address.h"
  16. #include "explorer/ast/declaration.h"
  17. #include "explorer/ast/element.h"
  18. #include "explorer/ast/expression.h"
  19. #include "explorer/ast/expression_category.h"
  20. #include "explorer/ast/value.h"
  21. #include "explorer/base/arena.h"
  22. #include "explorer/base/error_builders.h"
  23. #include "explorer/base/print_as_id.h"
  24. #include "explorer/base/source_location.h"
  25. #include "explorer/base/trace_stream.h"
  26. #include "explorer/interpreter/action.h"
  27. #include "explorer/interpreter/action_stack.h"
  28. #include "explorer/interpreter/heap.h"
  29. #include "explorer/interpreter/pattern_match.h"
  30. #include "explorer/interpreter/type_utils.h"
  31. #include "llvm/ADT/APInt.h"
  32. #include "llvm/ADT/ArrayRef.h"
  33. #include "llvm/ADT/STLExtras.h"
  34. #include "llvm/ADT/StringExtras.h"
  35. #include "llvm/Support/Casting.h"
  36. #include "llvm/Support/FormatVariadic.h"
  37. #include "llvm/Support/raw_ostream.h"
  38. using llvm::cast;
  39. using llvm::dyn_cast;
  40. using llvm::isa;
  41. namespace Carbon {
  42. // Limits for various overflow conditions.
  43. static constexpr int64_t MaxTodoSize = 1e3;
  44. static constexpr int64_t MaxStepsTaken = 1e6;
  45. static constexpr int64_t MaxArenaAllocated = 1e9;
  46. // Constructs an ActionStack suitable for the specified phase.
  47. static auto MakeTodo(Phase phase, Nonnull<Heap*> heap,
  48. Nonnull<TraceStream*> trace_stream) -> ActionStack {
  49. switch (phase) {
  50. case Phase::CompileTime:
  51. return ActionStack(trace_stream);
  52. case Phase::RunTime:
  53. return ActionStack(trace_stream, heap);
  54. }
  55. }
  56. // An Interpreter represents an instance of the Carbon abstract machine. It
  57. // manages the state of the abstract machine, and executes the steps of Actions
  58. // passed to it.
  59. class Interpreter {
  60. public:
  61. // Constructs an Interpreter which allocates values on `arena`, and prints
  62. // traces if `trace` is true. `phase` indicates whether it executes at
  63. // compile time or run time.
  64. Interpreter(Phase phase, Nonnull<Arena*> arena,
  65. Nonnull<TraceStream*> trace_stream,
  66. Nonnull<llvm::raw_ostream*> print_stream)
  67. : arena_(arena),
  68. heap_(trace_stream, arena),
  69. todo_(MakeTodo(phase, &heap_, trace_stream)),
  70. trace_stream_(trace_stream),
  71. print_stream_(print_stream),
  72. phase_(phase) {}
  73. // Runs all the steps of `action`.
  74. // It's not safe to call `RunAllSteps()` or `result()` after an error.
  75. auto RunAllSteps(std::unique_ptr<Action> action) -> ErrorOr<Success>;
  76. // The result produced by the `action` argument of the most recent
  77. // RunAllSteps call. Cannot be called if `action` was an action that doesn't
  78. // produce results.
  79. auto result() const -> Nonnull<const Value*> { return todo_.result(); }
  80. private:
  81. auto Step() -> ErrorOr<Success>;
  82. // State transitions for expressions value generation.
  83. auto StepValueExp() -> ErrorOr<Success>;
  84. // State transitions for expressions.
  85. auto StepExp() -> ErrorOr<Success>;
  86. // State transitions for lvalues.
  87. auto StepLocation() -> ErrorOr<Success>;
  88. // State transitions for witnesses.
  89. auto StepWitness() -> ErrorOr<Success>;
  90. // State transition for statements.
  91. auto StepStmt() -> ErrorOr<Success>;
  92. // State transition for declarations.
  93. auto StepDeclaration() -> ErrorOr<Success>;
  94. // State transition for object destruction.
  95. auto StepCleanUp() -> ErrorOr<Success>;
  96. auto StepDestroy() -> ErrorOr<Success>;
  97. // State transition for type instantiation.
  98. auto StepInstantiateType() -> ErrorOr<Success>;
  99. auto CreateStruct(const std::vector<FieldInitializer>& fields,
  100. const std::vector<Nonnull<const Value*>>& values)
  101. -> Nonnull<const Value*>;
  102. auto EvalPrim(Operator op, Nonnull<const Value*> static_type,
  103. const std::vector<Nonnull<const Value*>>& args,
  104. SourceLocation source_loc) -> ErrorOr<Nonnull<const Value*>>;
  105. // Returns the result of converting `value` to type `destination_type`.
  106. auto Convert(Nonnull<const Value*> value,
  107. Nonnull<const Value*> destination_type,
  108. SourceLocation source_loc) -> ErrorOr<Nonnull<const Value*>>;
  109. // Create a class value and its base class(es) from an init struct.
  110. auto ConvertStructToClass(Nonnull<const StructValue*> init,
  111. Nonnull<const NominalClassType*> class_type,
  112. SourceLocation source_loc)
  113. -> ErrorOr<Nonnull<const NominalClassValue*>>;
  114. // Evaluate an expression immediately, recursively, and return its result.
  115. //
  116. // TODO: Stop using this.
  117. auto EvalRecursively(std::unique_ptr<Action> action)
  118. -> ErrorOr<Nonnull<const Value*>>;
  119. // Evaluate an associated constant by evaluating its witness and looking
  120. // inside the impl for the corresponding value.
  121. //
  122. // TODO: This approach doesn't provide values that are known because they
  123. // appear in constraints:
  124. //
  125. // interface Iface { let N:! i32; }
  126. // fn PickType(N: i32) -> type { return i32; }
  127. // fn F[T:! Iface where .N == 5](x: T) {
  128. // var x: PickType(T.N) = 0;
  129. // }
  130. //
  131. // ... will fail because we can't resolve T.N to 5 at compile time.
  132. auto EvalAssociatedConstant(Nonnull<const AssociatedConstant*> assoc,
  133. SourceLocation source_loc)
  134. -> ErrorOr<Nonnull<const Value*>>;
  135. // Instantiate a type by replacing all type variables that occur inside the
  136. // type by the current values of those variables.
  137. //
  138. // For example, suppose T=i32 and U=bool. Then
  139. // __Fn (Point(T)) -> Point(U)
  140. // becomes
  141. // __Fn (Point(i32)) -> Point(bool)
  142. //
  143. // TODO: This should be an Action.
  144. auto InstantiateType(Nonnull<const Value*> type, SourceLocation source_loc)
  145. -> ErrorOr<Nonnull<const Value*>>;
  146. // Instantiate a set of bindings by replacing all type variables that occur
  147. // within it by the current values of those variables.
  148. auto InstantiateBindings(Nonnull<const Bindings*> bindings,
  149. SourceLocation source_loc)
  150. -> ErrorOr<Nonnull<const Bindings*>>;
  151. // Instantiate a witness by replacing all type variables and impl binding
  152. // references that occur within it by the current values of those variables.
  153. auto InstantiateWitness(Nonnull<const Witness*> witness,
  154. SourceLocation source_loc)
  155. -> ErrorOr<Nonnull<const Witness*>>;
  156. // Call the function `fun` with the given `arg` and the `witnesses`
  157. // for the function's impl bindings.
  158. auto CallFunction(const CallExpression& call, Nonnull<const Value*> fun,
  159. Nonnull<const Value*> arg, ImplWitnessMap&& witnesses,
  160. std::optional<AllocationId> location_received)
  161. -> ErrorOr<Success>;
  162. // Call the destructor method in `fun`, with any self argument bound to
  163. // `receiver`.
  164. auto CallDestructor(Nonnull<const DestructorDeclaration*> fun,
  165. ExpressionResult receiver) -> ErrorOr<Success>;
  166. // If the given method or destructor `decl` has a self argument, bind it to
  167. // `receiver`.
  168. void BindSelfIfPresent(Nonnull<const CallableDeclaration*> decl,
  169. ExpressionResult receiver, RuntimeScope& method_scope,
  170. BindingMap& generic_args,
  171. const SourceLocation& source_location);
  172. auto phase() const -> Phase { return phase_; }
  173. Nonnull<Arena*> arena_;
  174. Heap heap_;
  175. ActionStack todo_;
  176. Nonnull<TraceStream*> trace_stream_;
  177. // The stream for the Print intrinsic.
  178. Nonnull<llvm::raw_ostream*> print_stream_;
  179. Phase phase_;
  180. // The number of steps taken by the interpreter. Used for infinite loop
  181. // detection.
  182. int64_t steps_taken_ = 0;
  183. };
  184. //
  185. // State Operations
  186. //
  187. auto Interpreter::EvalPrim(Operator op, Nonnull<const Value*> /*static_type*/,
  188. const std::vector<Nonnull<const Value*>>& args,
  189. SourceLocation source_loc)
  190. -> ErrorOr<Nonnull<const Value*>> {
  191. switch (op) {
  192. case Operator::Neg:
  193. case Operator::Add:
  194. case Operator::Sub:
  195. case Operator::Div:
  196. case Operator::Mul: {
  197. llvm::APInt op0(64, cast<IntValue>(*args[0]).value());
  198. llvm::APInt result;
  199. if (op == Operator::Neg) {
  200. result = -op0;
  201. } else {
  202. llvm::APInt op1(64, cast<IntValue>(*args[1]).value());
  203. if (op == Operator::Add) {
  204. result = op0 + op1;
  205. } else if (op == Operator::Sub) {
  206. result = op0 - op1;
  207. } else if (op == Operator::Mul) {
  208. result = op0 * op1;
  209. } else if (op == Operator::Div) {
  210. if (op1.getSExtValue() == 0) {
  211. return ProgramError(source_loc) << "division by zero";
  212. }
  213. result = op0.sdiv(op1);
  214. }
  215. }
  216. if (result.isSignedIntN(32)) {
  217. return arena_->New<IntValue>(result.getSExtValue());
  218. } else {
  219. return ProgramError(source_loc) << "integer overflow";
  220. }
  221. }
  222. case Operator::Mod: {
  223. const auto& lhs = cast<IntValue>(*args[0]).value();
  224. const auto& rhs = cast<IntValue>(*args[1]).value();
  225. if (rhs == 0) {
  226. return ProgramError(source_loc) << "division by zero";
  227. }
  228. return arena_->New<IntValue>(lhs % rhs);
  229. }
  230. case Operator::Not:
  231. return arena_->New<BoolValue>(!cast<BoolValue>(*args[0]).value());
  232. case Operator::And:
  233. return arena_->New<BoolValue>(cast<BoolValue>(*args[0]).value() &&
  234. cast<BoolValue>(*args[1]).value());
  235. case Operator::Or:
  236. return arena_->New<BoolValue>(cast<BoolValue>(*args[0]).value() ||
  237. cast<BoolValue>(*args[1]).value());
  238. case Operator::Ptr:
  239. return arena_->New<PointerType>(args[0]);
  240. case Operator::Deref: {
  241. CARBON_ASSIGN_OR_RETURN(
  242. const auto* value,
  243. heap_.Read(cast<PointerValue>(*args[0]).address(), source_loc));
  244. return arena_->New<ReferenceExpressionValue>(
  245. value, cast<PointerValue>(*args[0]).address());
  246. }
  247. case Operator::AddressOf:
  248. return arena_->New<PointerValue>(cast<LocationValue>(*args[0]).address());
  249. case Operator::As:
  250. case Operator::Eq:
  251. case Operator::NotEq:
  252. case Operator::Less:
  253. case Operator::LessEq:
  254. case Operator::Greater:
  255. case Operator::GreaterEq:
  256. case Operator::BitwiseAnd:
  257. case Operator::BitwiseOr:
  258. case Operator::BitwiseXor:
  259. case Operator::BitShiftLeft:
  260. case Operator::BitShiftRight:
  261. case Operator::Complement:
  262. CARBON_FATAL() << "operator " << OperatorToString(op)
  263. << " should always be rewritten";
  264. }
  265. }
  266. auto Interpreter::CreateStruct(const std::vector<FieldInitializer>& fields,
  267. const std::vector<Nonnull<const Value*>>& values)
  268. -> Nonnull<const Value*> {
  269. std::vector<NamedValue> elements;
  270. for (const auto [field, value] : llvm::zip_equal(fields, values)) {
  271. elements.push_back({field.name(), value});
  272. }
  273. return arena_->New<StructValue>(std::move(elements));
  274. }
  275. auto Interpreter::StepLocation() -> ErrorOr<Success> {
  276. Action& act = todo_.CurrentAction();
  277. const Expression& exp = cast<LocationAction>(act).expression();
  278. switch (exp.kind()) {
  279. case ExpressionKind::IdentifierExpression: {
  280. // { {x :: C, E, F} :: S, H}
  281. // -> { {E(x) :: C, E, F} :: S, H}
  282. CARBON_ASSIGN_OR_RETURN(
  283. Nonnull<const Value*> value,
  284. todo_.ValueOfNode(cast<IdentifierExpression>(exp).value_node(),
  285. exp.source_loc()));
  286. CARBON_CHECK(isa<LocationValue>(value)) << *value;
  287. return todo_.FinishAction(value);
  288. }
  289. case ExpressionKind::SimpleMemberAccessExpression: {
  290. const auto& access = cast<SimpleMemberAccessExpression>(exp);
  291. const auto constant_value = access.constant_value();
  292. if (auto rewrite = access.rewritten_form()) {
  293. return todo_.ReplaceWith(std::make_unique<LocationAction>(*rewrite));
  294. }
  295. if (act.pos() == 0) {
  296. // { {e.f :: C, E, F} :: S, H}
  297. // -> { e :: [].f :: C, E, F} :: S, H}
  298. return todo_.Spawn(std::make_unique<LocationAction>(&access.object()));
  299. } else if (act.pos() == 1 && constant_value) {
  300. return todo_.Spawn(std::make_unique<TypeInstantiationAction>(
  301. *constant_value, access.source_loc()));
  302. } else {
  303. if (constant_value) {
  304. return todo_.FinishAction(act.results().back());
  305. } else {
  306. // { v :: [].f :: C, E, F} :: S, H}
  307. // -> { { &v.f :: C, E, F} :: S, H }
  308. Address object = cast<LocationValue>(*act.results()[0]).address();
  309. Address member = object.ElementAddress(&access.member());
  310. return todo_.FinishAction(arena_->New<LocationValue>(member));
  311. }
  312. }
  313. }
  314. case ExpressionKind::CompoundMemberAccessExpression: {
  315. const auto& access = cast<CompoundMemberAccessExpression>(exp);
  316. const auto constant_value = access.constant_value();
  317. if (act.pos() == 0) {
  318. return todo_.Spawn(std::make_unique<LocationAction>(&access.object()));
  319. }
  320. if (act.pos() == 1 && constant_value) {
  321. return todo_.Spawn(std::make_unique<TypeInstantiationAction>(
  322. *constant_value, access.source_loc()));
  323. } else {
  324. if (constant_value) {
  325. return todo_.FinishAction(act.results().back());
  326. }
  327. CARBON_CHECK(!access.member().interface().has_value())
  328. << "unexpected location interface member";
  329. CARBON_ASSIGN_OR_RETURN(
  330. Nonnull<const Value*> val,
  331. Convert(act.results()[0], *access.member().base_type(),
  332. exp.source_loc()));
  333. Address object = cast<LocationValue>(*val).address();
  334. Address field = object.ElementAddress(&access.member().member());
  335. return todo_.FinishAction(arena_->New<LocationValue>(field));
  336. }
  337. }
  338. case ExpressionKind::BaseAccessExpression: {
  339. const auto& access = cast<BaseAccessExpression>(exp);
  340. if (act.pos() == 0) {
  341. // Get LocationValue for expression.
  342. return todo_.Spawn(std::make_unique<LocationAction>(&access.object()));
  343. } else {
  344. // Append `.base` element to the address, and return the new
  345. // LocationValue.
  346. Address object = cast<LocationValue>(*act.results()[0]).address();
  347. Address base = object.ElementAddress(&access.element());
  348. return todo_.FinishAction(arena_->New<LocationValue>(base));
  349. }
  350. }
  351. case ExpressionKind::IndexExpression: {
  352. if (act.pos() == 0) {
  353. // { {e[i] :: C, E, F} :: S, H}
  354. // -> { e :: [][i] :: C, E, F} :: S, H}
  355. return todo_.Spawn(std::make_unique<LocationAction>(
  356. &cast<IndexExpression>(exp).object()));
  357. } else if (act.pos() == 1) {
  358. return todo_.Spawn(std::make_unique<ValueExpressionAction>(
  359. &cast<IndexExpression>(exp).offset()));
  360. } else {
  361. // { v :: [][i] :: C, E, F} :: S, H}
  362. // -> { { &v[i] :: C, E, F} :: S, H }
  363. Address object = cast<LocationValue>(*act.results()[0]).address();
  364. const auto index = cast<IntValue>(*act.results()[1]).value();
  365. Address field = object.ElementAddress(
  366. arena_->New<PositionalElement>(index, &exp.static_type()));
  367. return todo_.FinishAction(arena_->New<LocationValue>(field));
  368. }
  369. }
  370. case ExpressionKind::OperatorExpression: {
  371. const auto& op = cast<OperatorExpression>(exp);
  372. if (auto rewrite = op.rewritten_form()) {
  373. return todo_.ReplaceWith(std::make_unique<LocationAction>(*rewrite));
  374. }
  375. if (op.op() != Operator::Deref) {
  376. CARBON_FATAL()
  377. << "Can't treat primitive operator expression as location: " << exp;
  378. }
  379. if (act.pos() == 0) {
  380. return todo_.Spawn(
  381. std::make_unique<ValueExpressionAction>(op.arguments()[0]));
  382. } else {
  383. const auto& res = cast<PointerValue>(*act.results()[0]);
  384. return todo_.FinishAction(arena_->New<LocationValue>(res.address()));
  385. }
  386. break;
  387. }
  388. case ExpressionKind::TupleLiteral:
  389. case ExpressionKind::StructLiteral:
  390. case ExpressionKind::StructTypeLiteral:
  391. case ExpressionKind::IntLiteral:
  392. case ExpressionKind::BoolLiteral:
  393. case ExpressionKind::CallExpression:
  394. case ExpressionKind::IntTypeLiteral:
  395. case ExpressionKind::BoolTypeLiteral:
  396. case ExpressionKind::TypeTypeLiteral:
  397. case ExpressionKind::FunctionTypeLiteral:
  398. case ExpressionKind::StringLiteral:
  399. case ExpressionKind::StringTypeLiteral:
  400. case ExpressionKind::ValueLiteral:
  401. case ExpressionKind::IntrinsicExpression:
  402. case ExpressionKind::IfExpression:
  403. case ExpressionKind::WhereExpression:
  404. case ExpressionKind::DotSelfExpression:
  405. case ExpressionKind::ArrayTypeLiteral:
  406. case ExpressionKind::BuiltinConvertExpression:
  407. CARBON_FATAL() << "Can't treat expression as location: " << exp;
  408. case ExpressionKind::UnimplementedExpression:
  409. CARBON_FATAL() << "Unimplemented: " << exp;
  410. }
  411. }
  412. auto Interpreter::EvalRecursively(std::unique_ptr<Action> action)
  413. -> ErrorOr<Nonnull<const Value*>> {
  414. todo_.BeginRecursiveAction();
  415. CARBON_RETURN_IF_ERROR(todo_.Spawn(std::move(action)));
  416. // Note that the only `RecursiveAction` we can encounter here is our own --
  417. // if a nested action begins a recursive action, it will run until that
  418. // action is finished and popped off the queue before returning to us.
  419. while (!isa<RecursiveAction>(todo_.CurrentAction())) {
  420. CARBON_RETURN_IF_ERROR(Step());
  421. }
  422. if (trace_stream_->is_enabled()) {
  423. trace_stream_->End() << "recursive eval done\n";
  424. }
  425. Nonnull<const Value*> result =
  426. cast<RecursiveAction>(todo_.CurrentAction()).results()[0];
  427. CARBON_RETURN_IF_ERROR(todo_.FinishAction());
  428. return result;
  429. }
  430. auto Interpreter::EvalAssociatedConstant(
  431. Nonnull<const AssociatedConstant*> assoc, SourceLocation source_loc)
  432. -> ErrorOr<Nonnull<const Value*>> {
  433. // Instantiate the associated constant.
  434. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> interface,
  435. InstantiateType(&assoc->interface(), source_loc));
  436. CARBON_ASSIGN_OR_RETURN(Nonnull<const Witness*> witness,
  437. InstantiateWitness(&assoc->witness(), source_loc));
  438. const auto* impl_witness = dyn_cast<ImplWitness>(witness);
  439. if (!impl_witness) {
  440. CARBON_CHECK(phase() == Phase::CompileTime)
  441. << "symbolic witnesses should only be formed at compile time";
  442. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> base,
  443. InstantiateType(&assoc->base(), source_loc));
  444. return arena_->New<AssociatedConstant>(base, cast<InterfaceType>(interface),
  445. &assoc->constant(), witness);
  446. }
  447. // We have an impl. Extract the value from it.
  448. Nonnull<const ConstraintType*> constraint =
  449. impl_witness->declaration().constraint_type();
  450. std::optional<Nonnull<const Value*>> result;
  451. for (const auto& rewrite : constraint->rewrite_constraints()) {
  452. if (&rewrite.constant->constant() == &assoc->constant() &&
  453. TypeEqual(&rewrite.constant->interface(), interface, std::nullopt)) {
  454. // TODO: The value might depend on the parameters of the impl. We need to
  455. // substitute impl_witness->type_args() into the value.
  456. result = rewrite.converted_replacement;
  457. break;
  458. }
  459. }
  460. if (!result) {
  461. CARBON_FATAL() << impl_witness->declaration() << " with constraint "
  462. << *constraint
  463. << " is missing value for associated constant "
  464. << *interface << "." << assoc->constant().binding().name();
  465. }
  466. return *result;
  467. }
  468. auto Interpreter::InstantiateType(Nonnull<const Value*> type,
  469. SourceLocation source_loc)
  470. -> ErrorOr<Nonnull<const Value*>> {
  471. if (trace_stream_->is_enabled()) {
  472. trace_stream_->Start() << "instantiating type `" << *type << "` ("
  473. << source_loc << ")\n";
  474. }
  475. switch (type->kind()) {
  476. case Value::Kind::VariableType: {
  477. CARBON_ASSIGN_OR_RETURN(
  478. Nonnull<const Value*> value,
  479. todo_.ValueOfNode(&cast<VariableType>(*type).binding(), source_loc));
  480. if (const auto* location = dyn_cast<LocationValue>(value)) {
  481. CARBON_ASSIGN_OR_RETURN(value,
  482. heap_.Read(location->address(), source_loc));
  483. }
  484. return value;
  485. }
  486. case Value::Kind::InterfaceType: {
  487. const auto& interface_type = cast<InterfaceType>(*type);
  488. CARBON_ASSIGN_OR_RETURN(
  489. Nonnull<const Bindings*> bindings,
  490. InstantiateBindings(&interface_type.bindings(), source_loc));
  491. return arena_->New<InterfaceType>(&interface_type.declaration(),
  492. bindings);
  493. }
  494. case Value::Kind::NamedConstraintType: {
  495. const auto& constraint_type = cast<NamedConstraintType>(*type);
  496. CARBON_ASSIGN_OR_RETURN(
  497. Nonnull<const Bindings*> bindings,
  498. InstantiateBindings(&constraint_type.bindings(), source_loc));
  499. return arena_->New<NamedConstraintType>(&constraint_type.declaration(),
  500. bindings);
  501. }
  502. case Value::Kind::ChoiceType: {
  503. const auto& choice_type = cast<ChoiceType>(*type);
  504. CARBON_ASSIGN_OR_RETURN(
  505. Nonnull<const Bindings*> bindings,
  506. InstantiateBindings(&choice_type.bindings(), source_loc));
  507. return arena_->New<ChoiceType>(&choice_type.declaration(), bindings);
  508. }
  509. case Value::Kind::AssociatedConstant: {
  510. CARBON_ASSIGN_OR_RETURN(
  511. Nonnull<const Value*> type_value,
  512. EvalAssociatedConstant(cast<AssociatedConstant>(type), source_loc));
  513. return type_value;
  514. }
  515. default:
  516. return type;
  517. }
  518. }
  519. auto Interpreter::InstantiateBindings(Nonnull<const Bindings*> bindings,
  520. SourceLocation source_loc)
  521. -> ErrorOr<Nonnull<const Bindings*>> {
  522. BindingMap args = bindings->args();
  523. for (auto& [var, arg] : args) {
  524. CARBON_ASSIGN_OR_RETURN(arg, InstantiateType(arg, source_loc));
  525. }
  526. ImplWitnessMap witnesses = bindings->witnesses();
  527. for (auto& [bind, witness] : witnesses) {
  528. CARBON_ASSIGN_OR_RETURN(
  529. witness, InstantiateWitness(cast<Witness>(witness), source_loc));
  530. }
  531. if (args == bindings->args() && witnesses == bindings->witnesses()) {
  532. return bindings;
  533. }
  534. return arena_->New<Bindings>(std::move(args), std::move(witnesses));
  535. }
  536. auto Interpreter::InstantiateWitness(Nonnull<const Witness*> witness,
  537. SourceLocation source_loc)
  538. -> ErrorOr<Nonnull<const Witness*>> {
  539. CARBON_ASSIGN_OR_RETURN(
  540. Nonnull<const Value*> value,
  541. EvalRecursively(std::make_unique<WitnessAction>(witness, source_loc)));
  542. return cast<Witness>(value);
  543. }
  544. auto Interpreter::ConvertStructToClass(
  545. Nonnull<const StructValue*> init_struct,
  546. Nonnull<const NominalClassType*> class_type, SourceLocation source_loc)
  547. -> ErrorOr<Nonnull<const NominalClassValue*>> {
  548. std::vector<NamedValue> struct_values;
  549. std::optional<Nonnull<const NominalClassValue*>> base_instance;
  550. // Instantiate the `destination_type` to obtain the runtime
  551. // type of the object.
  552. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> inst_class,
  553. InstantiateType(class_type, source_loc));
  554. for (const auto& field : init_struct->elements()) {
  555. if (field.name == NominalClassValue::BaseField) {
  556. CARBON_CHECK(class_type->base().has_value())
  557. << "Invalid 'base' field for class '"
  558. << class_type->declaration().name() << "' without base class.";
  559. CARBON_ASSIGN_OR_RETURN(
  560. auto base,
  561. Convert(field.value, class_type->base().value(), source_loc));
  562. base_instance = cast<NominalClassValue>(base);
  563. } else {
  564. struct_values.push_back(field);
  565. }
  566. }
  567. CARBON_CHECK(!cast<NominalClassType>(inst_class)->base() || base_instance)
  568. << "Invalid conversion for `" << *inst_class << "`: base class missing";
  569. auto* converted_init_struct =
  570. arena_->New<StructValue>(std::move(struct_values));
  571. Nonnull<const NominalClassValue** const> class_value_ptr =
  572. base_instance ? (*base_instance)->class_value_ptr()
  573. : arena_->New<const NominalClassValue*>();
  574. return arena_->New<NominalClassValue>(inst_class, converted_init_struct,
  575. base_instance, class_value_ptr);
  576. }
  577. auto Interpreter::Convert(Nonnull<const Value*> value,
  578. Nonnull<const Value*> destination_type,
  579. SourceLocation source_loc)
  580. -> ErrorOr<Nonnull<const Value*>> {
  581. switch (value->kind()) {
  582. case Value::Kind::IntValue:
  583. case Value::Kind::FunctionValue:
  584. case Value::Kind::DestructorValue:
  585. case Value::Kind::BoundMethodValue:
  586. case Value::Kind::LocationValue:
  587. case Value::Kind::BoolValue:
  588. case Value::Kind::NominalClassValue:
  589. case Value::Kind::AlternativeValue:
  590. case Value::Kind::UninitializedValue:
  591. case Value::Kind::IntType:
  592. case Value::Kind::BoolType:
  593. case Value::Kind::TypeType:
  594. case Value::Kind::FunctionType:
  595. case Value::Kind::PointerType:
  596. case Value::Kind::TupleType:
  597. case Value::Kind::StructType:
  598. case Value::Kind::AutoType:
  599. case Value::Kind::NominalClassType:
  600. case Value::Kind::MixinPseudoType:
  601. case Value::Kind::InterfaceType:
  602. case Value::Kind::NamedConstraintType:
  603. case Value::Kind::ConstraintType:
  604. case Value::Kind::ImplWitness:
  605. case Value::Kind::BindingWitness:
  606. case Value::Kind::ConstraintWitness:
  607. case Value::Kind::ConstraintImplWitness:
  608. case Value::Kind::ParameterizedEntityName:
  609. case Value::Kind::ChoiceType:
  610. case Value::Kind::BindingPlaceholderValue:
  611. case Value::Kind::AddrValue:
  612. case Value::Kind::AlternativeConstructorValue:
  613. case Value::Kind::StringType:
  614. case Value::Kind::StringValue:
  615. case Value::Kind::TypeOfMixinPseudoType:
  616. case Value::Kind::TypeOfParameterizedEntityName:
  617. case Value::Kind::TypeOfMemberName:
  618. case Value::Kind::TypeOfNamespaceName:
  619. case Value::Kind::StaticArrayType:
  620. case Value::Kind::MemberName:
  621. // TODO: add `CARBON_CHECK(TypeEqual(type, value->dynamic_type()))`, once
  622. // we have Value::dynamic_type.
  623. return value;
  624. case Value::Kind::StructValue: {
  625. const auto& struct_val = cast<StructValue>(*value);
  626. switch (destination_type->kind()) {
  627. case Value::Kind::StructType: {
  628. const auto& destination_struct_type =
  629. cast<StructType>(*destination_type);
  630. std::vector<NamedValue> new_elements;
  631. for (const auto& [field_name, field_type] :
  632. destination_struct_type.fields()) {
  633. std::optional<Nonnull<const Value*>> old_value =
  634. struct_val.FindField(field_name);
  635. CARBON_ASSIGN_OR_RETURN(
  636. Nonnull<const Value*> val,
  637. Convert(*old_value, field_type, source_loc));
  638. new_elements.push_back({field_name, val});
  639. }
  640. return arena_->New<StructValue>(std::move(new_elements));
  641. }
  642. case Value::Kind::NominalClassType: {
  643. CARBON_ASSIGN_OR_RETURN(
  644. auto class_value,
  645. ConvertStructToClass(cast<StructValue>(value),
  646. cast<NominalClassType>(destination_type),
  647. source_loc));
  648. return class_value;
  649. }
  650. case Value::Kind::TypeType:
  651. case Value::Kind::ConstraintType:
  652. case Value::Kind::NamedConstraintType:
  653. case Value::Kind::InterfaceType: {
  654. CARBON_CHECK(struct_val.elements().empty())
  655. << "only empty structs convert to `type`";
  656. return arena_->New<StructType>();
  657. }
  658. default: {
  659. CARBON_CHECK(IsValueKindDependent(destination_type) ||
  660. isa<TypeType, ConstraintType>(destination_type))
  661. << "Can't convert value " << *value << " to type "
  662. << *destination_type;
  663. return value;
  664. }
  665. }
  666. }
  667. case Value::Kind::TupleValue: {
  668. const auto* tuple = cast<TupleValue>(value);
  669. std::vector<Nonnull<const Value*>> destination_element_types;
  670. switch (destination_type->kind()) {
  671. case Value::Kind::TupleType:
  672. destination_element_types =
  673. cast<TupleType>(destination_type)->elements();
  674. break;
  675. case Value::Kind::StaticArrayType: {
  676. const auto& array_type = cast<StaticArrayType>(*destination_type);
  677. CARBON_CHECK(array_type.has_size());
  678. destination_element_types.resize(array_type.size(),
  679. &array_type.element_type());
  680. break;
  681. }
  682. case Value::Kind::TypeType:
  683. case Value::Kind::ConstraintType:
  684. case Value::Kind::NamedConstraintType:
  685. case Value::Kind::InterfaceType: {
  686. std::vector<Nonnull<const Value*>> new_elements;
  687. Nonnull<const Value*> type_type = arena_->New<TypeType>();
  688. for (Nonnull<const Value*> value : tuple->elements()) {
  689. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> value_as_type,
  690. Convert(value, type_type, source_loc));
  691. new_elements.push_back(value_as_type);
  692. }
  693. return arena_->New<TupleType>(std::move(new_elements));
  694. }
  695. default: {
  696. CARBON_CHECK(IsValueKindDependent(destination_type) ||
  697. isa<TypeType, ConstraintType>(destination_type))
  698. << "Can't convert value " << *value << " to type "
  699. << *destination_type;
  700. return value;
  701. }
  702. }
  703. std::vector<Nonnull<const Value*>> new_elements;
  704. for (const auto [element, dest_type] :
  705. llvm::zip_equal(tuple->elements(), destination_element_types)) {
  706. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> val,
  707. Convert(element, dest_type, source_loc));
  708. new_elements.push_back(val);
  709. }
  710. return arena_->New<TupleValue>(std::move(new_elements));
  711. }
  712. case Value::Kind::VariableType: {
  713. std::optional<Nonnull<const Value*>> source_type;
  714. // While type-checking a `where` expression, we can evaluate a reference
  715. // to its self binding before we know its type. In this case, the self
  716. // binding is always a type.
  717. //
  718. // TODO: Add a conversion kind to BuiltinConvertExpression so that we
  719. // don't need to look at the types and reconstruct what kind of
  720. // conversion is being performed from here.
  721. if (cast<VariableType>(value)->binding().is_type_checked()) {
  722. CARBON_ASSIGN_OR_RETURN(
  723. source_type,
  724. InstantiateType(&cast<VariableType>(value)->binding().static_type(),
  725. source_loc));
  726. }
  727. if (isa<TypeType, ConstraintType, NamedConstraintType, InterfaceType>(
  728. destination_type) &&
  729. (!source_type ||
  730. isa<TypeType, ConstraintType, NamedConstraintType, InterfaceType>(
  731. *source_type))) {
  732. // No further conversions are required.
  733. return value;
  734. }
  735. // We need to convert this, and we don't know how because we don't have
  736. // the value yet.
  737. return ProgramError(source_loc)
  738. << "value of generic binding " << *value << " is not known";
  739. }
  740. case Value::Kind::AssociatedConstant: {
  741. CARBON_ASSIGN_OR_RETURN(
  742. Nonnull<const Value*> value,
  743. EvalAssociatedConstant(cast<AssociatedConstant>(value), source_loc));
  744. if (const auto* new_const = dyn_cast<AssociatedConstant>(value)) {
  745. // TODO: Detect whether conversions are required in type-checking.
  746. if (isa<TypeType, ConstraintType, NamedConstraintType, InterfaceType>(
  747. destination_type) &&
  748. isa<TypeType, ConstraintType, NamedConstraintType, InterfaceType>(
  749. new_const->constant().static_type())) {
  750. // No further conversions are required.
  751. return value;
  752. }
  753. // We need to convert this, and we don't know how because we don't have
  754. // the value yet.
  755. return ProgramError(source_loc)
  756. << "value of associated constant " << *value << " is not known";
  757. }
  758. return Convert(value, destination_type, source_loc);
  759. }
  760. case Value::Kind::PointerValue: {
  761. if (destination_type->kind() != Value::Kind::PointerType ||
  762. cast<PointerType>(destination_type)->pointee_type().kind() !=
  763. Value::Kind::NominalClassType) {
  764. // No conversion needed.
  765. return value;
  766. }
  767. // Get pointee value.
  768. const auto* src_ptr = cast<PointerValue>(value);
  769. CARBON_ASSIGN_OR_RETURN(const auto* pointee,
  770. heap_.Read(src_ptr->address(), source_loc))
  771. CARBON_CHECK(pointee->kind() == Value::Kind::NominalClassValue)
  772. << "Unexpected pointer type";
  773. // Conversion logic for subtyping for function arguments only.
  774. // TODO: Drop when able to rewrite subtyping in TypeChecker for arguments.
  775. const auto* dest_ptr = cast<PointerType>(destination_type);
  776. std::optional<Nonnull<const NominalClassValue*>> class_subobj =
  777. cast<NominalClassValue>(pointee);
  778. auto new_addr = src_ptr->address();
  779. while (class_subobj) {
  780. if (TypeEqual(&(*class_subobj)->type(), &dest_ptr->pointee_type(),
  781. std::nullopt)) {
  782. return arena_->New<PointerValue>(new_addr);
  783. }
  784. class_subobj = (*class_subobj)->base();
  785. new_addr = new_addr.ElementAddress(
  786. arena_->New<BaseElement>(&dest_ptr->pointee_type()));
  787. }
  788. // Unable to resolve, return as-is.
  789. // TODO: Produce error instead once we can properly substitute
  790. // parameterized types for pointers in function call parameters.
  791. return value;
  792. }
  793. case Value::Kind::ReferenceExpressionValue: {
  794. const auto* expr_value = cast<ReferenceExpressionValue>(value);
  795. CARBON_ASSIGN_OR_RETURN(
  796. Nonnull<const Value*> converted,
  797. Convert(expr_value->value(), destination_type, source_loc));
  798. if (converted == expr_value->value()) {
  799. return expr_value;
  800. } else {
  801. return converted;
  802. }
  803. }
  804. }
  805. }
  806. auto Interpreter::CallFunction(const CallExpression& call,
  807. Nonnull<const Value*> fun,
  808. Nonnull<const Value*> arg,
  809. ImplWitnessMap&& witnesses,
  810. std::optional<AllocationId> location_received)
  811. -> ErrorOr<Success> {
  812. if (trace_stream_->is_enabled()) {
  813. trace_stream_->Call() << "calling function: " << *fun << "\n";
  814. }
  815. switch (fun->kind()) {
  816. case Value::Kind::AlternativeConstructorValue: {
  817. const auto& alt = cast<AlternativeConstructorValue>(*fun);
  818. return todo_.FinishAction(arena_->New<AlternativeValue>(
  819. &alt.choice(), &alt.alternative(), cast<TupleValue>(arg)));
  820. }
  821. case Value::Kind::FunctionValue:
  822. case Value::Kind::BoundMethodValue: {
  823. const auto* func_val = cast<FunctionOrMethodValue>(fun);
  824. const FunctionDeclaration& function = func_val->declaration();
  825. if (!function.body().has_value()) {
  826. return ProgramError(call.source_loc())
  827. << "attempt to call function `" << function.name()
  828. << "` that has not been defined";
  829. }
  830. if (!function.is_type_checked()) {
  831. return ProgramError(call.source_loc())
  832. << "attempt to call function `" << function.name()
  833. << "` that has not been fully type-checked";
  834. }
  835. // Enter the binding scope to make any deduced arguments visible before
  836. // we resolve the self type and parameter type.
  837. auto& binding_scope = todo_.CurrentAction().scope().value();
  838. // Bring the deduced arguments and their witnesses into scope.
  839. for (const auto& [bind, val] : call.deduced_args()) {
  840. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> inst_val,
  841. InstantiateType(val, call.source_loc()));
  842. binding_scope.BindValue(bind->original(), inst_val);
  843. }
  844. for (const auto& [impl_bind, witness] : witnesses) {
  845. binding_scope.BindValue(impl_bind->original(), witness);
  846. }
  847. // Bring the arguments that are determined by the function value into
  848. // scope. This includes the arguments for the class of which the function
  849. // is a member.
  850. for (const auto& [bind, val] : func_val->type_args()) {
  851. binding_scope.BindValue(bind->original(), val);
  852. }
  853. for (const auto& [impl_bind, witness] : func_val->witnesses()) {
  854. binding_scope.BindValue(impl_bind->original(), witness);
  855. }
  856. RuntimeScope function_scope(&heap_);
  857. BindingMap generic_args;
  858. // Bind the receiver to the `self` parameter, if there is one.
  859. if (const auto* method_val = dyn_cast<BoundMethodValue>(func_val)) {
  860. BindSelfIfPresent(&function,
  861. ExpressionResult::Value(method_val->receiver()),
  862. function_scope, generic_args, call.source_loc());
  863. }
  864. CARBON_ASSIGN_OR_RETURN(
  865. Nonnull<const Value*> converted_args,
  866. Convert(arg, &function.param_pattern().static_type(),
  867. call.source_loc()));
  868. // Bind the arguments to the parameters.
  869. bool success = PatternMatch(&function.param_pattern().value(),
  870. ExpressionResult::Value(converted_args),
  871. call.source_loc(), &function_scope,
  872. generic_args, trace_stream_, this->arena_);
  873. CARBON_CHECK(success) << "Failed to bind arguments to parameters";
  874. return todo_.Spawn(std::make_unique<StatementAction>(*function.body(),
  875. location_received),
  876. std::move(function_scope));
  877. }
  878. case Value::Kind::ParameterizedEntityName: {
  879. const auto& name = cast<ParameterizedEntityName>(*fun);
  880. const Declaration& decl = name.declaration();
  881. RuntimeScope params_scope(&heap_);
  882. BindingMap generic_args;
  883. CARBON_CHECK(PatternMatch(&name.params().value(),
  884. ExpressionResult::Value(arg), call.source_loc(),
  885. &params_scope, generic_args, trace_stream_,
  886. this->arena_));
  887. Nonnull<const Bindings*> bindings =
  888. arena_->New<Bindings>(std::move(generic_args), std::move(witnesses));
  889. switch (decl.kind()) {
  890. case DeclarationKind::ClassDeclaration: {
  891. const auto& class_decl = cast<ClassDeclaration>(decl);
  892. return todo_.FinishAction(arena_->New<NominalClassType>(
  893. &class_decl, bindings, class_decl.base_type(), EmptyVTable()));
  894. }
  895. case DeclarationKind::InterfaceDeclaration:
  896. return todo_.FinishAction(arena_->New<InterfaceType>(
  897. &cast<InterfaceDeclaration>(decl), bindings));
  898. case DeclarationKind::ConstraintDeclaration:
  899. return todo_.FinishAction(arena_->New<NamedConstraintType>(
  900. &cast<ConstraintDeclaration>(decl), bindings));
  901. case DeclarationKind::ChoiceDeclaration:
  902. return todo_.FinishAction(arena_->New<ChoiceType>(
  903. &cast<ChoiceDeclaration>(decl), bindings));
  904. default:
  905. CARBON_FATAL() << "unknown kind of ParameterizedEntityName " << decl;
  906. }
  907. }
  908. default:
  909. return ProgramError(call.source_loc())
  910. << "in call, expected a function, not " << *fun;
  911. }
  912. }
  913. auto Interpreter::CallDestructor(Nonnull<const DestructorDeclaration*> fun,
  914. ExpressionResult receiver)
  915. -> ErrorOr<Success> {
  916. const DestructorDeclaration& method = *fun;
  917. CARBON_CHECK(method.is_method());
  918. RuntimeScope method_scope(&heap_);
  919. BindingMap generic_args;
  920. BindSelfIfPresent(fun, receiver, method_scope, generic_args,
  921. SourceLocation::DiagnosticsIgnored());
  922. CARBON_CHECK(method.body().has_value())
  923. << "Calling a method that's missing a body";
  924. auto act = std::make_unique<StatementAction>(*method.body(), std::nullopt);
  925. return todo_.Spawn(std::unique_ptr<Action>(std::move(act)),
  926. std::move(method_scope));
  927. }
  928. void Interpreter::BindSelfIfPresent(Nonnull<const CallableDeclaration*> decl,
  929. ExpressionResult receiver,
  930. RuntimeScope& method_scope,
  931. BindingMap& generic_args,
  932. const SourceLocation& source_location) {
  933. CARBON_CHECK(decl->is_method());
  934. const auto* self_pattern = &decl->self_pattern().value();
  935. if (const auto* placeholder =
  936. dyn_cast<BindingPlaceholderValue>(self_pattern)) {
  937. // Immutable self with `[self: Self]`
  938. if (placeholder->value_node().has_value()) {
  939. bool success =
  940. PatternMatch(placeholder, receiver, source_location, &method_scope,
  941. generic_args, trace_stream_, this->arena_);
  942. CARBON_CHECK(success) << "Failed to bind self";
  943. }
  944. } else {
  945. // Mutable self with `[addr self: Self*]`
  946. CARBON_CHECK(isa<AddrValue>(self_pattern));
  947. ExpressionResult v = receiver;
  948. // See if we need to make a LocationValue from the address provided in the
  949. // ExpressionResult
  950. if (receiver.value()->kind() != Value::Kind::LocationValue) {
  951. CARBON_CHECK(receiver.expression_category() ==
  952. ExpressionCategory::Reference);
  953. CARBON_CHECK(receiver.address().has_value());
  954. v = ExpressionResult::Value(
  955. arena_->New<LocationValue>(receiver.address().value()));
  956. }
  957. bool success = PatternMatch(self_pattern, v, source_location, &method_scope,
  958. generic_args, trace_stream_, this->arena_);
  959. CARBON_CHECK(success) << "Failed to bind addr self";
  960. }
  961. }
  962. // Returns true if the format string is okay to pass to formatv. This only
  963. // supports `{{` and `{N}` as special syntax.
  964. static auto ValidateFormatString(SourceLocation source_loc,
  965. const char* format_string, int num_args)
  966. -> ErrorOr<Success> {
  967. const char* cursor = format_string;
  968. while (true) {
  969. switch (*cursor) {
  970. case '\0':
  971. // End of string.
  972. return Success();
  973. case '{':
  974. // `{` is a special character.
  975. ++cursor;
  976. switch (*cursor) {
  977. case '\0':
  978. return ProgramError(source_loc)
  979. << "`{` must be followed by a second `{` or index in `"
  980. << format_string << "`";
  981. case '{':
  982. // Escaped `{`.
  983. ++cursor;
  984. break;
  985. case '}':
  986. return ProgramError(source_loc)
  987. << "Invalid `{}` in `" << format_string << "`";
  988. default:
  989. int index = 0;
  990. while (*cursor != '}') {
  991. if (*cursor == '\0') {
  992. return ProgramError(source_loc)
  993. << "Index incomplete in `" << format_string << "`";
  994. }
  995. if (*cursor < '0' || *cursor > '9') {
  996. return ProgramError(source_loc)
  997. << "Non-numeric character in index at offset "
  998. << cursor - format_string << " in `" << format_string
  999. << "`";
  1000. }
  1001. index = (10 * index) + (*cursor - '0');
  1002. if (index >= num_args) {
  1003. return ProgramError(source_loc)
  1004. << "Index invalid with argument count of " << num_args
  1005. << " at offset " << cursor - format_string << " in `"
  1006. << format_string << "`";
  1007. }
  1008. ++cursor;
  1009. }
  1010. // Move past the `}`.
  1011. ++cursor;
  1012. }
  1013. break;
  1014. default:
  1015. // Arbitrary text.
  1016. ++cursor;
  1017. }
  1018. }
  1019. llvm_unreachable("Loop returns directly");
  1020. }
  1021. auto Interpreter::StepInstantiateType() -> ErrorOr<Success> {
  1022. const Action& act = todo_.CurrentAction();
  1023. const Nonnull<const Value*> type = cast<TypeInstantiationAction>(act).type();
  1024. SourceLocation source_loc = cast<TypeInstantiationAction>(act).source_loc();
  1025. switch (type->kind()) {
  1026. case Value::Kind::NominalClassType: {
  1027. const auto& class_type = cast<NominalClassType>(*type);
  1028. std::optional<Nonnull<const NominalClassType*>> base = class_type.base();
  1029. if (act.pos() == 0 && base.has_value()) {
  1030. return todo_.Spawn(std::make_unique<TypeInstantiationAction>(
  1031. base.value(), source_loc));
  1032. } else {
  1033. if (base.has_value()) {
  1034. base = cast<NominalClassType>(act.results().back());
  1035. }
  1036. CARBON_ASSIGN_OR_RETURN(
  1037. Nonnull<const Bindings*> bindings,
  1038. InstantiateBindings(&class_type.bindings(), source_loc));
  1039. return todo_.FinishAction(arena_->New<NominalClassType>(
  1040. &class_type.declaration(), bindings, base, &class_type.vtable()));
  1041. }
  1042. }
  1043. case Value::Kind::PointerType: {
  1044. const auto* ptr = cast<PointerType>(type);
  1045. if (act.pos() == 0) {
  1046. return todo_.Spawn(std::make_unique<TypeInstantiationAction>(
  1047. &ptr->pointee_type(), source_loc));
  1048. } else {
  1049. const auto* actual_type = act.results().back();
  1050. return todo_.FinishAction(arena_->New<PointerType>(actual_type));
  1051. }
  1052. }
  1053. default:
  1054. CARBON_ASSIGN_OR_RETURN(auto inst_type, InstantiateType(type, source_loc))
  1055. return todo_.FinishAction(inst_type);
  1056. }
  1057. }
  1058. auto Interpreter::StepValueExp() -> ErrorOr<Success> {
  1059. auto& act = cast<ValueExpressionAction>(todo_.CurrentAction());
  1060. if (act.pos() == 0) {
  1061. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1062. &act.expression(), /*preserve_nested_categories=*/false,
  1063. act.location_received()));
  1064. } else {
  1065. CARBON_CHECK(act.results().size() == 1);
  1066. if (const auto* expr_value =
  1067. dyn_cast<ReferenceExpressionValue>(act.results()[0])) {
  1068. // Unwrap the ExpressionAction to only keep the resulting
  1069. // `Value*`.
  1070. return todo_.FinishAction(expr_value->value());
  1071. } else {
  1072. return todo_.FinishAction(act.results()[0]);
  1073. }
  1074. }
  1075. }
  1076. auto Interpreter::StepExp() -> ErrorOr<Success> {
  1077. auto& act = cast<ExpressionAction>(todo_.CurrentAction());
  1078. const Expression& exp = act.expression();
  1079. switch (exp.kind()) {
  1080. case ExpressionKind::IndexExpression: {
  1081. if (act.pos() == 0) {
  1082. // { { e[i] :: C, E, F} :: S, H}
  1083. // -> { { e :: [][i] :: C, E, F} :: S, H}
  1084. return todo_.Spawn(std::make_unique<ValueExpressionAction>(
  1085. &cast<IndexExpression>(exp).object()));
  1086. } else if (act.pos() == 1) {
  1087. return todo_.Spawn(std::make_unique<ValueExpressionAction>(
  1088. &cast<IndexExpression>(exp).offset()));
  1089. } else {
  1090. // { { v :: [][i] :: C, E, F} :: S, H}
  1091. // -> { { v_i :: C, E, F} : S, H}
  1092. CARBON_ASSIGN_OR_RETURN(
  1093. auto converted,
  1094. Convert(act.results()[0],
  1095. &cast<IndexExpression>(exp).object().static_type(),
  1096. exp.source_loc()));
  1097. const auto& tuple = cast<TupleValue>(*converted);
  1098. int i = cast<IntValue>(*act.results()[1]).value();
  1099. if (i < 0 || i >= static_cast<int>(tuple.elements().size())) {
  1100. return ProgramError(exp.source_loc())
  1101. << "index " << i << " out of range in " << tuple;
  1102. }
  1103. return todo_.FinishAction(tuple.elements()[i]);
  1104. }
  1105. }
  1106. case ExpressionKind::TupleLiteral: {
  1107. if (act.pos() <
  1108. static_cast<int>(cast<TupleLiteral>(exp).fields().size())) {
  1109. // { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
  1110. // H}
  1111. // -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
  1112. // H}
  1113. const auto* field = cast<TupleLiteral>(exp).fields()[act.pos()];
  1114. if (act.preserve_nested_categories()) {
  1115. return todo_.Spawn(std::make_unique<ExpressionAction>(field, false));
  1116. } else {
  1117. return todo_.Spawn(std::make_unique<ValueExpressionAction>(field));
  1118. }
  1119. } else {
  1120. return todo_.FinishAction(arena_->New<TupleValue>(act.results()));
  1121. }
  1122. }
  1123. case ExpressionKind::StructLiteral: {
  1124. const auto& literal = cast<StructLiteral>(exp);
  1125. if (act.pos() < static_cast<int>(literal.fields().size())) {
  1126. return todo_.Spawn(std::make_unique<ValueExpressionAction>(
  1127. &literal.fields()[act.pos()].expression()));
  1128. } else {
  1129. return todo_.FinishAction(
  1130. CreateStruct(literal.fields(), act.results()));
  1131. }
  1132. }
  1133. case ExpressionKind::SimpleMemberAccessExpression: {
  1134. const auto& access = cast<SimpleMemberAccessExpression>(exp);
  1135. if (auto rewrite = access.rewritten_form()) {
  1136. return todo_.ReplaceWith(std::make_unique<ExpressionAction>(
  1137. *rewrite, act.preserve_nested_categories(),
  1138. act.location_received()));
  1139. }
  1140. if (act.pos() == 0) {
  1141. // First, evaluate the first operand.
  1142. if (access.is_addr_me_method()) {
  1143. return todo_.Spawn(
  1144. std::make_unique<LocationAction>(&access.object()));
  1145. } else {
  1146. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1147. &access.object(), /*preserve_nested_categories=*/false));
  1148. }
  1149. } else {
  1150. if (auto constant_value = access.constant_value()) {
  1151. if (act.pos() == 1) {
  1152. return todo_.Spawn(std::make_unique<TypeInstantiationAction>(
  1153. *constant_value, access.source_loc()));
  1154. } else {
  1155. return todo_.FinishAction(act.results().back());
  1156. }
  1157. } else if (const auto* member_name_type =
  1158. dyn_cast<TypeOfMemberName>(&access.static_type())) {
  1159. // The result is a member name, such as in `Type.field_name`. Form a
  1160. // suitable member name value.
  1161. CARBON_CHECK(phase() == Phase::CompileTime)
  1162. << "should not form MemberNames at runtime";
  1163. auto found_in_interface = access.found_in_interface();
  1164. if (act.pos() == 1 && found_in_interface) {
  1165. return todo_.Spawn(std::make_unique<TypeInstantiationAction>(
  1166. *found_in_interface, exp.source_loc()));
  1167. } else {
  1168. if (found_in_interface) {
  1169. found_in_interface = cast<InterfaceType>(act.results().back());
  1170. }
  1171. std::optional<const Value*> type_result;
  1172. const auto* result =
  1173. act.results()[0]->kind() ==
  1174. Value::Kind::ReferenceExpressionValue
  1175. ? cast<ReferenceExpressionValue>(act.results()[0])->value()
  1176. : act.results()[0];
  1177. if (!isa<InterfaceType, NamedConstraintType, ConstraintType>(
  1178. result)) {
  1179. type_result = result;
  1180. }
  1181. const auto* member_name = arena_->New<MemberName>(
  1182. type_result, found_in_interface, &member_name_type->member());
  1183. return todo_.FinishAction(member_name);
  1184. }
  1185. } else {
  1186. // The result is the value of the named field, such as in
  1187. // `value.field_name`. Extract the value within the given object.
  1188. auto impl_has_value = access.impl().has_value();
  1189. if (act.pos() == 1) {
  1190. // Next, if we're accessing an interface member, evaluate the `impl`
  1191. // expression to find the corresponding witness.
  1192. if (impl_has_value) {
  1193. return todo_.Spawn(std::make_unique<WitnessAction>(
  1194. access.impl().value(), access.source_loc()));
  1195. } else {
  1196. return todo_.RunAgain();
  1197. }
  1198. } else if (act.pos() == 2) {
  1199. if (auto found_in_interface = access.found_in_interface()) {
  1200. return todo_.Spawn(std::make_unique<TypeInstantiationAction>(
  1201. *found_in_interface, exp.source_loc()));
  1202. } else {
  1203. return todo_.RunAgain();
  1204. }
  1205. } else if (act.pos() == 3) {
  1206. if (access.is_type_access()) {
  1207. return todo_.Spawn(std::make_unique<TypeInstantiationAction>(
  1208. &access.object().static_type(), access.source_loc()));
  1209. } else {
  1210. return todo_.RunAgain();
  1211. }
  1212. } else {
  1213. auto found_in_interface = access.found_in_interface();
  1214. if (found_in_interface) {
  1215. found_in_interface = cast<InterfaceType>(
  1216. impl_has_value ? act.results()[2] : act.results()[1]);
  1217. }
  1218. std::optional<Nonnull<const Witness*>> witness;
  1219. if (access.impl().has_value()) {
  1220. witness = cast<Witness>(act.results()[1]);
  1221. }
  1222. ElementPath::Component member(&access.member(), found_in_interface,
  1223. witness);
  1224. const Value* aggregate;
  1225. std::optional<Nonnull<const Value*>> me_value;
  1226. std::optional<Address> lhs_address;
  1227. if (access.is_type_access()) {
  1228. aggregate = act.results().back();
  1229. } else if (const auto* location =
  1230. dyn_cast<LocationValue>(act.results()[0])) {
  1231. lhs_address = location->address();
  1232. me_value = act.results()[0];
  1233. CARBON_ASSIGN_OR_RETURN(
  1234. aggregate,
  1235. this->heap_.Read(location->address(), exp.source_loc()));
  1236. } else if (const auto* expr_value =
  1237. dyn_cast<ReferenceExpressionValue>(
  1238. act.results()[0])) {
  1239. lhs_address = expr_value->address();
  1240. aggregate = expr_value->value();
  1241. me_value = aggregate;
  1242. } else {
  1243. aggregate = act.results()[0];
  1244. me_value = aggregate;
  1245. }
  1246. CARBON_ASSIGN_OR_RETURN(
  1247. Nonnull<const Value*> member_value,
  1248. aggregate->GetElement(arena_, ElementPath(member),
  1249. exp.source_loc(), me_value));
  1250. if (lhs_address) {
  1251. return todo_.FinishAction(arena_->New<ReferenceExpressionValue>(
  1252. member_value, lhs_address->ElementAddress(member.element())));
  1253. } else {
  1254. return todo_.FinishAction(member_value);
  1255. }
  1256. }
  1257. }
  1258. }
  1259. }
  1260. case ExpressionKind::CompoundMemberAccessExpression: {
  1261. const auto& access = cast<CompoundMemberAccessExpression>(exp);
  1262. bool forming_member_name = isa<TypeOfMemberName>(&access.static_type());
  1263. if (act.pos() == 0) {
  1264. // First, evaluate the first operand.
  1265. if (access.is_addr_me_method()) {
  1266. return todo_.Spawn(
  1267. std::make_unique<LocationAction>(&access.object()));
  1268. } else {
  1269. return todo_.Spawn(
  1270. std::make_unique<ValueExpressionAction>(&access.object()));
  1271. }
  1272. } else {
  1273. if (auto constant_value = access.constant_value()) {
  1274. if (act.pos() == 1) {
  1275. return todo_.Spawn(std::make_unique<TypeInstantiationAction>(
  1276. *constant_value, access.source_loc()));
  1277. } else {
  1278. return todo_.FinishAction(act.results().back());
  1279. }
  1280. } else if (forming_member_name) {
  1281. CARBON_CHECK(phase() == Phase::CompileTime)
  1282. << "should not form MemberNames at runtime";
  1283. if (auto found_in_interface = access.member().interface();
  1284. found_in_interface && act.pos() == 1) {
  1285. return todo_.Spawn(std::make_unique<TypeInstantiationAction>(
  1286. *found_in_interface, exp.source_loc()));
  1287. } else {
  1288. // If we're forming a member name, we must be in the outer
  1289. // evaluation in `Type.(Interface.method)`. Produce the same method
  1290. // name with its `type` field set.
  1291. if (found_in_interface) {
  1292. found_in_interface = cast<InterfaceType>(act.results().back());
  1293. }
  1294. CARBON_CHECK(!access.member().base_type().has_value())
  1295. << "compound member access forming a member name should be "
  1296. "performing impl lookup";
  1297. auto* member_name =
  1298. arena_->New<MemberName>(act.results()[0], found_in_interface,
  1299. &access.member().member());
  1300. return todo_.FinishAction(member_name);
  1301. }
  1302. } else {
  1303. auto impl_has_value = access.impl().has_value();
  1304. if (act.pos() == 1) {
  1305. if (impl_has_value) {
  1306. // Next, if we're accessing an interface member, evaluate the
  1307. // `impl` expression to find the corresponding witness.
  1308. return todo_.Spawn(std::make_unique<WitnessAction>(
  1309. access.impl().value(), access.source_loc()));
  1310. } else {
  1311. return todo_.RunAgain();
  1312. }
  1313. } else if (act.pos() == 2) {
  1314. if (auto found_in_interface = access.member().interface()) {
  1315. return todo_.Spawn(std::make_unique<TypeInstantiationAction>(
  1316. *found_in_interface, exp.source_loc()));
  1317. } else {
  1318. return todo_.RunAgain();
  1319. }
  1320. } else if (act.pos() == 3) {
  1321. if (access.is_type_access()) {
  1322. return todo_.Spawn(std::make_unique<TypeInstantiationAction>(
  1323. &access.object().static_type(), access.source_loc()));
  1324. } else {
  1325. return todo_.RunAgain();
  1326. }
  1327. } else {
  1328. // Access the object to find the named member.
  1329. auto found_in_interface = access.member().interface();
  1330. if (found_in_interface) {
  1331. found_in_interface = cast<InterfaceType>(
  1332. impl_has_value ? act.results()[2] : act.results()[1]);
  1333. }
  1334. Nonnull<const Value*> object = act.results()[0];
  1335. if (access.is_type_access()) {
  1336. object = act.results().back();
  1337. }
  1338. std::optional<Nonnull<const Witness*>> witness;
  1339. if (access.impl().has_value()) {
  1340. witness = cast<Witness>(act.results()[1]);
  1341. } else {
  1342. CARBON_CHECK(access.member().base_type().has_value())
  1343. << "compound access should have base type or impl";
  1344. CARBON_ASSIGN_OR_RETURN(
  1345. object, Convert(object, *access.member().base_type(),
  1346. exp.source_loc()));
  1347. }
  1348. ElementPath::Component field(&access.member().member(),
  1349. found_in_interface, witness);
  1350. CARBON_ASSIGN_OR_RETURN(
  1351. Nonnull<const Value*> member,
  1352. object->GetElement(arena_, ElementPath(field), exp.source_loc(),
  1353. object));
  1354. return todo_.FinishAction(member);
  1355. }
  1356. }
  1357. }
  1358. }
  1359. case ExpressionKind::BaseAccessExpression: {
  1360. const auto& access = cast<BaseAccessExpression>(exp);
  1361. if (act.pos() == 0) {
  1362. return todo_.Spawn(
  1363. std::make_unique<ValueExpressionAction>(&access.object()));
  1364. } else {
  1365. ElementPath::Component base_elt(&access.element(), std::nullopt,
  1366. std::nullopt);
  1367. const Value* value = act.results()[0];
  1368. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> base_value,
  1369. value->GetElement(arena_, ElementPath(base_elt),
  1370. exp.source_loc(), value));
  1371. return todo_.FinishAction(base_value);
  1372. }
  1373. }
  1374. case ExpressionKind::IdentifierExpression: {
  1375. CARBON_CHECK(act.pos() == 0);
  1376. const auto& ident = cast<IdentifierExpression>(exp);
  1377. // { {x :: C, E, F} :: S, H} -> { {H(E(x)) :: C, E, F} :: S, H}
  1378. CARBON_ASSIGN_OR_RETURN(
  1379. Nonnull<const Value*> value,
  1380. todo_.ValueOfNode(ident.value_node(), ident.source_loc()));
  1381. if (const auto* location = dyn_cast<LocationValue>(value)) {
  1382. CARBON_ASSIGN_OR_RETURN(
  1383. value, heap_.Read(location->address(), exp.source_loc()));
  1384. if (ident.expression_category() == ExpressionCategory::Reference) {
  1385. return todo_.FinishAction(arena_->New<ReferenceExpressionValue>(
  1386. value, location->address()));
  1387. }
  1388. }
  1389. return todo_.FinishAction(value);
  1390. }
  1391. case ExpressionKind::DotSelfExpression: {
  1392. CARBON_CHECK(act.pos() == 0);
  1393. const auto& dot_self = cast<DotSelfExpression>(exp);
  1394. return todo_.FinishAction(*dot_self.self_binding().symbolic_identity());
  1395. }
  1396. case ExpressionKind::IntLiteral:
  1397. CARBON_CHECK(act.pos() == 0);
  1398. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  1399. return todo_.FinishAction(
  1400. arena_->New<IntValue>(cast<IntLiteral>(exp).value()));
  1401. case ExpressionKind::BoolLiteral:
  1402. CARBON_CHECK(act.pos() == 0);
  1403. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  1404. return todo_.FinishAction(
  1405. arena_->New<BoolValue>(cast<BoolLiteral>(exp).value()));
  1406. case ExpressionKind::OperatorExpression: {
  1407. const auto& op = cast<OperatorExpression>(exp);
  1408. if (auto rewrite = op.rewritten_form()) {
  1409. return todo_.ReplaceWith(std::make_unique<ExpressionAction>(
  1410. *rewrite, act.preserve_nested_categories(),
  1411. act.location_received()));
  1412. }
  1413. if (act.pos() != static_cast<int>(op.arguments().size())) {
  1414. // { {v :: op(vs,[],e,es) :: C, E, F} :: S, H}
  1415. // -> { {e :: op(vs,v,[],es) :: C, E, F} :: S, H}
  1416. Nonnull<const Expression*> arg = op.arguments()[act.pos()];
  1417. if (op.op() == Operator::AddressOf) {
  1418. return todo_.Spawn(std::make_unique<LocationAction>(arg));
  1419. } else if ((op.op() == Operator::And || op.op() == Operator::Or) &&
  1420. act.pos() == 1) {
  1421. // Short-circuit evaluation for 'and' & 'or'
  1422. const auto* operand_value =
  1423. cast<BoolValue>(act.results()[act.pos() - 1]);
  1424. if ((op.op() == Operator::Or && operand_value->value()) ||
  1425. (op.op() == Operator::And && !operand_value->value())) {
  1426. return todo_.FinishAction(operand_value);
  1427. }
  1428. // No short-circuit, fall through to evaluate 2nd operand.
  1429. }
  1430. return todo_.Spawn(std::make_unique<ValueExpressionAction>(arg));
  1431. } else {
  1432. // { {v :: op(vs,[]) :: C, E, F} :: S, H}
  1433. // -> { {eval_prim(op, (vs,v)) :: C, E, F} :: S, H}
  1434. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> value,
  1435. EvalPrim(op.op(), &op.static_type(),
  1436. act.results(), exp.source_loc()));
  1437. return todo_.FinishAction(value);
  1438. }
  1439. }
  1440. case ExpressionKind::CallExpression: {
  1441. const auto& call = cast<CallExpression>(exp);
  1442. CARBON_CHECK(call.argument().kind() == ExpressionKind::TupleLiteral);
  1443. const auto& args = cast<TupleLiteral>(call.argument());
  1444. const int num_args = args.fields().size();
  1445. const int num_witnesses = call.witnesses().size();
  1446. const int function_call_pos = 1 + num_args + num_witnesses;
  1447. if (act.pos() == 0) {
  1448. // { {e1(e2) :: C, E, F} :: S, H}
  1449. // -> { {e1 :: [](e2) :: C, E, F} :: S, H}
  1450. act.StartScope(RuntimeScope(&heap_));
  1451. return todo_.Spawn(
  1452. std::make_unique<ValueExpressionAction>(&call.function()));
  1453. } else if (act.pos() < 1 + num_args) {
  1454. const auto* field = args.fields()[act.pos() - 1];
  1455. std::optional<AllocationId> alloc;
  1456. if (field->expression_category() == ExpressionCategory::Initializing) {
  1457. alloc = heap_.AllocateValue(
  1458. arena_->New<UninitializedValue>(&field->static_type()));
  1459. act.scope()->BindLifetimeToScope(Address(*alloc));
  1460. }
  1461. return todo_.Spawn(
  1462. std::make_unique<ExpressionAction>(field, false, alloc));
  1463. } else if (act.pos() < function_call_pos) {
  1464. auto iter = call.witnesses().begin();
  1465. std::advance(iter, act.pos() - 1 - num_args);
  1466. return todo_.Spawn(std::make_unique<WitnessAction>(
  1467. cast<Witness>(iter->second), call.source_loc()));
  1468. } else if (act.pos() == function_call_pos) {
  1469. // { { v2 :: v1([]) :: C, E, F} :: S, H}
  1470. // -> { {C',E',F'} :: {C, E, F} :: S, H}
  1471. // Prepare parameters tuple.
  1472. std::vector<Nonnull<const Value*>> param_values;
  1473. for (const auto& arg_result :
  1474. llvm::ArrayRef(act.results()).slice(1, num_args)) {
  1475. param_values.push_back(arg_result);
  1476. }
  1477. const auto* param_tuple = arena_->New<TupleValue>(param_values);
  1478. // Prepare witnesses.
  1479. ImplWitnessMap witnesses;
  1480. if (num_witnesses > 0) {
  1481. for (const auto [witness, result] : llvm::zip(
  1482. call.witnesses(),
  1483. llvm::ArrayRef(act.results()).drop_front(1 + num_args))) {
  1484. witnesses[witness.first] = result;
  1485. }
  1486. }
  1487. return CallFunction(call, act.results()[0], param_tuple,
  1488. std::move(witnesses), act.location_received());
  1489. } else if (act.pos() == 1 + function_call_pos) {
  1490. if (static_cast<int>(act.results().size()) < 1 + function_call_pos) {
  1491. // Control fell through without explicit return.
  1492. return todo_.FinishAction(TupleValue::Empty());
  1493. } else {
  1494. return todo_.FinishAction(act.results()[function_call_pos]);
  1495. }
  1496. } else {
  1497. CARBON_FATAL() << "in StepValueExp with Call pos " << act.pos();
  1498. }
  1499. }
  1500. case ExpressionKind::IntrinsicExpression: {
  1501. const auto& intrinsic = cast<IntrinsicExpression>(exp);
  1502. if (auto rewrite = intrinsic.rewritten_form()) {
  1503. return todo_.ReplaceWith(std::make_unique<ExpressionAction>(
  1504. *rewrite, act.preserve_nested_categories(),
  1505. act.location_received()));
  1506. }
  1507. if (act.pos() == 0) {
  1508. return todo_.Spawn(
  1509. std::make_unique<ValueExpressionAction>(&intrinsic.args()));
  1510. }
  1511. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  1512. const auto& args = cast<TupleValue>(*act.results()[0]).elements();
  1513. switch (cast<IntrinsicExpression>(exp).intrinsic()) {
  1514. case IntrinsicExpression::Intrinsic::Print: {
  1515. if (phase_ != Phase::RunTime) {
  1516. return ProgramError(exp.source_loc())
  1517. << "Print called before run time";
  1518. }
  1519. CARBON_ASSIGN_OR_RETURN(
  1520. Nonnull<const Value*> format_string_value,
  1521. Convert(args[0], arena_->New<StringType>(), exp.source_loc()));
  1522. const char* format_string =
  1523. cast<StringValue>(*format_string_value).value().c_str();
  1524. int num_format_args = args.size() - 1;
  1525. CARBON_RETURN_IF_ERROR(ValidateFormatString(
  1526. intrinsic.source_loc(), format_string, num_format_args));
  1527. switch (num_format_args) {
  1528. case 0:
  1529. *print_stream_ << llvm::formatv(format_string);
  1530. break;
  1531. case 1: {
  1532. *print_stream_ << llvm::formatv(format_string,
  1533. cast<IntValue>(*args[1]).value());
  1534. break;
  1535. }
  1536. default:
  1537. CARBON_FATAL() << "Too many format args: " << num_format_args;
  1538. }
  1539. // Implicit newline; currently no way to disable it.
  1540. *print_stream_ << "\n";
  1541. return todo_.FinishAction(TupleValue::Empty());
  1542. }
  1543. case IntrinsicExpression::Intrinsic::Assert: {
  1544. CARBON_CHECK(args.size() == 2);
  1545. CARBON_ASSIGN_OR_RETURN(
  1546. Nonnull<const Value*> condition,
  1547. Convert(args[0], arena_->New<BoolType>(), exp.source_loc()));
  1548. CARBON_ASSIGN_OR_RETURN(
  1549. Nonnull<const Value*> string_value,
  1550. Convert(args[1], arena_->New<StringType>(), exp.source_loc()));
  1551. bool condition_value = cast<BoolValue>(condition)->value();
  1552. if (!condition_value) {
  1553. return ProgramError(exp.source_loc()) << *string_value;
  1554. }
  1555. return todo_.FinishAction(TupleValue::Empty());
  1556. }
  1557. case IntrinsicExpression::Intrinsic::Alloc: {
  1558. CARBON_CHECK(args.size() == 1);
  1559. Address addr(heap_.AllocateValue(args[0]));
  1560. return todo_.FinishAction(arena_->New<PointerValue>(addr));
  1561. }
  1562. case IntrinsicExpression::Intrinsic::Dealloc: {
  1563. CARBON_CHECK(args.size() == 1);
  1564. CARBON_CHECK(act.pos() > 0);
  1565. const auto* ptr = cast<PointerValue>(args[0]);
  1566. CARBON_ASSIGN_OR_RETURN(const auto* pointee,
  1567. heap_.Read(ptr->address(), exp.source_loc()));
  1568. if (const auto* class_value = dyn_cast<NominalClassValue>(pointee)) {
  1569. // Handle destruction from base class pointer.
  1570. const auto* child_class_value = *class_value->class_value_ptr();
  1571. bool is_subtyped = child_class_value != class_value;
  1572. if (is_subtyped) {
  1573. // Error if destructor is not virtual.
  1574. const auto& class_type =
  1575. cast<NominalClassType>(class_value->type());
  1576. const auto& class_decl = class_type.declaration();
  1577. if ((*class_decl.destructor())->virt_override() ==
  1578. VirtualOverride::None) {
  1579. return ProgramError(exp.source_loc())
  1580. << "Deallocating a derived class from base class "
  1581. "pointer requires a virtual destructor";
  1582. }
  1583. }
  1584. const Address obj_addr = is_subtyped
  1585. ? ptr->address().DowncastedAddress()
  1586. : ptr->address();
  1587. if (act.pos() == 1) {
  1588. return todo_.Spawn(std::make_unique<DestroyAction>(
  1589. arena_->New<LocationValue>(obj_addr), child_class_value));
  1590. } else {
  1591. CARBON_RETURN_IF_ERROR(heap_.Deallocate(obj_addr));
  1592. return todo_.FinishAction(TupleValue::Empty());
  1593. }
  1594. } else {
  1595. if (act.pos() == 1) {
  1596. return todo_.Spawn(std::make_unique<DestroyAction>(
  1597. arena_->New<LocationValue>(ptr->address()), pointee));
  1598. } else {
  1599. CARBON_RETURN_IF_ERROR(heap_.Deallocate(ptr->address()));
  1600. return todo_.FinishAction(TupleValue::Empty());
  1601. }
  1602. }
  1603. }
  1604. case IntrinsicExpression::Intrinsic::PrintAllocs: {
  1605. CARBON_CHECK(args.empty());
  1606. heap_.Print(*print_stream_);
  1607. *print_stream_ << "\n";
  1608. return todo_.FinishAction(TupleValue::Empty());
  1609. }
  1610. case IntrinsicExpression::Intrinsic::Rand: {
  1611. CARBON_CHECK(args.size() == 2);
  1612. const int64_t low = cast<IntValue>(*args[0]).value();
  1613. const int64_t high = cast<IntValue>(*args[1]).value();
  1614. if (low >= high) {
  1615. return ProgramError(exp.source_loc())
  1616. << "Rand inputs must be ordered for a non-empty range: "
  1617. << low << " must be less than " << high;
  1618. }
  1619. // Use 64-bit to handle large ranges where `high - low` might exceed
  1620. // int32_t maximums.
  1621. static std::mt19937_64 generator(12);
  1622. const int64_t range = high - low;
  1623. // We avoid using std::uniform_int_distribution because it's not
  1624. // reproducible across builds/platforms.
  1625. int64_t r = (generator() % range) + low;
  1626. CARBON_CHECK(r >= std::numeric_limits<int32_t>::min() &&
  1627. r <= std::numeric_limits<int32_t>::max())
  1628. << "Non-int32 result: " << r;
  1629. CARBON_CHECK(r >= low && r <= high) << "Out-of-range result: " << r;
  1630. return todo_.FinishAction(arena_->New<IntValue>(r));
  1631. }
  1632. case IntrinsicExpression::Intrinsic::ImplicitAs: {
  1633. CARBON_CHECK(args.size() == 1);
  1634. // Build a constraint type that constrains its .Self type to satisfy
  1635. // the "ImplicitAs" intrinsic constraint. This involves creating a
  1636. // number of objects that all point to each other.
  1637. // TODO: Factor out a simple version of ConstraintTypeBuilder and
  1638. // use it from here.
  1639. auto* self_binding = arena_->New<GenericBinding>(
  1640. exp.source_loc(), ".Self",
  1641. arena_->New<TypeTypeLiteral>(exp.source_loc()),
  1642. GenericBinding::BindingKind::Checked);
  1643. auto* self = arena_->New<VariableType>(self_binding);
  1644. auto* impl_binding = arena_->New<ImplBinding>(
  1645. exp.source_loc(), self_binding, std::nullopt);
  1646. impl_binding->set_symbolic_identity(
  1647. arena_->New<BindingWitness>(impl_binding));
  1648. self_binding->set_symbolic_identity(self);
  1649. self_binding->set_value(self);
  1650. self_binding->set_impl_binding(impl_binding);
  1651. IntrinsicConstraint constraint(self, IntrinsicConstraint::ImplicitAs,
  1652. args);
  1653. auto* result = arena_->New<ConstraintType>(
  1654. self_binding, std::vector<ImplsConstraint>{},
  1655. std::vector<IntrinsicConstraint>{std::move(constraint)},
  1656. std::vector<EqualityConstraint>{},
  1657. std::vector<RewriteConstraint>{}, std::vector<LookupContext>{});
  1658. impl_binding->set_interface(result);
  1659. return todo_.FinishAction(result);
  1660. }
  1661. case IntrinsicExpression::Intrinsic::ImplicitAsConvert: {
  1662. CARBON_FATAL()
  1663. << "__intrinsic_implicit_as_convert should have been rewritten";
  1664. }
  1665. case IntrinsicExpression::Intrinsic::IntEq: {
  1666. CARBON_CHECK(args.size() == 2);
  1667. auto lhs = cast<IntValue>(*args[0]).value();
  1668. auto rhs = cast<IntValue>(*args[1]).value();
  1669. auto* result = arena_->New<BoolValue>(lhs == rhs);
  1670. return todo_.FinishAction(result);
  1671. }
  1672. case IntrinsicExpression::Intrinsic::StrEq: {
  1673. CARBON_CHECK(args.size() == 2);
  1674. const auto& lhs = cast<StringValue>(*args[0]).value();
  1675. const auto& rhs = cast<StringValue>(*args[1]).value();
  1676. auto* result = arena_->New<BoolValue>(lhs == rhs);
  1677. return todo_.FinishAction(result);
  1678. }
  1679. case IntrinsicExpression::Intrinsic::IntCompare: {
  1680. CARBON_CHECK(args.size() == 2);
  1681. auto lhs = cast<IntValue>(*args[0]).value();
  1682. auto rhs = cast<IntValue>(*args[1]).value();
  1683. if (lhs < rhs) {
  1684. auto* result = arena_->New<IntValue>(-1);
  1685. return todo_.FinishAction(result);
  1686. }
  1687. if (lhs == rhs) {
  1688. auto* result = arena_->New<IntValue>(0);
  1689. return todo_.FinishAction(result);
  1690. }
  1691. auto* result = arena_->New<IntValue>(1);
  1692. return todo_.FinishAction(result);
  1693. }
  1694. case IntrinsicExpression::Intrinsic::StrCompare: {
  1695. CARBON_CHECK(args.size() == 2);
  1696. const auto& lhs = cast<StringValue>(*args[0]).value();
  1697. const auto& rhs = cast<StringValue>(*args[1]).value();
  1698. if (lhs < rhs) {
  1699. auto* result = arena_->New<IntValue>(-1);
  1700. return todo_.FinishAction(result);
  1701. }
  1702. if (lhs == rhs) {
  1703. auto* result = arena_->New<IntValue>(0);
  1704. return todo_.FinishAction(result);
  1705. }
  1706. auto* result = arena_->New<IntValue>(1);
  1707. return todo_.FinishAction(result);
  1708. }
  1709. case IntrinsicExpression::Intrinsic::IntBitComplement: {
  1710. CARBON_CHECK(args.size() == 1);
  1711. return todo_.FinishAction(
  1712. arena_->New<IntValue>(~cast<IntValue>(*args[0]).value()));
  1713. }
  1714. case IntrinsicExpression::Intrinsic::IntBitAnd: {
  1715. CARBON_CHECK(args.size() == 2);
  1716. return todo_.FinishAction(
  1717. arena_->New<IntValue>(cast<IntValue>(*args[0]).value() &
  1718. cast<IntValue>(*args[1]).value()));
  1719. }
  1720. case IntrinsicExpression::Intrinsic::IntBitOr: {
  1721. CARBON_CHECK(args.size() == 2);
  1722. return todo_.FinishAction(
  1723. arena_->New<IntValue>(cast<IntValue>(*args[0]).value() |
  1724. cast<IntValue>(*args[1]).value()));
  1725. }
  1726. case IntrinsicExpression::Intrinsic::IntBitXor: {
  1727. CARBON_CHECK(args.size() == 2);
  1728. return todo_.FinishAction(
  1729. arena_->New<IntValue>(cast<IntValue>(*args[0]).value() ^
  1730. cast<IntValue>(*args[1]).value()));
  1731. }
  1732. case IntrinsicExpression::Intrinsic::IntLeftShift: {
  1733. CARBON_CHECK(args.size() == 2);
  1734. const auto& lhs = cast<IntValue>(*args[0]).value();
  1735. const auto& rhs = cast<IntValue>(*args[1]).value();
  1736. if (rhs >= 0 && rhs < 32) {
  1737. return todo_.FinishAction(
  1738. arena_->New<IntValue>(static_cast<uint32_t>(lhs) << rhs));
  1739. }
  1740. return ProgramError(exp.source_loc()) << "Integer overflow";
  1741. }
  1742. case IntrinsicExpression::Intrinsic::IntRightShift: {
  1743. CARBON_CHECK(args.size() == 2);
  1744. const auto& lhs = cast<IntValue>(*args[0]).value();
  1745. const auto& rhs = cast<IntValue>(*args[1]).value();
  1746. if (rhs >= 0 && rhs < 32) {
  1747. return todo_.FinishAction(arena_->New<IntValue>(lhs >> rhs));
  1748. }
  1749. return ProgramError(exp.source_loc()) << "Integer overflow";
  1750. }
  1751. }
  1752. }
  1753. case ExpressionKind::IntTypeLiteral: {
  1754. CARBON_CHECK(act.pos() == 0);
  1755. return todo_.FinishAction(arena_->New<IntType>());
  1756. }
  1757. case ExpressionKind::BoolTypeLiteral: {
  1758. CARBON_CHECK(act.pos() == 0);
  1759. return todo_.FinishAction(arena_->New<BoolType>());
  1760. }
  1761. case ExpressionKind::TypeTypeLiteral: {
  1762. CARBON_CHECK(act.pos() == 0);
  1763. return todo_.FinishAction(arena_->New<TypeType>());
  1764. }
  1765. case ExpressionKind::StringLiteral:
  1766. CARBON_CHECK(act.pos() == 0);
  1767. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  1768. return todo_.FinishAction(
  1769. arena_->New<StringValue>(cast<StringLiteral>(exp).value()));
  1770. case ExpressionKind::StringTypeLiteral: {
  1771. CARBON_CHECK(act.pos() == 0);
  1772. return todo_.FinishAction(arena_->New<StringType>());
  1773. }
  1774. case ExpressionKind::FunctionTypeLiteral:
  1775. case ExpressionKind::StructTypeLiteral:
  1776. case ExpressionKind::ArrayTypeLiteral:
  1777. case ExpressionKind::ValueLiteral: {
  1778. if (act.pos() == 0) {
  1779. return todo_.Spawn(std::make_unique<TypeInstantiationAction>(
  1780. &exp.static_type(), exp.source_loc()));
  1781. } else {
  1782. const auto* value = &cast<ConstantValueLiteral>(exp).constant_value();
  1783. Nonnull<const Value*> destination = act.results().back();
  1784. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> result,
  1785. Convert(value, destination, exp.source_loc()));
  1786. return todo_.FinishAction(result);
  1787. }
  1788. }
  1789. case ExpressionKind::IfExpression: {
  1790. const auto& if_expr = cast<IfExpression>(exp);
  1791. if (act.pos() == 0) {
  1792. return todo_.Spawn(
  1793. std::make_unique<ValueExpressionAction>(&if_expr.condition()));
  1794. } else if (act.pos() == 1) {
  1795. const auto& condition = cast<BoolValue>(*act.results()[0]);
  1796. return todo_.Spawn(std::make_unique<ValueExpressionAction>(
  1797. condition.value() ? &if_expr.then_expression()
  1798. : &if_expr.else_expression()));
  1799. } else {
  1800. return todo_.FinishAction(act.results()[1]);
  1801. }
  1802. break;
  1803. }
  1804. case ExpressionKind::WhereExpression: {
  1805. auto rewrite = cast<WhereExpression>(exp).rewritten_form();
  1806. CARBON_CHECK(rewrite) << "where expression should be rewritten";
  1807. return todo_.ReplaceWith(std::make_unique<ExpressionAction>(
  1808. *rewrite, act.preserve_nested_categories(), act.location_received()));
  1809. }
  1810. case ExpressionKind::BuiltinConvertExpression: {
  1811. const auto& convert_expr = cast<BuiltinConvertExpression>(exp);
  1812. if (auto rewrite = convert_expr.rewritten_form()) {
  1813. return todo_.ReplaceWith(std::make_unique<ExpressionAction>(
  1814. *rewrite, act.preserve_nested_categories(),
  1815. act.location_received()));
  1816. }
  1817. if (act.pos() == 0) {
  1818. return todo_.Spawn(std::make_unique<ValueExpressionAction>(
  1819. convert_expr.source_expression()));
  1820. } else if (act.pos() == 1) {
  1821. return todo_.Spawn(std::make_unique<TypeInstantiationAction>(
  1822. &convert_expr.static_type(), convert_expr.source_loc()));
  1823. } else {
  1824. // TODO: Remove all calls to Convert other than this one. We shouldn't
  1825. // need them any more.
  1826. Nonnull<const Value*> destination = act.results().back();
  1827. CARBON_ASSIGN_OR_RETURN(
  1828. Nonnull<const Value*> result,
  1829. Convert(act.results()[0], destination, convert_expr.source_loc()));
  1830. return todo_.FinishAction(result);
  1831. }
  1832. }
  1833. case ExpressionKind::UnimplementedExpression:
  1834. CARBON_FATAL() << "Unimplemented: " << exp;
  1835. } // switch (exp->kind)
  1836. }
  1837. auto Interpreter::StepWitness() -> ErrorOr<Success> {
  1838. auto& act = cast<WitnessAction>(todo_.CurrentAction());
  1839. const Witness* witness = act.witness();
  1840. switch (witness->kind()) {
  1841. case Value::Kind::BindingWitness: {
  1842. const ImplBinding* binding = cast<BindingWitness>(witness)->binding();
  1843. CARBON_ASSIGN_OR_RETURN(
  1844. Nonnull<const Value*> value,
  1845. todo_.ValueOfNode(binding, binding->type_var()->source_loc()));
  1846. if (const auto* location = dyn_cast<LocationValue>(value)) {
  1847. // TODO: Why do we store values for impl bindings on the heap?
  1848. CARBON_ASSIGN_OR_RETURN(
  1849. value,
  1850. heap_.Read(location->address(), binding->type_var()->source_loc()));
  1851. }
  1852. return todo_.FinishAction(value);
  1853. }
  1854. case Value::Kind::ConstraintWitness: {
  1855. llvm::ArrayRef<Nonnull<const Witness*>> witnesses =
  1856. cast<ConstraintWitness>(witness)->witnesses();
  1857. if (act.pos() < static_cast<int>(witnesses.size())) {
  1858. return todo_.Spawn(std::make_unique<WitnessAction>(witnesses[act.pos()],
  1859. act.source_loc()));
  1860. }
  1861. std::vector<Nonnull<const Witness*>> new_witnesses;
  1862. new_witnesses.reserve(witnesses.size());
  1863. for (const auto* witness : act.results()) {
  1864. new_witnesses.push_back(cast<Witness>(witness));
  1865. }
  1866. return todo_.FinishAction(
  1867. arena_->New<ConstraintWitness>(std::move(new_witnesses)));
  1868. }
  1869. case Value::Kind::ConstraintImplWitness: {
  1870. const auto* constraint_impl = cast<ConstraintImplWitness>(witness);
  1871. if (act.pos() == 0) {
  1872. return todo_.Spawn(std::make_unique<WitnessAction>(
  1873. constraint_impl->constraint_witness(), act.source_loc()));
  1874. }
  1875. return todo_.FinishAction(ConstraintImplWitness::Make(
  1876. arena_, cast<Witness>(act.results()[0]), constraint_impl->index()));
  1877. }
  1878. case Value::Kind::ImplWitness: {
  1879. const auto* impl_witness = cast<ImplWitness>(witness);
  1880. CARBON_ASSIGN_OR_RETURN(
  1881. Nonnull<const Bindings*> new_bindings,
  1882. InstantiateBindings(&impl_witness->bindings(),
  1883. impl_witness->declaration().source_loc()));
  1884. return todo_.FinishAction(
  1885. new_bindings == &impl_witness->bindings()
  1886. ? impl_witness
  1887. : arena_->New<ImplWitness>(&impl_witness->declaration(),
  1888. new_bindings));
  1889. }
  1890. default:
  1891. CARBON_FATAL() << "unexpected kind of witness " << *witness;
  1892. }
  1893. }
  1894. auto Interpreter::StepStmt() -> ErrorOr<Success> {
  1895. auto& act = cast<StatementAction>(todo_.CurrentAction());
  1896. const Statement& stmt = act.statement();
  1897. if (trace_stream_->is_enabled()) {
  1898. trace_stream_->Source() << "statement at (" << stmt.source_loc() << ")\n";
  1899. *trace_stream_ << "```\n" << stmt << "\n```\n";
  1900. }
  1901. switch (stmt.kind()) {
  1902. case StatementKind::Match: {
  1903. const auto& match_stmt = cast<Match>(stmt);
  1904. if (act.pos() == 0) {
  1905. // { { (match (e) ...) :: C, E, F} :: S, H}
  1906. // -> { { e :: (match ([]) ...) :: C, E, F} :: S, H}
  1907. act.StartScope(RuntimeScope(&heap_));
  1908. return todo_.Spawn(
  1909. std::make_unique<ValueExpressionAction>(&match_stmt.expression()));
  1910. } else {
  1911. int clause_num = act.pos() - 1;
  1912. if (clause_num >= static_cast<int>(match_stmt.clauses().size())) {
  1913. return todo_.FinishAction();
  1914. }
  1915. auto c = match_stmt.clauses()[clause_num];
  1916. RuntimeScope matches(&heap_);
  1917. BindingMap generic_args;
  1918. CARBON_ASSIGN_OR_RETURN(
  1919. Nonnull<const Value*> val,
  1920. Convert(act.results()[0], &c.pattern().static_type(),
  1921. stmt.source_loc()));
  1922. if (PatternMatch(&c.pattern().value(), ExpressionResult::Value(val),
  1923. stmt.source_loc(), &matches, generic_args,
  1924. trace_stream_, this->arena_)) {
  1925. // Ensure we don't process any more clauses.
  1926. act.set_pos(match_stmt.clauses().size() + 1);
  1927. todo_.MergeScope(std::move(matches));
  1928. return todo_.Spawn(
  1929. std::make_unique<StatementAction>(&c.statement(), std::nullopt));
  1930. } else {
  1931. return todo_.RunAgain();
  1932. }
  1933. }
  1934. }
  1935. case StatementKind::For: {
  1936. constexpr int TargetVarPosInResult = 0;
  1937. constexpr int CurrentIndexPosInResult = 1;
  1938. constexpr int EndIndexPosInResult = 2;
  1939. const auto* loop_var = &cast<BindingPlaceholderValue>(
  1940. cast<For>(stmt).variable_declaration().value());
  1941. if (act.pos() == 0) {
  1942. return todo_.Spawn(std::make_unique<ValueExpressionAction>(
  1943. &cast<For>(stmt).loop_target()));
  1944. }
  1945. if (act.pos() == 1) {
  1946. const auto* source_array =
  1947. cast<TupleValue>(act.results()[TargetVarPosInResult]);
  1948. int start_index = 0;
  1949. auto end_index = static_cast<int>(source_array->elements().size());
  1950. if (end_index == 0) {
  1951. return todo_.FinishAction();
  1952. }
  1953. act.AddResult(arena_->New<IntValue>(start_index));
  1954. act.AddResult(arena_->New<IntValue>(end_index));
  1955. todo_.Initialize(*(loop_var->value_node()),
  1956. source_array->elements()[start_index]);
  1957. act.ReplaceResult(CurrentIndexPosInResult,
  1958. arena_->New<IntValue>(start_index + 1));
  1959. return todo_.Spawn(std::make_unique<StatementAction>(
  1960. &cast<For>(stmt).body(), std::nullopt));
  1961. }
  1962. if (act.pos() >= 2) {
  1963. auto current_index =
  1964. cast<IntValue>(act.results()[CurrentIndexPosInResult])->value();
  1965. auto end_index =
  1966. cast<IntValue>(act.results()[EndIndexPosInResult])->value();
  1967. if (current_index < end_index) {
  1968. const auto* source_array =
  1969. cast<const TupleValue>(act.results()[TargetVarPosInResult]);
  1970. CARBON_ASSIGN_OR_RETURN(
  1971. Nonnull<const Value*> assigned_array_element,
  1972. todo_.ValueOfNode(*(loop_var->value_node()), stmt.source_loc()));
  1973. const auto* location = cast<LocationValue>(assigned_array_element);
  1974. CARBON_RETURN_IF_ERROR(heap_.Write(
  1975. location->address(), source_array->elements()[current_index],
  1976. stmt.source_loc()));
  1977. act.ReplaceResult(CurrentIndexPosInResult,
  1978. arena_->New<IntValue>(current_index + 1));
  1979. return todo_.Spawn(std::make_unique<StatementAction>(
  1980. &cast<For>(stmt).body(), std::nullopt));
  1981. }
  1982. }
  1983. return todo_.FinishAction();
  1984. }
  1985. case StatementKind::While:
  1986. // TODO: Rewrite While to use ReplaceResult to store condition result.
  1987. // This will remove the inconsistency between the while and for
  1988. // loops.
  1989. if (act.pos() % 2 == 0) {
  1990. // { { (while (e) s) :: C, E, F} :: S, H}
  1991. // -> { { e :: (while ([]) s) :: C, E, F} :: S, H}
  1992. act.Clear();
  1993. return todo_.Spawn(std::make_unique<ValueExpressionAction>(
  1994. &cast<While>(stmt).condition()));
  1995. } else {
  1996. CARBON_ASSIGN_OR_RETURN(
  1997. Nonnull<const Value*> condition,
  1998. Convert(act.results().back(), arena_->New<BoolType>(),
  1999. stmt.source_loc()));
  2000. if (cast<BoolValue>(*condition).value()) {
  2001. // { {true :: (while ([]) s) :: C, E, F} :: S, H}
  2002. // -> { { s :: (while (e) s) :: C, E, F } :: S, H}
  2003. return todo_.Spawn(std::make_unique<StatementAction>(
  2004. &cast<While>(stmt).body(), std::nullopt));
  2005. } else {
  2006. // { {false :: (while ([]) s) :: C, E, F} :: S, H}
  2007. // -> { { C, E, F } :: S, H}
  2008. return todo_.FinishAction();
  2009. }
  2010. }
  2011. case StatementKind::Break: {
  2012. CARBON_CHECK(act.pos() == 0);
  2013. // { { break; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  2014. // -> { { C, E', F} :: S, H}
  2015. return todo_.UnwindPast(&cast<Break>(stmt).loop());
  2016. }
  2017. case StatementKind::Continue: {
  2018. CARBON_CHECK(act.pos() == 0);
  2019. // { { continue; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  2020. // -> { { (while (e) s) :: C, E', F} :: S, H}
  2021. return todo_.UnwindTo(&cast<Continue>(stmt).loop());
  2022. }
  2023. case StatementKind::Block: {
  2024. const auto& block = cast<Block>(stmt);
  2025. if (act.pos() >= static_cast<int>(block.statements().size())) {
  2026. // If the position is past the end of the block, end processing. Note
  2027. // that empty blocks immediately end.
  2028. return todo_.FinishAction();
  2029. }
  2030. // Initialize a scope when starting a block.
  2031. if (act.pos() == 0) {
  2032. act.StartScope(RuntimeScope(&heap_));
  2033. }
  2034. // Process the next statement in the block. The position will be
  2035. // incremented as part of Spawn.
  2036. return todo_.Spawn(std::make_unique<StatementAction>(
  2037. block.statements()[act.pos()], act.location_received()));
  2038. }
  2039. case StatementKind::VariableDefinition: {
  2040. const auto& definition = cast<VariableDefinition>(stmt);
  2041. const bool has_initializing_expr =
  2042. definition.has_init() &&
  2043. definition.init().kind() == ExpressionKind::CallExpression &&
  2044. definition.init().expression_category() ==
  2045. ExpressionCategory::Initializing;
  2046. auto init_location = (act.location_received() && definition.is_returned())
  2047. ? act.location_received()
  2048. : act.location_created();
  2049. if (act.pos() == 0 && definition.has_init()) {
  2050. // { {(var x = e) :: C, E, F} :: S, H}
  2051. // -> { {e :: (var x = []) :: C, E, F} :: S, H}
  2052. if (has_initializing_expr && !init_location) {
  2053. // Allocate storage for initializing expression.
  2054. const auto allocation_id =
  2055. heap_.AllocateValue(arena_->New<UninitializedValue>(
  2056. &definition.init().static_type()));
  2057. act.set_location_created(allocation_id);
  2058. init_location = allocation_id;
  2059. RuntimeScope scope(&heap_);
  2060. scope.BindLifetimeToScope(Address(allocation_id));
  2061. todo_.MergeScope(std::move(scope));
  2062. }
  2063. return todo_.Spawn(std::make_unique<ExpressionAction>(
  2064. &definition.init(), /*preserve_nested_categories=*/false,
  2065. init_location));
  2066. } else {
  2067. // { { v :: (x = []) :: C, E, F} :: S, H}
  2068. // -> { { C, E(x := a), F} :: S, H(a := copy(v))}
  2069. Nonnull<const Value*> p = &definition.pattern().value();
  2070. Nonnull<const Value*> v;
  2071. std::optional<Address> v_location;
  2072. ExpressionCategory expr_category =
  2073. definition.has_init() ? definition.init().expression_category()
  2074. : ExpressionCategory::Value;
  2075. if (definition.has_init()) {
  2076. Nonnull<const Value*> result = act.results()[0];
  2077. std::optional<Nonnull<const ReferenceExpressionValue*>> v_expr =
  2078. (result->kind() == Value::Kind::ReferenceExpressionValue)
  2079. ? std::optional{cast<ReferenceExpressionValue>(result)}
  2080. : std::nullopt;
  2081. const auto init_location = act.location_created();
  2082. v = v_expr ? (*v_expr)->value() : result;
  2083. if (expr_category == ExpressionCategory::Reference) {
  2084. CARBON_CHECK(v_expr) << "Expecting ReferenceExpressionValue from "
  2085. "reference expression";
  2086. v_location = (*v_expr)->address();
  2087. CARBON_CHECK(v_location)
  2088. << "Expecting a valid address from reference expression";
  2089. } else if (has_initializing_expr && init_location &&
  2090. heap_.is_initialized(*init_location)) {
  2091. // Bind even if a conversion is necessary.
  2092. v_location = Address(*init_location);
  2093. CARBON_ASSIGN_OR_RETURN(
  2094. result, heap_.Read(*v_location, definition.source_loc()));
  2095. CARBON_CHECK(v == result);
  2096. } else {
  2097. // TODO: Prevent copies for Value expressions from Reference
  2098. // expression, once able to prevent mutations.
  2099. if (init_location && act.location_created()) {
  2100. // Location provided to initializing expression was not used.
  2101. heap_.Discard(*init_location);
  2102. }
  2103. expr_category = ExpressionCategory::Value;
  2104. const auto* dest_type = &definition.pattern().static_type();
  2105. CARBON_ASSIGN_OR_RETURN(v,
  2106. Convert(v, dest_type, stmt.source_loc()));
  2107. }
  2108. } else {
  2109. v = arena_->New<UninitializedValue>(p);
  2110. }
  2111. // If declaring a returned var, bind name to the location provided to
  2112. // initializing expression, if any.
  2113. RuntimeScope scope(&heap_);
  2114. if (definition.is_returned() && init_location) {
  2115. CARBON_CHECK(p->kind() == Value::Kind::BindingPlaceholderValue);
  2116. const auto value_node =
  2117. cast<BindingPlaceholderValue>(*p).value_node();
  2118. CARBON_CHECK(value_node);
  2119. const auto address = Address(*init_location);
  2120. scope.Bind(*value_node, address);
  2121. CARBON_RETURN_IF_ERROR(heap_.Write(address, v, stmt.source_loc()));
  2122. } else {
  2123. BindingMap generic_args;
  2124. bool matched =
  2125. PatternMatch(p, ExpressionResult(v, v_location, expr_category),
  2126. stmt.source_loc(), &scope, generic_args,
  2127. trace_stream_, this->arena_);
  2128. CARBON_CHECK(matched)
  2129. << stmt.source_loc()
  2130. << ": internal error in variable definition, match failed";
  2131. }
  2132. todo_.MergeScope(std::move(scope));
  2133. return todo_.FinishAction();
  2134. }
  2135. }
  2136. case StatementKind::ExpressionStatement:
  2137. if (act.pos() == 0) {
  2138. // { {e :: C, E, F} :: S, H}
  2139. // -> { {e :: C, E, F} :: S, H}
  2140. return todo_.Spawn(std::make_unique<ValueExpressionAction>(
  2141. &cast<ExpressionStatement>(stmt).expression()));
  2142. } else {
  2143. return todo_.FinishAction();
  2144. }
  2145. case StatementKind::Assign: {
  2146. const auto& assign = cast<Assign>(stmt);
  2147. if (auto rewrite = assign.rewritten_form()) {
  2148. if (act.pos() == 0) {
  2149. return todo_.Spawn(std::make_unique<ValueExpressionAction>(*rewrite));
  2150. } else {
  2151. return todo_.FinishAction();
  2152. }
  2153. }
  2154. if (act.pos() == 0) {
  2155. // { {(lv = e) :: C, E, F} :: S, H}
  2156. // -> { {lv :: ([] = e) :: C, E, F} :: S, H}
  2157. return todo_.Spawn(std::make_unique<LocationAction>(&assign.lhs()));
  2158. } else if (act.pos() == 1) {
  2159. // { { a :: ([] = e) :: C, E, F} :: S, H}
  2160. // -> { { e :: (a = []) :: C, E, F} :: S, H}
  2161. return todo_.Spawn(
  2162. std::make_unique<ValueExpressionAction>(&assign.rhs()));
  2163. } else {
  2164. // { { v :: (a = []) :: C, E, F} :: S, H}
  2165. // -> { { C, E, F} :: S, H(a := v)}
  2166. const auto& lval = cast<LocationValue>(*act.results()[0]);
  2167. CARBON_ASSIGN_OR_RETURN(
  2168. Nonnull<const Value*> rval,
  2169. Convert(act.results()[1], &assign.lhs().static_type(),
  2170. stmt.source_loc()));
  2171. CARBON_RETURN_IF_ERROR(
  2172. heap_.Write(lval.address(), rval, stmt.source_loc()));
  2173. return todo_.FinishAction();
  2174. }
  2175. }
  2176. case StatementKind::IncrementDecrement: {
  2177. const auto& inc_dec = cast<IncrementDecrement>(stmt);
  2178. if (act.pos() == 0) {
  2179. return todo_.Spawn(
  2180. std::make_unique<ValueExpressionAction>(*inc_dec.rewritten_form()));
  2181. } else {
  2182. return todo_.FinishAction();
  2183. }
  2184. }
  2185. case StatementKind::If:
  2186. if (act.pos() == 0) {
  2187. // { {(if (e) then_stmt else else_stmt) :: C, E, F} :: S, H}
  2188. // -> { { e :: (if ([]) then_stmt else else_stmt) :: C, E, F} :: S, H}
  2189. return todo_.Spawn(std::make_unique<ValueExpressionAction>(
  2190. &cast<If>(stmt).condition()));
  2191. } else if (act.pos() == 1) {
  2192. CARBON_ASSIGN_OR_RETURN(
  2193. Nonnull<const Value*> condition,
  2194. Convert(act.results()[0], arena_->New<BoolType>(),
  2195. stmt.source_loc()));
  2196. if (cast<BoolValue>(*condition).value()) {
  2197. // { {true :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  2198. // S, H}
  2199. // -> { { then_stmt :: C, E, F } :: S, H}
  2200. return todo_.Spawn(std::make_unique<StatementAction>(
  2201. &cast<If>(stmt).then_block(), std::nullopt));
  2202. } else if (cast<If>(stmt).else_block()) {
  2203. // { {false :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  2204. // S, H}
  2205. // -> { { else_stmt :: C, E, F } :: S, H}
  2206. return todo_.Spawn(std::make_unique<StatementAction>(
  2207. *cast<If>(stmt).else_block(), std::nullopt));
  2208. } else {
  2209. return todo_.FinishAction();
  2210. }
  2211. } else {
  2212. return todo_.FinishAction();
  2213. }
  2214. case StatementKind::ReturnVar: {
  2215. const auto& ret_var = cast<ReturnVar>(stmt);
  2216. const ValueNodeView& value_node = ret_var.value_node();
  2217. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> value,
  2218. todo_.ValueOfNode(value_node, stmt.source_loc()));
  2219. if (const auto* location = dyn_cast<LocationValue>(value)) {
  2220. CARBON_ASSIGN_OR_RETURN(
  2221. value, heap_.Read(location->address(), ret_var.source_loc()));
  2222. }
  2223. const CallableDeclaration& function = cast<Return>(stmt).function();
  2224. CARBON_ASSIGN_OR_RETURN(
  2225. Nonnull<const Value*> return_value,
  2226. Convert(value, &function.return_term().static_type(),
  2227. stmt.source_loc()));
  2228. return todo_.UnwindPast(*function.body(), return_value);
  2229. }
  2230. case StatementKind::ReturnExpression:
  2231. if (act.pos() == 0) {
  2232. // { {return e :: C, E, F} :: S, H}
  2233. // -> { {e :: return [] :: C, E, F} :: S, H}
  2234. return todo_.Spawn(std::make_unique<ValueExpressionAction>(
  2235. &cast<ReturnExpression>(stmt).expression()));
  2236. } else {
  2237. // { {v :: return [] :: C, E, F} :: {C', E', F'} :: S, H}
  2238. // -> { {v :: C', E', F'} :: S, H}
  2239. const CallableDeclaration& function = cast<Return>(stmt).function();
  2240. CARBON_ASSIGN_OR_RETURN(
  2241. Nonnull<const Value*> return_value,
  2242. Convert(act.results()[0], &function.return_term().static_type(),
  2243. stmt.source_loc()));
  2244. // Write to initialized storage location, if any.
  2245. if (const auto location = act.location_received()) {
  2246. CARBON_RETURN_IF_ERROR(
  2247. heap_.Write(Address(*location), return_value, stmt.source_loc()));
  2248. }
  2249. return todo_.UnwindPast(*function.body(), return_value);
  2250. }
  2251. }
  2252. }
  2253. auto Interpreter::StepDeclaration() -> ErrorOr<Success> {
  2254. Action& act = todo_.CurrentAction();
  2255. const Declaration& decl = cast<DeclarationAction>(act).declaration();
  2256. if (trace_stream_->is_enabled()) {
  2257. trace_stream_->Source() << "declaration at (" << decl.source_loc() << ")\n";
  2258. *trace_stream_ << "```\n" << decl << "\n```\n";
  2259. }
  2260. switch (decl.kind()) {
  2261. case DeclarationKind::VariableDeclaration: {
  2262. const auto& var_decl = cast<VariableDeclaration>(decl);
  2263. if (var_decl.has_initializer()) {
  2264. if (act.pos() == 0) {
  2265. return todo_.Spawn(
  2266. std::make_unique<ValueExpressionAction>(&var_decl.initializer()));
  2267. } else {
  2268. CARBON_ASSIGN_OR_RETURN(
  2269. Nonnull<const Value*> v,
  2270. Convert(act.results()[0], &var_decl.binding().static_type(),
  2271. var_decl.source_loc()));
  2272. todo_.Initialize(&var_decl.binding(), v);
  2273. return todo_.FinishAction();
  2274. }
  2275. } else {
  2276. Nonnull<const Value*> v =
  2277. arena_->New<UninitializedValue>(&var_decl.binding().value());
  2278. todo_.Initialize(&var_decl.binding(), v);
  2279. return todo_.FinishAction();
  2280. }
  2281. }
  2282. case DeclarationKind::NamespaceDeclaration:
  2283. case DeclarationKind::DestructorDeclaration:
  2284. case DeclarationKind::FunctionDeclaration:
  2285. case DeclarationKind::ClassDeclaration:
  2286. case DeclarationKind::MixinDeclaration:
  2287. case DeclarationKind::MixDeclaration:
  2288. case DeclarationKind::ChoiceDeclaration:
  2289. case DeclarationKind::InterfaceDeclaration:
  2290. case DeclarationKind::ConstraintDeclaration:
  2291. case DeclarationKind::InterfaceExtendDeclaration:
  2292. case DeclarationKind::InterfaceRequireDeclaration:
  2293. case DeclarationKind::AssociatedConstantDeclaration:
  2294. case DeclarationKind::ImplDeclaration:
  2295. case DeclarationKind::MatchFirstDeclaration:
  2296. case DeclarationKind::SelfDeclaration:
  2297. case DeclarationKind::AliasDeclaration:
  2298. case DeclarationKind::ExtendBaseDeclaration:
  2299. // These declarations have no run-time effects.
  2300. return todo_.FinishAction();
  2301. }
  2302. }
  2303. auto Interpreter::StepDestroy() -> ErrorOr<Success> {
  2304. const Action& act = todo_.CurrentAction();
  2305. const auto& destroy_act = cast<DestroyAction>(act);
  2306. switch (destroy_act.value()->kind()) {
  2307. case Value::Kind::NominalClassValue: {
  2308. const auto* class_obj = cast<NominalClassValue>(destroy_act.value());
  2309. const auto& class_decl =
  2310. cast<NominalClassType>(class_obj->type()).declaration();
  2311. const int member_count = class_decl.members().size();
  2312. if (act.pos() == 0) {
  2313. // Run the destructor, if there is one.
  2314. if (auto destructor = class_decl.destructor()) {
  2315. return CallDestructor(
  2316. *destructor, ExpressionResult::Reference(
  2317. class_obj, destroy_act.location()->address()));
  2318. } else {
  2319. return todo_.RunAgain();
  2320. }
  2321. } else if (act.pos() <= member_count) {
  2322. // Destroy members.
  2323. const int index = class_decl.members().size() - act.pos();
  2324. const auto& member = class_decl.members()[index];
  2325. if (const auto* var = dyn_cast<VariableDeclaration>(member)) {
  2326. const Address object = destroy_act.location()->address();
  2327. const Address var_addr =
  2328. object.ElementAddress(arena_->New<NamedElement>(var));
  2329. const auto v = heap_.Read(var_addr, var->source_loc());
  2330. CARBON_CHECK(v.ok())
  2331. << "Failed to read member `" << var->binding().name()
  2332. << "` from class `" << class_decl.name() << "`";
  2333. return todo_.Spawn(std::make_unique<DestroyAction>(
  2334. arena_->New<LocationValue>(var_addr), *v));
  2335. } else {
  2336. return todo_.RunAgain();
  2337. }
  2338. } else if (act.pos() == member_count + 1) {
  2339. // Destroy the parent, if there is one.
  2340. if (auto base = class_obj->base()) {
  2341. const Address obj_addr = destroy_act.location()->address();
  2342. const Address base_addr =
  2343. obj_addr.ElementAddress(arena_->New<BaseElement>(class_obj));
  2344. return todo_.Spawn(std::make_unique<DestroyAction>(
  2345. arena_->New<LocationValue>(base_addr), base.value()));
  2346. } else {
  2347. return todo_.RunAgain();
  2348. }
  2349. } else {
  2350. todo_.Pop();
  2351. return Success();
  2352. }
  2353. }
  2354. case Value::Kind::TupleValue: {
  2355. const auto* tuple = cast<TupleValue>(destroy_act.value());
  2356. const auto element_count = tuple->elements().size();
  2357. if (static_cast<size_t>(act.pos()) < element_count) {
  2358. const size_t index = element_count - act.pos() - 1;
  2359. const auto& item = tuple->elements()[index];
  2360. const auto object_addr = destroy_act.location()->address();
  2361. Address field_address = object_addr.ElementAddress(
  2362. arena_->New<PositionalElement>(index, item));
  2363. if (item->kind() == Value::Kind::NominalClassValue ||
  2364. item->kind() == Value::Kind::TupleValue) {
  2365. return todo_.Spawn(std::make_unique<DestroyAction>(
  2366. arena_->New<LocationValue>(field_address), item));
  2367. } else {
  2368. // The tuple element's type is an integral type (e.g., i32)
  2369. // or the type doesn't support destruction.
  2370. return todo_.RunAgain();
  2371. }
  2372. } else {
  2373. todo_.Pop();
  2374. return Success();
  2375. }
  2376. }
  2377. default:
  2378. // These declarations have no run-time effects.
  2379. todo_.Pop();
  2380. return Success();
  2381. }
  2382. CARBON_FATAL() << "Unreachable";
  2383. }
  2384. auto Interpreter::StepCleanUp() -> ErrorOr<Success> {
  2385. const Action& act = todo_.CurrentAction();
  2386. const auto& cleanup = cast<CleanUpAction>(act);
  2387. if (act.pos() < cleanup.allocations_count() * 2) {
  2388. const size_t alloc_index = cleanup.allocations_count() - act.pos() / 2 - 1;
  2389. auto allocation = act.scope()->allocations()[alloc_index];
  2390. if (heap_.is_discarded(allocation)) {
  2391. // Initializing expressions can generate discarded allocations.
  2392. return todo_.RunAgain();
  2393. }
  2394. if (act.pos() % 2 == 0) {
  2395. auto* location = arena_->New<LocationValue>(Address(allocation));
  2396. auto value = heap_.Read(location->address(), *cleanup.source_loc());
  2397. // Step over uninitialized values.
  2398. if (value.ok()) {
  2399. return todo_.Spawn(std::make_unique<DestroyAction>(location, *value));
  2400. } else {
  2401. return todo_.RunAgain();
  2402. }
  2403. } else {
  2404. CARBON_RETURN_IF_ERROR(heap_.Deallocate(allocation));
  2405. return todo_.RunAgain();
  2406. }
  2407. }
  2408. todo_.Pop();
  2409. return Success();
  2410. }
  2411. // State transition.
  2412. auto Interpreter::Step() -> ErrorOr<Success> {
  2413. Action& act = todo_.CurrentAction();
  2414. if (trace_stream_->is_enabled()) {
  2415. trace_stream_->Start() << "step " << act << " (" << act.source_loc()
  2416. << ") --->\n";
  2417. }
  2418. auto error_builder = [&] {
  2419. if (auto loc = act.source_loc()) {
  2420. return ProgramError(*loc);
  2421. }
  2422. return ErrorBuilder();
  2423. };
  2424. // Check for various overflow conditions before stepping.
  2425. if (todo_.size() > MaxTodoSize) {
  2426. return error_builder()
  2427. << "stack overflow: too many interpreter actions on stack";
  2428. }
  2429. if (++steps_taken_ > MaxStepsTaken) {
  2430. return error_builder()
  2431. << "possible infinite loop: too many interpreter steps executed";
  2432. }
  2433. if (arena_->allocated() > MaxArenaAllocated) {
  2434. return error_builder() << "out of memory: exceeded arena allocation limit";
  2435. }
  2436. switch (act.kind()) {
  2437. case Action::Kind::LocationAction:
  2438. CARBON_RETURN_IF_ERROR(StepLocation());
  2439. break;
  2440. case Action::Kind::ValueExpressionAction:
  2441. CARBON_RETURN_IF_ERROR(StepValueExp());
  2442. break;
  2443. case Action::Kind::ExpressionAction:
  2444. CARBON_RETURN_IF_ERROR(StepExp());
  2445. break;
  2446. case Action::Kind::WitnessAction:
  2447. CARBON_RETURN_IF_ERROR(StepWitness());
  2448. break;
  2449. case Action::Kind::StatementAction:
  2450. CARBON_RETURN_IF_ERROR(StepStmt());
  2451. break;
  2452. case Action::Kind::DeclarationAction:
  2453. CARBON_RETURN_IF_ERROR(StepDeclaration());
  2454. break;
  2455. case Action::Kind::CleanUpAction:
  2456. CARBON_RETURN_IF_ERROR(StepCleanUp());
  2457. break;
  2458. case Action::Kind::DestroyAction:
  2459. CARBON_RETURN_IF_ERROR(StepDestroy());
  2460. break;
  2461. case Action::Kind::TypeInstantiationAction:
  2462. CARBON_RETURN_IF_ERROR(StepInstantiateType());
  2463. break;
  2464. case Action::Kind::ScopeAction:
  2465. CARBON_FATAL() << "ScopeAction escaped ActionStack";
  2466. case Action::Kind::RecursiveAction:
  2467. CARBON_FATAL() << "Tried to step a RecursiveAction";
  2468. } // switch
  2469. return Success();
  2470. }
  2471. auto Interpreter::RunAllSteps(std::unique_ptr<Action> action)
  2472. -> ErrorOr<Success> {
  2473. todo_.Start(std::move(action));
  2474. while (!todo_.empty()) {
  2475. CARBON_RETURN_IF_ERROR(Step());
  2476. }
  2477. return Success();
  2478. }
  2479. auto InterpProgram(const AST& ast, Nonnull<Arena*> arena,
  2480. Nonnull<TraceStream*> trace_stream,
  2481. Nonnull<llvm::raw_ostream*> print_stream) -> ErrorOr<int> {
  2482. Interpreter interpreter(Phase::RunTime, arena, trace_stream, print_stream);
  2483. if (trace_stream->is_enabled()) {
  2484. trace_stream->SubHeading("initializing globals");
  2485. }
  2486. SetFileContext set_file_ctx(*trace_stream,
  2487. ast.declarations.front()->source_loc());
  2488. for (Nonnull<Declaration*> declaration : ast.declarations) {
  2489. set_file_ctx.update_source_loc(declaration->source_loc());
  2490. CARBON_RETURN_IF_ERROR(interpreter.RunAllSteps(
  2491. std::make_unique<DeclarationAction>(declaration)));
  2492. }
  2493. if (trace_stream->is_enabled()) {
  2494. trace_stream->SubHeading("calling main function");
  2495. }
  2496. CARBON_CHECK(ast.main_call);
  2497. set_file_ctx.update_source_loc(ast.main_call.value()->source_loc());
  2498. CARBON_RETURN_IF_ERROR(interpreter.RunAllSteps(
  2499. std::make_unique<ValueExpressionAction>(*ast.main_call)));
  2500. return cast<IntValue>(*interpreter.result()).value();
  2501. }
  2502. auto InterpExp(Nonnull<const Expression*> e, Nonnull<Arena*> arena,
  2503. Nonnull<TraceStream*> trace_stream,
  2504. Nonnull<llvm::raw_ostream*> print_stream)
  2505. -> ErrorOr<Nonnull<const Value*>> {
  2506. Interpreter interpreter(Phase::CompileTime, arena, trace_stream,
  2507. print_stream);
  2508. CARBON_RETURN_IF_ERROR(
  2509. interpreter.RunAllSteps(std::make_unique<ValueExpressionAction>(e)));
  2510. return interpreter.result();
  2511. }
  2512. } // namespace Carbon