interpreter.cpp 109 KB

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