interpreter.cpp 78 KB

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