interpreter.cpp 112 KB

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