interpreter.cpp 117 KB

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