interpreter.cpp 38 KB

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