interpreter.cpp 97 KB

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