interpreter.cpp 61 KB

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