interpreter.cpp 95 KB

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