interpreter.cpp 38 KB

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