interpreter.cpp 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017
  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 = cast<PrimitiveOperatorExpression>(exp);
  290. if (op.op() != Operator::Deref) {
  291. FATAL() << "Can't treat primitive operator expression as lvalue: " << exp;
  292. }
  293. if (act.pos() == 0) {
  294. return todo_.Spawn(
  295. std::make_unique<ExpressionAction>(op.arguments()[0]));
  296. } else {
  297. const PointerValue& res = cast<PointerValue>(*act.results()[0]);
  298. return todo_.FinishAction(arena_->New<LValue>(res.address()));
  299. }
  300. break;
  301. }
  302. case ExpressionKind::TupleLiteral:
  303. case ExpressionKind::StructLiteral:
  304. case ExpressionKind::StructTypeLiteral:
  305. case ExpressionKind::IntLiteral:
  306. case ExpressionKind::BoolLiteral:
  307. case ExpressionKind::CallExpression:
  308. case ExpressionKind::IntTypeLiteral:
  309. case ExpressionKind::BoolTypeLiteral:
  310. case ExpressionKind::TypeTypeLiteral:
  311. case ExpressionKind::FunctionTypeLiteral:
  312. case ExpressionKind::ContinuationTypeLiteral:
  313. case ExpressionKind::StringLiteral:
  314. case ExpressionKind::StringTypeLiteral:
  315. case ExpressionKind::IntrinsicExpression:
  316. FATAL() << "Can't treat expression as lvalue: " << exp;
  317. case ExpressionKind::UnimplementedExpression:
  318. FATAL() << "Unimplemented: " << exp;
  319. }
  320. }
  321. auto Interpreter::Convert(Nonnull<const Value*> value,
  322. Nonnull<const Value*> destination_type) const
  323. -> Nonnull<const Value*> {
  324. switch (value->kind()) {
  325. case Value::Kind::IntValue:
  326. case Value::Kind::FunctionValue:
  327. case Value::Kind::PointerValue:
  328. case Value::Kind::LValue:
  329. case Value::Kind::BoolValue:
  330. case Value::Kind::NominalClassValue:
  331. case Value::Kind::AlternativeValue:
  332. case Value::Kind::IntType:
  333. case Value::Kind::BoolType:
  334. case Value::Kind::TypeType:
  335. case Value::Kind::FunctionType:
  336. case Value::Kind::PointerType:
  337. case Value::Kind::AutoType:
  338. case Value::Kind::StructType:
  339. case Value::Kind::NominalClassType:
  340. case Value::Kind::ChoiceType:
  341. case Value::Kind::ContinuationType:
  342. case Value::Kind::VariableType:
  343. case Value::Kind::BindingPlaceholderValue:
  344. case Value::Kind::AlternativeConstructorValue:
  345. case Value::Kind::ContinuationValue:
  346. case Value::Kind::StringType:
  347. case Value::Kind::StringValue:
  348. case Value::Kind::TypeOfClassType:
  349. case Value::Kind::TypeOfChoiceType:
  350. // TODO: add `CHECK(TypeEqual(type, value->dynamic_type()))`, once we
  351. // have Value::dynamic_type.
  352. return value;
  353. case Value::Kind::StructValue: {
  354. const auto& struct_val = cast<StructValue>(*value);
  355. switch (destination_type->kind()) {
  356. case Value::Kind::StructType: {
  357. const auto& destination_struct_type =
  358. cast<StructType>(*destination_type);
  359. std::vector<NamedValue> new_elements;
  360. for (const auto& [field_name, field_type] :
  361. destination_struct_type.fields()) {
  362. std::optional<Nonnull<const Value*>> old_value =
  363. struct_val.FindField(field_name);
  364. new_elements.push_back(
  365. {.name = field_name, .value = Convert(*old_value, field_type)});
  366. }
  367. return arena_->New<StructValue>(std::move(new_elements));
  368. }
  369. case Value::Kind::NominalClassType:
  370. return arena_->New<NominalClassValue>(destination_type, value);
  371. default:
  372. FATAL() << "Can't convert value " << *value << " to type "
  373. << *destination_type;
  374. }
  375. }
  376. case Value::Kind::TupleValue: {
  377. const auto& tuple = cast<TupleValue>(value);
  378. const auto& destination_tuple_type = cast<TupleValue>(destination_type);
  379. CHECK(tuple->elements().size() ==
  380. destination_tuple_type->elements().size());
  381. std::vector<Nonnull<const Value*>> new_elements;
  382. for (size_t i = 0; i < tuple->elements().size(); ++i) {
  383. new_elements.push_back(Convert(tuple->elements()[i],
  384. destination_tuple_type->elements()[i]));
  385. }
  386. return arena_->New<TupleValue>(std::move(new_elements));
  387. }
  388. }
  389. }
  390. void Interpreter::StepExp() {
  391. Action& act = todo_.CurrentAction();
  392. const Expression& exp = cast<ExpressionAction>(act).expression();
  393. if (trace_) {
  394. llvm::outs() << "--- step exp " << exp << " (" << exp.source_loc()
  395. << ") --->\n";
  396. }
  397. switch (exp.kind()) {
  398. case ExpressionKind::IndexExpression: {
  399. if (act.pos() == 0) {
  400. // { { e[i] :: C, E, F} :: S, H}
  401. // -> { { e :: [][i] :: C, E, F} :: S, H}
  402. return todo_.Spawn(std::make_unique<ExpressionAction>(
  403. &cast<IndexExpression>(exp).aggregate()));
  404. } else if (act.pos() == 1) {
  405. return todo_.Spawn(std::make_unique<ExpressionAction>(
  406. &cast<IndexExpression>(exp).offset()));
  407. } else {
  408. // { { v :: [][i] :: C, E, F} :: S, H}
  409. // -> { { v_i :: C, E, F} : S, H}
  410. const auto& tuple = cast<TupleValue>(*act.results()[0]);
  411. int i = cast<IntValue>(*act.results()[1]).value();
  412. if (i < 0 || i >= static_cast<int>(tuple.elements().size())) {
  413. FATAL_RUNTIME_ERROR_NO_LINE()
  414. << "index " << i << " out of range in " << tuple;
  415. }
  416. return todo_.FinishAction(tuple.elements()[i]);
  417. }
  418. }
  419. case ExpressionKind::TupleLiteral: {
  420. if (act.pos() <
  421. static_cast<int>(cast<TupleLiteral>(exp).fields().size())) {
  422. // { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
  423. // H}
  424. // -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
  425. // H}
  426. return todo_.Spawn(std::make_unique<ExpressionAction>(
  427. cast<TupleLiteral>(exp).fields()[act.pos()]));
  428. } else {
  429. return todo_.FinishAction(arena_->New<TupleValue>(act.results()));
  430. }
  431. }
  432. case ExpressionKind::StructLiteral: {
  433. const auto& literal = cast<StructLiteral>(exp);
  434. if (act.pos() < static_cast<int>(literal.fields().size())) {
  435. return todo_.Spawn(std::make_unique<ExpressionAction>(
  436. &literal.fields()[act.pos()].expression()));
  437. } else {
  438. return todo_.FinishAction(
  439. CreateStruct(literal.fields(), act.results()));
  440. }
  441. }
  442. case ExpressionKind::StructTypeLiteral: {
  443. const auto& struct_type = cast<StructTypeLiteral>(exp);
  444. if (act.pos() < static_cast<int>(struct_type.fields().size())) {
  445. return todo_.Spawn(std::make_unique<ExpressionAction>(
  446. &struct_type.fields()[act.pos()].expression()));
  447. } else {
  448. std::vector<NamedValue> fields;
  449. for (size_t i = 0; i < struct_type.fields().size(); ++i) {
  450. fields.push_back({struct_type.fields()[i].name(), act.results()[i]});
  451. }
  452. return todo_.FinishAction(arena_->New<StructType>(std::move(fields)));
  453. }
  454. }
  455. case ExpressionKind::FieldAccessExpression: {
  456. const auto& access = cast<FieldAccessExpression>(exp);
  457. if (act.pos() == 0) {
  458. // { { e.f :: C, E, F} :: S, H}
  459. // -> { { e :: [].f :: C, E, F} :: S, H}
  460. return todo_.Spawn(
  461. std::make_unique<ExpressionAction>(&access.aggregate()));
  462. } else {
  463. // { { v :: [].f :: C, E, F} :: S, H}
  464. // -> { { v_f :: C, E, F} : S, H}
  465. return todo_.FinishAction(act.results()[0]->GetField(
  466. arena_, FieldPath(access.field()), exp.source_loc()));
  467. }
  468. }
  469. case ExpressionKind::IdentifierExpression: {
  470. CHECK(act.pos() == 0);
  471. const auto& ident = cast<IdentifierExpression>(exp);
  472. // { {x :: C, E, F} :: S, H} -> { {H(E(x)) :: C, E, F} :: S, H}
  473. Nonnull<const Value*> value =
  474. todo_.ValueOfName(ident.named_entity(), ident.source_loc());
  475. if (const auto* lvalue = dyn_cast<LValue>(value)) {
  476. value = heap_.Read(lvalue->address(), exp.source_loc());
  477. }
  478. return todo_.FinishAction(value);
  479. }
  480. case ExpressionKind::IntLiteral:
  481. CHECK(act.pos() == 0);
  482. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  483. return todo_.FinishAction(
  484. arena_->New<IntValue>(cast<IntLiteral>(exp).value()));
  485. case ExpressionKind::BoolLiteral:
  486. CHECK(act.pos() == 0);
  487. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  488. return todo_.FinishAction(
  489. arena_->New<BoolValue>(cast<BoolLiteral>(exp).value()));
  490. case ExpressionKind::PrimitiveOperatorExpression: {
  491. const auto& op = cast<PrimitiveOperatorExpression>(exp);
  492. if (act.pos() != static_cast<int>(op.arguments().size())) {
  493. // { {v :: op(vs,[],e,es) :: C, E, F} :: S, H}
  494. // -> { {e :: op(vs,v,[],es) :: C, E, F} :: S, H}
  495. Nonnull<const Expression*> arg = op.arguments()[act.pos()];
  496. if (op.op() == Operator::AddressOf) {
  497. return todo_.Spawn(std::make_unique<LValAction>(arg));
  498. } else {
  499. return todo_.Spawn(std::make_unique<ExpressionAction>(arg));
  500. }
  501. } else {
  502. // { {v :: op(vs,[]) :: C, E, F} :: S, H}
  503. // -> { {eval_prim(op, (vs,v)) :: C, E, F} :: S, H}
  504. return todo_.FinishAction(
  505. EvalPrim(op.op(), act.results(), exp.source_loc()));
  506. }
  507. }
  508. case ExpressionKind::CallExpression:
  509. if (act.pos() == 0) {
  510. // { {e1(e2) :: C, E, F} :: S, H}
  511. // -> { {e1 :: [](e2) :: C, E, F} :: S, H}
  512. return todo_.Spawn(std::make_unique<ExpressionAction>(
  513. &cast<CallExpression>(exp).function()));
  514. } else if (act.pos() == 1) {
  515. // { { v :: [](e) :: C, E, F} :: S, H}
  516. // -> { { e :: v([]) :: C, E, F} :: S, H}
  517. return todo_.Spawn(std::make_unique<ExpressionAction>(
  518. &cast<CallExpression>(exp).argument()));
  519. } else if (act.pos() == 2) {
  520. // { { v2 :: v1([]) :: C, E, F} :: S, H}
  521. // -> { {C',E',F'} :: {C, E, F} :: S, H}
  522. switch (act.results()[0]->kind()) {
  523. case Value::Kind::AlternativeConstructorValue: {
  524. const auto& alt =
  525. cast<AlternativeConstructorValue>(*act.results()[0]);
  526. return todo_.FinishAction(arena_->New<AlternativeValue>(
  527. alt.alt_name(), alt.choice_name(), act.results()[1]));
  528. }
  529. case Value::Kind::FunctionValue: {
  530. const FunctionDeclaration& function =
  531. cast<FunctionValue>(*act.results()[0]).declaration();
  532. Nonnull<const Value*> converted_args = Convert(
  533. act.results()[1], &function.param_pattern().static_type());
  534. RuntimeScope function_scope(&heap_);
  535. CHECK(PatternMatch(&function.param_pattern().value(),
  536. converted_args, exp.source_loc(),
  537. &function_scope));
  538. CHECK(function.body().has_value())
  539. << "Calling a function that's missing a body";
  540. return todo_.Spawn(
  541. std::make_unique<StatementAction>(*function.body()),
  542. std::move(function_scope));
  543. }
  544. default:
  545. FATAL_RUNTIME_ERROR(exp.source_loc())
  546. << "in call, expected a function, not " << *act.results()[0];
  547. }
  548. } else if (act.pos() == 3) {
  549. if (act.results().size() < 3) {
  550. // Control fell through without explicit return.
  551. return todo_.FinishAction(TupleValue::Empty());
  552. } else {
  553. return todo_.FinishAction(act.results()[2]);
  554. }
  555. } else {
  556. FATAL() << "in handle_value with Call pos " << act.pos();
  557. }
  558. case ExpressionKind::IntrinsicExpression: {
  559. const auto& intrinsic = cast<IntrinsicExpression>(exp);
  560. if (act.pos() == 0) {
  561. return todo_.Spawn(
  562. std::make_unique<ExpressionAction>(&intrinsic.args()));
  563. }
  564. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  565. switch (cast<IntrinsicExpression>(exp).intrinsic()) {
  566. case IntrinsicExpression::Intrinsic::Print: {
  567. const auto& args = cast<TupleValue>(*act.results()[0]);
  568. // TODO: This could eventually use something like llvm::formatv.
  569. llvm::outs() << cast<StringValue>(*args.elements()[0]).value();
  570. return todo_.FinishAction(TupleValue::Empty());
  571. }
  572. }
  573. }
  574. case ExpressionKind::IntTypeLiteral: {
  575. CHECK(act.pos() == 0);
  576. return todo_.FinishAction(arena_->New<IntType>());
  577. }
  578. case ExpressionKind::BoolTypeLiteral: {
  579. CHECK(act.pos() == 0);
  580. return todo_.FinishAction(arena_->New<BoolType>());
  581. }
  582. case ExpressionKind::TypeTypeLiteral: {
  583. CHECK(act.pos() == 0);
  584. return todo_.FinishAction(arena_->New<TypeType>());
  585. }
  586. case ExpressionKind::FunctionTypeLiteral: {
  587. if (act.pos() == 0) {
  588. return todo_.Spawn(std::make_unique<ExpressionAction>(
  589. &cast<FunctionTypeLiteral>(exp).parameter()));
  590. } else if (act.pos() == 1) {
  591. // { { pt :: fn [] -> e :: C, E, F} :: S, H}
  592. // -> { { e :: fn pt -> []) :: C, E, F} :: S, H}
  593. return todo_.Spawn(std::make_unique<ExpressionAction>(
  594. &cast<FunctionTypeLiteral>(exp).return_type()));
  595. } else {
  596. // { { rt :: fn pt -> [] :: C, E, F} :: S, H}
  597. // -> { fn pt -> rt :: {C, E, F} :: S, H}
  598. return todo_.FinishAction(arena_->New<FunctionType>(
  599. std::vector<Nonnull<const GenericBinding*>>(), act.results()[0],
  600. act.results()[1]));
  601. }
  602. }
  603. case ExpressionKind::ContinuationTypeLiteral: {
  604. CHECK(act.pos() == 0);
  605. return todo_.FinishAction(arena_->New<ContinuationType>());
  606. }
  607. case ExpressionKind::StringLiteral:
  608. CHECK(act.pos() == 0);
  609. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  610. return todo_.FinishAction(
  611. arena_->New<StringValue>(cast<StringLiteral>(exp).value()));
  612. case ExpressionKind::StringTypeLiteral: {
  613. CHECK(act.pos() == 0);
  614. return todo_.FinishAction(arena_->New<StringType>());
  615. }
  616. case ExpressionKind::UnimplementedExpression:
  617. FATAL() << "Unimplemented: " << exp;
  618. } // switch (exp->kind)
  619. }
  620. void Interpreter::StepPattern() {
  621. Action& act = todo_.CurrentAction();
  622. const Pattern& pattern = cast<PatternAction>(act).pattern();
  623. if (trace_) {
  624. llvm::outs() << "--- step pattern " << pattern << " ("
  625. << pattern.source_loc() << ") --->\n";
  626. }
  627. switch (pattern.kind()) {
  628. case PatternKind::AutoPattern: {
  629. CHECK(act.pos() == 0);
  630. return todo_.FinishAction(arena_->New<AutoType>());
  631. }
  632. case PatternKind::BindingPattern: {
  633. const auto& binding = cast<BindingPattern>(pattern);
  634. if (binding.name() != AnonymousName) {
  635. return todo_.FinishAction(
  636. arena_->New<BindingPlaceholderValue>(&binding));
  637. } else {
  638. return todo_.FinishAction(arena_->New<BindingPlaceholderValue>());
  639. }
  640. }
  641. case PatternKind::TuplePattern: {
  642. const auto& tuple = cast<TuplePattern>(pattern);
  643. if (act.pos() < static_cast<int>(tuple.fields().size())) {
  644. // { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
  645. // H}
  646. // -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
  647. // H}
  648. return todo_.Spawn(
  649. std::make_unique<PatternAction>(tuple.fields()[act.pos()]));
  650. } else {
  651. return todo_.FinishAction(arena_->New<TupleValue>(act.results()));
  652. }
  653. }
  654. case PatternKind::AlternativePattern: {
  655. const auto& alternative = cast<AlternativePattern>(pattern);
  656. if (act.pos() == 0) {
  657. return todo_.Spawn(
  658. std::make_unique<ExpressionAction>(&alternative.choice_type()));
  659. } else if (act.pos() == 1) {
  660. return todo_.Spawn(
  661. std::make_unique<PatternAction>(&alternative.arguments()));
  662. } else {
  663. CHECK(act.pos() == 2);
  664. const auto& choice_type = cast<ChoiceType>(*act.results()[0]);
  665. return todo_.FinishAction(arena_->New<AlternativeValue>(
  666. alternative.alternative_name(), choice_type.name(),
  667. act.results()[1]));
  668. }
  669. }
  670. case PatternKind::ExpressionPattern:
  671. if (act.pos() == 0) {
  672. return todo_.Spawn(std::make_unique<ExpressionAction>(
  673. &cast<ExpressionPattern>(pattern).expression()));
  674. } else {
  675. return todo_.FinishAction(act.results()[0]);
  676. }
  677. }
  678. }
  679. void Interpreter::StepStmt() {
  680. Action& act = todo_.CurrentAction();
  681. const Statement& stmt = cast<StatementAction>(act).statement();
  682. if (trace_) {
  683. llvm::outs() << "--- step stmt ";
  684. stmt.PrintDepth(1, llvm::outs());
  685. llvm::outs() << " (" << stmt.source_loc() << ") --->\n";
  686. }
  687. switch (stmt.kind()) {
  688. case StatementKind::Match: {
  689. const auto& match_stmt = cast<Match>(stmt);
  690. if (act.pos() == 0) {
  691. // { { (match (e) ...) :: C, E, F} :: S, H}
  692. // -> { { e :: (match ([]) ...) :: C, E, F} :: S, H}
  693. act.StartScope(RuntimeScope(&heap_));
  694. return todo_.Spawn(
  695. std::make_unique<ExpressionAction>(&match_stmt.expression()));
  696. } else {
  697. int clause_num = act.pos() - 1;
  698. if (clause_num >= static_cast<int>(match_stmt.clauses().size())) {
  699. return todo_.FinishAction();
  700. }
  701. auto c = match_stmt.clauses()[clause_num];
  702. RuntimeScope matches(&heap_);
  703. if (PatternMatch(&c.pattern().value(),
  704. Convert(act.results()[0], &c.pattern().static_type()),
  705. stmt.source_loc(), &matches)) {
  706. // Ensure we don't process any more clauses.
  707. act.set_pos(match_stmt.clauses().size() + 1);
  708. todo_.MergeScope(std::move(matches));
  709. return todo_.Spawn(std::make_unique<StatementAction>(&c.statement()));
  710. } else {
  711. return todo_.RunAgain();
  712. }
  713. }
  714. }
  715. case StatementKind::While:
  716. if (act.pos() % 2 == 0) {
  717. // { { (while (e) s) :: C, E, F} :: S, H}
  718. // -> { { e :: (while ([]) s) :: C, E, F} :: S, H}
  719. act.Clear();
  720. return todo_.Spawn(
  721. std::make_unique<ExpressionAction>(&cast<While>(stmt).condition()));
  722. } else {
  723. Nonnull<const Value*> condition =
  724. Convert(act.results().back(), arena_->New<BoolType>());
  725. if (cast<BoolValue>(*condition).value()) {
  726. // { {true :: (while ([]) s) :: C, E, F} :: S, H}
  727. // -> { { s :: (while (e) s) :: C, E, F } :: S, H}
  728. return todo_.Spawn(
  729. std::make_unique<StatementAction>(&cast<While>(stmt).body()));
  730. } else {
  731. // { {false :: (while ([]) s) :: C, E, F} :: S, H}
  732. // -> { { C, E, F } :: S, H}
  733. return todo_.FinishAction();
  734. }
  735. }
  736. case StatementKind::Break: {
  737. CHECK(act.pos() == 0);
  738. // { { break; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  739. // -> { { C, E', F} :: S, H}
  740. return todo_.UnwindPast(&cast<Break>(stmt).loop());
  741. }
  742. case StatementKind::Continue: {
  743. CHECK(act.pos() == 0);
  744. // { { continue; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  745. // -> { { (while (e) s) :: C, E', F} :: S, H}
  746. return todo_.UnwindTo(&cast<Continue>(stmt).loop());
  747. }
  748. case StatementKind::Block: {
  749. const auto& block = cast<Block>(stmt);
  750. if (act.pos() >= static_cast<int>(block.statements().size())) {
  751. // If the position is past the end of the block, end processing. Note
  752. // that empty blocks immediately end.
  753. return todo_.FinishAction();
  754. }
  755. // Initialize a scope when starting a block.
  756. if (act.pos() == 0) {
  757. act.StartScope(RuntimeScope(&heap_));
  758. }
  759. // Process the next statement in the block. The position will be
  760. // incremented as part of Spawn.
  761. return todo_.Spawn(
  762. std::make_unique<StatementAction>(block.statements()[act.pos()]));
  763. }
  764. case StatementKind::VariableDefinition: {
  765. const auto& definition = cast<VariableDefinition>(stmt);
  766. if (act.pos() == 0) {
  767. // { {(var x = e) :: C, E, F} :: S, H}
  768. // -> { {e :: (var x = []) :: C, E, F} :: S, H}
  769. return todo_.Spawn(
  770. std::make_unique<ExpressionAction>(&definition.init()));
  771. } else {
  772. // { { v :: (x = []) :: C, E, F} :: S, H}
  773. // -> { { C, E(x := a), F} :: S, H(a := copy(v))}
  774. Nonnull<const Value*> v =
  775. Convert(act.results()[0], &definition.pattern().static_type());
  776. Nonnull<const Value*> p =
  777. &cast<VariableDefinition>(stmt).pattern().value();
  778. RuntimeScope matches(&heap_);
  779. CHECK(PatternMatch(p, v, stmt.source_loc(), &matches))
  780. << stmt.source_loc()
  781. << ": internal error in variable definition, match failed";
  782. todo_.MergeScope(std::move(matches));
  783. return todo_.FinishAction();
  784. }
  785. }
  786. case StatementKind::ExpressionStatement:
  787. if (act.pos() == 0) {
  788. // { {e :: C, E, F} :: S, H}
  789. // -> { {e :: C, E, F} :: S, H}
  790. return todo_.Spawn(std::make_unique<ExpressionAction>(
  791. &cast<ExpressionStatement>(stmt).expression()));
  792. } else {
  793. return todo_.FinishAction();
  794. }
  795. case StatementKind::Assign: {
  796. const auto& assign = cast<Assign>(stmt);
  797. if (act.pos() == 0) {
  798. // { {(lv = e) :: C, E, F} :: S, H}
  799. // -> { {lv :: ([] = e) :: C, E, F} :: S, H}
  800. return todo_.Spawn(std::make_unique<LValAction>(&assign.lhs()));
  801. } else if (act.pos() == 1) {
  802. // { { a :: ([] = e) :: C, E, F} :: S, H}
  803. // -> { { e :: (a = []) :: C, E, F} :: S, H}
  804. return todo_.Spawn(std::make_unique<ExpressionAction>(&assign.rhs()));
  805. } else {
  806. // { { v :: (a = []) :: C, E, F} :: S, H}
  807. // -> { { C, E, F} :: S, H(a := v)}
  808. const auto& lval = cast<LValue>(*act.results()[0]);
  809. Nonnull<const Value*> rval =
  810. Convert(act.results()[1], &assign.lhs().static_type());
  811. heap_.Write(lval.address(), rval, stmt.source_loc());
  812. return todo_.FinishAction();
  813. }
  814. }
  815. case StatementKind::If:
  816. if (act.pos() == 0) {
  817. // { {(if (e) then_stmt else else_stmt) :: C, E, F} :: S, H}
  818. // -> { { e :: (if ([]) then_stmt else else_stmt) :: C, E, F} :: S, H}
  819. return todo_.Spawn(
  820. std::make_unique<ExpressionAction>(&cast<If>(stmt).condition()));
  821. } else if (act.pos() == 1) {
  822. Nonnull<const Value*> condition =
  823. Convert(act.results()[0], arena_->New<BoolType>());
  824. if (cast<BoolValue>(*condition).value()) {
  825. // { {true :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  826. // S, H}
  827. // -> { { then_stmt :: C, E, F } :: S, H}
  828. return todo_.Spawn(
  829. std::make_unique<StatementAction>(&cast<If>(stmt).then_block()));
  830. } else if (cast<If>(stmt).else_block()) {
  831. // { {false :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  832. // S, H}
  833. // -> { { else_stmt :: C, E, F } :: S, H}
  834. return todo_.Spawn(
  835. std::make_unique<StatementAction>(*cast<If>(stmt).else_block()));
  836. } else {
  837. return todo_.FinishAction();
  838. }
  839. } else {
  840. return todo_.FinishAction();
  841. }
  842. case StatementKind::Return:
  843. if (act.pos() == 0) {
  844. // { {return e :: C, E, F} :: S, H}
  845. // -> { {e :: return [] :: C, E, F} :: S, H}
  846. return todo_.Spawn(std::make_unique<ExpressionAction>(
  847. &cast<Return>(stmt).expression()));
  848. } else {
  849. // { {v :: return [] :: C, E, F} :: {C', E', F'} :: S, H}
  850. // -> { {v :: C', E', F'} :: S, H}
  851. const FunctionDeclaration& function = cast<Return>(stmt).function();
  852. return todo_.UnwindPast(
  853. *function.body(),
  854. Convert(act.results()[0], &function.return_term().static_type()));
  855. }
  856. case StatementKind::Continuation: {
  857. CHECK(act.pos() == 0);
  858. const auto& continuation = cast<Continuation>(stmt);
  859. // Create a continuation object by creating a frame similar the
  860. // way one is created in a function call.
  861. auto fragment = arena_->New<ContinuationValue::StackFragment>();
  862. stack_fragments_.push_back(fragment);
  863. todo_.InitializeFragment(*fragment, &continuation.body());
  864. // Bind the continuation object to the continuation variable
  865. todo_.Initialize(&cast<Continuation>(stmt),
  866. arena_->New<ContinuationValue>(fragment));
  867. return todo_.FinishAction();
  868. }
  869. case StatementKind::Run: {
  870. auto& run = cast<Run>(stmt);
  871. if (act.pos() == 0) {
  872. // Evaluate the argument of the run statement.
  873. return todo_.Spawn(std::make_unique<ExpressionAction>(&run.argument()));
  874. } else if (act.pos() == 1) {
  875. // Push the continuation onto the current stack.
  876. return todo_.Resume(cast<const ContinuationValue>(act.results()[0]));
  877. } else {
  878. return todo_.FinishAction();
  879. }
  880. }
  881. case StatementKind::Await:
  882. CHECK(act.pos() == 0);
  883. return todo_.Suspend();
  884. }
  885. }
  886. void Interpreter::StepDeclaration() {
  887. Action& act = todo_.CurrentAction();
  888. const Declaration& decl = cast<DeclarationAction>(act).declaration();
  889. if (trace_) {
  890. llvm::outs() << "--- step declaration (" << decl.source_loc() << ") --->\n";
  891. }
  892. switch (decl.kind()) {
  893. case DeclarationKind::VariableDeclaration: {
  894. const auto& var_decl = cast<VariableDeclaration>(decl);
  895. if (act.pos() == 0) {
  896. return todo_.Spawn(
  897. std::make_unique<ExpressionAction>(&var_decl.initializer()));
  898. } else {
  899. todo_.Initialize(&var_decl.binding(), act.results()[0]);
  900. return todo_.FinishAction();
  901. }
  902. }
  903. case DeclarationKind::FunctionDeclaration:
  904. case DeclarationKind::ClassDeclaration:
  905. case DeclarationKind::ChoiceDeclaration:
  906. // These declarations have no run-time effects.
  907. return todo_.FinishAction();
  908. }
  909. }
  910. // State transition.
  911. void Interpreter::Step() {
  912. Action& act = todo_.CurrentAction();
  913. switch (act.kind()) {
  914. case Action::Kind::LValAction:
  915. StepLvalue();
  916. break;
  917. case Action::Kind::ExpressionAction:
  918. StepExp();
  919. break;
  920. case Action::Kind::PatternAction:
  921. StepPattern();
  922. break;
  923. case Action::Kind::StatementAction:
  924. StepStmt();
  925. break;
  926. case Action::Kind::DeclarationAction:
  927. StepDeclaration();
  928. break;
  929. case Action::Kind::ScopeAction:
  930. FATAL() << "ScopeAction escaped ActionStack";
  931. } // switch
  932. }
  933. void Interpreter::RunAllSteps(std::unique_ptr<Action> action) {
  934. if (trace_) {
  935. PrintState(llvm::outs());
  936. }
  937. todo_.Start(std::move(action));
  938. while (!todo_.IsEmpty()) {
  939. Step();
  940. if (trace_) {
  941. PrintState(llvm::outs());
  942. }
  943. }
  944. }
  945. auto InterpProgram(const AST& ast, Nonnull<Arena*> arena, bool trace) -> int {
  946. Interpreter interpreter(Phase::RunTime, arena, trace);
  947. if (trace) {
  948. llvm::outs() << "********** initializing globals **********\n";
  949. }
  950. for (Nonnull<Declaration*> declaration : ast.declarations) {
  951. interpreter.RunAllSteps(std::make_unique<DeclarationAction>(declaration));
  952. }
  953. if (trace) {
  954. llvm::outs() << "********** calling main function **********\n";
  955. }
  956. interpreter.RunAllSteps(std::make_unique<ExpressionAction>(*ast.main_call));
  957. return cast<IntValue>(*interpreter.result()).value();
  958. }
  959. auto InterpExp(Nonnull<const Expression*> e, Nonnull<Arena*> arena, bool trace)
  960. -> Nonnull<const Value*> {
  961. Interpreter interpreter(Phase::CompileTime, arena, trace);
  962. interpreter.RunAllSteps(std::make_unique<ExpressionAction>(e));
  963. return interpreter.result();
  964. }
  965. auto InterpPattern(Nonnull<const Pattern*> p, Nonnull<Arena*> arena, bool trace)
  966. -> Nonnull<const Value*> {
  967. Interpreter interpreter(Phase::CompileTime, arena, trace);
  968. interpreter.RunAllSteps(std::make_unique<PatternAction>(p));
  969. return interpreter.result();
  970. }
  971. } // namespace Carbon