interpreter.cpp 39 KB

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