interpreter.cpp 41 KB

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