interpreter.cpp 97 KB

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