interpreter.cpp 91 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214
  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 " << ToString(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::IndexExpression: {
  419. if (act.pos() == 0) {
  420. // { {e[i] :: C, E, F} :: S, H}
  421. // -> { e :: [][i] :: C, E, F} :: S, H}
  422. return todo_.Spawn(
  423. std::make_unique<LValAction>(&cast<IndexExpression>(exp).object()));
  424. } else if (act.pos() == 1) {
  425. return todo_.Spawn(std::make_unique<ExpressionAction>(
  426. &cast<IndexExpression>(exp).offset()));
  427. } else {
  428. // { v :: [][i] :: C, E, F} :: S, H}
  429. // -> { { &v[i] :: C, E, F} :: S, H }
  430. Address object = cast<LValue>(*act.results()[0]).address();
  431. const auto index = cast<IntValue>(*act.results()[1]).value();
  432. Address field = object.ElementAddress(
  433. arena_->New<PositionalElement>(index, &exp.static_type()));
  434. return todo_.FinishAction(arena_->New<LValue>(field));
  435. }
  436. }
  437. case ExpressionKind::OperatorExpression: {
  438. const auto& op = cast<OperatorExpression>(exp);
  439. if (auto rewrite = op.rewritten_form()) {
  440. return todo_.ReplaceWith(std::make_unique<LValAction>(*rewrite));
  441. }
  442. if (op.op() != Operator::Deref) {
  443. CARBON_FATAL()
  444. << "Can't treat primitive operator expression as lvalue: " << exp;
  445. }
  446. if (act.pos() == 0) {
  447. return todo_.Spawn(
  448. std::make_unique<ExpressionAction>(op.arguments()[0]));
  449. } else {
  450. const auto& res = cast<PointerValue>(*act.results()[0]);
  451. return todo_.FinishAction(arena_->New<LValue>(res.address()));
  452. }
  453. break;
  454. }
  455. case ExpressionKind::TupleLiteral:
  456. case ExpressionKind::StructLiteral:
  457. case ExpressionKind::StructTypeLiteral:
  458. case ExpressionKind::IntLiteral:
  459. case ExpressionKind::BoolLiteral:
  460. case ExpressionKind::CallExpression:
  461. case ExpressionKind::IntTypeLiteral:
  462. case ExpressionKind::BoolTypeLiteral:
  463. case ExpressionKind::TypeTypeLiteral:
  464. case ExpressionKind::FunctionTypeLiteral:
  465. case ExpressionKind::ContinuationTypeLiteral:
  466. case ExpressionKind::StringLiteral:
  467. case ExpressionKind::StringTypeLiteral:
  468. case ExpressionKind::ValueLiteral:
  469. case ExpressionKind::IntrinsicExpression:
  470. case ExpressionKind::IfExpression:
  471. case ExpressionKind::WhereExpression:
  472. case ExpressionKind::DotSelfExpression:
  473. case ExpressionKind::ArrayTypeLiteral:
  474. case ExpressionKind::BuiltinConvertExpression:
  475. CARBON_FATAL() << "Can't treat expression as lvalue: " << exp;
  476. case ExpressionKind::UnimplementedExpression:
  477. CARBON_FATAL() << "Unimplemented: " << exp;
  478. }
  479. }
  480. auto Interpreter::EvalRecursively(std::unique_ptr<Action> action)
  481. -> ErrorOr<Nonnull<const Value*>> {
  482. if (trace_stream_) {
  483. **trace_stream_ << "--- recursive eval\n";
  484. PrintState(**trace_stream_);
  485. }
  486. todo_.BeginRecursiveAction();
  487. CARBON_RETURN_IF_ERROR(todo_.Spawn(std::move(action)));
  488. // Note that the only `RecursiveAction` we can encounter here is our own --
  489. // if a nested action begins a recursive action, it will run until that
  490. // action is finished and popped off the queue before returning to us.
  491. while (!isa<RecursiveAction>(todo_.CurrentAction())) {
  492. CARBON_RETURN_IF_ERROR(Step());
  493. if (trace_stream_) {
  494. PrintState(**trace_stream_);
  495. }
  496. }
  497. if (trace_stream_) {
  498. **trace_stream_ << "--- recursive eval done\n";
  499. }
  500. Nonnull<const Value*> result =
  501. cast<RecursiveAction>(todo_.CurrentAction()).results()[0];
  502. CARBON_RETURN_IF_ERROR(todo_.FinishAction());
  503. return result;
  504. }
  505. auto Interpreter::EvalAssociatedConstant(
  506. Nonnull<const AssociatedConstant*> assoc, SourceLocation source_loc)
  507. -> ErrorOr<Nonnull<const Value*>> {
  508. // Instantiate the associated constant.
  509. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> interface,
  510. InstantiateType(&assoc->interface(), source_loc));
  511. CARBON_ASSIGN_OR_RETURN(Nonnull<const Witness*> witness,
  512. InstantiateWitness(&assoc->witness()));
  513. const auto* impl_witness = dyn_cast<ImplWitness>(witness);
  514. if (!impl_witness) {
  515. CARBON_CHECK(phase() == Phase::CompileTime)
  516. << "symbolic witnesses should only be formed at compile time";
  517. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> base,
  518. InstantiateType(&assoc->base(), source_loc));
  519. return arena_->New<AssociatedConstant>(base, cast<InterfaceType>(interface),
  520. &assoc->constant(), witness);
  521. }
  522. // We have an impl. Extract the value from it.
  523. Nonnull<const ConstraintType*> constraint =
  524. impl_witness->declaration().constraint_type();
  525. std::optional<Nonnull<const Value*>> result;
  526. for (auto& rewrite : constraint->rewrite_constraints()) {
  527. if (&rewrite.constant->constant() == &assoc->constant() &&
  528. TypeEqual(&rewrite.constant->interface(), interface, std::nullopt)) {
  529. // TODO: The value might depend on the parameters of the impl. We need to
  530. // substitute impl_witness->type_args() into the value.
  531. result = rewrite.converted_replacement;
  532. break;
  533. }
  534. }
  535. if (!result) {
  536. CARBON_FATAL() << impl_witness->declaration() << " with constraint "
  537. << *constraint
  538. << " is missing value for associated constant "
  539. << *interface << "." << assoc->constant().binding().name();
  540. }
  541. return *result;
  542. }
  543. auto Interpreter::InstantiateType(Nonnull<const Value*> type,
  544. SourceLocation source_loc)
  545. -> ErrorOr<Nonnull<const Value*>> {
  546. switch (type->kind()) {
  547. case Value::Kind::VariableType: {
  548. CARBON_ASSIGN_OR_RETURN(
  549. Nonnull<const Value*> value,
  550. todo_.ValueOfNode(&cast<VariableType>(*type).binding(), source_loc));
  551. if (const auto* lvalue = dyn_cast<LValue>(value)) {
  552. CARBON_ASSIGN_OR_RETURN(value,
  553. heap_.Read(lvalue->address(), source_loc));
  554. }
  555. return value;
  556. }
  557. case Value::Kind::InterfaceType: {
  558. const auto& interface_type = cast<InterfaceType>(*type);
  559. CARBON_ASSIGN_OR_RETURN(
  560. Nonnull<const Bindings*> bindings,
  561. InstantiateBindings(&interface_type.bindings(), source_loc));
  562. return arena_->New<InterfaceType>(&interface_type.declaration(),
  563. bindings);
  564. }
  565. case Value::Kind::NamedConstraintType: {
  566. const auto& constraint_type = cast<NamedConstraintType>(*type);
  567. CARBON_ASSIGN_OR_RETURN(
  568. Nonnull<const Bindings*> bindings,
  569. InstantiateBindings(&constraint_type.bindings(), source_loc));
  570. return arena_->New<NamedConstraintType>(&constraint_type.declaration(),
  571. bindings);
  572. }
  573. case Value::Kind::NominalClassType: {
  574. const auto& class_type = cast<NominalClassType>(*type);
  575. std::optional<Nonnull<const NominalClassType*>> base = class_type.base();
  576. if (base.has_value()) {
  577. CARBON_ASSIGN_OR_RETURN(const auto inst_base,
  578. InstantiateType(base.value(), source_loc));
  579. base = cast<NominalClassType>(inst_base);
  580. }
  581. CARBON_ASSIGN_OR_RETURN(
  582. Nonnull<const Bindings*> bindings,
  583. InstantiateBindings(&class_type.bindings(), source_loc));
  584. return arena_->New<NominalClassType>(&class_type.declaration(), bindings,
  585. base);
  586. }
  587. case Value::Kind::ChoiceType: {
  588. const auto& choice_type = cast<ChoiceType>(*type);
  589. CARBON_ASSIGN_OR_RETURN(
  590. Nonnull<const Bindings*> bindings,
  591. InstantiateBindings(&choice_type.bindings(), source_loc));
  592. return arena_->New<ChoiceType>(&choice_type.declaration(), bindings);
  593. }
  594. case Value::Kind::AssociatedConstant: {
  595. CARBON_ASSIGN_OR_RETURN(
  596. Nonnull<const Value*> type_value,
  597. EvalAssociatedConstant(cast<AssociatedConstant>(type), source_loc));
  598. return type_value;
  599. }
  600. case Value::Kind::PointerType: {
  601. const auto* ptr = cast<PointerType>(type);
  602. CARBON_ASSIGN_OR_RETURN(
  603. const auto* actual_type,
  604. InstantiateType(&ptr->pointee_type(), source_loc));
  605. return arena_->New<PointerType>(actual_type);
  606. }
  607. default:
  608. return type;
  609. }
  610. }
  611. auto Interpreter::InstantiateBindings(Nonnull<const Bindings*> bindings,
  612. SourceLocation source_loc)
  613. -> ErrorOr<Nonnull<const Bindings*>> {
  614. BindingMap args = bindings->args();
  615. for (auto& [var, arg] : args) {
  616. CARBON_ASSIGN_OR_RETURN(arg, InstantiateType(arg, source_loc));
  617. }
  618. ImplWitnessMap witnesses = bindings->witnesses();
  619. for (auto& [bind, witness] : witnesses) {
  620. CARBON_ASSIGN_OR_RETURN(witness,
  621. InstantiateWitness(cast<Witness>(witness)));
  622. }
  623. if (args == bindings->args() && witnesses == bindings->witnesses()) {
  624. return bindings;
  625. }
  626. return arena_->New<Bindings>(std::move(args), std::move(witnesses));
  627. }
  628. auto Interpreter::InstantiateWitness(Nonnull<const Witness*> witness)
  629. -> ErrorOr<Nonnull<const Witness*>> {
  630. CARBON_ASSIGN_OR_RETURN(
  631. Nonnull<const Value*> value,
  632. EvalRecursively(std::make_unique<WitnessAction>(witness)));
  633. return cast<Witness>(value);
  634. }
  635. auto Interpreter::ConvertStructToClass(
  636. Nonnull<const StructValue*> init_struct,
  637. Nonnull<const NominalClassType*> class_type, SourceLocation source_loc)
  638. -> ErrorOr<Nonnull<NominalClassValue*>> {
  639. std::vector<NamedValue> struct_values;
  640. std::optional<Nonnull<const NominalClassValue*>> base_instance;
  641. // Instantiate the `destination_type` to obtain the runtime
  642. // type of the object.
  643. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> inst_class,
  644. InstantiateType(class_type, source_loc));
  645. for (const auto& field : init_struct->elements()) {
  646. if (field.name == NominalClassValue::BaseField) {
  647. CARBON_CHECK(class_type->base().has_value())
  648. << "Invalid 'base' field for class '"
  649. << class_type->declaration().name() << "' without base class.";
  650. CARBON_ASSIGN_OR_RETURN(
  651. auto base,
  652. Convert(field.value, class_type->base().value(), source_loc));
  653. base_instance = cast<NominalClassValue>(base);
  654. } else {
  655. struct_values.push_back(field);
  656. }
  657. }
  658. auto* converted_init_struct =
  659. arena_->New<StructValue>(std::move(struct_values));
  660. return arena_->New<NominalClassValue>(inst_class, converted_init_struct,
  661. base_instance);
  662. }
  663. auto Interpreter::Convert(Nonnull<const Value*> value,
  664. Nonnull<const Value*> destination_type,
  665. SourceLocation source_loc)
  666. -> ErrorOr<Nonnull<const Value*>> {
  667. switch (value->kind()) {
  668. case Value::Kind::IntValue:
  669. case Value::Kind::FunctionValue:
  670. case Value::Kind::DestructorValue:
  671. case Value::Kind::BoundMethodValue:
  672. case Value::Kind::LValue:
  673. case Value::Kind::BoolValue:
  674. case Value::Kind::NominalClassValue:
  675. case Value::Kind::AlternativeValue:
  676. case Value::Kind::UninitializedValue:
  677. case Value::Kind::IntType:
  678. case Value::Kind::BoolType:
  679. case Value::Kind::TypeType:
  680. case Value::Kind::FunctionType:
  681. case Value::Kind::PointerType:
  682. case Value::Kind::TupleType:
  683. case Value::Kind::StructType:
  684. case Value::Kind::AutoType:
  685. case Value::Kind::NominalClassType:
  686. case Value::Kind::MixinPseudoType:
  687. case Value::Kind::InterfaceType:
  688. case Value::Kind::NamedConstraintType:
  689. case Value::Kind::ConstraintType:
  690. case Value::Kind::ImplWitness:
  691. case Value::Kind::BindingWitness:
  692. case Value::Kind::ConstraintWitness:
  693. case Value::Kind::ConstraintImplWitness:
  694. case Value::Kind::ParameterizedEntityName:
  695. case Value::Kind::ChoiceType:
  696. case Value::Kind::ContinuationType:
  697. case Value::Kind::VariableType:
  698. case Value::Kind::BindingPlaceholderValue:
  699. case Value::Kind::AddrValue:
  700. case Value::Kind::AlternativeConstructorValue:
  701. case Value::Kind::ContinuationValue:
  702. case Value::Kind::StringType:
  703. case Value::Kind::StringValue:
  704. case Value::Kind::TypeOfMixinPseudoType:
  705. case Value::Kind::TypeOfParameterizedEntityName:
  706. case Value::Kind::TypeOfMemberName:
  707. case Value::Kind::StaticArrayType:
  708. case Value::Kind::MemberName:
  709. // TODO: add `CARBON_CHECK(TypeEqual(type, value->dynamic_type()))`, once
  710. // we have Value::dynamic_type.
  711. return value;
  712. case Value::Kind::StructValue: {
  713. const auto& struct_val = cast<StructValue>(*value);
  714. switch (destination_type->kind()) {
  715. case Value::Kind::StructType: {
  716. const auto& destination_struct_type =
  717. cast<StructType>(*destination_type);
  718. std::vector<NamedValue> new_elements;
  719. for (const auto& [field_name, field_type] :
  720. destination_struct_type.fields()) {
  721. std::optional<Nonnull<const Value*>> old_value =
  722. struct_val.FindField(field_name);
  723. CARBON_ASSIGN_OR_RETURN(
  724. Nonnull<const Value*> val,
  725. Convert(*old_value, field_type, source_loc));
  726. new_elements.push_back({field_name, val});
  727. }
  728. return arena_->New<StructValue>(std::move(new_elements));
  729. }
  730. case Value::Kind::NominalClassType: {
  731. CARBON_ASSIGN_OR_RETURN(
  732. auto class_value,
  733. ConvertStructToClass(cast<StructValue>(value),
  734. cast<NominalClassType>(destination_type),
  735. source_loc));
  736. return class_value;
  737. }
  738. case Value::Kind::TypeType:
  739. case Value::Kind::ConstraintType:
  740. case Value::Kind::NamedConstraintType:
  741. case Value::Kind::InterfaceType: {
  742. CARBON_CHECK(struct_val.elements().empty())
  743. << "only empty structs convert to Type";
  744. return arena_->New<StructType>();
  745. }
  746. default: {
  747. CARBON_CHECK(IsValueKindDependent(destination_type) ||
  748. isa<TypeType, ConstraintType>(destination_type))
  749. << "Can't convert value " << *value << " to type "
  750. << *destination_type;
  751. return value;
  752. }
  753. }
  754. }
  755. case Value::Kind::TupleValue: {
  756. const auto* tuple = cast<TupleValue>(value);
  757. std::vector<Nonnull<const Value*>> destination_element_types;
  758. switch (destination_type->kind()) {
  759. case Value::Kind::TupleType:
  760. destination_element_types =
  761. cast<TupleType>(destination_type)->elements();
  762. break;
  763. case Value::Kind::StaticArrayType: {
  764. const auto& array_type = cast<StaticArrayType>(*destination_type);
  765. destination_element_types.resize(array_type.size(),
  766. &array_type.element_type());
  767. break;
  768. }
  769. case Value::Kind::TypeType:
  770. case Value::Kind::ConstraintType:
  771. case Value::Kind::NamedConstraintType:
  772. case Value::Kind::InterfaceType: {
  773. std::vector<Nonnull<const Value*>> new_elements;
  774. Nonnull<const Value*> type_type = arena_->New<TypeType>();
  775. for (Nonnull<const Value*> value : tuple->elements()) {
  776. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> value_as_type,
  777. Convert(value, type_type, source_loc));
  778. new_elements.push_back(value_as_type);
  779. }
  780. return arena_->New<TupleType>(std::move(new_elements));
  781. }
  782. default: {
  783. CARBON_CHECK(IsValueKindDependent(destination_type) ||
  784. isa<TypeType, ConstraintType>(destination_type))
  785. << "Can't convert value " << *value << " to type "
  786. << *destination_type;
  787. return value;
  788. }
  789. }
  790. CARBON_CHECK(tuple->elements().size() ==
  791. destination_element_types.size());
  792. std::vector<Nonnull<const Value*>> new_elements;
  793. for (size_t i = 0; i < tuple->elements().size(); ++i) {
  794. CARBON_ASSIGN_OR_RETURN(
  795. Nonnull<const Value*> val,
  796. Convert(tuple->elements()[i], destination_element_types[i],
  797. source_loc));
  798. new_elements.push_back(val);
  799. }
  800. return arena_->New<TupleValue>(std::move(new_elements));
  801. }
  802. case Value::Kind::AssociatedConstant: {
  803. CARBON_ASSIGN_OR_RETURN(
  804. Nonnull<const Value*> value,
  805. EvalAssociatedConstant(cast<AssociatedConstant>(value), source_loc));
  806. if (auto* new_const = dyn_cast<AssociatedConstant>(value)) {
  807. // TODO: Detect whether conversions are required in type-checking.
  808. if (isa<TypeType, ConstraintType, NamedConstraintType, InterfaceType>(
  809. destination_type) &&
  810. isa<TypeType, ConstraintType, NamedConstraintType, InterfaceType>(
  811. new_const->constant().static_type())) {
  812. // No further conversions are required.
  813. return value;
  814. }
  815. // We need to convert this, and we don't know how because we don't have
  816. // the value yet.
  817. return ProgramError(source_loc)
  818. << "value of associated constant " << *value << " is not known";
  819. }
  820. return Convert(value, destination_type, source_loc);
  821. }
  822. case Value::Kind::PointerValue: {
  823. if (destination_type->kind() != Value::Kind::PointerType ||
  824. cast<PointerType>(destination_type)->pointee_type().kind() !=
  825. Value::Kind::NominalClassType) {
  826. // No conversion needed.
  827. return value;
  828. }
  829. // Get pointee value.
  830. const auto* src_ptr = cast<PointerValue>(value);
  831. CARBON_ASSIGN_OR_RETURN(const auto* pointee,
  832. heap_.Read(src_ptr->address(), source_loc))
  833. CARBON_CHECK(pointee->kind() == Value::Kind::NominalClassValue)
  834. << "Unexpected pointer type";
  835. const auto* dest_ptr = cast<PointerType>(destination_type);
  836. std::optional<Nonnull<const NominalClassValue*>> class_subobj =
  837. cast<NominalClassValue>(pointee);
  838. auto new_addr = src_ptr->address();
  839. while (class_subobj) {
  840. if (TypeEqual(&(*class_subobj)->type(), &dest_ptr->pointee_type(),
  841. std::nullopt)) {
  842. return arena_->New<PointerValue>(new_addr);
  843. }
  844. class_subobj = (*class_subobj)->base();
  845. new_addr = new_addr.ElementAddress(
  846. arena_->New<BaseElement>(&dest_ptr->pointee_type()));
  847. }
  848. // Unable to resolve, return as-is.
  849. // TODO: Produce error instead once we can properly substitute
  850. // parameterized types for pointers in function call parameters.
  851. return value;
  852. }
  853. }
  854. }
  855. auto Interpreter::CallDestructor(Nonnull<const DestructorDeclaration*> fun,
  856. Nonnull<const Value*> receiver)
  857. -> ErrorOr<Success> {
  858. const DestructorDeclaration& method = *fun;
  859. CARBON_CHECK(method.is_method());
  860. RuntimeScope method_scope(&heap_);
  861. BindingMap generic_args;
  862. // TODO: move this logic into PatternMatch, and call it here.
  863. auto p = &method.self_pattern().value();
  864. const auto& placeholder = cast<BindingPlaceholderValue>(*p);
  865. if (placeholder.value_node().has_value()) {
  866. method_scope.Bind(*placeholder.value_node(), receiver);
  867. }
  868. CARBON_CHECK(method.body().has_value())
  869. << "Calling a method that's missing a body";
  870. auto act = std::make_unique<StatementAction>(*method.body());
  871. return todo_.Spawn(std::unique_ptr<Action>(std::move(act)),
  872. std::move(method_scope));
  873. }
  874. auto Interpreter::CallFunction(const CallExpression& call,
  875. Nonnull<const Value*> fun,
  876. Nonnull<const Value*> arg,
  877. ImplWitnessMap&& witnesses) -> ErrorOr<Success> {
  878. if (trace_stream_) {
  879. **trace_stream_ << "calling function: " << *fun << "\n";
  880. }
  881. switch (fun->kind()) {
  882. case Value::Kind::AlternativeConstructorValue: {
  883. const auto& alt = cast<AlternativeConstructorValue>(*fun);
  884. return todo_.FinishAction(arena_->New<AlternativeValue>(
  885. alt.alt_name(), alt.choice_name(), arg));
  886. }
  887. case Value::Kind::FunctionValue: {
  888. const auto& fun_val = cast<FunctionValue>(*fun);
  889. const FunctionDeclaration& function = fun_val.declaration();
  890. if (!function.body().has_value()) {
  891. return ProgramError(call.source_loc())
  892. << "attempt to call function `" << function.name()
  893. << "` that has not been defined";
  894. }
  895. if (!function.is_type_checked()) {
  896. return ProgramError(call.source_loc())
  897. << "attempt to call function `" << function.name()
  898. << "` that has not been fully type-checked";
  899. }
  900. RuntimeScope binding_scope(&heap_);
  901. // Bring the class type arguments into scope.
  902. for (const auto& [bind, val] : fun_val.type_args()) {
  903. binding_scope.Initialize(bind, val);
  904. }
  905. // Bring the deduced type arguments into scope.
  906. for (const auto& [bind, val] : call.deduced_args()) {
  907. binding_scope.Initialize(bind, val);
  908. }
  909. // Bring the impl witness tables into scope.
  910. for (const auto& [impl_bind, witness] : witnesses) {
  911. binding_scope.Initialize(impl_bind, witness);
  912. }
  913. for (const auto& [impl_bind, witness] : fun_val.witnesses()) {
  914. binding_scope.Initialize(impl_bind, witness);
  915. }
  916. // Enter the binding scope to make any deduced arguments visible before
  917. // we resolve the parameter type.
  918. todo_.CurrentAction().StartScope(std::move(binding_scope));
  919. CARBON_ASSIGN_OR_RETURN(
  920. Nonnull<const Value*> converted_args,
  921. Convert(arg, &function.param_pattern().static_type(),
  922. call.source_loc()));
  923. RuntimeScope function_scope(&heap_);
  924. BindingMap generic_args;
  925. CARBON_CHECK(PatternMatch(
  926. &function.param_pattern().value(), converted_args, call.source_loc(),
  927. &function_scope, generic_args, trace_stream_, this->arena_));
  928. return todo_.Spawn(std::make_unique<StatementAction>(*function.body()),
  929. std::move(function_scope));
  930. }
  931. case Value::Kind::BoundMethodValue: {
  932. const auto& m = cast<BoundMethodValue>(*fun);
  933. const FunctionDeclaration& method = m.declaration();
  934. CARBON_CHECK(method.is_method());
  935. CARBON_ASSIGN_OR_RETURN(
  936. Nonnull<const Value*> converted_args,
  937. Convert(arg, &method.param_pattern().static_type(),
  938. call.source_loc()));
  939. RuntimeScope method_scope(&heap_);
  940. BindingMap generic_args;
  941. // Bind the receiver to the `self` parameter.
  942. auto p = &method.self_pattern().value();
  943. if (p->kind() == Value::Kind::BindingPlaceholderValue) {
  944. // TODO: move this logic into PatternMatch
  945. const auto& placeholder = cast<BindingPlaceholderValue>(*p);
  946. if (placeholder.value_node().has_value()) {
  947. method_scope.Bind(*placeholder.value_node(), m.receiver());
  948. }
  949. } else {
  950. CARBON_CHECK(PatternMatch(&method.self_pattern().value(), m.receiver(),
  951. call.source_loc(), &method_scope,
  952. generic_args, trace_stream_, this->arena_));
  953. }
  954. // Bind the arguments to the parameters.
  955. CARBON_CHECK(PatternMatch(&method.param_pattern().value(), converted_args,
  956. call.source_loc(), &method_scope, generic_args,
  957. trace_stream_, this->arena_));
  958. // Bring the class type arguments into scope.
  959. for (const auto& [bind, val] : m.type_args()) {
  960. method_scope.Initialize(bind->original(), val);
  961. }
  962. // Bring the deduced type arguments into scope.
  963. for (const auto& [bind, val] : call.deduced_args()) {
  964. method_scope.Initialize(bind->original(), val);
  965. }
  966. // Bring the impl witness tables into scope.
  967. for (const auto& [impl_bind, witness] : witnesses) {
  968. method_scope.Initialize(impl_bind->original(), witness);
  969. }
  970. for (const auto& [impl_bind, witness] : m.witnesses()) {
  971. method_scope.Initialize(impl_bind->original(), witness);
  972. }
  973. CARBON_CHECK(method.body().has_value())
  974. << "Calling a method that's missing a body";
  975. return todo_.Spawn(std::make_unique<StatementAction>(*method.body()),
  976. std::move(method_scope));
  977. }
  978. case Value::Kind::ParameterizedEntityName: {
  979. const auto& name = cast<ParameterizedEntityName>(*fun);
  980. const Declaration& decl = name.declaration();
  981. RuntimeScope params_scope(&heap_);
  982. BindingMap generic_args;
  983. CARBON_CHECK(PatternMatch(&name.params().value(), arg, call.source_loc(),
  984. &params_scope, generic_args, trace_stream_,
  985. this->arena_));
  986. Nonnull<const Bindings*> bindings =
  987. arena_->New<Bindings>(std::move(generic_args), std::move(witnesses));
  988. switch (decl.kind()) {
  989. case DeclarationKind::ClassDeclaration: {
  990. const auto& class_decl = cast<ClassDeclaration>(decl);
  991. return todo_.FinishAction(arena_->New<NominalClassType>(
  992. &class_decl, bindings, class_decl.base_type()));
  993. }
  994. case DeclarationKind::InterfaceDeclaration:
  995. return todo_.FinishAction(arena_->New<InterfaceType>(
  996. &cast<InterfaceDeclaration>(decl), bindings));
  997. case DeclarationKind::ConstraintDeclaration:
  998. return todo_.FinishAction(arena_->New<NamedConstraintType>(
  999. &cast<ConstraintDeclaration>(decl), bindings));
  1000. case DeclarationKind::ChoiceDeclaration:
  1001. return todo_.FinishAction(arena_->New<ChoiceType>(
  1002. &cast<ChoiceDeclaration>(decl), bindings));
  1003. default:
  1004. CARBON_FATAL() << "unknown kind of ParameterizedEntityName " << decl;
  1005. }
  1006. }
  1007. default:
  1008. return ProgramError(call.source_loc())
  1009. << "in call, expected a function, not " << *fun;
  1010. }
  1011. }
  1012. auto Interpreter::StepExp() -> ErrorOr<Success> {
  1013. Action& act = todo_.CurrentAction();
  1014. const Expression& exp = cast<ExpressionAction>(act).expression();
  1015. if (trace_stream_) {
  1016. **trace_stream_ << "--- step exp " << exp << " ." << act.pos() << "."
  1017. << " (" << exp.source_loc() << ") --->\n";
  1018. }
  1019. switch (exp.kind()) {
  1020. case ExpressionKind::IndexExpression: {
  1021. if (act.pos() == 0) {
  1022. // { { e[i] :: C, E, F} :: S, H}
  1023. // -> { { e :: [][i] :: C, E, F} :: S, H}
  1024. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1025. &cast<IndexExpression>(exp).object()));
  1026. } else if (act.pos() == 1) {
  1027. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1028. &cast<IndexExpression>(exp).offset()));
  1029. } else {
  1030. // { { v :: [][i] :: C, E, F} :: S, H}
  1031. // -> { { v_i :: C, E, F} : S, H}
  1032. const auto& tuple = cast<TupleValue>(*act.results()[0]);
  1033. int i = cast<IntValue>(*act.results()[1]).value();
  1034. if (i < 0 || i >= static_cast<int>(tuple.elements().size())) {
  1035. return ProgramError(exp.source_loc())
  1036. << "index " << i << " out of range in " << tuple;
  1037. }
  1038. return todo_.FinishAction(tuple.elements()[i]);
  1039. }
  1040. }
  1041. case ExpressionKind::TupleLiteral: {
  1042. if (act.pos() <
  1043. static_cast<int>(cast<TupleLiteral>(exp).fields().size())) {
  1044. // { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
  1045. // H}
  1046. // -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
  1047. // H}
  1048. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1049. cast<TupleLiteral>(exp).fields()[act.pos()]));
  1050. } else {
  1051. return todo_.FinishAction(arena_->New<TupleValue>(act.results()));
  1052. }
  1053. }
  1054. case ExpressionKind::StructLiteral: {
  1055. const auto& literal = cast<StructLiteral>(exp);
  1056. if (act.pos() < static_cast<int>(literal.fields().size())) {
  1057. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1058. &literal.fields()[act.pos()].expression()));
  1059. } else {
  1060. return todo_.FinishAction(
  1061. CreateStruct(literal.fields(), act.results()));
  1062. }
  1063. }
  1064. case ExpressionKind::SimpleMemberAccessExpression: {
  1065. const auto& access = cast<SimpleMemberAccessExpression>(exp);
  1066. bool forming_member_name = isa<TypeOfMemberName>(&access.static_type());
  1067. if (act.pos() == 0) {
  1068. // First, evaluate the first operand.
  1069. if (access.is_addr_me_method()) {
  1070. return todo_.Spawn(std::make_unique<LValAction>(&access.object()));
  1071. } else {
  1072. return todo_.Spawn(
  1073. std::make_unique<ExpressionAction>(&access.object()));
  1074. }
  1075. } else if (act.pos() == 1 && access.impl().has_value() &&
  1076. !forming_member_name) {
  1077. // Next, if we're accessing an interface member, evaluate the `impl`
  1078. // expression to find the corresponding witness.
  1079. return todo_.Spawn(
  1080. std::make_unique<WitnessAction>(access.impl().value()));
  1081. } else {
  1082. // Finally, produce the result.
  1083. if (auto constant_value = access.constant_value()) {
  1084. CARBON_ASSIGN_OR_RETURN(
  1085. Nonnull<const Value*> instantiated,
  1086. InstantiateType(*constant_value, access.source_loc()));
  1087. return todo_.FinishAction(instantiated);
  1088. }
  1089. std::optional<Nonnull<const InterfaceType*>> found_in_interface =
  1090. access.found_in_interface();
  1091. if (found_in_interface) {
  1092. CARBON_ASSIGN_OR_RETURN(
  1093. Nonnull<const Value*> instantiated,
  1094. InstantiateType(*found_in_interface, exp.source_loc()));
  1095. found_in_interface = cast<InterfaceType>(instantiated);
  1096. }
  1097. if (const auto* member_name_type =
  1098. dyn_cast<TypeOfMemberName>(&access.static_type())) {
  1099. // The result is a member name, such as in `Type.field_name`. Form a
  1100. // suitable member name value.
  1101. CARBON_CHECK(phase() == Phase::CompileTime)
  1102. << "should not form MemberNames at runtime";
  1103. std::optional<const Value*> type_result;
  1104. if (!isa<InterfaceType, NamedConstraintType, ConstraintType>(
  1105. act.results()[0])) {
  1106. type_result = act.results()[0];
  1107. }
  1108. MemberName* member_name = arena_->New<MemberName>(
  1109. type_result, found_in_interface, member_name_type->member());
  1110. return todo_.FinishAction(member_name);
  1111. } else {
  1112. // The result is the value of the named field, such as in
  1113. // `value.field_name`. Extract the value within the given object.
  1114. std::optional<Nonnull<const Witness*>> witness;
  1115. if (access.impl().has_value()) {
  1116. witness = cast<Witness>(act.results()[1]);
  1117. }
  1118. ElementPath::Component member(&access.member(), found_in_interface,
  1119. witness);
  1120. const Value* aggregate;
  1121. if (access.is_type_access()) {
  1122. CARBON_ASSIGN_OR_RETURN(
  1123. aggregate, InstantiateType(&access.object().static_type(),
  1124. access.source_loc()));
  1125. } else if (const auto* lvalue = dyn_cast<LValue>(act.results()[0])) {
  1126. CARBON_ASSIGN_OR_RETURN(
  1127. aggregate,
  1128. this->heap_.Read(lvalue->address(), exp.source_loc()));
  1129. } else {
  1130. aggregate = act.results()[0];
  1131. }
  1132. CARBON_ASSIGN_OR_RETURN(
  1133. Nonnull<const Value*> member_value,
  1134. aggregate->GetElement(arena_, ElementPath(member),
  1135. exp.source_loc(), act.results()[0]));
  1136. return todo_.FinishAction(member_value);
  1137. }
  1138. }
  1139. }
  1140. case ExpressionKind::CompoundMemberAccessExpression: {
  1141. const auto& access = cast<CompoundMemberAccessExpression>(exp);
  1142. bool forming_member_name = isa<TypeOfMemberName>(&access.static_type());
  1143. if (act.pos() == 0) {
  1144. // First, evaluate the first operand.
  1145. if (access.is_addr_me_method()) {
  1146. return todo_.Spawn(std::make_unique<LValAction>(&access.object()));
  1147. } else {
  1148. return todo_.Spawn(
  1149. std::make_unique<ExpressionAction>(&access.object()));
  1150. }
  1151. } else if (act.pos() == 1 && access.impl().has_value() &&
  1152. !forming_member_name) {
  1153. // Next, if we're accessing an interface member, evaluate the `impl`
  1154. // expression to find the corresponding witness.
  1155. return todo_.Spawn(
  1156. std::make_unique<WitnessAction>(access.impl().value()));
  1157. } else {
  1158. // Finally, produce the result.
  1159. if (auto constant_value = access.constant_value()) {
  1160. CARBON_ASSIGN_OR_RETURN(
  1161. Nonnull<const Value*> instantiated,
  1162. InstantiateType(*constant_value, access.source_loc()));
  1163. return todo_.FinishAction(instantiated);
  1164. }
  1165. std::optional<Nonnull<const InterfaceType*>> found_in_interface =
  1166. access.member().interface();
  1167. if (found_in_interface) {
  1168. CARBON_ASSIGN_OR_RETURN(
  1169. Nonnull<const Value*> instantiated,
  1170. InstantiateType(*found_in_interface, exp.source_loc()));
  1171. found_in_interface = cast<InterfaceType>(instantiated);
  1172. }
  1173. if (forming_member_name) {
  1174. // If we're forming a member name, we must be in the outer evaluation
  1175. // in `Type.(Interface.method)`. Produce the same method name with
  1176. // its `type` field set.
  1177. CARBON_CHECK(phase() == Phase::CompileTime)
  1178. << "should not form MemberNames at runtime";
  1179. CARBON_CHECK(!access.member().base_type().has_value())
  1180. << "compound member access forming a member name should be "
  1181. "performing impl lookup";
  1182. auto* member_name = arena_->New<MemberName>(
  1183. act.results()[0], found_in_interface, access.member().member());
  1184. return todo_.FinishAction(member_name);
  1185. } else {
  1186. // Access the object to find the named member.
  1187. Nonnull<const Value*> object = act.results()[0];
  1188. if (access.is_type_access()) {
  1189. CARBON_ASSIGN_OR_RETURN(
  1190. object, InstantiateType(&access.object().static_type(),
  1191. access.source_loc()));
  1192. }
  1193. std::optional<Nonnull<const Witness*>> witness;
  1194. if (access.impl().has_value()) {
  1195. witness = cast<Witness>(act.results()[1]);
  1196. } else {
  1197. CARBON_CHECK(access.member().base_type().has_value())
  1198. << "compound access should have base type or impl";
  1199. CARBON_ASSIGN_OR_RETURN(
  1200. object, Convert(object, *access.member().base_type(),
  1201. exp.source_loc()));
  1202. }
  1203. ElementPath::Component field(&access.member().member(),
  1204. found_in_interface, witness);
  1205. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> member,
  1206. object->GetElement(arena_, ElementPath(field),
  1207. exp.source_loc(), object));
  1208. return todo_.FinishAction(member);
  1209. }
  1210. }
  1211. }
  1212. case ExpressionKind::IdentifierExpression: {
  1213. CARBON_CHECK(act.pos() == 0);
  1214. const auto& ident = cast<IdentifierExpression>(exp);
  1215. // { {x :: C, E, F} :: S, H} -> { {H(E(x)) :: C, E, F} :: S, H}
  1216. CARBON_ASSIGN_OR_RETURN(
  1217. Nonnull<const Value*> value,
  1218. todo_.ValueOfNode(ident.value_node(), ident.source_loc()));
  1219. if (const auto* lvalue = dyn_cast<LValue>(value)) {
  1220. CARBON_ASSIGN_OR_RETURN(
  1221. value, heap_.Read(lvalue->address(), exp.source_loc()));
  1222. }
  1223. return todo_.FinishAction(value);
  1224. }
  1225. case ExpressionKind::DotSelfExpression: {
  1226. CARBON_CHECK(act.pos() == 0);
  1227. const auto& dot_self = cast<DotSelfExpression>(exp);
  1228. return todo_.FinishAction(*dot_self.self_binding().symbolic_identity());
  1229. }
  1230. case ExpressionKind::IntLiteral:
  1231. CARBON_CHECK(act.pos() == 0);
  1232. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  1233. return todo_.FinishAction(
  1234. arena_->New<IntValue>(cast<IntLiteral>(exp).value()));
  1235. case ExpressionKind::BoolLiteral:
  1236. CARBON_CHECK(act.pos() == 0);
  1237. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  1238. return todo_.FinishAction(
  1239. arena_->New<BoolValue>(cast<BoolLiteral>(exp).value()));
  1240. case ExpressionKind::OperatorExpression: {
  1241. const auto& op = cast<OperatorExpression>(exp);
  1242. if (auto rewrite = op.rewritten_form()) {
  1243. return todo_.ReplaceWith(std::make_unique<ExpressionAction>(*rewrite));
  1244. }
  1245. if (act.pos() != static_cast<int>(op.arguments().size())) {
  1246. // { {v :: op(vs,[],e,es) :: C, E, F} :: S, H}
  1247. // -> { {e :: op(vs,v,[],es) :: C, E, F} :: S, H}
  1248. Nonnull<const Expression*> arg = op.arguments()[act.pos()];
  1249. if (op.op() == Operator::AddressOf) {
  1250. return todo_.Spawn(std::make_unique<LValAction>(arg));
  1251. } else if ((op.op() == Operator::And || op.op() == Operator::Or) &&
  1252. act.pos() == 1) {
  1253. // Short-circuit evaluation for 'and' & 'or'
  1254. const auto* operand_value =
  1255. cast<BoolValue>(act.results()[act.pos() - 1]);
  1256. if ((op.op() == Operator::Or && operand_value->value()) ||
  1257. (op.op() == Operator::And && !operand_value->value())) {
  1258. return todo_.FinishAction(operand_value);
  1259. }
  1260. // No short-circuit, fall through to evaluate 2nd operand.
  1261. }
  1262. return todo_.Spawn(std::make_unique<ExpressionAction>(arg));
  1263. } else {
  1264. // { {v :: op(vs,[]) :: C, E, F} :: S, H}
  1265. // -> { {eval_prim(op, (vs,v)) :: C, E, F} :: S, H}
  1266. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> value,
  1267. EvalPrim(op.op(), &op.static_type(),
  1268. act.results(), exp.source_loc()));
  1269. return todo_.FinishAction(value);
  1270. }
  1271. }
  1272. case ExpressionKind::CallExpression: {
  1273. const auto& call = cast<CallExpression>(exp);
  1274. unsigned int num_impls = call.impls().size();
  1275. if (act.pos() == 0) {
  1276. // { {e1(e2) :: C, E, F} :: S, H}
  1277. // -> { {e1 :: [](e2) :: C, E, F} :: S, H}
  1278. return todo_.Spawn(
  1279. std::make_unique<ExpressionAction>(&call.function()));
  1280. } else if (act.pos() == 1) {
  1281. // { { v :: [](e) :: C, E, F} :: S, H}
  1282. // -> { { e :: v([]) :: C, E, F} :: S, H}
  1283. return todo_.Spawn(
  1284. std::make_unique<ExpressionAction>(&call.argument()));
  1285. } else if (num_impls > 0 && act.pos() < 2 + static_cast<int>(num_impls)) {
  1286. auto iter = call.impls().begin();
  1287. std::advance(iter, act.pos() - 2);
  1288. return todo_.Spawn(
  1289. std::make_unique<WitnessAction>(cast<Witness>(iter->second)));
  1290. } else if (act.pos() == 2 + static_cast<int>(num_impls)) {
  1291. // { { v2 :: v1([]) :: C, E, F} :: S, H}
  1292. // -> { {C',E',F'} :: {C, E, F} :: S, H}
  1293. ImplWitnessMap witnesses;
  1294. if (num_impls > 0) {
  1295. int i = 2;
  1296. for (const auto& [impl_bind, impl_exp] : call.impls()) {
  1297. witnesses[impl_bind] = act.results()[i];
  1298. ++i;
  1299. }
  1300. }
  1301. return CallFunction(call, act.results()[0], act.results()[1],
  1302. std::move(witnesses));
  1303. } else if (act.pos() == 3 + static_cast<int>(num_impls)) {
  1304. if (act.results().size() < 3 + num_impls) {
  1305. // Control fell through without explicit return.
  1306. return todo_.FinishAction(TupleValue::Empty());
  1307. } else {
  1308. return todo_.FinishAction(
  1309. act.results()[2 + static_cast<int>(num_impls)]);
  1310. }
  1311. } else {
  1312. CARBON_FATAL() << "in StepExp with Call pos " << act.pos();
  1313. }
  1314. }
  1315. case ExpressionKind::IntrinsicExpression: {
  1316. const auto& intrinsic = cast<IntrinsicExpression>(exp);
  1317. if (act.pos() == 0) {
  1318. return todo_.Spawn(
  1319. std::make_unique<ExpressionAction>(&intrinsic.args()));
  1320. }
  1321. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  1322. const auto& args = cast<TupleValue>(*act.results()[0]).elements();
  1323. switch (cast<IntrinsicExpression>(exp).intrinsic()) {
  1324. case IntrinsicExpression::Intrinsic::Print: {
  1325. CARBON_ASSIGN_OR_RETURN(
  1326. Nonnull<const Value*> format_string_value,
  1327. Convert(args[0], arena_->New<StringType>(), exp.source_loc()));
  1328. const char* format_string =
  1329. cast<StringValue>(*format_string_value).value().c_str();
  1330. switch (args.size()) {
  1331. case 1:
  1332. llvm::outs() << llvm::formatv(format_string);
  1333. break;
  1334. case 2:
  1335. llvm::outs() << llvm::formatv(format_string,
  1336. cast<IntValue>(*args[1]).value());
  1337. break;
  1338. default:
  1339. CARBON_FATAL() << "Unexpected arg count: " << args.size();
  1340. }
  1341. // Implicit newline; currently no way to disable it.
  1342. llvm::outs() << "\n";
  1343. return todo_.FinishAction(TupleValue::Empty());
  1344. }
  1345. case IntrinsicExpression::Intrinsic::Assert: {
  1346. CARBON_CHECK(args.size() == 2);
  1347. CARBON_ASSIGN_OR_RETURN(
  1348. Nonnull<const Value*> condition,
  1349. Convert(args[0], arena_->New<BoolType>(), exp.source_loc()));
  1350. CARBON_ASSIGN_OR_RETURN(
  1351. Nonnull<const Value*> string_value,
  1352. Convert(args[1], arena_->New<StringType>(), exp.source_loc()));
  1353. bool condition_value = cast<BoolValue>(condition)->value();
  1354. if (!condition_value) {
  1355. return ProgramError(exp.source_loc()) << *string_value;
  1356. }
  1357. return todo_.FinishAction(TupleValue::Empty());
  1358. }
  1359. case IntrinsicExpression::Intrinsic::Alloc: {
  1360. CARBON_CHECK(args.size() == 1);
  1361. Address addr(heap_.AllocateValue(args[0]));
  1362. return todo_.FinishAction(arena_->New<PointerValue>(addr));
  1363. }
  1364. case IntrinsicExpression::Intrinsic::Dealloc: {
  1365. CARBON_CHECK(args.size() == 1);
  1366. heap_.Deallocate(cast<PointerValue>(args[0])->address());
  1367. return todo_.FinishAction(TupleValue::Empty());
  1368. }
  1369. case IntrinsicExpression::Intrinsic::Rand: {
  1370. CARBON_CHECK(args.size() == 2);
  1371. const auto& low = cast<IntValue>(*args[0]).value();
  1372. const auto& high = cast<IntValue>(*args[1]).value();
  1373. CARBON_CHECK(high > low);
  1374. // We avoid using std::uniform_int_distribution because it's not
  1375. // reproducible across builds/platforms.
  1376. int r = (generator() % (high - low)) + low;
  1377. return todo_.FinishAction(arena_->New<IntValue>(r));
  1378. }
  1379. case IntrinsicExpression::Intrinsic::IntEq: {
  1380. CARBON_CHECK(args.size() == 2);
  1381. auto lhs = cast<IntValue>(*args[0]).value();
  1382. auto rhs = cast<IntValue>(*args[1]).value();
  1383. auto* result = arena_->New<BoolValue>(lhs == rhs);
  1384. return todo_.FinishAction(result);
  1385. }
  1386. case IntrinsicExpression::Intrinsic::StrEq: {
  1387. CARBON_CHECK(args.size() == 2);
  1388. const auto& lhs = cast<StringValue>(*args[0]).value();
  1389. const auto& rhs = cast<StringValue>(*args[1]).value();
  1390. auto* result = arena_->New<BoolValue>(lhs == rhs);
  1391. return todo_.FinishAction(result);
  1392. }
  1393. case IntrinsicExpression::Intrinsic::IntCompare: {
  1394. CARBON_CHECK(args.size() == 2);
  1395. auto lhs = cast<IntValue>(*args[0]).value();
  1396. auto rhs = cast<IntValue>(*args[1]).value();
  1397. if (lhs < rhs) {
  1398. auto* result = arena_->New<IntValue>(-1);
  1399. return todo_.FinishAction(result);
  1400. }
  1401. if (lhs == rhs) {
  1402. auto* result = arena_->New<IntValue>(0);
  1403. return todo_.FinishAction(result);
  1404. }
  1405. auto* result = arena_->New<IntValue>(1);
  1406. return todo_.FinishAction(result);
  1407. }
  1408. case IntrinsicExpression::Intrinsic::StrCompare: {
  1409. CARBON_CHECK(args.size() == 2);
  1410. const auto& lhs = cast<StringValue>(*args[0]).value();
  1411. const auto& rhs = cast<StringValue>(*args[1]).value();
  1412. if (lhs < rhs) {
  1413. auto* result = arena_->New<IntValue>(-1);
  1414. return todo_.FinishAction(result);
  1415. }
  1416. if (lhs == rhs) {
  1417. auto* result = arena_->New<IntValue>(0);
  1418. return todo_.FinishAction(result);
  1419. }
  1420. auto* result = arena_->New<IntValue>(1);
  1421. return todo_.FinishAction(result);
  1422. }
  1423. case IntrinsicExpression::Intrinsic::IntBitComplement: {
  1424. CARBON_CHECK(args.size() == 1);
  1425. return todo_.FinishAction(
  1426. arena_->New<IntValue>(~cast<IntValue>(*args[0]).value()));
  1427. }
  1428. case IntrinsicExpression::Intrinsic::IntBitAnd: {
  1429. CARBON_CHECK(args.size() == 2);
  1430. return todo_.FinishAction(
  1431. arena_->New<IntValue>(cast<IntValue>(*args[0]).value() &
  1432. cast<IntValue>(*args[1]).value()));
  1433. }
  1434. case IntrinsicExpression::Intrinsic::IntBitOr: {
  1435. CARBON_CHECK(args.size() == 2);
  1436. return todo_.FinishAction(
  1437. arena_->New<IntValue>(cast<IntValue>(*args[0]).value() |
  1438. cast<IntValue>(*args[1]).value()));
  1439. }
  1440. case IntrinsicExpression::Intrinsic::IntBitXor: {
  1441. CARBON_CHECK(args.size() == 2);
  1442. return todo_.FinishAction(
  1443. arena_->New<IntValue>(cast<IntValue>(*args[0]).value() ^
  1444. cast<IntValue>(*args[1]).value()));
  1445. }
  1446. case IntrinsicExpression::Intrinsic::IntLeftShift: {
  1447. CARBON_CHECK(args.size() == 2);
  1448. // TODO: Runtime error if RHS is too large.
  1449. return todo_.FinishAction(arena_->New<IntValue>(
  1450. static_cast<uint32_t>(cast<IntValue>(*args[0]).value())
  1451. << cast<IntValue>(*args[1]).value()));
  1452. }
  1453. case IntrinsicExpression::Intrinsic::IntRightShift: {
  1454. CARBON_CHECK(args.size() == 2);
  1455. // TODO: Runtime error if RHS is too large.
  1456. return todo_.FinishAction(
  1457. arena_->New<IntValue>(cast<IntValue>(*args[0]).value() >>
  1458. cast<IntValue>(*args[1]).value()));
  1459. }
  1460. }
  1461. }
  1462. case ExpressionKind::IntTypeLiteral: {
  1463. CARBON_CHECK(act.pos() == 0);
  1464. return todo_.FinishAction(arena_->New<IntType>());
  1465. }
  1466. case ExpressionKind::BoolTypeLiteral: {
  1467. CARBON_CHECK(act.pos() == 0);
  1468. return todo_.FinishAction(arena_->New<BoolType>());
  1469. }
  1470. case ExpressionKind::TypeTypeLiteral: {
  1471. CARBON_CHECK(act.pos() == 0);
  1472. return todo_.FinishAction(arena_->New<TypeType>());
  1473. }
  1474. case ExpressionKind::ContinuationTypeLiteral: {
  1475. CARBON_CHECK(act.pos() == 0);
  1476. return todo_.FinishAction(arena_->New<ContinuationType>());
  1477. }
  1478. case ExpressionKind::StringLiteral:
  1479. CARBON_CHECK(act.pos() == 0);
  1480. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  1481. return todo_.FinishAction(
  1482. arena_->New<StringValue>(cast<StringLiteral>(exp).value()));
  1483. case ExpressionKind::StringTypeLiteral: {
  1484. CARBON_CHECK(act.pos() == 0);
  1485. return todo_.FinishAction(arena_->New<StringType>());
  1486. }
  1487. case ExpressionKind::FunctionTypeLiteral:
  1488. case ExpressionKind::StructTypeLiteral:
  1489. case ExpressionKind::ArrayTypeLiteral:
  1490. case ExpressionKind::ValueLiteral: {
  1491. CARBON_CHECK(act.pos() == 0);
  1492. auto* value = &cast<ConstantValueLiteral>(exp).constant_value();
  1493. CARBON_ASSIGN_OR_RETURN(
  1494. Nonnull<const Value*> destination,
  1495. InstantiateType(&exp.static_type(), exp.source_loc()));
  1496. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> result,
  1497. Convert(value, destination, exp.source_loc()));
  1498. return todo_.FinishAction(result);
  1499. }
  1500. case ExpressionKind::IfExpression: {
  1501. const auto& if_expr = cast<IfExpression>(exp);
  1502. if (act.pos() == 0) {
  1503. return todo_.Spawn(
  1504. std::make_unique<ExpressionAction>(&if_expr.condition()));
  1505. } else if (act.pos() == 1) {
  1506. const auto& condition = cast<BoolValue>(*act.results()[0]);
  1507. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1508. condition.value() ? &if_expr.then_expression()
  1509. : &if_expr.else_expression()));
  1510. } else {
  1511. return todo_.FinishAction(act.results()[1]);
  1512. }
  1513. break;
  1514. }
  1515. case ExpressionKind::WhereExpression: {
  1516. auto rewrite = cast<WhereExpression>(exp).rewritten_form();
  1517. CARBON_CHECK(rewrite) << "where expression should be rewritten";
  1518. return todo_.ReplaceWith(std::make_unique<ExpressionAction>(*rewrite));
  1519. }
  1520. case ExpressionKind::BuiltinConvertExpression: {
  1521. const auto& convert_expr = cast<BuiltinConvertExpression>(exp);
  1522. if (act.pos() == 0) {
  1523. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1524. convert_expr.source_expression()));
  1525. } else {
  1526. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> destination,
  1527. InstantiateType(&convert_expr.static_type(),
  1528. convert_expr.source_loc()));
  1529. // TODO: Remove all calls to Convert other than this one. We shouldn't
  1530. // need them any more.
  1531. CARBON_ASSIGN_OR_RETURN(
  1532. Nonnull<const Value*> result,
  1533. Convert(act.results()[0], destination, convert_expr.source_loc()));
  1534. return todo_.FinishAction(result);
  1535. }
  1536. }
  1537. case ExpressionKind::UnimplementedExpression:
  1538. CARBON_FATAL() << "Unimplemented: " << exp;
  1539. } // switch (exp->kind)
  1540. }
  1541. auto Interpreter::StepWitness() -> ErrorOr<Success> {
  1542. Action& act = todo_.CurrentAction();
  1543. const Witness* witness = cast<WitnessAction>(act).witness();
  1544. if (trace_stream_) {
  1545. **trace_stream_ << "--- step witness " << *witness << " ." << act.pos()
  1546. << ". --->\n";
  1547. }
  1548. switch (witness->kind()) {
  1549. case Value::Kind::BindingWitness: {
  1550. const ImplBinding* binding = cast<BindingWitness>(witness)->binding();
  1551. CARBON_ASSIGN_OR_RETURN(
  1552. Nonnull<const Value*> value,
  1553. todo_.ValueOfNode(binding, binding->type_var()->source_loc()));
  1554. if (const auto* lvalue = dyn_cast<LValue>(value)) {
  1555. // TODO: Why do we store values for impl bindings on the heap?
  1556. CARBON_ASSIGN_OR_RETURN(
  1557. value,
  1558. heap_.Read(lvalue->address(), binding->type_var()->source_loc()));
  1559. }
  1560. return todo_.FinishAction(value);
  1561. }
  1562. case Value::Kind::ConstraintWitness: {
  1563. llvm::ArrayRef<Nonnull<const Witness*>> witnesses =
  1564. cast<ConstraintWitness>(witness)->witnesses();
  1565. if (act.pos() < static_cast<int>(witnesses.size())) {
  1566. return todo_.Spawn(
  1567. std::make_unique<WitnessAction>(witnesses[act.pos()]));
  1568. }
  1569. std::vector<Nonnull<const Witness*>> new_witnesses;
  1570. new_witnesses.reserve(witnesses.size());
  1571. for (const auto* witness : act.results()) {
  1572. new_witnesses.push_back(cast<Witness>(witness));
  1573. }
  1574. return todo_.FinishAction(
  1575. arena_->New<ConstraintWitness>(std::move(new_witnesses)));
  1576. }
  1577. case Value::Kind::ConstraintImplWitness: {
  1578. const auto* constraint_impl = cast<ConstraintImplWitness>(witness);
  1579. if (act.pos() == 0) {
  1580. return todo_.Spawn(std::make_unique<WitnessAction>(
  1581. constraint_impl->constraint_witness()));
  1582. }
  1583. return todo_.FinishAction(ConstraintImplWitness::Make(
  1584. arena_, cast<Witness>(act.results()[0]), constraint_impl->index()));
  1585. }
  1586. case Value::Kind::ImplWitness: {
  1587. const auto* impl_witness = cast<ImplWitness>(witness);
  1588. CARBON_ASSIGN_OR_RETURN(
  1589. Nonnull<const Bindings*> new_bindings,
  1590. InstantiateBindings(&impl_witness->bindings(),
  1591. impl_witness->declaration().source_loc()));
  1592. return todo_.FinishAction(
  1593. new_bindings == &impl_witness->bindings()
  1594. ? impl_witness
  1595. : arena_->New<ImplWitness>(&impl_witness->declaration(),
  1596. new_bindings));
  1597. }
  1598. default:
  1599. CARBON_FATAL() << "unexpected kind of witness " << *witness;
  1600. }
  1601. }
  1602. auto Interpreter::StepStmt() -> ErrorOr<Success> {
  1603. Action& act = todo_.CurrentAction();
  1604. const Statement& stmt = cast<StatementAction>(act).statement();
  1605. if (trace_stream_) {
  1606. **trace_stream_ << "--- step stmt ";
  1607. stmt.PrintDepth(1, **trace_stream_);
  1608. **trace_stream_ << " ." << act.pos() << ". "
  1609. << "(" << stmt.source_loc() << ") --->\n";
  1610. }
  1611. switch (stmt.kind()) {
  1612. case StatementKind::Match: {
  1613. const auto& match_stmt = cast<Match>(stmt);
  1614. if (act.pos() == 0) {
  1615. // { { (match (e) ...) :: C, E, F} :: S, H}
  1616. // -> { { e :: (match ([]) ...) :: C, E, F} :: S, H}
  1617. act.StartScope(RuntimeScope(&heap_));
  1618. return todo_.Spawn(
  1619. std::make_unique<ExpressionAction>(&match_stmt.expression()));
  1620. } else {
  1621. int clause_num = act.pos() - 1;
  1622. if (clause_num >= static_cast<int>(match_stmt.clauses().size())) {
  1623. return todo_.FinishAction();
  1624. }
  1625. auto c = match_stmt.clauses()[clause_num];
  1626. RuntimeScope matches(&heap_);
  1627. BindingMap generic_args;
  1628. CARBON_ASSIGN_OR_RETURN(
  1629. Nonnull<const Value*> val,
  1630. Convert(act.results()[0], &c.pattern().static_type(),
  1631. stmt.source_loc()));
  1632. if (PatternMatch(&c.pattern().value(), val, stmt.source_loc(), &matches,
  1633. generic_args, trace_stream_, this->arena_)) {
  1634. // Ensure we don't process any more clauses.
  1635. act.set_pos(match_stmt.clauses().size() + 1);
  1636. todo_.MergeScope(std::move(matches));
  1637. return todo_.Spawn(std::make_unique<StatementAction>(&c.statement()));
  1638. } else {
  1639. return todo_.RunAgain();
  1640. }
  1641. }
  1642. }
  1643. case StatementKind::For: {
  1644. constexpr int TargetVarPosInResult = 0;
  1645. constexpr int CurrentIndexPosInResult = 1;
  1646. constexpr int EndIndexPosInResult = 2;
  1647. const auto* loop_var = &cast<BindingPlaceholderValue>(
  1648. cast<For>(stmt).variable_declaration().value());
  1649. if (act.pos() == 0) {
  1650. return todo_.Spawn(
  1651. std::make_unique<ExpressionAction>(&cast<For>(stmt).loop_target()));
  1652. }
  1653. if (act.pos() == 1) {
  1654. const auto* source_array =
  1655. cast<TupleValue>(act.results()[TargetVarPosInResult]);
  1656. int start_index = 0;
  1657. auto end_index = static_cast<int>(source_array->elements().size());
  1658. if (end_index == 0) {
  1659. return todo_.FinishAction();
  1660. }
  1661. act.AddResult(arena_->New<IntValue>(start_index));
  1662. act.AddResult(arena_->New<IntValue>(end_index));
  1663. todo_.Initialize(*(loop_var->value_node()),
  1664. source_array->elements()[start_index]);
  1665. act.ReplaceResult(CurrentIndexPosInResult,
  1666. arena_->New<IntValue>(start_index + 1));
  1667. return todo_.Spawn(
  1668. std::make_unique<StatementAction>(&cast<For>(stmt).body()));
  1669. }
  1670. if (act.pos() >= 2) {
  1671. auto current_index =
  1672. cast<IntValue>(act.results()[CurrentIndexPosInResult])->value();
  1673. auto end_index =
  1674. cast<IntValue>(act.results()[EndIndexPosInResult])->value();
  1675. if (current_index < end_index) {
  1676. const auto* source_array =
  1677. cast<const TupleValue>(act.results()[TargetVarPosInResult]);
  1678. CARBON_ASSIGN_OR_RETURN(
  1679. Nonnull<const Value*> assigned_array_element,
  1680. todo_.ValueOfNode(*(loop_var->value_node()), stmt.source_loc()));
  1681. const auto* lvalue = cast<LValue>(assigned_array_element);
  1682. CARBON_RETURN_IF_ERROR(heap_.Write(
  1683. lvalue->address(), source_array->elements()[current_index],
  1684. stmt.source_loc()));
  1685. act.ReplaceResult(CurrentIndexPosInResult,
  1686. arena_->New<IntValue>(current_index + 1));
  1687. return todo_.Spawn(
  1688. std::make_unique<StatementAction>(&cast<For>(stmt).body()));
  1689. }
  1690. }
  1691. return todo_.FinishAction();
  1692. }
  1693. case StatementKind::While:
  1694. // TODO: Rewrite While to use ReplaceResult to store condition result.
  1695. // This will remove the inconsistency between the while and for
  1696. // loops.
  1697. if (act.pos() % 2 == 0) {
  1698. // { { (while (e) s) :: C, E, F} :: S, H}
  1699. // -> { { e :: (while ([]) s) :: C, E, F} :: S, H}
  1700. act.Clear();
  1701. return todo_.Spawn(
  1702. std::make_unique<ExpressionAction>(&cast<While>(stmt).condition()));
  1703. } else {
  1704. CARBON_ASSIGN_OR_RETURN(
  1705. Nonnull<const Value*> condition,
  1706. Convert(act.results().back(), arena_->New<BoolType>(),
  1707. stmt.source_loc()));
  1708. if (cast<BoolValue>(*condition).value()) {
  1709. // { {true :: (while ([]) s) :: C, E, F} :: S, H}
  1710. // -> { { s :: (while (e) s) :: C, E, F } :: S, H}
  1711. return todo_.Spawn(
  1712. std::make_unique<StatementAction>(&cast<While>(stmt).body()));
  1713. } else {
  1714. // { {false :: (while ([]) s) :: C, E, F} :: S, H}
  1715. // -> { { C, E, F } :: S, H}
  1716. return todo_.FinishAction();
  1717. }
  1718. }
  1719. case StatementKind::Break: {
  1720. CARBON_CHECK(act.pos() == 0);
  1721. // { { break; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  1722. // -> { { C, E', F} :: S, H}
  1723. return todo_.UnwindPast(&cast<Break>(stmt).loop());
  1724. }
  1725. case StatementKind::Continue: {
  1726. CARBON_CHECK(act.pos() == 0);
  1727. // { { continue; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  1728. // -> { { (while (e) s) :: C, E', F} :: S, H}
  1729. return todo_.UnwindTo(&cast<Continue>(stmt).loop());
  1730. }
  1731. case StatementKind::Block: {
  1732. const auto& block = cast<Block>(stmt);
  1733. if (act.pos() >= static_cast<int>(block.statements().size())) {
  1734. // If the position is past the end of the block, end processing. Note
  1735. // that empty blocks immediately end.
  1736. return todo_.FinishAction();
  1737. }
  1738. // Initialize a scope when starting a block.
  1739. if (act.pos() == 0) {
  1740. act.StartScope(RuntimeScope(&heap_));
  1741. }
  1742. // Process the next statement in the block. The position will be
  1743. // incremented as part of Spawn.
  1744. return todo_.Spawn(
  1745. std::make_unique<StatementAction>(block.statements()[act.pos()]));
  1746. }
  1747. case StatementKind::VariableDefinition: {
  1748. const auto& definition = cast<VariableDefinition>(stmt);
  1749. const auto* dest_type = &definition.pattern().static_type();
  1750. if (const auto* dest_class = dyn_cast<NominalClassType>(dest_type)) {
  1751. if (dest_class->declaration().extensibility() ==
  1752. ClassExtensibility::Abstract) {
  1753. return ProgramError(stmt.source_loc())
  1754. << "Cannot instantiate abstract class "
  1755. << dest_class->declaration().name();
  1756. }
  1757. }
  1758. if (act.pos() == 0 && definition.has_init()) {
  1759. // { {(var x = e) :: C, E, F} :: S, H}
  1760. // -> { {e :: (var x = []) :: C, E, F} :: S, H}
  1761. return todo_.Spawn(
  1762. std::make_unique<ExpressionAction>(&definition.init()));
  1763. } else {
  1764. // { { v :: (x = []) :: C, E, F} :: S, H}
  1765. // -> { { C, E(x := a), F} :: S, H(a := copy(v))}
  1766. Nonnull<const Value*> p =
  1767. &cast<VariableDefinition>(stmt).pattern().value();
  1768. Nonnull<const Value*> v;
  1769. if (definition.has_init()) {
  1770. CARBON_ASSIGN_OR_RETURN(
  1771. v, Convert(act.results()[0], dest_type, stmt.source_loc()));
  1772. } else {
  1773. v = arena_->New<UninitializedValue>(p);
  1774. }
  1775. RuntimeScope matches(&heap_);
  1776. BindingMap generic_args;
  1777. CARBON_CHECK(PatternMatch(p, v, stmt.source_loc(), &matches,
  1778. generic_args, trace_stream_, this->arena_))
  1779. << stmt.source_loc()
  1780. << ": internal error in variable definition, match failed";
  1781. todo_.MergeScope(std::move(matches));
  1782. return todo_.FinishAction();
  1783. }
  1784. }
  1785. case StatementKind::ExpressionStatement:
  1786. if (act.pos() == 0) {
  1787. // { {e :: C, E, F} :: S, H}
  1788. // -> { {e :: C, E, F} :: S, H}
  1789. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1790. &cast<ExpressionStatement>(stmt).expression()));
  1791. } else {
  1792. return todo_.FinishAction();
  1793. }
  1794. case StatementKind::Assign: {
  1795. const auto& assign = cast<Assign>(stmt);
  1796. if (act.pos() == 0) {
  1797. // { {(lv = e) :: C, E, F} :: S, H}
  1798. // -> { {lv :: ([] = e) :: C, E, F} :: S, H}
  1799. return todo_.Spawn(std::make_unique<LValAction>(&assign.lhs()));
  1800. } else if (act.pos() == 1) {
  1801. // { { a :: ([] = e) :: C, E, F} :: S, H}
  1802. // -> { { e :: (a = []) :: C, E, F} :: S, H}
  1803. return todo_.Spawn(std::make_unique<ExpressionAction>(&assign.rhs()));
  1804. } else {
  1805. // { { v :: (a = []) :: C, E, F} :: S, H}
  1806. // -> { { C, E, F} :: S, H(a := v)}
  1807. const auto& lval = cast<LValue>(*act.results()[0]);
  1808. CARBON_ASSIGN_OR_RETURN(
  1809. Nonnull<const Value*> rval,
  1810. Convert(act.results()[1], &assign.lhs().static_type(),
  1811. stmt.source_loc()));
  1812. CARBON_RETURN_IF_ERROR(
  1813. heap_.Write(lval.address(), rval, stmt.source_loc()));
  1814. return todo_.FinishAction();
  1815. }
  1816. }
  1817. case StatementKind::If:
  1818. if (act.pos() == 0) {
  1819. // { {(if (e) then_stmt else else_stmt) :: C, E, F} :: S, H}
  1820. // -> { { e :: (if ([]) then_stmt else else_stmt) :: C, E, F} :: S, H}
  1821. return todo_.Spawn(
  1822. std::make_unique<ExpressionAction>(&cast<If>(stmt).condition()));
  1823. } else if (act.pos() == 1) {
  1824. CARBON_ASSIGN_OR_RETURN(
  1825. Nonnull<const Value*> condition,
  1826. Convert(act.results()[0], arena_->New<BoolType>(),
  1827. stmt.source_loc()));
  1828. if (cast<BoolValue>(*condition).value()) {
  1829. // { {true :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  1830. // S, H}
  1831. // -> { { then_stmt :: C, E, F } :: S, H}
  1832. return todo_.Spawn(
  1833. std::make_unique<StatementAction>(&cast<If>(stmt).then_block()));
  1834. } else if (cast<If>(stmt).else_block()) {
  1835. // { {false :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  1836. // S, H}
  1837. // -> { { else_stmt :: C, E, F } :: S, H}
  1838. return todo_.Spawn(
  1839. std::make_unique<StatementAction>(*cast<If>(stmt).else_block()));
  1840. } else {
  1841. return todo_.FinishAction();
  1842. }
  1843. } else {
  1844. return todo_.FinishAction();
  1845. }
  1846. case StatementKind::ReturnVar: {
  1847. const auto& ret_var = cast<ReturnVar>(stmt);
  1848. const ValueNodeView& value_node = ret_var.value_node();
  1849. if (trace_stream_) {
  1850. **trace_stream_ << "--- step returned var "
  1851. << cast<BindingPattern>(value_node.base()).name()
  1852. << " ." << act.pos() << "."
  1853. << " (" << stmt.source_loc() << ") --->\n";
  1854. }
  1855. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> value,
  1856. todo_.ValueOfNode(value_node, stmt.source_loc()));
  1857. if (const auto* lvalue = dyn_cast<LValue>(value)) {
  1858. CARBON_ASSIGN_OR_RETURN(
  1859. value, heap_.Read(lvalue->address(), ret_var.source_loc()));
  1860. }
  1861. const CallableDeclaration& function = cast<Return>(stmt).function();
  1862. CARBON_ASSIGN_OR_RETURN(
  1863. Nonnull<const Value*> return_value,
  1864. Convert(value, &function.return_term().static_type(),
  1865. stmt.source_loc()));
  1866. return todo_.UnwindPast(*function.body(), return_value);
  1867. }
  1868. case StatementKind::ReturnExpression:
  1869. if (act.pos() == 0) {
  1870. // { {return e :: C, E, F} :: S, H}
  1871. // -> { {e :: return [] :: C, E, F} :: S, H}
  1872. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1873. &cast<ReturnExpression>(stmt).expression()));
  1874. } else {
  1875. // { {v :: return [] :: C, E, F} :: {C', E', F'} :: S, H}
  1876. // -> { {v :: C', E', F'} :: S, H}
  1877. const CallableDeclaration& function = cast<Return>(stmt).function();
  1878. CARBON_ASSIGN_OR_RETURN(
  1879. Nonnull<const Value*> return_value,
  1880. Convert(act.results()[0], &function.return_term().static_type(),
  1881. stmt.source_loc()));
  1882. return todo_.UnwindPast(*function.body(), return_value);
  1883. }
  1884. case StatementKind::Continuation: {
  1885. CARBON_CHECK(act.pos() == 0);
  1886. const auto& continuation = cast<Continuation>(stmt);
  1887. // Create a continuation object by creating a frame similar the
  1888. // way one is created in a function call.
  1889. auto* fragment = arena_->New<ContinuationValue::StackFragment>();
  1890. stack_fragments_.push_back(fragment);
  1891. todo_.InitializeFragment(*fragment, &continuation.body());
  1892. // Bind the continuation object to the continuation variable
  1893. todo_.Initialize(&cast<Continuation>(stmt),
  1894. arena_->New<ContinuationValue>(fragment));
  1895. return todo_.FinishAction();
  1896. }
  1897. case StatementKind::Run: {
  1898. const auto& run = cast<Run>(stmt);
  1899. if (act.pos() == 0) {
  1900. // Evaluate the argument of the run statement.
  1901. return todo_.Spawn(std::make_unique<ExpressionAction>(&run.argument()));
  1902. } else if (act.pos() == 1) {
  1903. // Push the continuation onto the current stack.
  1904. return todo_.Resume(cast<const ContinuationValue>(act.results()[0]));
  1905. } else {
  1906. return todo_.FinishAction();
  1907. }
  1908. }
  1909. case StatementKind::Await:
  1910. CARBON_CHECK(act.pos() == 0);
  1911. return todo_.Suspend();
  1912. }
  1913. }
  1914. auto Interpreter::StepDeclaration() -> ErrorOr<Success> {
  1915. Action& act = todo_.CurrentAction();
  1916. const Declaration& decl = cast<DeclarationAction>(act).declaration();
  1917. if (trace_stream_) {
  1918. **trace_stream_ << "--- step decl ";
  1919. decl.PrintID(**trace_stream_);
  1920. **trace_stream_ << " ." << act.pos() << ". "
  1921. << "(" << decl.source_loc() << ") --->\n";
  1922. }
  1923. switch (decl.kind()) {
  1924. case DeclarationKind::VariableDeclaration: {
  1925. const auto& var_decl = cast<VariableDeclaration>(decl);
  1926. if (var_decl.has_initializer()) {
  1927. if (act.pos() == 0) {
  1928. return todo_.Spawn(
  1929. std::make_unique<ExpressionAction>(&var_decl.initializer()));
  1930. } else {
  1931. CARBON_ASSIGN_OR_RETURN(
  1932. Nonnull<const Value*> v,
  1933. Convert(act.results()[0], &var_decl.binding().static_type(),
  1934. var_decl.source_loc()));
  1935. todo_.Initialize(&var_decl.binding(), v);
  1936. return todo_.FinishAction();
  1937. }
  1938. } else {
  1939. Nonnull<const Value*> v =
  1940. arena_->New<UninitializedValue>(&var_decl.binding().value());
  1941. todo_.Initialize(&var_decl.binding(), v);
  1942. return todo_.FinishAction();
  1943. }
  1944. }
  1945. case DeclarationKind::DestructorDeclaration:
  1946. case DeclarationKind::FunctionDeclaration:
  1947. case DeclarationKind::ClassDeclaration:
  1948. case DeclarationKind::MixinDeclaration:
  1949. case DeclarationKind::MixDeclaration:
  1950. case DeclarationKind::ChoiceDeclaration:
  1951. case DeclarationKind::InterfaceDeclaration:
  1952. case DeclarationKind::ConstraintDeclaration:
  1953. case DeclarationKind::InterfaceExtendsDeclaration:
  1954. case DeclarationKind::InterfaceImplDeclaration:
  1955. case DeclarationKind::AssociatedConstantDeclaration:
  1956. case DeclarationKind::ImplDeclaration:
  1957. case DeclarationKind::SelfDeclaration:
  1958. case DeclarationKind::AliasDeclaration:
  1959. // These declarations have no run-time effects.
  1960. return todo_.FinishAction();
  1961. }
  1962. }
  1963. auto Interpreter::StepDestroy() -> ErrorOr<Success> {
  1964. const Action& act = todo_.CurrentAction();
  1965. const auto& destroy_act = cast<DestroyAction>(act);
  1966. switch (destroy_act.value()->kind()) {
  1967. case Value::Kind::NominalClassValue: {
  1968. const auto* class_obj = cast<NominalClassValue>(destroy_act.value());
  1969. const auto& class_decl =
  1970. cast<NominalClassType>(class_obj->type()).declaration();
  1971. const int member_count = class_decl.members().size();
  1972. if (act.pos() == 0) {
  1973. // Run the destructor, if there is one.
  1974. if (auto destructor = class_decl.destructor()) {
  1975. return CallDestructor(*destructor, class_obj);
  1976. } else {
  1977. return todo_.RunAgain();
  1978. }
  1979. } else if (act.pos() <= member_count) {
  1980. // Destroy members.
  1981. const int index = class_decl.members().size() - act.pos();
  1982. const auto& member = class_decl.members()[index];
  1983. if (const auto* var = dyn_cast<VariableDeclaration>(member)) {
  1984. const Address object = destroy_act.lvalue()->address();
  1985. const Address var_addr =
  1986. object.ElementAddress(arena_->New<NamedElement>(var));
  1987. const auto v = heap_.Read(var_addr, SourceLocation("destructor", 1));
  1988. CARBON_CHECK(v.ok())
  1989. << "Failed to read member `" << var->binding().name()
  1990. << "` from class `" << class_decl.name() << "`";
  1991. return todo_.Spawn(std::make_unique<DestroyAction>(
  1992. arena_->New<LValue>(var_addr), *v));
  1993. } else {
  1994. return todo_.RunAgain();
  1995. }
  1996. } else if (act.pos() == member_count + 1) {
  1997. // Destroy the parent, if there is one.
  1998. if (auto base = class_obj->base()) {
  1999. const Address obj_addr = destroy_act.lvalue()->address();
  2000. const Address base_addr =
  2001. obj_addr.ElementAddress(arena_->New<BaseElement>(class_obj));
  2002. return todo_.Spawn(std::make_unique<DestroyAction>(
  2003. arena_->New<LValue>(base_addr), base.value()));
  2004. } else {
  2005. return todo_.RunAgain();
  2006. }
  2007. } else {
  2008. todo_.Pop();
  2009. return Success();
  2010. }
  2011. }
  2012. case Value::Kind::TupleValue: {
  2013. const auto* tuple = cast<TupleValue>(destroy_act.value());
  2014. const auto element_count = tuple->elements().size();
  2015. if (static_cast<size_t>(act.pos()) < element_count) {
  2016. const size_t index = element_count - act.pos() - 1;
  2017. const auto& item = tuple->elements()[index];
  2018. const auto object_addr = destroy_act.lvalue()->address();
  2019. Address field_address = object_addr.ElementAddress(
  2020. arena_->New<PositionalElement>(index, item));
  2021. if (item->kind() == Value::Kind::NominalClassValue ||
  2022. item->kind() == Value::Kind::TupleValue) {
  2023. return todo_.Spawn(std::make_unique<DestroyAction>(
  2024. arena_->New<LValue>(field_address), item));
  2025. } else {
  2026. // The tuple element's type is an integral type (e.g., i32)
  2027. // or the type doesn't support destruction.
  2028. return todo_.RunAgain();
  2029. }
  2030. } else {
  2031. todo_.Pop();
  2032. return Success();
  2033. }
  2034. }
  2035. default:
  2036. // These declarations have no run-time effects.
  2037. todo_.Pop();
  2038. return Success();
  2039. }
  2040. CARBON_FATAL() << "Unreachable";
  2041. }
  2042. auto Interpreter::StepCleanUp() -> ErrorOr<Success> {
  2043. Action& act = todo_.CurrentAction();
  2044. CleanupAction& cleanup = cast<CleanupAction>(act);
  2045. if (act.pos() < cleanup.allocations_count()) {
  2046. auto allocation =
  2047. act.scope()->allocations()[cleanup.allocations_count() - act.pos() - 1];
  2048. auto lvalue = arena_->New<LValue>(Address(allocation));
  2049. SourceLocation source_loc("destructor", 1);
  2050. auto value = heap_.Read(lvalue->address(), source_loc);
  2051. // Step over uninitialized values
  2052. if (value.ok()) {
  2053. return todo_.Spawn(std::make_unique<DestroyAction>(lvalue, *value));
  2054. }
  2055. }
  2056. todo_.Pop();
  2057. return Success();
  2058. }
  2059. // State transition.
  2060. auto Interpreter::Step() -> ErrorOr<Success> {
  2061. Action& act = todo_.CurrentAction();
  2062. switch (act.kind()) {
  2063. case Action::Kind::LValAction:
  2064. CARBON_RETURN_IF_ERROR(StepLvalue());
  2065. break;
  2066. case Action::Kind::ExpressionAction:
  2067. CARBON_RETURN_IF_ERROR(StepExp());
  2068. break;
  2069. case Action::Kind::WitnessAction:
  2070. CARBON_RETURN_IF_ERROR(StepWitness());
  2071. break;
  2072. case Action::Kind::StatementAction:
  2073. CARBON_RETURN_IF_ERROR(StepStmt());
  2074. break;
  2075. case Action::Kind::DeclarationAction:
  2076. CARBON_RETURN_IF_ERROR(StepDeclaration());
  2077. break;
  2078. case Action::Kind::CleanUpAction:
  2079. CARBON_RETURN_IF_ERROR(StepCleanUp());
  2080. break;
  2081. case Action::Kind::DestroyAction:
  2082. CARBON_RETURN_IF_ERROR(StepDestroy());
  2083. break;
  2084. case Action::Kind::ScopeAction:
  2085. CARBON_FATAL() << "ScopeAction escaped ActionStack";
  2086. case Action::Kind::RecursiveAction:
  2087. CARBON_FATAL() << "Tried to step a RecursiveAction";
  2088. } // switch
  2089. return Success();
  2090. }
  2091. auto Interpreter::RunAllSteps(std::unique_ptr<Action> action)
  2092. -> ErrorOr<Success> {
  2093. if (trace_stream_) {
  2094. PrintState(**trace_stream_);
  2095. }
  2096. todo_.Start(std::move(action));
  2097. while (!todo_.IsEmpty()) {
  2098. CARBON_RETURN_IF_ERROR(Step());
  2099. if (trace_stream_) {
  2100. PrintState(**trace_stream_);
  2101. }
  2102. }
  2103. return Success();
  2104. }
  2105. auto InterpProgram(const AST& ast, Nonnull<Arena*> arena,
  2106. std::optional<Nonnull<llvm::raw_ostream*>> trace_stream)
  2107. -> ErrorOr<int> {
  2108. Interpreter interpreter(Phase::RunTime, arena, trace_stream);
  2109. if (trace_stream) {
  2110. **trace_stream << "********** initializing globals **********\n";
  2111. }
  2112. for (Nonnull<Declaration*> declaration : ast.declarations) {
  2113. CARBON_RETURN_IF_ERROR(interpreter.RunAllSteps(
  2114. std::make_unique<DeclarationAction>(declaration)));
  2115. }
  2116. if (trace_stream) {
  2117. **trace_stream << "********** calling main function **********\n";
  2118. }
  2119. CARBON_RETURN_IF_ERROR(interpreter.RunAllSteps(
  2120. std::make_unique<ExpressionAction>(*ast.main_call)));
  2121. return cast<IntValue>(*interpreter.result()).value();
  2122. }
  2123. auto InterpExp(Nonnull<const Expression*> e, Nonnull<Arena*> arena,
  2124. std::optional<Nonnull<llvm::raw_ostream*>> trace_stream)
  2125. -> ErrorOr<Nonnull<const Value*>> {
  2126. Interpreter interpreter(Phase::CompileTime, arena, trace_stream);
  2127. CARBON_RETURN_IF_ERROR(
  2128. interpreter.RunAllSteps(std::make_unique<ExpressionAction>(e)));
  2129. return interpreter.result();
  2130. }
  2131. } // namespace Carbon