interpreter.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041
  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.h"
  16. #include "executable_semantics/interpreter/action.h"
  17. #include "executable_semantics/interpreter/stack.h"
  18. #include "llvm/ADT/StringExtras.h"
  19. #include "llvm/Support/Casting.h"
  20. using llvm::cast;
  21. using llvm::dyn_cast;
  22. using llvm::isa;
  23. namespace Carbon {
  24. // Selects between compile-time and run-time behavior.
  25. enum class Phase { CompileTime, RunTime };
  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, bool trace)
  44. : arena_(arena),
  45. heap_(arena),
  46. todo_(MakeTodo(phase, &heap_)),
  47. trace_(trace) {}
  48. ~Interpreter();
  49. // Runs all the steps of `action`.
  50. void RunAllSteps(std::unique_ptr<Action> action);
  51. // The result produced by the `action` argument of the most recent
  52. // RunAllSteps call. Cannot be called if `action` was an action that doesn't
  53. // produce results.
  54. auto result() const -> Nonnull<const Value*> { return todo_.result(); }
  55. private:
  56. void Step();
  57. // State transitions for expressions.
  58. void StepExp();
  59. // State transitions for lvalues.
  60. void StepLvalue();
  61. // State transitions for patterns.
  62. void StepPattern();
  63. // State transition for statements.
  64. void StepStmt();
  65. // State transition for declarations.
  66. void StepDeclaration();
  67. auto CreateStruct(const std::vector<FieldInitializer>& fields,
  68. const std::vector<Nonnull<const Value*>>& values)
  69. -> Nonnull<const Value*>;
  70. auto EvalPrim(Operator op, const std::vector<Nonnull<const Value*>>& args,
  71. SourceLocation source_loc) -> Nonnull<const Value*>;
  72. // Returns the result of converting `value` to type `destination_type`.
  73. auto Convert(Nonnull<const Value*> value,
  74. Nonnull<const Value*> destination_type) const
  75. -> Nonnull<const Value*>;
  76. void PrintState(llvm::raw_ostream& out);
  77. Nonnull<Arena*> arena_;
  78. Heap heap_;
  79. ActionStack todo_;
  80. // The underlying states of continuation values. All StackFragments created
  81. // during execution are tracked here, in order to safely deallocate the
  82. // contents of any non-completed continuations at the end of execution.
  83. std::vector<Nonnull<ContinuationValue::StackFragment*>> stack_fragments_;
  84. bool trace_;
  85. };
  86. Interpreter::~Interpreter() {
  87. // Clean up any remaining suspended continuations.
  88. for (Nonnull<ContinuationValue::StackFragment*> fragment : stack_fragments_) {
  89. fragment->Clear();
  90. }
  91. }
  92. //
  93. // State Operations
  94. //
  95. void Interpreter::PrintState(llvm::raw_ostream& out) {
  96. out << "{\nstack: " << todo_;
  97. out << "\nheap: " << heap_;
  98. if (!todo_.IsEmpty()) {
  99. out << "\nvalues: ";
  100. todo_.PrintScopes(out);
  101. }
  102. out << "\n}\n";
  103. }
  104. auto Interpreter::EvalPrim(Operator op,
  105. const std::vector<Nonnull<const Value*>>& args,
  106. SourceLocation source_loc) -> Nonnull<const Value*> {
  107. switch (op) {
  108. case Operator::Neg:
  109. return arena_->New<IntValue>(-cast<IntValue>(*args[0]).value());
  110. case Operator::Add:
  111. return arena_->New<IntValue>(cast<IntValue>(*args[0]).value() +
  112. cast<IntValue>(*args[1]).value());
  113. case Operator::Sub:
  114. return arena_->New<IntValue>(cast<IntValue>(*args[0]).value() -
  115. cast<IntValue>(*args[1]).value());
  116. case Operator::Mul:
  117. return arena_->New<IntValue>(cast<IntValue>(*args[0]).value() *
  118. cast<IntValue>(*args[1]).value());
  119. case Operator::Not:
  120. return arena_->New<BoolValue>(!cast<BoolValue>(*args[0]).value());
  121. case Operator::And:
  122. return arena_->New<BoolValue>(cast<BoolValue>(*args[0]).value() &&
  123. cast<BoolValue>(*args[1]).value());
  124. case Operator::Or:
  125. return arena_->New<BoolValue>(cast<BoolValue>(*args[0]).value() ||
  126. cast<BoolValue>(*args[1]).value());
  127. case Operator::Eq:
  128. return arena_->New<BoolValue>(ValueEqual(args[0], args[1]));
  129. case Operator::Ptr:
  130. return arena_->New<PointerType>(args[0]);
  131. case Operator::Deref:
  132. return heap_.Read(cast<PointerValue>(*args[0]).address(), source_loc);
  133. case Operator::AddressOf:
  134. return arena_->New<PointerValue>(cast<LValue>(*args[0]).address());
  135. }
  136. }
  137. auto Interpreter::CreateStruct(const std::vector<FieldInitializer>& fields,
  138. const std::vector<Nonnull<const Value*>>& values)
  139. -> Nonnull<const Value*> {
  140. CHECK(fields.size() == values.size());
  141. std::vector<NamedValue> elements;
  142. for (size_t i = 0; i < fields.size(); ++i) {
  143. elements.push_back({.name = fields[i].name(), .value = values[i]});
  144. }
  145. return arena_->New<StructValue>(std::move(elements));
  146. }
  147. auto PatternMatch(Nonnull<const Value*> p, Nonnull<const Value*> v,
  148. SourceLocation source_loc,
  149. std::optional<Nonnull<RuntimeScope*>> bindings) -> bool {
  150. switch (p->kind()) {
  151. case Value::Kind::BindingPlaceholderValue: {
  152. if (!bindings.has_value()) {
  153. // TODO: move this to typechecker.
  154. FATAL_COMPILATION_ERROR(source_loc)
  155. << "Name bindings are not supported in this context";
  156. }
  157. const auto& placeholder = cast<BindingPlaceholderValue>(*p);
  158. if (placeholder.named_entity().has_value()) {
  159. (*bindings)->Initialize(*placeholder.named_entity(), v);
  160. }
  161. return true;
  162. }
  163. case Value::Kind::TupleValue:
  164. switch (v->kind()) {
  165. case Value::Kind::TupleValue: {
  166. const auto& p_tup = cast<TupleValue>(*p);
  167. const auto& v_tup = cast<TupleValue>(*v);
  168. if (p_tup.elements().size() != v_tup.elements().size()) {
  169. FATAL_PROGRAM_ERROR(source_loc)
  170. << "arity mismatch in tuple pattern match:\n pattern: "
  171. << p_tup << "\n value: " << v_tup;
  172. }
  173. for (size_t i = 0; i < p_tup.elements().size(); ++i) {
  174. if (!PatternMatch(p_tup.elements()[i], v_tup.elements()[i],
  175. source_loc, bindings)) {
  176. return false;
  177. }
  178. } // for
  179. return true;
  180. }
  181. default:
  182. FATAL() << "expected a tuple value in pattern, not " << *v;
  183. }
  184. case Value::Kind::StructValue: {
  185. const auto& p_struct = cast<StructValue>(*p);
  186. const auto& v_struct = cast<StructValue>(*v);
  187. CHECK(p_struct.elements().size() == v_struct.elements().size());
  188. for (size_t i = 0; i < p_struct.elements().size(); ++i) {
  189. CHECK(p_struct.elements()[i].name == v_struct.elements()[i].name);
  190. if (!PatternMatch(p_struct.elements()[i].value,
  191. v_struct.elements()[i].value, source_loc, bindings)) {
  192. return false;
  193. }
  194. }
  195. return true;
  196. }
  197. case Value::Kind::AlternativeValue:
  198. switch (v->kind()) {
  199. case Value::Kind::AlternativeValue: {
  200. const auto& p_alt = cast<AlternativeValue>(*p);
  201. const auto& v_alt = cast<AlternativeValue>(*v);
  202. if (p_alt.choice_name() != v_alt.choice_name() ||
  203. p_alt.alt_name() != v_alt.alt_name()) {
  204. return false;
  205. }
  206. return PatternMatch(&p_alt.argument(), &v_alt.argument(), source_loc,
  207. bindings);
  208. }
  209. default:
  210. FATAL() << "expected a choice alternative in pattern, not " << *v;
  211. }
  212. case Value::Kind::FunctionType:
  213. switch (v->kind()) {
  214. case Value::Kind::FunctionType: {
  215. const auto& p_fn = cast<FunctionType>(*p);
  216. const auto& v_fn = cast<FunctionType>(*v);
  217. if (!PatternMatch(&p_fn.parameters(), &v_fn.parameters(), source_loc,
  218. bindings)) {
  219. return false;
  220. }
  221. if (!PatternMatch(&p_fn.return_type(), &v_fn.return_type(),
  222. source_loc, bindings)) {
  223. return false;
  224. }
  225. return true;
  226. }
  227. default:
  228. return false;
  229. }
  230. case Value::Kind::AutoType:
  231. // `auto` matches any type, without binding any new names. We rely
  232. // on the typechecker to ensure that `v` is a type.
  233. return true;
  234. default:
  235. return ValueEqual(p, v);
  236. }
  237. }
  238. void Interpreter::StepLvalue() {
  239. Action& act = todo_.CurrentAction();
  240. const Expression& exp = cast<LValAction>(act).expression();
  241. if (trace_) {
  242. llvm::outs() << "--- step lvalue " << exp << " (" << exp.source_loc()
  243. << ") --->\n";
  244. }
  245. switch (exp.kind()) {
  246. case ExpressionKind::IdentifierExpression: {
  247. // { {x :: C, E, F} :: S, H}
  248. // -> { {E(x) :: C, E, F} :: S, H}
  249. Nonnull<const Value*> value = todo_.ValueOfName(
  250. cast<IdentifierExpression>(exp).named_entity(), exp.source_loc());
  251. CHECK(isa<LValue>(value)) << *value;
  252. return todo_.FinishAction(value);
  253. }
  254. case ExpressionKind::FieldAccessExpression: {
  255. if (act.pos() == 0) {
  256. // { {e.f :: C, E, F} :: S, H}
  257. // -> { e :: [].f :: C, E, F} :: S, H}
  258. return todo_.Spawn(std::make_unique<LValAction>(
  259. &cast<FieldAccessExpression>(exp).aggregate()));
  260. } else {
  261. // { v :: [].f :: C, E, F} :: S, H}
  262. // -> { { &v.f :: C, E, F} :: S, H }
  263. Address aggregate = cast<LValue>(*act.results()[0]).address();
  264. Address field = aggregate.SubobjectAddress(
  265. cast<FieldAccessExpression>(exp).field());
  266. return todo_.FinishAction(arena_->New<LValue>(field));
  267. }
  268. }
  269. case ExpressionKind::IndexExpression: {
  270. if (act.pos() == 0) {
  271. // { {e[i] :: C, E, F} :: S, H}
  272. // -> { e :: [][i] :: C, E, F} :: S, H}
  273. return todo_.Spawn(std::make_unique<LValAction>(
  274. &cast<IndexExpression>(exp).aggregate()));
  275. } else if (act.pos() == 1) {
  276. return todo_.Spawn(std::make_unique<ExpressionAction>(
  277. &cast<IndexExpression>(exp).offset()));
  278. } else {
  279. // { v :: [][i] :: C, E, F} :: S, H}
  280. // -> { { &v[i] :: C, E, F} :: S, H }
  281. Address aggregate = cast<LValue>(*act.results()[0]).address();
  282. std::string f =
  283. std::to_string(cast<IntValue>(*act.results()[1]).value());
  284. Address field = aggregate.SubobjectAddress(f);
  285. return todo_.FinishAction(arena_->New<LValue>(field));
  286. }
  287. }
  288. case ExpressionKind::PrimitiveOperatorExpression: {
  289. const PrimitiveOperatorExpression& op =
  290. cast<PrimitiveOperatorExpression>(exp);
  291. if (op.op() != Operator::Deref) {
  292. FATAL() << "Can't treat primitive operator expression as lvalue: "
  293. << exp;
  294. }
  295. if (act.pos() == 0) {
  296. return todo_.Spawn(
  297. std::make_unique<ExpressionAction>(op.arguments()[0]));
  298. } else {
  299. const PointerValue& res = cast<PointerValue>(*act.results()[0]);
  300. return todo_.FinishAction(arena_->New<LValue>(res.address()));
  301. }
  302. break;
  303. }
  304. case ExpressionKind::TupleLiteral:
  305. case ExpressionKind::StructLiteral:
  306. case ExpressionKind::StructTypeLiteral:
  307. case ExpressionKind::IntLiteral:
  308. case ExpressionKind::BoolLiteral:
  309. case ExpressionKind::CallExpression:
  310. case ExpressionKind::IntTypeLiteral:
  311. case ExpressionKind::BoolTypeLiteral:
  312. case ExpressionKind::TypeTypeLiteral:
  313. case ExpressionKind::FunctionTypeLiteral:
  314. case ExpressionKind::ContinuationTypeLiteral:
  315. case ExpressionKind::StringLiteral:
  316. case ExpressionKind::StringTypeLiteral:
  317. case ExpressionKind::IntrinsicExpression:
  318. FATAL() << "Can't treat expression as lvalue: " << exp;
  319. case ExpressionKind::UnimplementedExpression:
  320. FATAL() << "Unimplemented: " << exp;
  321. }
  322. }
  323. auto Interpreter::Convert(Nonnull<const Value*> value,
  324. Nonnull<const Value*> destination_type) const
  325. -> Nonnull<const Value*> {
  326. switch (value->kind()) {
  327. case Value::Kind::IntValue:
  328. case Value::Kind::FunctionValue:
  329. case Value::Kind::BoundMethodValue:
  330. case Value::Kind::PointerValue:
  331. case Value::Kind::LValue:
  332. case Value::Kind::BoolValue:
  333. case Value::Kind::NominalClassValue:
  334. case Value::Kind::AlternativeValue:
  335. case Value::Kind::IntType:
  336. case Value::Kind::BoolType:
  337. case Value::Kind::TypeType:
  338. case Value::Kind::FunctionType:
  339. case Value::Kind::PointerType:
  340. case Value::Kind::AutoType:
  341. case Value::Kind::StructType:
  342. case Value::Kind::NominalClassType:
  343. case Value::Kind::ChoiceType:
  344. case Value::Kind::ContinuationType:
  345. case Value::Kind::VariableType:
  346. case Value::Kind::BindingPlaceholderValue:
  347. case Value::Kind::AlternativeConstructorValue:
  348. case Value::Kind::ContinuationValue:
  349. case Value::Kind::StringType:
  350. case Value::Kind::StringValue:
  351. case Value::Kind::TypeOfClassType:
  352. case Value::Kind::TypeOfChoiceType:
  353. // TODO: add `CHECK(TypeEqual(type, value->dynamic_type()))`, once we
  354. // have Value::dynamic_type.
  355. return value;
  356. case Value::Kind::StructValue: {
  357. const auto& struct_val = cast<StructValue>(*value);
  358. switch (destination_type->kind()) {
  359. case Value::Kind::StructType: {
  360. const auto& destination_struct_type =
  361. cast<StructType>(*destination_type);
  362. std::vector<NamedValue> new_elements;
  363. for (const auto& [field_name, field_type] :
  364. destination_struct_type.fields()) {
  365. std::optional<Nonnull<const Value*>> old_value =
  366. struct_val.FindField(field_name);
  367. new_elements.push_back(
  368. {.name = field_name, .value = Convert(*old_value, field_type)});
  369. }
  370. return arena_->New<StructValue>(std::move(new_elements));
  371. }
  372. case Value::Kind::NominalClassType:
  373. return arena_->New<NominalClassValue>(destination_type, value);
  374. default:
  375. FATAL() << "Can't convert value " << *value << " to type "
  376. << *destination_type;
  377. }
  378. }
  379. case Value::Kind::TupleValue: {
  380. const auto& tuple = cast<TupleValue>(value);
  381. const auto& destination_tuple_type = cast<TupleValue>(destination_type);
  382. CHECK(tuple->elements().size() ==
  383. destination_tuple_type->elements().size());
  384. std::vector<Nonnull<const Value*>> new_elements;
  385. for (size_t i = 0; i < tuple->elements().size(); ++i) {
  386. new_elements.push_back(Convert(tuple->elements()[i],
  387. destination_tuple_type->elements()[i]));
  388. }
  389. return arena_->New<TupleValue>(std::move(new_elements));
  390. }
  391. }
  392. }
  393. void Interpreter::StepExp() {
  394. Action& act = todo_.CurrentAction();
  395. const Expression& exp = cast<ExpressionAction>(act).expression();
  396. if (trace_) {
  397. llvm::outs() << "--- step exp " << exp << " (" << exp.source_loc()
  398. << ") --->\n";
  399. }
  400. switch (exp.kind()) {
  401. case ExpressionKind::IndexExpression: {
  402. if (act.pos() == 0) {
  403. // { { e[i] :: C, E, F} :: S, H}
  404. // -> { { e :: [][i] :: C, E, F} :: S, H}
  405. return todo_.Spawn(std::make_unique<ExpressionAction>(
  406. &cast<IndexExpression>(exp).aggregate()));
  407. } else if (act.pos() == 1) {
  408. return todo_.Spawn(std::make_unique<ExpressionAction>(
  409. &cast<IndexExpression>(exp).offset()));
  410. } else {
  411. // { { v :: [][i] :: C, E, F} :: S, H}
  412. // -> { { v_i :: C, E, F} : S, H}
  413. const auto& tuple = cast<TupleValue>(*act.results()[0]);
  414. int i = cast<IntValue>(*act.results()[1]).value();
  415. if (i < 0 || i >= static_cast<int>(tuple.elements().size())) {
  416. FATAL_RUNTIME_ERROR_NO_LINE()
  417. << "index " << i << " out of range in " << tuple;
  418. }
  419. return todo_.FinishAction(tuple.elements()[i]);
  420. }
  421. }
  422. case ExpressionKind::TupleLiteral: {
  423. if (act.pos() <
  424. static_cast<int>(cast<TupleLiteral>(exp).fields().size())) {
  425. // { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
  426. // H}
  427. // -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
  428. // H}
  429. return todo_.Spawn(std::make_unique<ExpressionAction>(
  430. cast<TupleLiteral>(exp).fields()[act.pos()]));
  431. } else {
  432. return todo_.FinishAction(arena_->New<TupleValue>(act.results()));
  433. }
  434. }
  435. case ExpressionKind::StructLiteral: {
  436. const auto& literal = cast<StructLiteral>(exp);
  437. if (act.pos() < static_cast<int>(literal.fields().size())) {
  438. return todo_.Spawn(std::make_unique<ExpressionAction>(
  439. &literal.fields()[act.pos()].expression()));
  440. } else {
  441. return todo_.FinishAction(
  442. CreateStruct(literal.fields(), act.results()));
  443. }
  444. }
  445. case ExpressionKind::StructTypeLiteral: {
  446. const auto& struct_type = cast<StructTypeLiteral>(exp);
  447. if (act.pos() < static_cast<int>(struct_type.fields().size())) {
  448. return todo_.Spawn(std::make_unique<ExpressionAction>(
  449. &struct_type.fields()[act.pos()].expression()));
  450. } else {
  451. std::vector<NamedValue> fields;
  452. for (size_t i = 0; i < struct_type.fields().size(); ++i) {
  453. fields.push_back({struct_type.fields()[i].name(), act.results()[i]});
  454. }
  455. return todo_.FinishAction(arena_->New<StructType>(std::move(fields)));
  456. }
  457. }
  458. case ExpressionKind::FieldAccessExpression: {
  459. const auto& access = cast<FieldAccessExpression>(exp);
  460. if (act.pos() == 0) {
  461. // { { e.f :: C, E, F} :: S, H}
  462. // -> { { e :: [].f :: C, E, F} :: S, H}
  463. return todo_.Spawn(
  464. std::make_unique<ExpressionAction>(&access.aggregate()));
  465. } else {
  466. // { { v :: [].f :: C, E, F} :: S, H}
  467. // -> { { v_f :: C, E, F} : S, H}
  468. return todo_.FinishAction(act.results()[0]->GetField(
  469. arena_, FieldPath(access.field()), exp.source_loc()));
  470. }
  471. }
  472. case ExpressionKind::IdentifierExpression: {
  473. CHECK(act.pos() == 0);
  474. const auto& ident = cast<IdentifierExpression>(exp);
  475. // { {x :: C, E, F} :: S, H} -> { {H(E(x)) :: C, E, F} :: S, H}
  476. Nonnull<const Value*> value =
  477. todo_.ValueOfName(ident.named_entity(), ident.source_loc());
  478. if (const auto* lvalue = dyn_cast<LValue>(value)) {
  479. value = heap_.Read(lvalue->address(), exp.source_loc());
  480. }
  481. return todo_.FinishAction(value);
  482. }
  483. case ExpressionKind::IntLiteral:
  484. CHECK(act.pos() == 0);
  485. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  486. return todo_.FinishAction(
  487. arena_->New<IntValue>(cast<IntLiteral>(exp).value()));
  488. case ExpressionKind::BoolLiteral:
  489. CHECK(act.pos() == 0);
  490. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  491. return todo_.FinishAction(
  492. arena_->New<BoolValue>(cast<BoolLiteral>(exp).value()));
  493. case ExpressionKind::PrimitiveOperatorExpression: {
  494. const auto& op = cast<PrimitiveOperatorExpression>(exp);
  495. if (act.pos() != static_cast<int>(op.arguments().size())) {
  496. // { {v :: op(vs,[],e,es) :: C, E, F} :: S, H}
  497. // -> { {e :: op(vs,v,[],es) :: C, E, F} :: S, H}
  498. Nonnull<const Expression*> arg = op.arguments()[act.pos()];
  499. if (op.op() == Operator::AddressOf) {
  500. return todo_.Spawn(std::make_unique<LValAction>(arg));
  501. } else {
  502. return todo_.Spawn(std::make_unique<ExpressionAction>(arg));
  503. }
  504. } else {
  505. // { {v :: op(vs,[]) :: C, E, F} :: S, H}
  506. // -> { {eval_prim(op, (vs,v)) :: C, E, F} :: S, H}
  507. return todo_.FinishAction(
  508. EvalPrim(op.op(), act.results(), exp.source_loc()));
  509. }
  510. }
  511. case ExpressionKind::CallExpression:
  512. if (act.pos() == 0) {
  513. // { {e1(e2) :: C, E, F} :: S, H}
  514. // -> { {e1 :: [](e2) :: C, E, F} :: S, H}
  515. return todo_.Spawn(std::make_unique<ExpressionAction>(
  516. &cast<CallExpression>(exp).function()));
  517. } else if (act.pos() == 1) {
  518. // { { v :: [](e) :: C, E, F} :: S, H}
  519. // -> { { e :: v([]) :: C, E, F} :: S, H}
  520. return todo_.Spawn(std::make_unique<ExpressionAction>(
  521. &cast<CallExpression>(exp).argument()));
  522. } else if (act.pos() == 2) {
  523. // { { v2 :: v1([]) :: C, E, F} :: S, H}
  524. // -> { {C',E',F'} :: {C, E, F} :: S, H}
  525. switch (act.results()[0]->kind()) {
  526. case Value::Kind::AlternativeConstructorValue: {
  527. const auto& alt =
  528. cast<AlternativeConstructorValue>(*act.results()[0]);
  529. return todo_.FinishAction(arena_->New<AlternativeValue>(
  530. alt.alt_name(), alt.choice_name(), act.results()[1]));
  531. }
  532. case Value::Kind::FunctionValue: {
  533. const FunctionDeclaration& function =
  534. cast<FunctionValue>(*act.results()[0]).declaration();
  535. Nonnull<const Value*> converted_args = Convert(
  536. act.results()[1], &function.param_pattern().static_type());
  537. RuntimeScope function_scope(&heap_);
  538. CHECK(PatternMatch(&function.param_pattern().value(),
  539. converted_args, exp.source_loc(),
  540. &function_scope));
  541. CHECK(function.body().has_value())
  542. << "Calling a function that's missing a body";
  543. return todo_.Spawn(
  544. std::make_unique<StatementAction>(*function.body()),
  545. std::move(function_scope));
  546. }
  547. case Value::Kind::BoundMethodValue: {
  548. const BoundMethodValue& m =
  549. cast<BoundMethodValue>(*act.results()[0]);
  550. const FunctionDeclaration& method = m.declaration();
  551. Nonnull<const Value*> converted_args = Convert(
  552. act.results()[1], &method.param_pattern().static_type());
  553. RuntimeScope method_scope(&heap_);
  554. CHECK(PatternMatch(&method.me_pattern().value(), m.receiver(),
  555. exp.source_loc(), &method_scope));
  556. CHECK(PatternMatch(&method.param_pattern().value(), converted_args,
  557. exp.source_loc(), &method_scope));
  558. CHECK(method.body().has_value())
  559. << "Calling a method that's missing a body";
  560. return todo_.Spawn(
  561. std::make_unique<StatementAction>(*method.body()),
  562. std::move(method_scope));
  563. }
  564. default:
  565. FATAL_RUNTIME_ERROR(exp.source_loc())
  566. << "in call, expected a function, not " << *act.results()[0];
  567. }
  568. } else if (act.pos() == 3) {
  569. if (act.results().size() < 3) {
  570. // Control fell through without explicit return.
  571. return todo_.FinishAction(TupleValue::Empty());
  572. } else {
  573. return todo_.FinishAction(act.results()[2]);
  574. }
  575. } else {
  576. FATAL() << "in handle_value with Call pos " << act.pos();
  577. }
  578. case ExpressionKind::IntrinsicExpression: {
  579. const auto& intrinsic = cast<IntrinsicExpression>(exp);
  580. if (act.pos() == 0) {
  581. return todo_.Spawn(
  582. std::make_unique<ExpressionAction>(&intrinsic.args()));
  583. }
  584. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  585. switch (cast<IntrinsicExpression>(exp).intrinsic()) {
  586. case IntrinsicExpression::Intrinsic::Print: {
  587. const auto& args = cast<TupleValue>(*act.results()[0]);
  588. // TODO: This could eventually use something like llvm::formatv.
  589. llvm::outs() << cast<StringValue>(*args.elements()[0]).value();
  590. return todo_.FinishAction(TupleValue::Empty());
  591. }
  592. }
  593. }
  594. case ExpressionKind::IntTypeLiteral: {
  595. CHECK(act.pos() == 0);
  596. return todo_.FinishAction(arena_->New<IntType>());
  597. }
  598. case ExpressionKind::BoolTypeLiteral: {
  599. CHECK(act.pos() == 0);
  600. return todo_.FinishAction(arena_->New<BoolType>());
  601. }
  602. case ExpressionKind::TypeTypeLiteral: {
  603. CHECK(act.pos() == 0);
  604. return todo_.FinishAction(arena_->New<TypeType>());
  605. }
  606. case ExpressionKind::FunctionTypeLiteral: {
  607. if (act.pos() == 0) {
  608. return todo_.Spawn(std::make_unique<ExpressionAction>(
  609. &cast<FunctionTypeLiteral>(exp).parameter()));
  610. } else if (act.pos() == 1) {
  611. // { { pt :: fn [] -> e :: C, E, F} :: S, H}
  612. // -> { { e :: fn pt -> []) :: C, E, F} :: S, H}
  613. return todo_.Spawn(std::make_unique<ExpressionAction>(
  614. &cast<FunctionTypeLiteral>(exp).return_type()));
  615. } else {
  616. // { { rt :: fn pt -> [] :: C, E, F} :: S, H}
  617. // -> { fn pt -> rt :: {C, E, F} :: S, H}
  618. return todo_.FinishAction(arena_->New<FunctionType>(
  619. std::vector<Nonnull<const GenericBinding*>>(), act.results()[0],
  620. act.results()[1]));
  621. }
  622. }
  623. case ExpressionKind::ContinuationTypeLiteral: {
  624. CHECK(act.pos() == 0);
  625. return todo_.FinishAction(arena_->New<ContinuationType>());
  626. }
  627. case ExpressionKind::StringLiteral:
  628. CHECK(act.pos() == 0);
  629. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  630. return todo_.FinishAction(
  631. arena_->New<StringValue>(cast<StringLiteral>(exp).value()));
  632. case ExpressionKind::StringTypeLiteral: {
  633. CHECK(act.pos() == 0);
  634. return todo_.FinishAction(arena_->New<StringType>());
  635. }
  636. case ExpressionKind::UnimplementedExpression:
  637. FATAL() << "Unimplemented: " << exp;
  638. } // switch (exp->kind)
  639. }
  640. void Interpreter::StepPattern() {
  641. Action& act = todo_.CurrentAction();
  642. const Pattern& pattern = cast<PatternAction>(act).pattern();
  643. if (trace_) {
  644. llvm::outs() << "--- step pattern " << pattern << " ("
  645. << pattern.source_loc() << ") --->\n";
  646. }
  647. switch (pattern.kind()) {
  648. case PatternKind::AutoPattern: {
  649. CHECK(act.pos() == 0);
  650. return todo_.FinishAction(arena_->New<AutoType>());
  651. }
  652. case PatternKind::BindingPattern: {
  653. const auto& binding = cast<BindingPattern>(pattern);
  654. if (binding.name() != AnonymousName) {
  655. return todo_.FinishAction(
  656. arena_->New<BindingPlaceholderValue>(&binding));
  657. } else {
  658. return todo_.FinishAction(arena_->New<BindingPlaceholderValue>());
  659. }
  660. }
  661. case PatternKind::TuplePattern: {
  662. const auto& tuple = cast<TuplePattern>(pattern);
  663. if (act.pos() < static_cast<int>(tuple.fields().size())) {
  664. // { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
  665. // H}
  666. // -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
  667. // H}
  668. return todo_.Spawn(
  669. std::make_unique<PatternAction>(tuple.fields()[act.pos()]));
  670. } else {
  671. return todo_.FinishAction(arena_->New<TupleValue>(act.results()));
  672. }
  673. }
  674. case PatternKind::AlternativePattern: {
  675. const auto& alternative = cast<AlternativePattern>(pattern);
  676. if (act.pos() == 0) {
  677. return todo_.Spawn(
  678. std::make_unique<ExpressionAction>(&alternative.choice_type()));
  679. } else if (act.pos() == 1) {
  680. return todo_.Spawn(
  681. std::make_unique<PatternAction>(&alternative.arguments()));
  682. } else {
  683. CHECK(act.pos() == 2);
  684. const auto& choice_type = cast<ChoiceType>(*act.results()[0]);
  685. return todo_.FinishAction(arena_->New<AlternativeValue>(
  686. alternative.alternative_name(), choice_type.name(),
  687. act.results()[1]));
  688. }
  689. }
  690. case PatternKind::ExpressionPattern:
  691. if (act.pos() == 0) {
  692. return todo_.Spawn(std::make_unique<ExpressionAction>(
  693. &cast<ExpressionPattern>(pattern).expression()));
  694. } else {
  695. return todo_.FinishAction(act.results()[0]);
  696. }
  697. }
  698. }
  699. void Interpreter::StepStmt() {
  700. Action& act = todo_.CurrentAction();
  701. const Statement& stmt = cast<StatementAction>(act).statement();
  702. if (trace_) {
  703. llvm::outs() << "--- step stmt ";
  704. stmt.PrintDepth(1, llvm::outs());
  705. llvm::outs() << " (" << stmt.source_loc() << ") --->\n";
  706. }
  707. switch (stmt.kind()) {
  708. case StatementKind::Match: {
  709. const auto& match_stmt = cast<Match>(stmt);
  710. if (act.pos() == 0) {
  711. // { { (match (e) ...) :: C, E, F} :: S, H}
  712. // -> { { e :: (match ([]) ...) :: C, E, F} :: S, H}
  713. act.StartScope(RuntimeScope(&heap_));
  714. return todo_.Spawn(
  715. std::make_unique<ExpressionAction>(&match_stmt.expression()));
  716. } else {
  717. int clause_num = act.pos() - 1;
  718. if (clause_num >= static_cast<int>(match_stmt.clauses().size())) {
  719. return todo_.FinishAction();
  720. }
  721. auto c = match_stmt.clauses()[clause_num];
  722. RuntimeScope matches(&heap_);
  723. if (PatternMatch(&c.pattern().value(),
  724. Convert(act.results()[0], &c.pattern().static_type()),
  725. stmt.source_loc(), &matches)) {
  726. // Ensure we don't process any more clauses.
  727. act.set_pos(match_stmt.clauses().size() + 1);
  728. todo_.MergeScope(std::move(matches));
  729. return todo_.Spawn(std::make_unique<StatementAction>(&c.statement()));
  730. } else {
  731. return todo_.RunAgain();
  732. }
  733. }
  734. }
  735. case StatementKind::While:
  736. if (act.pos() % 2 == 0) {
  737. // { { (while (e) s) :: C, E, F} :: S, H}
  738. // -> { { e :: (while ([]) s) :: C, E, F} :: S, H}
  739. act.Clear();
  740. return todo_.Spawn(
  741. std::make_unique<ExpressionAction>(&cast<While>(stmt).condition()));
  742. } else {
  743. Nonnull<const Value*> condition =
  744. Convert(act.results().back(), arena_->New<BoolType>());
  745. if (cast<BoolValue>(*condition).value()) {
  746. // { {true :: (while ([]) s) :: C, E, F} :: S, H}
  747. // -> { { s :: (while (e) s) :: C, E, F } :: S, H}
  748. return todo_.Spawn(
  749. std::make_unique<StatementAction>(&cast<While>(stmt).body()));
  750. } else {
  751. // { {false :: (while ([]) s) :: C, E, F} :: S, H}
  752. // -> { { C, E, F } :: S, H}
  753. return todo_.FinishAction();
  754. }
  755. }
  756. case StatementKind::Break: {
  757. CHECK(act.pos() == 0);
  758. // { { break; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  759. // -> { { C, E', F} :: S, H}
  760. return todo_.UnwindPast(&cast<Break>(stmt).loop());
  761. }
  762. case StatementKind::Continue: {
  763. CHECK(act.pos() == 0);
  764. // { { continue; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  765. // -> { { (while (e) s) :: C, E', F} :: S, H}
  766. return todo_.UnwindTo(&cast<Continue>(stmt).loop());
  767. }
  768. case StatementKind::Block: {
  769. const auto& block = cast<Block>(stmt);
  770. if (act.pos() >= static_cast<int>(block.statements().size())) {
  771. // If the position is past the end of the block, end processing. Note
  772. // that empty blocks immediately end.
  773. return todo_.FinishAction();
  774. }
  775. // Initialize a scope when starting a block.
  776. if (act.pos() == 0) {
  777. act.StartScope(RuntimeScope(&heap_));
  778. }
  779. // Process the next statement in the block. The position will be
  780. // incremented as part of Spawn.
  781. return todo_.Spawn(
  782. std::make_unique<StatementAction>(block.statements()[act.pos()]));
  783. }
  784. case StatementKind::VariableDefinition: {
  785. const auto& definition = cast<VariableDefinition>(stmt);
  786. if (act.pos() == 0) {
  787. // { {(var x = e) :: C, E, F} :: S, H}
  788. // -> { {e :: (var x = []) :: C, E, F} :: S, H}
  789. return todo_.Spawn(
  790. std::make_unique<ExpressionAction>(&definition.init()));
  791. } else {
  792. // { { v :: (x = []) :: C, E, F} :: S, H}
  793. // -> { { C, E(x := a), F} :: S, H(a := copy(v))}
  794. Nonnull<const Value*> v =
  795. Convert(act.results()[0], &definition.pattern().static_type());
  796. Nonnull<const Value*> p =
  797. &cast<VariableDefinition>(stmt).pattern().value();
  798. RuntimeScope matches(&heap_);
  799. CHECK(PatternMatch(p, v, stmt.source_loc(), &matches))
  800. << stmt.source_loc()
  801. << ": internal error in variable definition, match failed";
  802. todo_.MergeScope(std::move(matches));
  803. return todo_.FinishAction();
  804. }
  805. }
  806. case StatementKind::ExpressionStatement:
  807. if (act.pos() == 0) {
  808. // { {e :: C, E, F} :: S, H}
  809. // -> { {e :: C, E, F} :: S, H}
  810. return todo_.Spawn(std::make_unique<ExpressionAction>(
  811. &cast<ExpressionStatement>(stmt).expression()));
  812. } else {
  813. return todo_.FinishAction();
  814. }
  815. case StatementKind::Assign: {
  816. const auto& assign = cast<Assign>(stmt);
  817. if (act.pos() == 0) {
  818. // { {(lv = e) :: C, E, F} :: S, H}
  819. // -> { {lv :: ([] = e) :: C, E, F} :: S, H}
  820. return todo_.Spawn(std::make_unique<LValAction>(&assign.lhs()));
  821. } else if (act.pos() == 1) {
  822. // { { a :: ([] = e) :: C, E, F} :: S, H}
  823. // -> { { e :: (a = []) :: C, E, F} :: S, H}
  824. return todo_.Spawn(std::make_unique<ExpressionAction>(&assign.rhs()));
  825. } else {
  826. // { { v :: (a = []) :: C, E, F} :: S, H}
  827. // -> { { C, E, F} :: S, H(a := v)}
  828. const auto& lval = cast<LValue>(*act.results()[0]);
  829. Nonnull<const Value*> rval =
  830. Convert(act.results()[1], &assign.lhs().static_type());
  831. heap_.Write(lval.address(), rval, stmt.source_loc());
  832. return todo_.FinishAction();
  833. }
  834. }
  835. case StatementKind::If:
  836. if (act.pos() == 0) {
  837. // { {(if (e) then_stmt else else_stmt) :: C, E, F} :: S, H}
  838. // -> { { e :: (if ([]) then_stmt else else_stmt) :: C, E, F} :: S, H}
  839. return todo_.Spawn(
  840. std::make_unique<ExpressionAction>(&cast<If>(stmt).condition()));
  841. } else if (act.pos() == 1) {
  842. Nonnull<const Value*> condition =
  843. Convert(act.results()[0], arena_->New<BoolType>());
  844. if (cast<BoolValue>(*condition).value()) {
  845. // { {true :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  846. // S, H}
  847. // -> { { then_stmt :: C, E, F } :: S, H}
  848. return todo_.Spawn(
  849. std::make_unique<StatementAction>(&cast<If>(stmt).then_block()));
  850. } else if (cast<If>(stmt).else_block()) {
  851. // { {false :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  852. // S, H}
  853. // -> { { else_stmt :: C, E, F } :: S, H}
  854. return todo_.Spawn(
  855. std::make_unique<StatementAction>(*cast<If>(stmt).else_block()));
  856. } else {
  857. return todo_.FinishAction();
  858. }
  859. } else {
  860. return todo_.FinishAction();
  861. }
  862. case StatementKind::Return:
  863. if (act.pos() == 0) {
  864. // { {return e :: C, E, F} :: S, H}
  865. // -> { {e :: return [] :: C, E, F} :: S, H}
  866. return todo_.Spawn(std::make_unique<ExpressionAction>(
  867. &cast<Return>(stmt).expression()));
  868. } else {
  869. // { {v :: return [] :: C, E, F} :: {C', E', F'} :: S, H}
  870. // -> { {v :: C', E', F'} :: S, H}
  871. const FunctionDeclaration& function = cast<Return>(stmt).function();
  872. return todo_.UnwindPast(
  873. *function.body(),
  874. Convert(act.results()[0], &function.return_term().static_type()));
  875. }
  876. case StatementKind::Continuation: {
  877. CHECK(act.pos() == 0);
  878. const auto& continuation = cast<Continuation>(stmt);
  879. // Create a continuation object by creating a frame similar the
  880. // way one is created in a function call.
  881. auto fragment = arena_->New<ContinuationValue::StackFragment>();
  882. stack_fragments_.push_back(fragment);
  883. todo_.InitializeFragment(*fragment, &continuation.body());
  884. // Bind the continuation object to the continuation variable
  885. todo_.Initialize(&cast<Continuation>(stmt),
  886. arena_->New<ContinuationValue>(fragment));
  887. return todo_.FinishAction();
  888. }
  889. case StatementKind::Run: {
  890. auto& run = cast<Run>(stmt);
  891. if (act.pos() == 0) {
  892. // Evaluate the argument of the run statement.
  893. return todo_.Spawn(std::make_unique<ExpressionAction>(&run.argument()));
  894. } else if (act.pos() == 1) {
  895. // Push the continuation onto the current stack.
  896. return todo_.Resume(cast<const ContinuationValue>(act.results()[0]));
  897. } else {
  898. return todo_.FinishAction();
  899. }
  900. }
  901. case StatementKind::Await:
  902. CHECK(act.pos() == 0);
  903. return todo_.Suspend();
  904. }
  905. }
  906. void Interpreter::StepDeclaration() {
  907. Action& act = todo_.CurrentAction();
  908. const Declaration& decl = cast<DeclarationAction>(act).declaration();
  909. if (trace_) {
  910. llvm::outs() << "--- step declaration (" << decl.source_loc() << ") --->\n";
  911. }
  912. switch (decl.kind()) {
  913. case DeclarationKind::VariableDeclaration: {
  914. const auto& var_decl = cast<VariableDeclaration>(decl);
  915. if (var_decl.has_initializer()) {
  916. if (act.pos() == 0) {
  917. return todo_.Spawn(
  918. std::make_unique<ExpressionAction>(&var_decl.initializer()));
  919. } else {
  920. todo_.Initialize(&var_decl.binding(), act.results()[0]);
  921. return todo_.FinishAction();
  922. }
  923. } else {
  924. return todo_.FinishAction();
  925. }
  926. }
  927. case DeclarationKind::FunctionDeclaration:
  928. case DeclarationKind::ClassDeclaration:
  929. case DeclarationKind::ChoiceDeclaration:
  930. // These declarations have no run-time effects.
  931. return todo_.FinishAction();
  932. }
  933. }
  934. // State transition.
  935. void Interpreter::Step() {
  936. Action& act = todo_.CurrentAction();
  937. switch (act.kind()) {
  938. case Action::Kind::LValAction:
  939. StepLvalue();
  940. break;
  941. case Action::Kind::ExpressionAction:
  942. StepExp();
  943. break;
  944. case Action::Kind::PatternAction:
  945. StepPattern();
  946. break;
  947. case Action::Kind::StatementAction:
  948. StepStmt();
  949. break;
  950. case Action::Kind::DeclarationAction:
  951. StepDeclaration();
  952. break;
  953. case Action::Kind::ScopeAction:
  954. FATAL() << "ScopeAction escaped ActionStack";
  955. } // switch
  956. }
  957. void Interpreter::RunAllSteps(std::unique_ptr<Action> action) {
  958. if (trace_) {
  959. PrintState(llvm::outs());
  960. }
  961. todo_.Start(std::move(action));
  962. while (!todo_.IsEmpty()) {
  963. Step();
  964. if (trace_) {
  965. PrintState(llvm::outs());
  966. }
  967. }
  968. }
  969. auto InterpProgram(const AST& ast, Nonnull<Arena*> arena, bool trace) -> int {
  970. Interpreter interpreter(Phase::RunTime, arena, trace);
  971. if (trace) {
  972. llvm::outs() << "********** initializing globals **********\n";
  973. }
  974. for (Nonnull<Declaration*> declaration : ast.declarations) {
  975. interpreter.RunAllSteps(std::make_unique<DeclarationAction>(declaration));
  976. }
  977. if (trace) {
  978. llvm::outs() << "********** calling main function **********\n";
  979. }
  980. interpreter.RunAllSteps(std::make_unique<ExpressionAction>(*ast.main_call));
  981. return cast<IntValue>(*interpreter.result()).value();
  982. }
  983. auto InterpExp(Nonnull<const Expression*> e, Nonnull<Arena*> arena, bool trace)
  984. -> Nonnull<const Value*> {
  985. Interpreter interpreter(Phase::CompileTime, arena, trace);
  986. interpreter.RunAllSteps(std::make_unique<ExpressionAction>(e));
  987. return interpreter.result();
  988. }
  989. auto InterpPattern(Nonnull<const Pattern*> p, Nonnull<Arena*> arena, bool trace)
  990. -> Nonnull<const Value*> {
  991. Interpreter interpreter(Phase::CompileTime, arena, trace);
  992. interpreter.RunAllSteps(std::make_unique<PatternAction>(p));
  993. return interpreter.result();
  994. }
  995. } // namespace Carbon