interpreter.cpp 62 KB

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