value.cpp 30 KB

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