interpreter.cpp 111 KB

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