interpreter.cpp 117 KB

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