interpreter.cpp 95 KB

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