interpreter.cpp 39 KB

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