interpreter.cpp 96 KB

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