interpreter.cpp 64 KB

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