interpreter.cpp 72 KB

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