interpreter.cpp 100 KB

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