interpreter.cpp 88 KB

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