interpreter.cpp 104 KB

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