interpreter.cpp 39 KB

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