interpreter.cpp 54 KB

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