interpreter.cpp 85 KB

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