interpreter.cpp 92 KB

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