value.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759
  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 "explorer/interpreter/value.h"
  5. #include <algorithm>
  6. #include "common/check.h"
  7. #include "explorer/common/arena.h"
  8. #include "explorer/common/error_builders.h"
  9. #include "explorer/interpreter/action.h"
  10. #include "llvm/ADT/StringExtras.h"
  11. #include "llvm/Support/Casting.h"
  12. #include "llvm/Support/Error.h"
  13. namespace Carbon {
  14. using llvm::cast;
  15. using llvm::dyn_cast;
  16. auto StructValue::FindField(const std::string& name) const
  17. -> std::optional<Nonnull<const Value*>> {
  18. for (const NamedValue& element : elements_) {
  19. if (element.name == name) {
  20. return element.value;
  21. }
  22. }
  23. return std::nullopt;
  24. }
  25. static auto GetMember(Nonnull<Arena*> arena, Nonnull<const Value*> v,
  26. const FieldPath::Component& field,
  27. SourceLocation source_loc)
  28. -> ErrorOr<Nonnull<const Value*>> {
  29. const std::string& f = field.name();
  30. if (field.witness().has_value()) {
  31. Nonnull<const Witness*> witness = *field.witness();
  32. switch (witness->kind()) {
  33. case Value::Kind::Witness: {
  34. if (std::optional<Nonnull<const Declaration*>> mem_decl =
  35. FindMember(f, witness->declaration().members());
  36. mem_decl.has_value()) {
  37. const auto& fun_decl = cast<FunctionDeclaration>(**mem_decl);
  38. if (fun_decl.is_method()) {
  39. return arena->New<BoundMethodValue>(
  40. &fun_decl, v, witness->type_args(), witness->witnesses());
  41. } else {
  42. // Class function.
  43. auto fun = cast<FunctionValue>(*fun_decl.constant_value());
  44. return arena->New<FunctionValue>(&fun->declaration(),
  45. witness->type_args(),
  46. witness->witnesses());
  47. }
  48. } else {
  49. return CompilationError(source_loc)
  50. << "member " << f << " not in " << *witness;
  51. }
  52. }
  53. default:
  54. CARBON_FATAL() << "expected Witness, not " << *witness;
  55. }
  56. }
  57. switch (v->kind()) {
  58. case Value::Kind::StructValue: {
  59. std::optional<Nonnull<const Value*>> field =
  60. cast<StructValue>(*v).FindField(f);
  61. if (field == std::nullopt) {
  62. return RuntimeError(source_loc) << "member " << f << " not in " << *v;
  63. }
  64. return *field;
  65. }
  66. case Value::Kind::NominalClassValue: {
  67. const auto& object = cast<NominalClassValue>(*v);
  68. // Look for a field.
  69. // Note that the value representation of an empty class is a
  70. // `StructType`, not a `StructValue`.
  71. std::optional<Nonnull<const Value*>> field;
  72. if (auto* struct_value = dyn_cast<StructValue>(&object.inits())) {
  73. field = struct_value->FindField(f);
  74. }
  75. if (field.has_value()) {
  76. return *field;
  77. } else {
  78. // Look for a method in the object's class
  79. const auto& class_type = cast<NominalClassType>(object.type());
  80. std::optional<Nonnull<const FunctionValue*>> func =
  81. class_type.FindFunction(f);
  82. if (func == std::nullopt) {
  83. return RuntimeError(source_loc) << "member " << f << " not in " << *v
  84. << " or its " << class_type;
  85. } else if ((*func)->declaration().is_method()) {
  86. // Found a method. Turn it into a bound method.
  87. const FunctionValue& m = cast<FunctionValue>(**func);
  88. return arena->New<BoundMethodValue>(&m.declaration(), &object,
  89. class_type.type_args(),
  90. class_type.witnesses());
  91. } else {
  92. // Found a class function
  93. return arena->New<FunctionValue>(&(*func)->declaration(),
  94. class_type.type_args(),
  95. class_type.witnesses());
  96. }
  97. }
  98. }
  99. case Value::Kind::ChoiceType: {
  100. const auto& choice = cast<ChoiceType>(*v);
  101. if (!choice.FindAlternative(f)) {
  102. return RuntimeError(source_loc)
  103. << "alternative " << f << " not in " << *v;
  104. }
  105. return arena->New<AlternativeConstructorValue>(f, choice.name());
  106. }
  107. case Value::Kind::NominalClassType: {
  108. // Access a class function.
  109. const NominalClassType& class_type = cast<NominalClassType>(*v);
  110. std::optional<Nonnull<const FunctionValue*>> fun =
  111. class_type.FindFunction(f);
  112. if (fun == std::nullopt) {
  113. return RuntimeError(source_loc)
  114. << "class function " << f << " not in " << *v;
  115. }
  116. return arena->New<FunctionValue>(&(*fun)->declaration(),
  117. class_type.type_args(),
  118. class_type.witnesses());
  119. }
  120. default:
  121. CARBON_FATAL() << "field access not allowed for value " << *v;
  122. }
  123. }
  124. auto Value::GetField(Nonnull<Arena*> arena, const FieldPath& path,
  125. SourceLocation source_loc) const
  126. -> ErrorOr<Nonnull<const Value*>> {
  127. Nonnull<const Value*> value(this);
  128. for (const FieldPath::Component& field : path.components_) {
  129. CARBON_ASSIGN_OR_RETURN(value, GetMember(arena, value, field, source_loc));
  130. }
  131. return value;
  132. }
  133. static auto SetFieldImpl(
  134. Nonnull<Arena*> arena, Nonnull<const Value*> value,
  135. std::vector<FieldPath::Component>::const_iterator path_begin,
  136. std::vector<FieldPath::Component>::const_iterator path_end,
  137. Nonnull<const Value*> field_value, SourceLocation source_loc)
  138. -> ErrorOr<Nonnull<const Value*>> {
  139. if (path_begin == path_end) {
  140. return field_value;
  141. }
  142. switch (value->kind()) {
  143. case Value::Kind::StructValue: {
  144. std::vector<NamedValue> elements = cast<StructValue>(*value).elements();
  145. auto it = std::find_if(elements.begin(), elements.end(),
  146. [path_begin](const NamedValue& element) {
  147. return element.name == (*path_begin).name();
  148. });
  149. if (it == elements.end()) {
  150. return RuntimeError(source_loc)
  151. << "field " << (*path_begin).name() << " not in " << *value;
  152. }
  153. CARBON_ASSIGN_OR_RETURN(
  154. it->value, SetFieldImpl(arena, it->value, path_begin + 1, path_end,
  155. field_value, source_loc));
  156. return arena->New<StructValue>(elements);
  157. }
  158. case Value::Kind::NominalClassValue: {
  159. return SetFieldImpl(arena, &cast<NominalClassValue>(*value).inits(),
  160. path_begin, path_end, field_value, source_loc);
  161. }
  162. case Value::Kind::TupleValue: {
  163. std::vector<Nonnull<const Value*>> elements =
  164. cast<TupleValue>(*value).elements();
  165. // TODO(geoffromer): update FieldPath to hold integers as well as strings.
  166. int index = std::stoi((*path_begin).name());
  167. if (index < 0 || static_cast<size_t>(index) >= elements.size()) {
  168. return RuntimeError(source_loc) << "index " << (*path_begin).name()
  169. << " out of range in " << *value;
  170. }
  171. CARBON_ASSIGN_OR_RETURN(
  172. elements[index], SetFieldImpl(arena, elements[index], path_begin + 1,
  173. path_end, field_value, source_loc));
  174. return arena->New<TupleValue>(elements);
  175. }
  176. default:
  177. CARBON_FATAL() << "field access not allowed for value " << *value;
  178. }
  179. }
  180. auto Value::SetField(Nonnull<Arena*> arena, const FieldPath& path,
  181. Nonnull<const Value*> field_value,
  182. SourceLocation source_loc) const
  183. -> ErrorOr<Nonnull<const Value*>> {
  184. return SetFieldImpl(arena, Nonnull<const Value*>(this),
  185. path.components_.begin(), path.components_.end(),
  186. field_value, source_loc);
  187. }
  188. void Value::Print(llvm::raw_ostream& out) const {
  189. switch (kind()) {
  190. case Value::Kind::AlternativeConstructorValue: {
  191. const auto& alt = cast<AlternativeConstructorValue>(*this);
  192. out << alt.choice_name() << "." << alt.alt_name();
  193. break;
  194. }
  195. case Value::Kind::BindingPlaceholderValue: {
  196. const auto& placeholder = cast<BindingPlaceholderValue>(*this);
  197. out << "Placeholder<";
  198. if (placeholder.value_node().has_value()) {
  199. out << (*placeholder.value_node());
  200. } else {
  201. out << "_";
  202. }
  203. out << ">";
  204. break;
  205. }
  206. case Value::Kind::AlternativeValue: {
  207. const auto& alt = cast<AlternativeValue>(*this);
  208. out << "alt " << alt.choice_name() << "." << alt.alt_name() << " "
  209. << alt.argument();
  210. break;
  211. }
  212. case Value::Kind::StructValue: {
  213. const auto& struct_val = cast<StructValue>(*this);
  214. out << "{";
  215. llvm::ListSeparator sep;
  216. for (const NamedValue& element : struct_val.elements()) {
  217. out << sep << "." << element.name << " = " << *element.value;
  218. }
  219. out << "}";
  220. break;
  221. }
  222. case Value::Kind::NominalClassValue: {
  223. const auto& s = cast<NominalClassValue>(*this);
  224. out << cast<NominalClassType>(s.type()).declaration().name() << s.inits();
  225. break;
  226. }
  227. case Value::Kind::TupleValue: {
  228. out << "(";
  229. llvm::ListSeparator sep;
  230. for (Nonnull<const Value*> element : cast<TupleValue>(*this).elements()) {
  231. out << sep << *element;
  232. }
  233. out << ")";
  234. break;
  235. }
  236. case Value::Kind::IntValue:
  237. out << cast<IntValue>(*this).value();
  238. break;
  239. case Value::Kind::BoolValue:
  240. out << (cast<BoolValue>(*this).value() ? "true" : "false");
  241. break;
  242. case Value::Kind::FunctionValue:
  243. out << "fun<" << cast<FunctionValue>(*this).declaration().name() << ">";
  244. break;
  245. case Value::Kind::BoundMethodValue:
  246. out << "bound_method<"
  247. << cast<BoundMethodValue>(*this).declaration().name() << ">";
  248. break;
  249. case Value::Kind::PointerValue:
  250. out << "ptr<" << cast<PointerValue>(*this).address() << ">";
  251. break;
  252. case Value::Kind::LValue:
  253. out << "lval<" << cast<LValue>(*this).address() << ">";
  254. break;
  255. case Value::Kind::BoolType:
  256. out << "Bool";
  257. break;
  258. case Value::Kind::IntType:
  259. out << "i32";
  260. break;
  261. case Value::Kind::TypeType:
  262. out << "Type";
  263. break;
  264. case Value::Kind::AutoType:
  265. out << "auto";
  266. break;
  267. case Value::Kind::ContinuationType:
  268. out << "Continuation";
  269. break;
  270. case Value::Kind::PointerType:
  271. out << cast<PointerType>(*this).type() << "*";
  272. break;
  273. case Value::Kind::FunctionType: {
  274. const auto& fn_type = cast<FunctionType>(*this);
  275. out << "fn ";
  276. if (!fn_type.deduced_bindings().empty()) {
  277. out << "[";
  278. unsigned int i = 0;
  279. for (Nonnull<const GenericBinding*> deduced :
  280. fn_type.deduced_bindings()) {
  281. if (i != 0) {
  282. out << ", ";
  283. }
  284. out << deduced->name() << ":! " << deduced->type();
  285. ++i;
  286. }
  287. out << "]";
  288. }
  289. out << fn_type.parameters() << " -> " << fn_type.return_type();
  290. break;
  291. }
  292. case Value::Kind::StructType: {
  293. out << "{";
  294. llvm::ListSeparator sep;
  295. for (const auto& [name, type] : cast<StructType>(*this).fields()) {
  296. out << sep << "." << name << ": " << *type;
  297. }
  298. out << "}";
  299. break;
  300. }
  301. case Value::Kind::NominalClassType: {
  302. const auto& class_type = cast<NominalClassType>(*this);
  303. out << "class " << class_type.declaration().name();
  304. if (!class_type.type_args().empty()) {
  305. out << "(";
  306. llvm::ListSeparator sep;
  307. for (const auto& [bind, val] : class_type.type_args()) {
  308. out << sep << bind->name() << " = " << *val;
  309. }
  310. out << ")";
  311. }
  312. if (!class_type.impls().empty()) {
  313. out << " impls ";
  314. llvm::ListSeparator sep;
  315. for (const auto& [impl_bind, impl] : class_type.impls()) {
  316. out << sep << *impl;
  317. }
  318. }
  319. if (!class_type.witnesses().empty()) {
  320. out << " witnesses ";
  321. llvm::ListSeparator sep;
  322. for (const auto& [impl_bind, witness] : class_type.witnesses()) {
  323. out << sep << *witness;
  324. }
  325. }
  326. break;
  327. }
  328. case Value::Kind::InterfaceType: {
  329. const auto& iface_type = cast<InterfaceType>(*this);
  330. out << "interface " << iface_type.declaration().name();
  331. if (!iface_type.args().empty()) {
  332. out << "(";
  333. llvm::ListSeparator sep;
  334. for (const auto& [bind, val] : iface_type.args()) {
  335. out << sep << bind->name() << " = " << *val;
  336. }
  337. out << ")";
  338. }
  339. break;
  340. }
  341. case Value::Kind::Witness: {
  342. const auto& witness = cast<Witness>(*this);
  343. out << "witness " << *witness.declaration().impl_type() << " as "
  344. << witness.declaration().interface();
  345. break;
  346. }
  347. case Value::Kind::ParameterizedEntityName:
  348. out << *GetName(cast<ParameterizedEntityName>(*this).declaration());
  349. break;
  350. case Value::Kind::MemberName: {
  351. const auto& member_name = cast<MemberName>(*this);
  352. if (member_name.base_type().has_value()) {
  353. out << *member_name.base_type().value();
  354. }
  355. if (member_name.base_type().has_value() &&
  356. member_name.interface().has_value()) {
  357. out << "(";
  358. }
  359. if (member_name.interface().has_value()) {
  360. out << *member_name.interface().value();
  361. }
  362. out << "." << member_name.name();
  363. if (member_name.base_type().has_value() &&
  364. member_name.interface().has_value()) {
  365. out << ")";
  366. }
  367. break;
  368. }
  369. case Value::Kind::ChoiceType:
  370. out << "choice " << cast<ChoiceType>(*this).name();
  371. break;
  372. case Value::Kind::VariableType:
  373. out << cast<VariableType>(*this).binding();
  374. break;
  375. case Value::Kind::ContinuationValue: {
  376. out << cast<ContinuationValue>(*this).stack();
  377. break;
  378. }
  379. case Value::Kind::StringType:
  380. out << "String";
  381. break;
  382. case Value::Kind::StringValue:
  383. out << "\"";
  384. out.write_escaped(cast<StringValue>(*this).value());
  385. out << "\"";
  386. break;
  387. case Value::Kind::TypeOfClassType:
  388. out << "typeof(" << cast<TypeOfClassType>(*this).class_type() << ")";
  389. break;
  390. case Value::Kind::TypeOfInterfaceType:
  391. out << "typeof("
  392. << cast<TypeOfInterfaceType>(*this)
  393. .interface_type()
  394. .declaration()
  395. .name()
  396. << ")";
  397. break;
  398. case Value::Kind::TypeOfChoiceType:
  399. out << "typeof(" << cast<TypeOfChoiceType>(*this).choice_type().name()
  400. << ")";
  401. break;
  402. case Value::Kind::TypeOfParameterizedEntityName:
  403. out << "parameterized entity name "
  404. << cast<TypeOfParameterizedEntityName>(*this).name();
  405. break;
  406. case Value::Kind::TypeOfMemberName: {
  407. out << "member name " << cast<TypeOfMemberName>(*this).member().name();
  408. break;
  409. }
  410. case Value::Kind::StaticArrayType: {
  411. const auto& array_type = cast<StaticArrayType>(*this);
  412. out << "[" << array_type.element_type() << "; " << array_type.size()
  413. << "]";
  414. break;
  415. }
  416. }
  417. }
  418. ContinuationValue::StackFragment::~StackFragment() {
  419. CARBON_CHECK(reversed_todo_.empty())
  420. << "All StackFragments must be empty before the Carbon program ends.";
  421. }
  422. void ContinuationValue::StackFragment::StoreReversed(
  423. std::vector<std::unique_ptr<Action>> reversed_todo) {
  424. CARBON_CHECK(reversed_todo_.empty());
  425. reversed_todo_ = std::move(reversed_todo);
  426. }
  427. void ContinuationValue::StackFragment::RestoreTo(
  428. Stack<std::unique_ptr<Action>>& todo) {
  429. while (!reversed_todo_.empty()) {
  430. todo.Push(std::move(reversed_todo_.back()));
  431. reversed_todo_.pop_back();
  432. }
  433. }
  434. void ContinuationValue::StackFragment::Clear() {
  435. // We destroy the underlying Actions explicitly to ensure they're
  436. // destroyed in the correct order.
  437. for (auto& action : reversed_todo_) {
  438. action.reset();
  439. }
  440. reversed_todo_.clear();
  441. }
  442. void ContinuationValue::StackFragment::Print(llvm::raw_ostream& out) const {
  443. out << "{";
  444. llvm::ListSeparator sep(" :: ");
  445. for (const std::unique_ptr<Action>& action : reversed_todo_) {
  446. out << sep << *action;
  447. }
  448. out << "}";
  449. }
  450. auto TypeEqual(Nonnull<const Value*> t1, Nonnull<const Value*> t2) -> bool {
  451. if (t1->kind() != t2->kind()) {
  452. return false;
  453. }
  454. switch (t1->kind()) {
  455. case Value::Kind::PointerType:
  456. return TypeEqual(&cast<PointerType>(*t1).type(),
  457. &cast<PointerType>(*t2).type());
  458. case Value::Kind::FunctionType: {
  459. const auto& fn1 = cast<FunctionType>(*t1);
  460. const auto& fn2 = cast<FunctionType>(*t2);
  461. return TypeEqual(&fn1.parameters(), &fn2.parameters()) &&
  462. TypeEqual(&fn1.return_type(), &fn2.return_type());
  463. }
  464. case Value::Kind::StructType: {
  465. const auto& struct1 = cast<StructType>(*t1);
  466. const auto& struct2 = cast<StructType>(*t2);
  467. if (struct1.fields().size() != struct2.fields().size()) {
  468. return false;
  469. }
  470. for (size_t i = 0; i < struct1.fields().size(); ++i) {
  471. if (struct1.fields()[i].name != struct2.fields()[i].name ||
  472. !TypeEqual(struct1.fields()[i].value, struct2.fields()[i].value)) {
  473. return false;
  474. }
  475. }
  476. return true;
  477. }
  478. case Value::Kind::NominalClassType:
  479. if (cast<NominalClassType>(*t1).declaration().name() !=
  480. cast<NominalClassType>(*t2).declaration().name()) {
  481. return false;
  482. }
  483. for (const auto& [ty_var1, ty1] :
  484. cast<NominalClassType>(*t1).type_args()) {
  485. if (!ValueEqual(ty1,
  486. cast<NominalClassType>(*t2).type_args().at(ty_var1))) {
  487. return false;
  488. }
  489. }
  490. return true;
  491. case Value::Kind::InterfaceType:
  492. if (cast<InterfaceType>(*t1).declaration().name() !=
  493. cast<InterfaceType>(*t2).declaration().name()) {
  494. return false;
  495. }
  496. for (const auto& [ty_var1, ty1] : cast<InterfaceType>(*t1).args()) {
  497. if (!ValueEqual(ty1, cast<InterfaceType>(*t2).args().at(ty_var1))) {
  498. return false;
  499. }
  500. }
  501. return true;
  502. case Value::Kind::ChoiceType:
  503. return cast<ChoiceType>(*t1).name() == cast<ChoiceType>(*t2).name();
  504. case Value::Kind::TupleValue: {
  505. const auto& tup1 = cast<TupleValue>(*t1);
  506. const auto& tup2 = cast<TupleValue>(*t2);
  507. if (tup1.elements().size() != tup2.elements().size()) {
  508. return false;
  509. }
  510. for (size_t i = 0; i < tup1.elements().size(); ++i) {
  511. if (!TypeEqual(tup1.elements()[i], tup2.elements()[i])) {
  512. return false;
  513. }
  514. }
  515. return true;
  516. }
  517. case Value::Kind::IntType:
  518. case Value::Kind::BoolType:
  519. case Value::Kind::ContinuationType:
  520. case Value::Kind::TypeType:
  521. case Value::Kind::StringType:
  522. return true;
  523. case Value::Kind::VariableType:
  524. return &cast<VariableType>(*t1).binding() ==
  525. &cast<VariableType>(*t2).binding();
  526. case Value::Kind::TypeOfClassType:
  527. return TypeEqual(&cast<TypeOfClassType>(*t1).class_type(),
  528. &cast<TypeOfClassType>(*t2).class_type());
  529. case Value::Kind::TypeOfInterfaceType:
  530. return TypeEqual(&cast<TypeOfInterfaceType>(*t1).interface_type(),
  531. &cast<TypeOfInterfaceType>(*t2).interface_type());
  532. case Value::Kind::TypeOfChoiceType:
  533. return TypeEqual(&cast<TypeOfChoiceType>(*t1).choice_type(),
  534. &cast<TypeOfChoiceType>(*t2).choice_type());
  535. case Value::Kind::StaticArrayType: {
  536. const auto& array1 = cast<StaticArrayType>(*t1);
  537. const auto& array2 = cast<StaticArrayType>(*t2);
  538. return TypeEqual(&array1.element_type(), &array2.element_type()) &&
  539. array1.size() == array2.size();
  540. }
  541. case Value::Kind::IntValue:
  542. case Value::Kind::BoolValue:
  543. case Value::Kind::FunctionValue:
  544. case Value::Kind::BoundMethodValue:
  545. case Value::Kind::StructValue:
  546. case Value::Kind::NominalClassValue:
  547. case Value::Kind::AlternativeValue:
  548. case Value::Kind::AlternativeConstructorValue:
  549. case Value::Kind::StringValue:
  550. case Value::Kind::PointerValue:
  551. case Value::Kind::LValue:
  552. case Value::Kind::BindingPlaceholderValue:
  553. case Value::Kind::ContinuationValue:
  554. case Value::Kind::ParameterizedEntityName:
  555. case Value::Kind::MemberName:
  556. case Value::Kind::TypeOfParameterizedEntityName:
  557. case Value::Kind::TypeOfMemberName:
  558. CARBON_FATAL() << "TypeEqual used to compare non-type values\n"
  559. << *t1 << "\n"
  560. << *t2;
  561. case Value::Kind::Witness:
  562. CARBON_FATAL() << "TypeEqual: unexpected Witness";
  563. break;
  564. case Value::Kind::AutoType:
  565. CARBON_FATAL() << "TypeEqual: unexpected AutoType";
  566. break;
  567. }
  568. }
  569. // Returns true if the two values are equal and returns false otherwise.
  570. //
  571. // This function implements the `==` operator of Carbon.
  572. auto ValueEqual(Nonnull<const Value*> v1, Nonnull<const Value*> v2) -> bool {
  573. if (v1->kind() != v2->kind()) {
  574. return false;
  575. }
  576. switch (v1->kind()) {
  577. case Value::Kind::IntValue:
  578. return cast<IntValue>(*v1).value() == cast<IntValue>(*v2).value();
  579. case Value::Kind::BoolValue:
  580. return cast<BoolValue>(*v1).value() == cast<BoolValue>(*v2).value();
  581. case Value::Kind::FunctionValue: {
  582. std::optional<Nonnull<const Statement*>> body1 =
  583. cast<FunctionValue>(*v1).declaration().body();
  584. std::optional<Nonnull<const Statement*>> body2 =
  585. cast<FunctionValue>(*v2).declaration().body();
  586. return body1.has_value() == body2.has_value() &&
  587. (!body1.has_value() || *body1 == *body2);
  588. }
  589. case Value::Kind::BoundMethodValue: {
  590. const auto& m1 = cast<BoundMethodValue>(*v1);
  591. const auto& m2 = cast<BoundMethodValue>(*v2);
  592. std::optional<Nonnull<const Statement*>> body1 = m1.declaration().body();
  593. std::optional<Nonnull<const Statement*>> body2 = m2.declaration().body();
  594. return ValueEqual(m1.receiver(), m2.receiver()) &&
  595. body1.has_value() == body2.has_value() &&
  596. (!body1.has_value() || *body1 == *body2);
  597. }
  598. case Value::Kind::TupleValue: {
  599. const std::vector<Nonnull<const Value*>>& elements1 =
  600. cast<TupleValue>(*v1).elements();
  601. const std::vector<Nonnull<const Value*>>& elements2 =
  602. cast<TupleValue>(*v2).elements();
  603. if (elements1.size() != elements2.size()) {
  604. return false;
  605. }
  606. for (size_t i = 0; i < elements1.size(); ++i) {
  607. if (!ValueEqual(elements1[i], elements2[i])) {
  608. return false;
  609. }
  610. }
  611. return true;
  612. }
  613. case Value::Kind::StructValue: {
  614. const auto& struct_v1 = cast<StructValue>(*v1);
  615. const auto& struct_v2 = cast<StructValue>(*v2);
  616. CARBON_CHECK(struct_v1.elements().size() == struct_v2.elements().size());
  617. for (size_t i = 0; i < struct_v1.elements().size(); ++i) {
  618. CARBON_CHECK(struct_v1.elements()[i].name ==
  619. struct_v2.elements()[i].name);
  620. if (!ValueEqual(struct_v1.elements()[i].value,
  621. struct_v2.elements()[i].value)) {
  622. return false;
  623. }
  624. }
  625. return true;
  626. }
  627. case Value::Kind::StringValue:
  628. return cast<StringValue>(*v1).value() == cast<StringValue>(*v2).value();
  629. case Value::Kind::ParameterizedEntityName: {
  630. std::optional<std::string> name1 =
  631. GetName(cast<ParameterizedEntityName>(v1)->declaration());
  632. std::optional<std::string> name2 =
  633. GetName(cast<ParameterizedEntityName>(v2)->declaration());
  634. CARBON_CHECK(name1.has_value() && name2.has_value())
  635. << "parameterized name refers to unnamed declaration";
  636. return *name1 == *name2;
  637. }
  638. case Value::Kind::IntType:
  639. case Value::Kind::BoolType:
  640. case Value::Kind::TypeType:
  641. case Value::Kind::FunctionType:
  642. case Value::Kind::PointerType:
  643. case Value::Kind::AutoType:
  644. case Value::Kind::StructType:
  645. case Value::Kind::NominalClassType:
  646. case Value::Kind::InterfaceType:
  647. case Value::Kind::Witness:
  648. case Value::Kind::ChoiceType:
  649. case Value::Kind::ContinuationType:
  650. case Value::Kind::VariableType:
  651. case Value::Kind::StringType:
  652. case Value::Kind::TypeOfClassType:
  653. case Value::Kind::TypeOfInterfaceType:
  654. case Value::Kind::TypeOfChoiceType:
  655. case Value::Kind::TypeOfParameterizedEntityName:
  656. case Value::Kind::TypeOfMemberName:
  657. case Value::Kind::StaticArrayType:
  658. return TypeEqual(v1, v2);
  659. case Value::Kind::NominalClassValue:
  660. case Value::Kind::AlternativeValue:
  661. case Value::Kind::BindingPlaceholderValue:
  662. case Value::Kind::AlternativeConstructorValue:
  663. case Value::Kind::ContinuationValue:
  664. case Value::Kind::PointerValue:
  665. case Value::Kind::LValue:
  666. case Value::Kind::MemberName:
  667. // TODO: support pointer comparisons once we have a clearer distinction
  668. // between pointers and lvalues.
  669. CARBON_FATAL() << "ValueEqual does not support this kind of value: "
  670. << *v1;
  671. }
  672. }
  673. auto ChoiceType::FindAlternative(std::string_view name) const
  674. -> std::optional<Nonnull<const Value*>> {
  675. for (const NamedValue& alternative : alternatives_) {
  676. if (alternative.name == name) {
  677. return alternative.value;
  678. }
  679. }
  680. return std::nullopt;
  681. }
  682. auto NominalClassType::FindFunction(const std::string& name) const
  683. -> std::optional<Nonnull<const FunctionValue*>> {
  684. for (const auto& member : declaration().members()) {
  685. switch (member->kind()) {
  686. case DeclarationKind::FunctionDeclaration: {
  687. const auto& fun = cast<FunctionDeclaration>(*member);
  688. if (fun.name() == name) {
  689. return &cast<FunctionValue>(**fun.constant_value());
  690. }
  691. break;
  692. }
  693. default:
  694. break;
  695. }
  696. }
  697. return std::nullopt;
  698. }
  699. auto FindMember(const std::string& name,
  700. llvm::ArrayRef<Nonnull<Declaration*>> members)
  701. -> std::optional<Nonnull<const Declaration*>> {
  702. for (Nonnull<const Declaration*> member : members) {
  703. if (std::optional<std::string> mem_name = GetName(*member);
  704. mem_name.has_value()) {
  705. if (*mem_name == name) {
  706. return member;
  707. }
  708. }
  709. }
  710. return std::nullopt;
  711. }
  712. auto Member::name() const -> std::string {
  713. if (const Declaration* decl = member_.dyn_cast<const Declaration*>()) {
  714. return GetName(*decl).value();
  715. } else {
  716. return member_.get<const NamedValue*>()->name;
  717. }
  718. }
  719. auto Member::type() const -> const Value& {
  720. if (const Declaration* decl = member_.dyn_cast<const Declaration*>()) {
  721. return decl->static_type();
  722. } else {
  723. return *member_.get<const NamedValue*>()->value;
  724. }
  725. }
  726. void ImplBinding::Print(llvm::raw_ostream& out) const {
  727. out << "impl binding " << *type_var_ << " as " << *iface_;
  728. }
  729. void ImplBinding::PrintID(llvm::raw_ostream& out) const {
  730. out << *type_var_ << " as " << *iface_;
  731. }
  732. } // namespace Carbon