interpreter.cpp 111 KB

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