interpreter.cpp 70 KB

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