value.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  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/value.h"
  5. #include <algorithm>
  6. #include "common/check.h"
  7. #include "executable_semantics/common/arena.h"
  8. #include "executable_semantics/common/error.h"
  9. #include "executable_semantics/interpreter/action.h"
  10. #include "llvm/ADT/StringExtras.h"
  11. #include "llvm/Support/Casting.h"
  12. namespace Carbon {
  13. using llvm::cast;
  14. auto StructValue::FindField(const std::string& name) const
  15. -> std::optional<Nonnull<const Value*>> {
  16. for (const NamedValue& element : elements_) {
  17. if (element.name == name) {
  18. return element.value;
  19. }
  20. }
  21. return std::nullopt;
  22. }
  23. static auto GetMember(Nonnull<Arena*> arena, Nonnull<const Value*> v,
  24. const std::string& f, SourceLocation source_loc)
  25. -> Nonnull<const Value*> {
  26. switch (v->kind()) {
  27. case Value::Kind::StructValue: {
  28. std::optional<Nonnull<const Value*>> field =
  29. cast<StructValue>(*v).FindField(f);
  30. if (field == std::nullopt) {
  31. FATAL_RUNTIME_ERROR(source_loc) << "member " << f << " not in " << *v;
  32. }
  33. return *field;
  34. }
  35. case Value::Kind::NominalClassValue: {
  36. const NominalClassValue& object = cast<NominalClassValue>(*v);
  37. // Look for a field
  38. std::optional<Nonnull<const Value*>> field =
  39. cast<StructValue>(object.inits()).FindField(f);
  40. if (field == std::nullopt) {
  41. // Look for a method in the object's class
  42. const NominalClassType& class_type =
  43. cast<NominalClassType>(object.type());
  44. std::optional<Nonnull<const FunctionValue*>> func =
  45. class_type.FindFunction(f);
  46. if (func == std::nullopt) {
  47. FATAL_RUNTIME_ERROR(source_loc) << "member " << f << " not in " << *v
  48. << " or its class " << class_type;
  49. } else if ((*func)->declaration().is_method()) {
  50. // Found a method. Turn it into a bound method.
  51. const FunctionValue& m = cast<FunctionValue>(**func);
  52. return arena->New<BoundMethodValue>(&m.declaration(), &object);
  53. } else {
  54. // Found a class function
  55. return *func;
  56. }
  57. }
  58. return *field;
  59. }
  60. case Value::Kind::ChoiceType: {
  61. const auto& choice = cast<ChoiceType>(*v);
  62. if (!choice.FindAlternative(f)) {
  63. FATAL_RUNTIME_ERROR(source_loc)
  64. << "alternative " << f << " not in " << *v;
  65. }
  66. return arena->New<AlternativeConstructorValue>(f, choice.name());
  67. }
  68. case Value::Kind::NominalClassType: {
  69. const NominalClassType& class_type = cast<NominalClassType>(*v);
  70. std::optional<Nonnull<const FunctionValue*>> fun =
  71. class_type.FindFunction(f);
  72. if (fun == std::nullopt) {
  73. FATAL_RUNTIME_ERROR(source_loc)
  74. << "class function " << f << " not in " << *v;
  75. }
  76. return *fun;
  77. }
  78. default:
  79. FATAL() << "field access not allowed for value " << *v;
  80. }
  81. }
  82. auto Value::GetField(Nonnull<Arena*> arena, const FieldPath& path,
  83. SourceLocation source_loc) const -> Nonnull<const Value*> {
  84. Nonnull<const Value*> value(this);
  85. for (const std::string& field : path.components_) {
  86. value = GetMember(arena, value, field, source_loc);
  87. }
  88. return value;
  89. }
  90. static auto SetFieldImpl(Nonnull<Arena*> arena, Nonnull<const Value*> value,
  91. std::vector<std::string>::const_iterator path_begin,
  92. std::vector<std::string>::const_iterator path_end,
  93. Nonnull<const Value*> field_value,
  94. SourceLocation source_loc) -> Nonnull<const Value*> {
  95. if (path_begin == path_end) {
  96. return field_value;
  97. }
  98. switch (value->kind()) {
  99. case Value::Kind::StructValue: {
  100. std::vector<NamedValue> elements = cast<StructValue>(*value).elements();
  101. auto it = std::find_if(elements.begin(), elements.end(),
  102. [path_begin](const NamedValue& element) {
  103. return element.name == *path_begin;
  104. });
  105. if (it == elements.end()) {
  106. FATAL_RUNTIME_ERROR(source_loc)
  107. << "field " << *path_begin << " not in " << *value;
  108. }
  109. it->value = SetFieldImpl(arena, it->value, path_begin + 1, path_end,
  110. field_value, source_loc);
  111. return arena->New<StructValue>(elements);
  112. }
  113. case Value::Kind::NominalClassValue: {
  114. return SetFieldImpl(arena, &cast<NominalClassValue>(*value).inits(),
  115. path_begin, path_end, field_value, source_loc);
  116. }
  117. case Value::Kind::TupleValue: {
  118. std::vector<Nonnull<const Value*>> elements =
  119. cast<TupleValue>(*value).elements();
  120. // TODO(geoffromer): update FieldPath to hold integers as well as strings.
  121. int index = std::stoi(*path_begin);
  122. if (index < 0 || static_cast<size_t>(index) >= elements.size()) {
  123. FATAL_RUNTIME_ERROR(source_loc)
  124. << "index " << *path_begin << " out of range in " << *value;
  125. }
  126. elements[index] = SetFieldImpl(arena, elements[index], path_begin + 1,
  127. path_end, field_value, source_loc);
  128. return arena->New<TupleValue>(elements);
  129. }
  130. default:
  131. FATAL() << "field access not allowed for value " << *value;
  132. }
  133. }
  134. auto Value::SetField(Nonnull<Arena*> arena, const FieldPath& path,
  135. Nonnull<const Value*> field_value,
  136. SourceLocation source_loc) const -> Nonnull<const Value*> {
  137. return SetFieldImpl(arena, Nonnull<const Value*>(this),
  138. path.components_.begin(), path.components_.end(),
  139. field_value, source_loc);
  140. }
  141. void Value::Print(llvm::raw_ostream& out) const {
  142. switch (kind()) {
  143. case Value::Kind::AlternativeConstructorValue: {
  144. const auto& alt = cast<AlternativeConstructorValue>(*this);
  145. out << alt.choice_name() << "." << alt.alt_name();
  146. break;
  147. }
  148. case Value::Kind::BindingPlaceholderValue: {
  149. const auto& placeholder = cast<BindingPlaceholderValue>(*this);
  150. out << "Placeholder<";
  151. if (placeholder.named_entity().has_value()) {
  152. out << (*placeholder.named_entity()).name();
  153. } else {
  154. out << "_";
  155. }
  156. out << ">";
  157. break;
  158. }
  159. case Value::Kind::AlternativeValue: {
  160. const auto& alt = cast<AlternativeValue>(*this);
  161. out << "alt " << alt.choice_name() << "." << alt.alt_name() << " "
  162. << alt.argument();
  163. break;
  164. }
  165. case Value::Kind::StructValue: {
  166. const auto& struct_val = cast<StructValue>(*this);
  167. out << "{";
  168. llvm::ListSeparator sep;
  169. for (const NamedValue& element : struct_val.elements()) {
  170. out << sep << "." << element.name << " = " << *element.value;
  171. }
  172. out << "}";
  173. break;
  174. }
  175. case Value::Kind::NominalClassValue: {
  176. const auto& s = cast<NominalClassValue>(*this);
  177. out << cast<NominalClassType>(s.type()).declaration().name() << s.inits();
  178. break;
  179. }
  180. case Value::Kind::TupleValue: {
  181. out << "(";
  182. llvm::ListSeparator sep;
  183. for (Nonnull<const Value*> element : cast<TupleValue>(*this).elements()) {
  184. out << sep << *element;
  185. }
  186. out << ")";
  187. break;
  188. }
  189. case Value::Kind::IntValue:
  190. out << cast<IntValue>(*this).value();
  191. break;
  192. case Value::Kind::BoolValue:
  193. out << (cast<BoolValue>(*this).value() ? "true" : "false");
  194. break;
  195. case Value::Kind::FunctionValue:
  196. out << "fun<" << cast<FunctionValue>(*this).declaration().name() << ">";
  197. break;
  198. case Value::Kind::BoundMethodValue:
  199. out << "bound_method<"
  200. << cast<BoundMethodValue>(*this).declaration().name() << ">";
  201. break;
  202. case Value::Kind::PointerValue:
  203. out << "ptr<" << cast<PointerValue>(*this).address() << ">";
  204. break;
  205. case Value::Kind::LValue:
  206. out << "lval<" << cast<LValue>(*this).address() << ">";
  207. break;
  208. case Value::Kind::BoolType:
  209. out << "Bool";
  210. break;
  211. case Value::Kind::IntType:
  212. out << "i32";
  213. break;
  214. case Value::Kind::TypeType:
  215. out << "Type";
  216. break;
  217. case Value::Kind::AutoType:
  218. out << "auto";
  219. break;
  220. case Value::Kind::ContinuationType:
  221. out << "Continuation";
  222. break;
  223. case Value::Kind::PointerType:
  224. out << cast<PointerType>(*this).type() << "*";
  225. break;
  226. case Value::Kind::FunctionType: {
  227. const auto& fn_type = cast<FunctionType>(*this);
  228. out << "fn ";
  229. if (fn_type.deduced().size() > 0) {
  230. out << "[";
  231. unsigned int i = 0;
  232. for (Nonnull<const GenericBinding*> deduced : fn_type.deduced()) {
  233. if (i != 0) {
  234. out << ", ";
  235. }
  236. out << deduced->name() << ":! " << deduced->type();
  237. ++i;
  238. }
  239. out << "]";
  240. }
  241. out << fn_type.parameters() << " -> " << fn_type.return_type();
  242. break;
  243. }
  244. case Value::Kind::StructType: {
  245. out << "{";
  246. llvm::ListSeparator sep;
  247. for (const auto& [name, type] : cast<StructType>(*this).fields()) {
  248. out << sep << "." << name << ": " << *type;
  249. }
  250. out << "}";
  251. break;
  252. }
  253. case Value::Kind::NominalClassType: {
  254. const NominalClassType& class_type = cast<NominalClassType>(*this);
  255. out << "class " << class_type.declaration().name();
  256. break;
  257. }
  258. case Value::Kind::ChoiceType:
  259. out << "choice " << cast<ChoiceType>(*this).name();
  260. break;
  261. case Value::Kind::VariableType:
  262. out << cast<VariableType>(*this).binding().name();
  263. break;
  264. case Value::Kind::ContinuationValue: {
  265. out << cast<ContinuationValue>(*this).stack();
  266. break;
  267. }
  268. case Value::Kind::StringType:
  269. out << "String";
  270. break;
  271. case Value::Kind::StringValue:
  272. out << "\"";
  273. out.write_escaped(cast<StringValue>(*this).value());
  274. out << "\"";
  275. break;
  276. case Value::Kind::TypeOfClassType:
  277. out << "typeof("
  278. << cast<TypeOfClassType>(*this).class_type().declaration().name()
  279. << ")";
  280. break;
  281. case Value::Kind::TypeOfChoiceType:
  282. out << "typeof(" << cast<TypeOfChoiceType>(*this).choice_type().name()
  283. << ")";
  284. break;
  285. }
  286. }
  287. ContinuationValue::StackFragment::~StackFragment() {
  288. CHECK(reversed_todo_.empty())
  289. << "All StackFragments must be empty before the Carbon program ends.";
  290. }
  291. void ContinuationValue::StackFragment::StoreReversed(
  292. std::vector<std::unique_ptr<Action>> reversed_todo) {
  293. CHECK(reversed_todo_.empty());
  294. reversed_todo_ = std::move(reversed_todo);
  295. }
  296. void ContinuationValue::StackFragment::RestoreTo(
  297. Stack<std::unique_ptr<Action>>& todo) {
  298. while (!reversed_todo_.empty()) {
  299. todo.Push(std::move(reversed_todo_.back()));
  300. reversed_todo_.pop_back();
  301. }
  302. }
  303. void ContinuationValue::StackFragment::Clear() {
  304. // We destroy the underlying Actions explicitly to ensure they're
  305. // destroyed in the correct order.
  306. for (auto& action : reversed_todo_) {
  307. action.reset();
  308. }
  309. reversed_todo_.clear();
  310. }
  311. void ContinuationValue::StackFragment::Print(llvm::raw_ostream& out) const {
  312. out << "{";
  313. llvm::ListSeparator sep(" :: ");
  314. for (const std::unique_ptr<Action>& action : reversed_todo_) {
  315. out << sep << *action;
  316. }
  317. out << "}";
  318. }
  319. auto TypeEqual(Nonnull<const Value*> t1, Nonnull<const Value*> t2) -> bool {
  320. if (t1->kind() != t2->kind()) {
  321. return false;
  322. }
  323. switch (t1->kind()) {
  324. case Value::Kind::PointerType:
  325. return TypeEqual(&cast<PointerType>(*t1).type(),
  326. &cast<PointerType>(*t2).type());
  327. case Value::Kind::FunctionType: {
  328. const auto& fn1 = cast<FunctionType>(*t1);
  329. const auto& fn2 = cast<FunctionType>(*t2);
  330. return TypeEqual(&fn1.parameters(), &fn2.parameters()) &&
  331. TypeEqual(&fn1.return_type(), &fn2.return_type());
  332. }
  333. case Value::Kind::StructType: {
  334. const auto& struct1 = cast<StructType>(*t1);
  335. const auto& struct2 = cast<StructType>(*t2);
  336. if (struct1.fields().size() != struct2.fields().size()) {
  337. return false;
  338. }
  339. for (size_t i = 0; i < struct1.fields().size(); ++i) {
  340. if (struct1.fields()[i].name != struct2.fields()[i].name ||
  341. !TypeEqual(struct1.fields()[i].value, struct2.fields()[i].value)) {
  342. return false;
  343. }
  344. }
  345. return true;
  346. }
  347. case Value::Kind::NominalClassType:
  348. return cast<NominalClassType>(*t1).declaration().name() ==
  349. cast<NominalClassType>(*t2).declaration().name();
  350. case Value::Kind::ChoiceType:
  351. return cast<ChoiceType>(*t1).name() == cast<ChoiceType>(*t2).name();
  352. case Value::Kind::TupleValue: {
  353. const auto& tup1 = cast<TupleValue>(*t1);
  354. const auto& tup2 = cast<TupleValue>(*t2);
  355. if (tup1.elements().size() != tup2.elements().size()) {
  356. return false;
  357. }
  358. for (size_t i = 0; i < tup1.elements().size(); ++i) {
  359. if (!TypeEqual(tup1.elements()[i], tup2.elements()[i])) {
  360. return false;
  361. }
  362. }
  363. return true;
  364. }
  365. case Value::Kind::IntType:
  366. case Value::Kind::BoolType:
  367. case Value::Kind::ContinuationType:
  368. case Value::Kind::TypeType:
  369. case Value::Kind::StringType:
  370. return true;
  371. case Value::Kind::VariableType:
  372. return &cast<VariableType>(*t1).binding() ==
  373. &cast<VariableType>(*t2).binding();
  374. case Value::Kind::TypeOfClassType:
  375. return TypeEqual(&cast<TypeOfClassType>(*t1).class_type(),
  376. &cast<TypeOfClassType>(*t2).class_type());
  377. case Value::Kind::TypeOfChoiceType:
  378. return TypeEqual(&cast<TypeOfChoiceType>(*t1).choice_type(),
  379. &cast<TypeOfChoiceType>(*t2).choice_type());
  380. default:
  381. FATAL() << "TypeEqual used to compare non-type values\n"
  382. << *t1 << "\n"
  383. << *t2;
  384. }
  385. }
  386. // Returns true if the two values are equal and returns false otherwise.
  387. //
  388. // This function implements the `==` operator of Carbon.
  389. auto ValueEqual(Nonnull<const Value*> v1, Nonnull<const Value*> v2) -> bool {
  390. if (v1->kind() != v2->kind()) {
  391. return false;
  392. }
  393. switch (v1->kind()) {
  394. case Value::Kind::IntValue:
  395. return cast<IntValue>(*v1).value() == cast<IntValue>(*v2).value();
  396. case Value::Kind::BoolValue:
  397. return cast<BoolValue>(*v1).value() == cast<BoolValue>(*v2).value();
  398. case Value::Kind::FunctionValue: {
  399. std::optional<Nonnull<const Statement*>> body1 =
  400. cast<FunctionValue>(*v1).declaration().body();
  401. std::optional<Nonnull<const Statement*>> body2 =
  402. cast<FunctionValue>(*v2).declaration().body();
  403. return body1.has_value() == body2.has_value() &&
  404. (!body1.has_value() || *body1 == *body2);
  405. }
  406. case Value::Kind::BoundMethodValue: {
  407. const BoundMethodValue& m1 = cast<BoundMethodValue>(*v1);
  408. const BoundMethodValue& m2 = cast<BoundMethodValue>(*v2);
  409. std::optional<Nonnull<const Statement*>> body1 = m1.declaration().body();
  410. std::optional<Nonnull<const Statement*>> body2 = m2.declaration().body();
  411. return ValueEqual(m1.receiver(), m2.receiver()) &&
  412. body1.has_value() == body2.has_value() &&
  413. (!body1.has_value() || *body1 == *body2);
  414. }
  415. case Value::Kind::TupleValue: {
  416. const std::vector<Nonnull<const Value*>>& elements1 =
  417. cast<TupleValue>(*v1).elements();
  418. const std::vector<Nonnull<const Value*>>& elements2 =
  419. cast<TupleValue>(*v2).elements();
  420. if (elements1.size() != elements2.size()) {
  421. return false;
  422. }
  423. for (size_t i = 0; i < elements1.size(); ++i) {
  424. if (!ValueEqual(elements1[i], elements2[i])) {
  425. return false;
  426. }
  427. }
  428. return true;
  429. }
  430. case Value::Kind::StructValue: {
  431. const auto& struct_v1 = cast<StructValue>(*v1);
  432. const auto& struct_v2 = cast<StructValue>(*v2);
  433. CHECK(struct_v1.elements().size() == struct_v2.elements().size());
  434. for (size_t i = 0; i < struct_v1.elements().size(); ++i) {
  435. CHECK(struct_v1.elements()[i].name == struct_v2.elements()[i].name);
  436. if (!ValueEqual(struct_v1.elements()[i].value,
  437. struct_v2.elements()[i].value)) {
  438. return false;
  439. }
  440. }
  441. return true;
  442. }
  443. case Value::Kind::StringValue:
  444. return cast<StringValue>(*v1).value() == cast<StringValue>(*v2).value();
  445. case Value::Kind::IntType:
  446. case Value::Kind::BoolType:
  447. case Value::Kind::TypeType:
  448. case Value::Kind::FunctionType:
  449. case Value::Kind::PointerType:
  450. case Value::Kind::AutoType:
  451. case Value::Kind::StructType:
  452. case Value::Kind::NominalClassType:
  453. case Value::Kind::ChoiceType:
  454. case Value::Kind::ContinuationType:
  455. case Value::Kind::VariableType:
  456. case Value::Kind::StringType:
  457. case Value::Kind::TypeOfClassType:
  458. case Value::Kind::TypeOfChoiceType:
  459. return TypeEqual(v1, v2);
  460. case Value::Kind::NominalClassValue:
  461. case Value::Kind::AlternativeValue:
  462. case Value::Kind::BindingPlaceholderValue:
  463. case Value::Kind::AlternativeConstructorValue:
  464. case Value::Kind::ContinuationValue:
  465. case Value::Kind::PointerValue:
  466. case Value::Kind::LValue:
  467. // TODO: support pointer comparisons once we have a clearer distinction
  468. // between pointers and lvalues.
  469. FATAL() << "ValueEqual does not support this kind of value: " << *v1;
  470. }
  471. }
  472. auto ChoiceType::FindAlternative(std::string_view name) const
  473. -> std::optional<Nonnull<const Value*>> {
  474. for (const NamedValue& alternative : alternatives_) {
  475. if (alternative.name == name) {
  476. return alternative.value;
  477. }
  478. }
  479. return std::nullopt;
  480. }
  481. auto NominalClassType::FindFunction(const std::string& name) const
  482. -> std::optional<Nonnull<const FunctionValue*>> {
  483. for (const auto& member : declaration().members()) {
  484. switch (member->kind()) {
  485. case DeclarationKind::FunctionDeclaration: {
  486. const auto& fun = cast<FunctionDeclaration>(*member);
  487. if (fun.name() == name) {
  488. return &cast<FunctionValue>(**fun.constant_value());
  489. }
  490. break;
  491. }
  492. default:
  493. break;
  494. }
  495. }
  496. return std::nullopt;
  497. }
  498. auto FieldTypes(const NominalClassType& class_type) -> std::vector<NamedValue> {
  499. std::vector<NamedValue> field_types;
  500. for (Nonnull<Declaration*> m : class_type.declaration().members()) {
  501. switch (m->kind()) {
  502. case DeclarationKind::VariableDeclaration: {
  503. const auto& var = cast<VariableDeclaration>(*m);
  504. field_types.push_back({.name = var.binding().name(),
  505. .value = &var.binding().static_type()});
  506. break;
  507. }
  508. default:
  509. break;
  510. }
  511. }
  512. return field_types;
  513. }
  514. auto NominalClassType::FindMember(const std::string& name) const
  515. -> std::optional<Nonnull<const Declaration*>> {
  516. for (const auto& member : declaration().members()) {
  517. switch (member->kind()) {
  518. case DeclarationKind::FunctionDeclaration: {
  519. const auto& fun = cast<FunctionDeclaration>(*member);
  520. if (fun.name() == name) {
  521. return &fun;
  522. }
  523. break;
  524. }
  525. case DeclarationKind::VariableDeclaration: {
  526. const auto& var = cast<VariableDeclaration>(*member);
  527. if (var.binding().name() == name) {
  528. return &var;
  529. }
  530. break;
  531. }
  532. default:
  533. break;
  534. }
  535. }
  536. return std::nullopt;
  537. }
  538. } // namespace Carbon