interpreter.cpp 60 KB

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