interpreter.cpp 59 KB

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