interpreter.cpp 116 KB

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