interpreter.cpp 108 KB

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