value.cpp 31 KB

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