interpreter.cpp 53 KB

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