interpreter.cpp 88 KB

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