facet_type.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  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 "toolchain/check/facet_type.h"
  5. #include <compare>
  6. #include "llvm/ADT/ArrayRef.h"
  7. #include "toolchain/check/convert.h"
  8. #include "toolchain/check/diagnostic_helpers.h"
  9. #include "toolchain/check/generic.h"
  10. #include "toolchain/check/import_ref.h"
  11. #include "toolchain/check/inst.h"
  12. #include "toolchain/check/interface.h"
  13. #include "toolchain/check/subst.h"
  14. #include "toolchain/check/type.h"
  15. #include "toolchain/check/type_completion.h"
  16. #include "toolchain/sem_ir/ids.h"
  17. #include "toolchain/sem_ir/typed_insts.h"
  18. namespace Carbon::Check {
  19. auto FacetTypeFromInterface(Context& context, SemIR::InterfaceId interface_id,
  20. SemIR::SpecificId specific_id) -> SemIR::FacetType {
  21. SemIR::FacetTypeId facet_type_id = context.facet_types().Add(
  22. SemIR::FacetTypeInfo{.extend_constraints = {{interface_id, specific_id}},
  23. .other_requirements = false});
  24. return {.type_id = SemIR::TypeType::TypeId, .facet_type_id = facet_type_id};
  25. }
  26. // Returns whether the `LookupImplWitness` of `witness_id` matches `interface`.
  27. static auto WitnessQueryMatchesInterface(
  28. Context& context, SemIR::InstId witness_id,
  29. const SemIR::SpecificInterface& interface) -> bool {
  30. auto lookup = context.insts().GetAs<SemIR::LookupImplWitness>(witness_id);
  31. return interface ==
  32. context.specific_interfaces().Get(lookup.query_specific_interface_id);
  33. }
  34. static auto IncompleteFacetTypeDiagnosticBuilder(
  35. Context& context, SemIR::LocId loc_id, SemIR::TypeInstId facet_type_inst_id,
  36. bool is_definition) -> DiagnosticBuilder {
  37. if (is_definition) {
  38. CARBON_DIAGNOSTIC(ImplAsIncompleteFacetTypeDefinition, Error,
  39. "definition of impl as incomplete facet type {0}",
  40. InstIdAsType);
  41. return context.emitter().Build(loc_id, ImplAsIncompleteFacetTypeDefinition,
  42. facet_type_inst_id);
  43. } else {
  44. CARBON_DIAGNOSTIC(
  45. ImplAsIncompleteFacetTypeRewrites, Error,
  46. "declaration of impl as incomplete facet type {0} with rewrites",
  47. InstIdAsType);
  48. return context.emitter().Build(loc_id, ImplAsIncompleteFacetTypeRewrites,
  49. facet_type_inst_id);
  50. }
  51. }
  52. auto InitialFacetTypeImplWitness(
  53. Context& context, SemIR::LocId witness_loc_id,
  54. SemIR::TypeInstId facet_type_inst_id, SemIR::TypeInstId self_type_inst_id,
  55. const SemIR::SpecificInterface& interface_to_witness,
  56. SemIR::SpecificId self_specific_id, bool is_definition) -> SemIR::InstId {
  57. // TODO: Finish facet type resolution. This code currently only handles
  58. // rewrite constraints that set associated constants to a concrete value.
  59. // Need logic to topologically sort rewrites to respect dependencies, and
  60. // afterwards reject duplicates that are not identical.
  61. auto facet_type_id =
  62. context.types().GetTypeIdForTypeInstId(facet_type_inst_id);
  63. CARBON_CHECK(facet_type_id != SemIR::ErrorInst::TypeId);
  64. auto facet_type = context.types().GetAs<SemIR::FacetType>(facet_type_id);
  65. // TODO: This is currently a copy because I'm not sure whether anything could
  66. // cause the facet type store to resize before we are done with it.
  67. auto facet_type_info = context.facet_types().Get(facet_type.facet_type_id);
  68. if (!is_definition && facet_type_info.rewrite_constraints.empty()) {
  69. auto witness_table_inst_id = AddInst<SemIR::ImplWitnessTable>(
  70. context, witness_loc_id,
  71. {.elements_id = context.inst_blocks().AddPlaceholder(),
  72. .impl_id = SemIR::ImplId::None});
  73. return AddInst<SemIR::ImplWitness>(
  74. context, witness_loc_id,
  75. {.type_id = GetSingletonType(context, SemIR::WitnessType::TypeInstId),
  76. .witness_table_id = witness_table_inst_id,
  77. .specific_id = self_specific_id});
  78. }
  79. if (!RequireCompleteType(
  80. context, facet_type_id, SemIR::LocId(facet_type_inst_id), [&] {
  81. return IncompleteFacetTypeDiagnosticBuilder(
  82. context, witness_loc_id, facet_type_inst_id, is_definition);
  83. })) {
  84. return SemIR::ErrorInst::InstId;
  85. }
  86. const auto& interface =
  87. context.interfaces().Get(interface_to_witness.interface_id);
  88. auto assoc_entities =
  89. context.inst_blocks().Get(interface.associated_entities_id);
  90. // TODO: When this function is used for things other than just impls, may want
  91. // to only load the specific associated entities that are mentioned in rewrite
  92. // rules.
  93. for (auto decl_id : assoc_entities) {
  94. LoadImportRef(context, decl_id);
  95. }
  96. SemIR::InstId witness_inst_id = SemIR::InstId::None;
  97. llvm::MutableArrayRef<SemIR::InstId> table;
  98. {
  99. auto elements_id =
  100. context.inst_blocks().AddUninitialized(assoc_entities.size());
  101. table = context.inst_blocks().GetMutable(elements_id);
  102. for (auto& uninit : table) {
  103. uninit = SemIR::ImplWitnessTablePlaceholder::TypeInstId;
  104. }
  105. auto witness_table_inst_id = AddInst<SemIR::ImplWitnessTable>(
  106. context, witness_loc_id,
  107. {.elements_id = elements_id, .impl_id = SemIR::ImplId::None});
  108. witness_inst_id = AddInst<SemIR::ImplWitness>(
  109. context, witness_loc_id,
  110. {.type_id = GetSingletonType(context, SemIR::WitnessType::TypeInstId),
  111. .witness_table_id = witness_table_inst_id,
  112. .specific_id = self_specific_id});
  113. }
  114. for (auto rewrite : facet_type_info.rewrite_constraints) {
  115. auto access =
  116. context.insts().GetAs<SemIR::ImplWitnessAccess>(rewrite.lhs_id);
  117. if (!WitnessQueryMatchesInterface(context, access.witness_id,
  118. interface_to_witness)) {
  119. continue;
  120. }
  121. auto& table_entry = table[access.index.index];
  122. if (table_entry == SemIR::ErrorInst::InstId) {
  123. // Don't overwrite an error value. This prioritizes not generating
  124. // multiple errors for one associated constant over picking a value
  125. // for it to use to attempt recovery.
  126. continue;
  127. }
  128. auto rewrite_inst_id = rewrite.rhs_id;
  129. if (rewrite_inst_id == SemIR::ErrorInst::InstId) {
  130. table_entry = SemIR::ErrorInst::InstId;
  131. continue;
  132. }
  133. auto decl_id = context.constant_values().GetConstantInstId(
  134. assoc_entities[access.index.index]);
  135. CARBON_CHECK(decl_id.has_value(), "Non-constant associated entity");
  136. if (decl_id == SemIR::ErrorInst::InstId) {
  137. table_entry = SemIR::ErrorInst::InstId;
  138. continue;
  139. }
  140. auto assoc_constant_decl =
  141. context.insts().TryGetAs<SemIR::AssociatedConstantDecl>(decl_id);
  142. if (!assoc_constant_decl) {
  143. auto type_id = context.insts().Get(decl_id).type_id();
  144. auto type_inst = context.types().GetAsInst(type_id);
  145. auto fn_type = type_inst.As<SemIR::FunctionType>();
  146. const auto& fn = context.functions().Get(fn_type.function_id);
  147. CARBON_DIAGNOSTIC(RewriteForAssociatedFunction, Error,
  148. "rewrite specified for associated function {0}",
  149. SemIR::NameId);
  150. context.emitter().Emit(facet_type_inst_id, RewriteForAssociatedFunction,
  151. fn.name_id);
  152. table_entry = SemIR::ErrorInst::InstId;
  153. continue;
  154. }
  155. // FacetTypes resolution disallows two rewrites to the same associated
  156. // constant, so we won't ever have a facet write twice to the same position
  157. // in the witness table.
  158. CARBON_CHECK(table_entry == SemIR::ImplWitnessTablePlaceholder::TypeInstId);
  159. // If the associated constant has a symbolic type, convert the rewrite
  160. // value to that type now we know the value of `Self`.
  161. SemIR::TypeId assoc_const_type_id = assoc_constant_decl->type_id;
  162. if (assoc_const_type_id.is_symbolic()) {
  163. // Get the type of the associated constant in this interface with this
  164. // value for `Self`.
  165. assoc_const_type_id = GetTypeForSpecificAssociatedEntity(
  166. context, SemIR::LocId(facet_type_inst_id),
  167. interface_to_witness.specific_id, decl_id,
  168. context.types().GetTypeIdForTypeInstId(self_type_inst_id),
  169. witness_inst_id);
  170. // Perform the conversion of the value to the type. We skipped this when
  171. // forming the facet type because the type of the associated constant
  172. // was symbolic.
  173. auto converted_inst_id =
  174. ConvertToValueOfType(context, SemIR::LocId(facet_type_inst_id),
  175. rewrite_inst_id, assoc_const_type_id);
  176. // Canonicalize the converted constant value.
  177. converted_inst_id =
  178. context.constant_values().GetConstantInstId(converted_inst_id);
  179. // The result of conversion can be non-constant even if the original
  180. // value was constant.
  181. if (converted_inst_id.has_value()) {
  182. rewrite_inst_id = converted_inst_id;
  183. } else {
  184. const auto& assoc_const = context.associated_constants().Get(
  185. assoc_constant_decl->assoc_const_id);
  186. CARBON_DIAGNOSTIC(
  187. AssociatedConstantNotConstantAfterConversion, Error,
  188. "associated constant {0} given value {1} that is not constant "
  189. "after conversion to {2}",
  190. SemIR::NameId, InstIdAsConstant, SemIR::TypeId);
  191. context.emitter().Emit(
  192. facet_type_inst_id, AssociatedConstantNotConstantAfterConversion,
  193. assoc_const.name_id, rewrite_inst_id, assoc_const_type_id);
  194. rewrite_inst_id = SemIR::ErrorInst::InstId;
  195. }
  196. }
  197. CARBON_CHECK(rewrite_inst_id == context.constant_values().GetConstantInstId(
  198. rewrite_inst_id),
  199. "Rewritten value for associated constant is not canonical.");
  200. table_entry = AddInst<SemIR::ImplWitnessAssociatedConstant>(
  201. context, witness_loc_id,
  202. {.type_id = context.insts().Get(rewrite_inst_id).type_id(),
  203. .inst_id = rewrite_inst_id});
  204. }
  205. return witness_inst_id;
  206. }
  207. auto RequireCompleteFacetTypeForImplDefinition(
  208. Context& context, SemIR::LocId loc_id, SemIR::TypeInstId facet_type_inst_id)
  209. -> bool {
  210. auto facet_type_id =
  211. context.types().GetTypeIdForTypeInstId(facet_type_inst_id);
  212. return RequireCompleteType(
  213. context, facet_type_id, SemIR::LocId(facet_type_inst_id), [&] {
  214. return IncompleteFacetTypeDiagnosticBuilder(context, loc_id,
  215. facet_type_inst_id,
  216. /*is_definition=*/true);
  217. });
  218. }
  219. auto AllocateFacetTypeImplWitness(Context& context,
  220. SemIR::InterfaceId interface_id,
  221. SemIR::InstBlockId witness_id) -> void {
  222. const auto& interface = context.interfaces().Get(interface_id);
  223. CARBON_CHECK(interface.is_complete());
  224. auto assoc_entities =
  225. context.inst_blocks().Get(interface.associated_entities_id);
  226. for (auto decl_id : assoc_entities) {
  227. LoadImportRef(context, decl_id);
  228. }
  229. llvm::SmallVector<SemIR::InstId> empty_table(
  230. assoc_entities.size(), SemIR::ImplWitnessTablePlaceholder::TypeInstId);
  231. context.inst_blocks().ReplacePlaceholder(witness_id, empty_table);
  232. }
  233. // Returns an ordering between two values in a rewrite constraint. Two
  234. // `ImplWitnessAccess` instructions that refer to the same associated constant
  235. // through the same facet value are treated as equivalent. Otherwise, the
  236. // ordering is somewhat arbitrary with `ImplWitnessAccess` instructions coming
  237. // first.
  238. static auto CompareFacetTypeConstraintValues(Context& context,
  239. SemIR::InstId lhs_id,
  240. SemIR::InstId rhs_id)
  241. -> std::weak_ordering {
  242. if (lhs_id == rhs_id) {
  243. return std::weak_ordering::equivalent;
  244. }
  245. auto lhs_access = context.insts().TryGetAs<SemIR::ImplWitnessAccess>(lhs_id);
  246. auto rhs_access = context.insts().TryGetAs<SemIR::ImplWitnessAccess>(rhs_id);
  247. if (lhs_access && rhs_access) {
  248. auto lhs_lookup = context.insts().TryGetAs<SemIR::LookupImplWitness>(
  249. lhs_access->witness_id);
  250. auto rhs_lookup = context.insts().TryGetAs<SemIR::LookupImplWitness>(
  251. rhs_access->witness_id);
  252. if (lhs_lookup && rhs_lookup) {
  253. auto lhs_self = context.insts().TryGetAs<SemIR::BindSymbolicName>(
  254. context.constant_values().GetConstantInstId(
  255. lhs_lookup->query_self_inst_id));
  256. auto rhs_self = context.insts().TryGetAs<SemIR::BindSymbolicName>(
  257. context.constant_values().GetConstantInstId(
  258. rhs_lookup->query_self_inst_id));
  259. if (lhs_self && rhs_self) {
  260. if (lhs_self->entity_name_id != rhs_self->entity_name_id) {
  261. return lhs_self->entity_name_id.index <=>
  262. rhs_self->entity_name_id.index;
  263. }
  264. if (lhs_access->index != rhs_access->index) {
  265. return lhs_access->index <=> rhs_access->index;
  266. }
  267. return lhs_lookup->query_specific_interface_id.index <=>
  268. rhs_lookup->query_specific_interface_id.index;
  269. }
  270. }
  271. // We do *not* want to get the evaluated result of `ImplWitnessAccess` here,
  272. // we want to keep them as a reference to an associated constant for the
  273. // resolution phase.
  274. return lhs_id.index <=> rhs_id.index;
  275. }
  276. // ImplWitnessAccess sorts before other instructions.
  277. if (lhs_access) {
  278. return std::weak_ordering::less;
  279. }
  280. if (rhs_access) {
  281. return std::weak_ordering::greater;
  282. }
  283. return context.constant_values().GetConstantInstId(lhs_id).index <=>
  284. context.constant_values().GetConstantInstId(rhs_id).index;
  285. }
  286. // Sort and dedupe the rewrite constraints, with accesses to the same associated
  287. // constants through the same facet value being treated as equivalent.
  288. static auto SortAndDedupeRewriteConstraints(
  289. Context& context,
  290. llvm::SmallVector<SemIR::FacetTypeInfo::RewriteConstraint>& rewrites) {
  291. auto ord = [&](const SemIR::FacetTypeInfo::RewriteConstraint& a,
  292. const SemIR::FacetTypeInfo::RewriteConstraint& b) {
  293. auto lhs = CompareFacetTypeConstraintValues(context, a.lhs_id, b.lhs_id);
  294. if (lhs != std::weak_ordering::equivalent) {
  295. return lhs;
  296. }
  297. auto rhs = CompareFacetTypeConstraintValues(context, a.rhs_id, b.rhs_id);
  298. return rhs;
  299. };
  300. auto less = [&](const SemIR::FacetTypeInfo::RewriteConstraint& a,
  301. const SemIR::FacetTypeInfo::RewriteConstraint& b) {
  302. return ord(a, b) == std::weak_ordering::less;
  303. };
  304. llvm::stable_sort(rewrites, less);
  305. auto eq = [&](const SemIR::FacetTypeInfo::RewriteConstraint& a,
  306. const SemIR::FacetTypeInfo::RewriteConstraint& b) {
  307. return ord(a, b) == std::weak_ordering::equivalent;
  308. };
  309. rewrites.erase(llvm::unique(rewrites, eq), rewrites.end());
  310. }
  311. // To be used for substituting into the RHS of a rewrite constraint.
  312. //
  313. // It will substitute any `ImplWitnessAccess` into `.Self` (a reference to an
  314. // associated constant) with the RHS of another rewrite constraint that writes
  315. // to the same associated constant. For example:
  316. // ```
  317. // Z where .X = () and .Y = .X
  318. // ```
  319. // Here the second `.X` is an `ImplWitnessAccess` which would be substituted by
  320. // finding the first rewrite constraint, where the LHS is for the same
  321. // associated constant and using its RHS. So the substitution would produce:
  322. // ```
  323. // Z where .X = () and .Y = ()
  324. // ```
  325. //
  326. // This additionally diagnoses cycles when the `ImplWitnessAccess` is reading
  327. // from the same rewrite constraint, and is thus assigning to the associated
  328. // constant a value that refers to the same associated constant, such as with
  329. // `Z where .X = C(.X)`. In the event of a cycle, the `ImplWitnessAccess` is
  330. // replaced with `ErrorInst` so that further evaluation of the
  331. // `ImplWitnessAccess` will not loop infinitely.
  332. class SubstImplWitnessAccessCallbacks : public SubstInstCallbacks {
  333. public:
  334. // The `rewrites` is the set of rewrite constraints that are being
  335. // substituted, and where it looks for rewritten values to substitute from.
  336. //
  337. // The `substituting_constraint` is the rewrite constraint for which the RHS
  338. // is being substituted with the value from another rewrite constraint, if
  339. // possible. That is, `.Y = .X` in the example in the class docs.
  340. explicit SubstImplWitnessAccessCallbacks(
  341. Context* context, SemIR::LocId loc_id,
  342. llvm::ArrayRef<SemIR::FacetTypeInfo::RewriteConstraint> rewrites,
  343. const SemIR::FacetTypeInfo::RewriteConstraint* substituting_constraint)
  344. : SubstInstCallbacks(context),
  345. loc_id_(loc_id),
  346. rewrites_(rewrites),
  347. substituting_constraint_(substituting_constraint) {}
  348. auto Subst(SemIR::InstId& rhs_inst_id) const -> bool override {
  349. if (!context().insts().Is<SemIR::ImplWitnessAccess>(rhs_inst_id)) {
  350. return context().constant_values().Get(rhs_inst_id).is_concrete();
  351. }
  352. // TODO: We could consider something better than linear search here, such as
  353. // a map. However that would probably require heap allocations which may be
  354. // worse overall since the number of rewrite constraints is generally low.
  355. for (const auto& search_constraint : rewrites_) {
  356. if (CompareFacetTypeConstraintValues(context(), search_constraint.lhs_id,
  357. rhs_inst_id) ==
  358. std::weak_ordering::equivalent) {
  359. if (&search_constraint == substituting_constraint_) {
  360. if (search_constraint.rhs_id != SemIR::ErrorInst::InstId) {
  361. CARBON_DIAGNOSTIC(FacetTypeConstraintCycle, Error,
  362. "found cycle in facet type constraint for {0}",
  363. InstIdAsConstant);
  364. // TODO: It would be nice to note the places where the values are
  365. // assigned but rewrite constraint instructions are from canonical
  366. // constant values, and have no locations. We'd need to store a
  367. // location along with them in the rewrite constraints, and track
  368. // propagation of locations here, which may imply heap allocations.
  369. context().emitter().Emit(loc_id_, FacetTypeConstraintCycle,
  370. substituting_constraint_->lhs_id);
  371. rhs_inst_id = SemIR::ErrorInst::InstId;
  372. }
  373. } else {
  374. rhs_inst_id = search_constraint.rhs_id;
  375. }
  376. }
  377. }
  378. // Never recurse into ImplWitnessAccess, we don't want to substitute into
  379. // FacetTypes found within. We only substitute ImplWitnessAccesses that
  380. // appear directly on the RHS.
  381. return true;
  382. }
  383. auto Rebuild(SemIR::InstId /*orig_inst_id*/, SemIR::Inst new_inst) const
  384. -> SemIR::InstId override {
  385. return RebuildNewInst(loc_id_, new_inst);
  386. }
  387. private:
  388. SemIR::LocId loc_id_;
  389. llvm::ArrayRef<SemIR::FacetTypeInfo::RewriteConstraint> rewrites_;
  390. const SemIR::FacetTypeInfo::RewriteConstraint* substituting_constraint_;
  391. };
  392. auto ResolveFacetTypeRewriteConstraints(
  393. Context& context, SemIR::LocId loc_id,
  394. llvm::SmallVector<SemIR::FacetTypeInfo::RewriteConstraint>& rewrites)
  395. -> void {
  396. if (rewrites.empty()) {
  397. return;
  398. }
  399. while (true) {
  400. bool applied_rewrite = false;
  401. for (auto& constraint : rewrites) {
  402. if (constraint.lhs_id == SemIR::ErrorInst::InstId ||
  403. constraint.rhs_id == SemIR::ErrorInst::InstId) {
  404. continue;
  405. }
  406. auto lhs_access =
  407. context.insts().TryGetAs<SemIR::ImplWitnessAccess>(constraint.lhs_id);
  408. if (!lhs_access) {
  409. continue;
  410. }
  411. // Replace any `ImplWitnessAccess` in the RHS of this constraint with the
  412. // RHS of another constraint that sets the value of the associated
  413. // constant being accessed in the RHS.
  414. auto subst_inst_id =
  415. SubstInst(context, constraint.rhs_id,
  416. SubstImplWitnessAccessCallbacks(&context, loc_id, rewrites,
  417. &constraint));
  418. if (subst_inst_id != constraint.rhs_id) {
  419. constraint.rhs_id = subst_inst_id;
  420. if (constraint.rhs_id != SemIR::ErrorInst::InstId) {
  421. // If the RHS is replaced with a non-error value, we need to do
  422. // another pass so that the new RHS value can continue to propagate.
  423. applied_rewrite = true;
  424. }
  425. }
  426. }
  427. if (!applied_rewrite) {
  428. break;
  429. }
  430. }
  431. // We sort the constraints so that we can find different values being written
  432. // to the same LHS by looking at consecutive rewrite constraints.
  433. //
  434. // It is important to dedupe so that we don't have redundant rewrite
  435. // constraints, as these lead to being diagnosed as a cycle. For example:
  436. // ```
  437. // (T:! Z where .X = .Y) where .X = .Y
  438. // ```
  439. // Here we drop one of the `.X = .Y` in the resulting facet type. If we don't,
  440. // then the `.X` in the outer facet type can be evaluated to `.Y` from the
  441. // inner facet type, resulting in `.Y = .Y` which is a cycle. By deduping, we
  442. // avoid any LHS of a rewrite constraint from being evaluated to the RHS of
  443. // a duplicate rewrite constraint.
  444. SortAndDedupeRewriteConstraints(context, rewrites);
  445. for (size_t i = 0; i < rewrites.size() - 1; ++i) {
  446. auto& constraint = rewrites[i];
  447. if (constraint.lhs_id == SemIR::ErrorInst::InstId ||
  448. constraint.rhs_id == SemIR::ErrorInst::InstId) {
  449. continue;
  450. }
  451. auto lhs_access =
  452. context.insts().TryGetAs<SemIR::ImplWitnessAccess>(constraint.lhs_id);
  453. if (!lhs_access) {
  454. continue;
  455. }
  456. // This loop moves `i` to the last position with the same LHS value, so that
  457. // we don't diagnose more than once within the same contiguous range of
  458. // assignments to a single LHS value.
  459. for (; i < rewrites.size() - 1; ++i) {
  460. auto& next = rewrites[i + 1];
  461. auto next_lhs_access =
  462. context.insts().TryGetAs<SemIR::ImplWitnessAccess>(next.lhs_id);
  463. if (!next_lhs_access) {
  464. break;
  465. }
  466. if (CompareFacetTypeConstraintValues(context, constraint.lhs_id,
  467. next.lhs_id) !=
  468. std::weak_ordering::equivalent) {
  469. break;
  470. }
  471. if (constraint.rhs_id != SemIR::ErrorInst::InstId &&
  472. next.rhs_id != SemIR::ErrorInst::InstId) {
  473. CARBON_DIAGNOSTIC(
  474. AssociatedConstantWithDifferentValues, Error,
  475. "associated constant {0} given two different values {1} and {2}",
  476. InstIdAsConstant, InstIdAsConstant, InstIdAsConstant);
  477. // Use inst id ordering as a simple proxy for source ordering, to try
  478. // to name the values in the same order they appear in the facet type.
  479. auto source_order1 = constraint.rhs_id.index < next.rhs_id.index
  480. ? constraint.rhs_id
  481. : next.rhs_id;
  482. auto source_order2 = constraint.rhs_id.index >= next.rhs_id.index
  483. ? constraint.rhs_id
  484. : next.rhs_id;
  485. // TODO: It would be nice to note the places where the values are
  486. // assigned but rewrite constraint instructions are from canonical
  487. // constant values, and have no locations. We'd need to store a
  488. // location along with them in the rewrite constraints.
  489. context.emitter().Emit(loc_id, AssociatedConstantWithDifferentValues,
  490. constraint.lhs_id, source_order1, source_order2);
  491. }
  492. constraint.rhs_id = SemIR::ErrorInst::InstId;
  493. next.rhs_id = SemIR::ErrorInst::InstId;
  494. }
  495. }
  496. }
  497. } // namespace Carbon::Check