interpreter.cpp 39 KB

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