interpreter.cpp 96 KB

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