interpreter.cpp 35 KB

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