interpreter.cpp 88 KB

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