interpreter.cpp 88 KB

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