interpreter.cpp 109 KB

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