facet_type.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  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 "llvm/ADT/STLExtras.h"
  8. #include "toolchain/base/kind_switch.h"
  9. #include "toolchain/check/convert.h"
  10. #include "toolchain/check/diagnostic_helpers.h"
  11. #include "toolchain/check/generic.h"
  12. #include "toolchain/check/import_ref.h"
  13. #include "toolchain/check/inst.h"
  14. #include "toolchain/check/interface.h"
  15. #include "toolchain/check/subst.h"
  16. #include "toolchain/check/type.h"
  17. #include "toolchain/check/type_completion.h"
  18. #include "toolchain/sem_ir/ids.h"
  19. #include "toolchain/sem_ir/typed_insts.h"
  20. namespace Carbon::Check {
  21. auto FacetTypeFromInterface(Context& context, SemIR::InterfaceId interface_id,
  22. SemIR::SpecificId specific_id) -> SemIR::FacetType {
  23. auto info = SemIR::FacetTypeInfo{};
  24. info.extend_constraints.push_back({interface_id, specific_id});
  25. info.Canonicalize();
  26. SemIR::FacetTypeId facet_type_id = context.facet_types().Add(info);
  27. return {.type_id = SemIR::TypeType::TypeId, .facet_type_id = facet_type_id};
  28. }
  29. auto FacetTypeFromNamedConstraint(Context& context,
  30. SemIR::NamedConstraintId named_constraint_id,
  31. SemIR::SpecificId specific_id)
  32. -> SemIR::FacetType {
  33. auto info = SemIR::FacetTypeInfo{};
  34. info.extend_named_constraints.push_back({named_constraint_id, specific_id});
  35. info.Canonicalize();
  36. SemIR::FacetTypeId facet_type_id = context.facet_types().Add(info);
  37. return {.type_id = SemIR::TypeType::TypeId, .facet_type_id = facet_type_id};
  38. }
  39. // Returns whether the `LookupImplWitness` of `witness_id` matches `interface`.
  40. static auto WitnessQueryMatchesInterface(
  41. Context& context, SemIR::InstId witness_id,
  42. const SemIR::SpecificInterface& interface) -> bool {
  43. auto lookup = context.insts().GetAs<SemIR::LookupImplWitness>(witness_id);
  44. return interface ==
  45. context.specific_interfaces().Get(lookup.query_specific_interface_id);
  46. }
  47. auto GetImplWitnessAccessWithoutSubstitution(Context& context,
  48. SemIR::InstId inst_id)
  49. -> SemIR::InstId {
  50. if (auto inst = context.insts().TryGetAs<SemIR::ImplWitnessAccessSubstituted>(
  51. inst_id)) {
  52. return inst->impl_witness_access_id;
  53. }
  54. return inst_id;
  55. }
  56. auto InitialFacetTypeImplWitness(
  57. Context& context, SemIR::LocId witness_loc_id,
  58. SemIR::TypeInstId facet_type_inst_id, SemIR::TypeInstId self_type_inst_id,
  59. const SemIR::SpecificInterface& interface_to_witness,
  60. SemIR::SpecificId self_specific_id) -> SemIR::InstId {
  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. const auto& facet_type_info =
  66. context.facet_types().Get(facet_type.facet_type_id);
  67. // An iterator over the rewrite_constraints where the LHS of the rewrite names
  68. // a member of the `interface_to_witness`. This filters out rewrites of names
  69. // from other interfaces, as they do not set values in the witness table.
  70. auto rewrites_into_interface_to_witness = llvm::make_filter_range(
  71. facet_type_info.rewrite_constraints,
  72. [&](const SemIR::FacetTypeInfo::RewriteConstraint& rewrite) {
  73. auto access = context.insts().GetAs<SemIR::ImplWitnessAccess>(
  74. GetImplWitnessAccessWithoutSubstitution(context, rewrite.lhs_id));
  75. return WitnessQueryMatchesInterface(context, access.witness_id,
  76. interface_to_witness);
  77. });
  78. if (rewrites_into_interface_to_witness.empty()) {
  79. // The witness table is not needed until the definition. Make a placeholder
  80. // for the declaration.
  81. auto witness_table_inst_id = AddInst<SemIR::ImplWitnessTable>(
  82. context, witness_loc_id,
  83. {.elements_id = context.inst_blocks().AddPlaceholder(),
  84. .impl_id = SemIR::ImplId::None});
  85. return AddInst<SemIR::ImplWitness>(
  86. context, witness_loc_id,
  87. {.type_id = GetSingletonType(context, SemIR::WitnessType::TypeInstId),
  88. .witness_table_id = witness_table_inst_id,
  89. .specific_id = self_specific_id});
  90. }
  91. const auto& interface =
  92. context.interfaces().Get(interface_to_witness.interface_id);
  93. if (!interface.is_complete()) {
  94. // This is a declaration with rewrite constraints into `.Self`, but the
  95. // interface is not complete. Those rewrites have already been diagnosed as
  96. // an error in their member access.
  97. return SemIR::ErrorInst::InstId;
  98. }
  99. auto assoc_entities =
  100. context.inst_blocks().Get(interface.associated_entities_id);
  101. // TODO: When this function is used for things other than just impls, may want
  102. // to only load the specific associated entities that are mentioned in rewrite
  103. // rules.
  104. for (auto decl_id : assoc_entities) {
  105. LoadImportRef(context, decl_id);
  106. }
  107. SemIR::InstId witness_inst_id = SemIR::InstId::None;
  108. llvm::MutableArrayRef<SemIR::InstId> table;
  109. {
  110. auto elements_id =
  111. context.inst_blocks().AddUninitialized(assoc_entities.size());
  112. table = context.inst_blocks().GetMutable(elements_id);
  113. for (auto& uninit : table) {
  114. uninit = SemIR::InstId::ImplWitnessTablePlaceholder;
  115. }
  116. auto witness_table_inst_id = AddInst<SemIR::ImplWitnessTable>(
  117. context, witness_loc_id,
  118. {.elements_id = elements_id, .impl_id = SemIR::ImplId::None});
  119. witness_inst_id = AddInst<SemIR::ImplWitness>(
  120. context, witness_loc_id,
  121. {.type_id = GetSingletonType(context, SemIR::WitnessType::TypeInstId),
  122. .witness_table_id = witness_table_inst_id,
  123. .specific_id = self_specific_id});
  124. }
  125. for (auto rewrite : rewrites_into_interface_to_witness) {
  126. auto access = context.insts().GetAs<SemIR::ImplWitnessAccess>(
  127. GetImplWitnessAccessWithoutSubstitution(context, rewrite.lhs_id));
  128. auto& table_entry = table[access.index.index];
  129. if (table_entry == SemIR::ErrorInst::InstId) {
  130. // Don't overwrite an error value. This prioritizes not generating
  131. // multiple errors for one associated constant over picking a value
  132. // for it to use to attempt recovery.
  133. continue;
  134. }
  135. auto rewrite_inst_id = rewrite.rhs_id;
  136. if (rewrite_inst_id == SemIR::ErrorInst::InstId) {
  137. table_entry = SemIR::ErrorInst::InstId;
  138. continue;
  139. }
  140. auto decl_id = context.constant_values().GetConstantInstId(
  141. assoc_entities[access.index.index]);
  142. CARBON_CHECK(decl_id.has_value(), "Non-constant associated entity");
  143. if (decl_id == SemIR::ErrorInst::InstId) {
  144. table_entry = SemIR::ErrorInst::InstId;
  145. continue;
  146. }
  147. auto assoc_constant_decl =
  148. context.insts().TryGetAs<SemIR::AssociatedConstantDecl>(decl_id);
  149. if (!assoc_constant_decl) {
  150. auto type_id = context.insts().Get(decl_id).type_id();
  151. auto type_inst = context.types().GetAsInst(type_id);
  152. auto fn_type = type_inst.As<SemIR::FunctionType>();
  153. const auto& fn = context.functions().Get(fn_type.function_id);
  154. CARBON_DIAGNOSTIC(RewriteForAssociatedFunction, Error,
  155. "rewrite specified for associated function {0}",
  156. SemIR::NameId);
  157. context.emitter().Emit(facet_type_inst_id, RewriteForAssociatedFunction,
  158. fn.name_id);
  159. table_entry = SemIR::ErrorInst::InstId;
  160. continue;
  161. }
  162. // FacetTypes resolution disallows two rewrites to the same associated
  163. // constant, so we won't ever have a facet write twice to the same position
  164. // in the witness table.
  165. CARBON_CHECK(table_entry == SemIR::InstId::ImplWitnessTablePlaceholder);
  166. // If the associated constant has a symbolic type, convert the rewrite
  167. // value to that type now we know the value of `Self`.
  168. SemIR::TypeId assoc_const_type_id = assoc_constant_decl->type_id;
  169. if (assoc_const_type_id.is_symbolic()) {
  170. // Get the type of the associated constant in this interface with this
  171. // value for `Self`.
  172. assoc_const_type_id = GetTypeForSpecificAssociatedEntity(
  173. context, SemIR::LocId(facet_type_inst_id),
  174. interface_to_witness.specific_id, decl_id,
  175. context.types().GetTypeIdForTypeInstId(self_type_inst_id),
  176. witness_inst_id);
  177. // Perform the conversion of the value to the type. We skipped this when
  178. // forming the facet type because the type of the associated constant
  179. // was symbolic.
  180. auto converted_inst_id =
  181. ConvertToValueOfType(context, SemIR::LocId(facet_type_inst_id),
  182. rewrite_inst_id, assoc_const_type_id);
  183. // Canonicalize the converted constant value.
  184. converted_inst_id =
  185. context.constant_values().GetConstantInstId(converted_inst_id);
  186. // The result of conversion can be non-constant even if the original
  187. // value was constant.
  188. if (converted_inst_id.has_value()) {
  189. rewrite_inst_id = converted_inst_id;
  190. } else {
  191. const auto& assoc_const = context.associated_constants().Get(
  192. assoc_constant_decl->assoc_const_id);
  193. CARBON_DIAGNOSTIC(
  194. AssociatedConstantNotConstantAfterConversion, Error,
  195. "associated constant {0} given value {1} that is not constant "
  196. "after conversion to {2}",
  197. SemIR::NameId, InstIdAsConstant, SemIR::TypeId);
  198. context.emitter().Emit(
  199. facet_type_inst_id, AssociatedConstantNotConstantAfterConversion,
  200. assoc_const.name_id, rewrite_inst_id, assoc_const_type_id);
  201. rewrite_inst_id = SemIR::ErrorInst::InstId;
  202. }
  203. }
  204. CARBON_CHECK(rewrite_inst_id == context.constant_values().GetConstantInstId(
  205. rewrite_inst_id),
  206. "Rewritten value for associated constant is not canonical.");
  207. table_entry = AddInst<SemIR::ImplWitnessAssociatedConstant>(
  208. context, witness_loc_id,
  209. {.type_id = context.insts().Get(rewrite_inst_id).type_id(),
  210. .inst_id = rewrite_inst_id});
  211. }
  212. return witness_inst_id;
  213. }
  214. // A mapping of each associated constant (represented as `ImplWitnessAccess`) to
  215. // its value (represented as an `InstId`). Used to track rewrite constraints,
  216. // with the LHS mapping to the resolved value of the RHS.
  217. class AccessRewriteValues {
  218. public:
  219. enum State {
  220. NotRewritten,
  221. BeingRewritten,
  222. FullyRewritten,
  223. };
  224. struct Value {
  225. State state;
  226. SemIR::InstId inst_id;
  227. };
  228. auto InsertNotRewritten(
  229. Context& context, SemIR::KnownInstId<SemIR::ImplWitnessAccess> access_id,
  230. SemIR::InstId inst_id) -> void {
  231. map_.Insert(context.constant_values().Get(access_id),
  232. {NotRewritten, inst_id});
  233. }
  234. // Finds and returns a pointer into the cache for a given ImplWitnessAccess.
  235. // The pointer will be invalidated by mutating the cache. Returns `nullptr`
  236. // if `access` is not found.
  237. auto FindRef(Context& context,
  238. SemIR::KnownInstId<SemIR::ImplWitnessAccess> access_id)
  239. -> Value* {
  240. auto result = map_.Lookup(context.constant_values().Get(access_id));
  241. if (!result) {
  242. return nullptr;
  243. }
  244. return &result.value();
  245. }
  246. auto SetBeingRewritten(Value& value) -> void {
  247. if (value.state == NotRewritten) {
  248. value.state = BeingRewritten;
  249. }
  250. }
  251. auto SetFullyRewritten(Context& context, Value& value, SemIR::InstId inst_id)
  252. -> void {
  253. if (value.state == FullyRewritten) {
  254. CARBON_CHECK(context.constant_values().Get(value.inst_id) ==
  255. context.constant_values().Get(inst_id));
  256. }
  257. value = {FullyRewritten, inst_id};
  258. }
  259. private:
  260. // Try avoid heap allocations in the common case where there are a small
  261. // number of rewrite rules referring to each other by keeping up to 16 on
  262. // the stack.
  263. //
  264. // TODO: Revisit if 16 is an appropriate number when we can measure how deep
  265. // rewrite constraint chains go in practice.
  266. Map<SemIR::ConstantId, Value, 16> map_;
  267. };
  268. // To be used for substituting into the RHS of a rewrite constraint.
  269. //
  270. // It will substitute any `ImplWitnessAccess` into `.Self` (a reference to an
  271. // associated constant) with the RHS of another rewrite constraint that writes
  272. // to the same associated constant. For example:
  273. // ```
  274. // Z where .X = () and .Y = .X
  275. // ```
  276. // Here the second `.X` is an `ImplWitnessAccess` which would be substituted by
  277. // finding the first rewrite constraint, where the LHS is for the same
  278. // associated constant and using its RHS. So the substitution would produce:
  279. // ```
  280. // Z where .X = () and .Y = ()
  281. // ```
  282. //
  283. // This additionally diagnoses cycles when the `ImplWitnessAccess` is reading
  284. // from the same rewrite constraint, and is thus assigning to the associated
  285. // constant a value that refers to the same associated constant, such as with `Z
  286. // where .X = C(.X)`. In the event of a cycle, the `ImplWitnessAccess` is
  287. // replaced with `ErrorInst` so that further evaluation of the
  288. // `ImplWitnessAccess` will not loop infinitely.
  289. //
  290. // The `rewrite_values` given to the constructor must be set up initially with
  291. // each rewrite rule of an associated constant inserted with its unresolved
  292. // value via `InsertNotRewritten`. Then for each rewrite rule of an associated
  293. // constant, the LHS access should be set as being rewritten with its state
  294. // changed to `BeingRewritten` in order to detect cycles before performing
  295. // SubstInst. The result of SubstInst should be preserved afterward by changing
  296. // the state and value for the LHS to `FullyRewritten` and the subst output
  297. // instruction, respectively, to avoid duplicating work.
  298. class SubstImplWitnessAccessCallbacks : public SubstInstCallbacks {
  299. public:
  300. explicit SubstImplWitnessAccessCallbacks(Context* context,
  301. SemIR::LocId loc_id,
  302. AccessRewriteValues* rewrite_values)
  303. : SubstInstCallbacks(context),
  304. loc_id_(loc_id),
  305. rewrite_values_(rewrite_values) {}
  306. auto Subst(SemIR::InstId& rhs_inst_id) -> SubstResult override {
  307. auto rhs_access =
  308. context().insts().TryGetAsWithId<SemIR::ImplWitnessAccess>(rhs_inst_id);
  309. if (!rhs_access) {
  310. // We only want to substitute ImplWitnessAccesses written directly on the
  311. // RHS of the rewrite constraint, not when they are nested inside facet
  312. // types that are part of the RHS, like `.X = C as (I where .Y = {})`.
  313. if (context().insts().Is<SemIR::FacetType>(rhs_inst_id)) {
  314. return SubstResult::FullySubstituted;
  315. }
  316. if (context().constant_values().Get(rhs_inst_id).is_concrete()) {
  317. // There's no ImplWitnessAccess that we care about inside this
  318. // instruction.
  319. return SubstResult::FullySubstituted;
  320. }
  321. if (auto subst =
  322. context().insts().TryGetAs<SemIR::ImplWitnessAccessSubstituted>(
  323. rhs_inst_id)) {
  324. // The reference to an associated constant was eagerly replaced with the
  325. // value of an earlier rewrite constraint, but may need further
  326. // substitution if it contains an `ImplWitnessAccess`.
  327. rhs_inst_id = subst->value_id;
  328. substs_in_progress_.push_back(rhs_inst_id);
  329. return SubstResult::SubstAgain;
  330. }
  331. // SubstOperands will result in a Rebuild or ReuseUnchanged callback, so
  332. // push the non-ImplWitnessAccess to get proper bracketing, allowing us
  333. // to pop it in the paired callback.
  334. substs_in_progress_.push_back(rhs_inst_id);
  335. return SubstResult::SubstOperands;
  336. }
  337. // If the access is going through a nested `ImplWitnessAccess`, that
  338. // access needs to be resolved to a facet value first. If it can't be
  339. // resolved then the outer one can not be either.
  340. if (auto lookup = context().insts().TryGetAs<SemIR::LookupImplWitness>(
  341. rhs_access->inst.witness_id)) {
  342. if (context().insts().Is<SemIR::ImplWitnessAccess>(
  343. lookup->query_self_inst_id)) {
  344. substs_in_progress_.push_back(rhs_inst_id);
  345. return SubstResult::SubstOperandsAndRetry;
  346. }
  347. }
  348. auto* rewrite_value =
  349. rewrite_values_->FindRef(context(), rhs_access->inst_id);
  350. if (!rewrite_value) {
  351. // The RHS refers to an associated constant for which there is no rewrite
  352. // rule.
  353. return SubstResult::FullySubstituted;
  354. }
  355. // Diagnose a cycle if the RHS refers to something that depends on the value
  356. // of the RHS.
  357. if (rewrite_value->state == AccessRewriteValues::BeingRewritten) {
  358. CARBON_DIAGNOSTIC(FacetTypeConstraintCycle, Error,
  359. "found cycle in facet type constraint for {0}",
  360. InstIdAsConstant);
  361. // TODO: It would be nice to note the places where the values are
  362. // assigned but rewrite constraint instructions are from canonical
  363. // constant values, and have no locations. We'd need to store a location
  364. // along with them in the rewrite constraints, and track propagation of
  365. // locations here, which may imply heap allocations.
  366. context().emitter().Emit(loc_id_, FacetTypeConstraintCycle, rhs_inst_id);
  367. rhs_inst_id = SemIR::ErrorInst::InstId;
  368. return SubstResult::FullySubstituted;
  369. } else if (rewrite_value->state == AccessRewriteValues::FullyRewritten) {
  370. rhs_inst_id = rewrite_value->inst_id;
  371. return SubstResult::FullySubstituted;
  372. }
  373. // We have a non-rewritten RHS. We need to recurse on rewriting it. Reuse
  374. // the previous lookup by mutating it in place.
  375. rewrite_values_->SetBeingRewritten(*rewrite_value);
  376. // The ImplWitnessAccess was replaced with some other instruction, which may
  377. // contain or be another ImplWitnessAccess. Keep track of the associated
  378. // constant we are now computing the value of.
  379. substs_in_progress_.push_back(rhs_inst_id);
  380. rhs_inst_id = rewrite_value->inst_id;
  381. return SubstResult::SubstAgain;
  382. }
  383. auto Rebuild(SemIR::InstId /*orig_inst_id*/, SemIR::Inst new_inst)
  384. -> SemIR::InstId override {
  385. auto inst_id = RebuildNewInst(loc_id_, new_inst);
  386. auto subst_inst_id = substs_in_progress_.pop_back_val();
  387. if (auto access =
  388. context().insts().TryGetAsWithId<SemIR::ImplWitnessAccess>(
  389. subst_inst_id)) {
  390. if (auto* rewrite_value =
  391. rewrite_values_->FindRef(context(), access->inst_id)) {
  392. rewrite_values_->SetFullyRewritten(context(), *rewrite_value, inst_id);
  393. }
  394. }
  395. return inst_id;
  396. }
  397. auto ReuseUnchanged(SemIR::InstId orig_inst_id) -> SemIR::InstId override {
  398. auto subst_inst_id = substs_in_progress_.pop_back_val();
  399. if (auto access =
  400. context().insts().TryGetAsWithId<SemIR::ImplWitnessAccess>(
  401. subst_inst_id)) {
  402. if (auto* rewrite_value =
  403. rewrite_values_->FindRef(context(), access->inst_id)) {
  404. rewrite_values_->SetFullyRewritten(context(), *rewrite_value,
  405. orig_inst_id);
  406. }
  407. }
  408. return orig_inst_id;
  409. }
  410. private:
  411. struct SubstInProgress {
  412. // The associated constant whose value is being determined, represented as
  413. // an ImplWitnessAccess. Or another instruction that we are recursing
  414. // through.
  415. SemIR::InstId inst_id;
  416. };
  417. // The location of the rewrite constraints as a whole.
  418. SemIR::LocId loc_id_;
  419. // Tracks the resolved value of each rewrite constraint, keyed by the
  420. // `ImplWitnessAccess` of the associated constant on the LHS of the
  421. // constraint. The value of each associated constant may be changed during
  422. // substitution, replaced with a fully resolved value for the RHS. This allows
  423. // us to cache work; when a value for an associated constant is found once it
  424. // can be reused cheaply, avoiding exponential runtime when rewrite rules
  425. // refer to each other in ways that create exponential references.
  426. AccessRewriteValues* rewrite_values_;
  427. // A stack of instructions being replaced in Subst(). When it's an associated
  428. // constant, then it represents the constant value is being determined,
  429. // represented as an ImplWitnessAccess.
  430. //
  431. // Avoid heap allocations in common cases, if there are chains of instructions
  432. // in associated constants with a depth at most 16.
  433. llvm::SmallVector<SemIR::InstId, 16> substs_in_progress_;
  434. };
  435. auto ResolveFacetTypeRewriteConstraints(
  436. Context& context, SemIR::LocId loc_id,
  437. llvm::SmallVector<SemIR::FacetTypeInfo::RewriteConstraint>& rewrites)
  438. -> bool {
  439. if (rewrites.empty()) {
  440. return true;
  441. }
  442. AccessRewriteValues rewrite_values;
  443. for (auto& constraint : rewrites) {
  444. auto lhs_access = context.insts().TryGetAsWithId<SemIR::ImplWitnessAccess>(
  445. GetImplWitnessAccessWithoutSubstitution(context, constraint.lhs_id));
  446. if (!lhs_access) {
  447. continue;
  448. }
  449. rewrite_values.InsertNotRewritten(context, lhs_access->inst_id,
  450. constraint.rhs_id);
  451. }
  452. for (auto& constraint : rewrites) {
  453. auto lhs_access = context.insts().TryGetAsWithId<SemIR::ImplWitnessAccess>(
  454. GetImplWitnessAccessWithoutSubstitution(context, constraint.lhs_id));
  455. if (!lhs_access) {
  456. continue;
  457. }
  458. auto* lhs_rewrite_value =
  459. rewrite_values.FindRef(context, lhs_access->inst_id);
  460. // Every LHS was added with InsertNotRewritten above.
  461. CARBON_CHECK(lhs_rewrite_value);
  462. rewrite_values.SetBeingRewritten(*lhs_rewrite_value);
  463. auto replace_witness_callbacks =
  464. SubstImplWitnessAccessCallbacks(&context, loc_id, &rewrite_values);
  465. auto rhs_subst_inst_id =
  466. SubstInst(context, constraint.rhs_id, replace_witness_callbacks);
  467. if (rhs_subst_inst_id == SemIR::ErrorInst::InstId) {
  468. return false;
  469. }
  470. if (lhs_rewrite_value->state == AccessRewriteValues::FullyRewritten) {
  471. auto rhs_existing_const_id =
  472. context.constant_values().Get(lhs_rewrite_value->inst_id);
  473. auto rhs_subst_const_id =
  474. context.constant_values().Get(rhs_subst_inst_id);
  475. if (rhs_subst_const_id != rhs_existing_const_id) {
  476. if (rhs_existing_const_id != SemIR::ErrorInst::ConstantId) {
  477. CARBON_DIAGNOSTIC(AssociatedConstantWithDifferentValues, Error,
  478. "associated constant {0} given two different "
  479. "values {1} and {2}",
  480. InstIdAsConstant, InstIdAsConstant,
  481. InstIdAsConstant);
  482. // Use inst id ordering as a simple proxy for source ordering, to
  483. // try to name the values in the same order they appear in the facet
  484. // type.
  485. auto source_order1 =
  486. lhs_rewrite_value->inst_id.index < rhs_subst_inst_id.index
  487. ? lhs_rewrite_value->inst_id
  488. : rhs_subst_inst_id;
  489. auto source_order2 =
  490. lhs_rewrite_value->inst_id.index >= rhs_subst_inst_id.index
  491. ? lhs_rewrite_value->inst_id
  492. : rhs_subst_inst_id;
  493. // TODO: It would be nice to note the places where the values are
  494. // assigned but rewrite constraint instructions are from canonical
  495. // constant values, and have no locations. We'd need to store a
  496. // location along with them in the rewrite constraints.
  497. context.emitter().Emit(loc_id, AssociatedConstantWithDifferentValues,
  498. GetImplWitnessAccessWithoutSubstitution(
  499. context, constraint.lhs_id),
  500. source_order1, source_order2);
  501. }
  502. return false;
  503. }
  504. }
  505. rewrite_values.SetFullyRewritten(context, *lhs_rewrite_value,
  506. rhs_subst_inst_id);
  507. }
  508. // Rebuild the `rewrites` vector with resolved values for the RHS. Drop any
  509. // duplicate rewrites in the `rewrites` vector by walking through the
  510. // `rewrite_values` map and dropping the computed RHS value for each LHS the
  511. // first time we see it, and erasing the constraint from the vector if we see
  512. // the same LHS again.
  513. size_t keep_size = rewrites.size();
  514. for (size_t i = 0; i < keep_size;) {
  515. auto& constraint = rewrites[i];
  516. auto lhs_access = context.insts().TryGetAsWithId<SemIR::ImplWitnessAccess>(
  517. GetImplWitnessAccessWithoutSubstitution(context, constraint.lhs_id));
  518. if (!lhs_access) {
  519. ++i;
  520. continue;
  521. }
  522. auto& rewrite_value = *rewrite_values.FindRef(context, lhs_access->inst_id);
  523. auto rhs_id = std::exchange(rewrite_value.inst_id, SemIR::InstId::None);
  524. if (rhs_id == SemIR::InstId::None) {
  525. std::swap(rewrites[i], rewrites[keep_size - 1]);
  526. --keep_size;
  527. } else {
  528. rewrites[i].rhs_id = rhs_id;
  529. ++i;
  530. }
  531. }
  532. rewrites.erase(rewrites.begin() + keep_size, rewrites.end());
  533. return true;
  534. }
  535. auto MakePeriodSelfFacetValue(Context& context, SemIR::TypeId self_type_id)
  536. -> SemIR::InstId {
  537. auto entity_name_id = context.entity_names().AddCanonical({
  538. .name_id = SemIR::NameId::PeriodSelf,
  539. .parent_scope_id = context.scope_stack().PeekNameScopeId(),
  540. });
  541. auto inst_id = AddInst(
  542. context, SemIR::LocIdAndInst::NoLoc<SemIR::SymbolicBinding>({
  543. .type_id = self_type_id,
  544. .entity_name_id = entity_name_id,
  545. // `None` because there is no equivalent non-symbolic value.
  546. .value_id = SemIR::InstId::None,
  547. }));
  548. auto existing =
  549. context.scope_stack().LookupOrAddName(SemIR::NameId::PeriodSelf, inst_id);
  550. // Shouldn't have any names in newly created scope.
  551. CARBON_CHECK(!existing.has_value());
  552. return inst_id;
  553. }
  554. } // namespace Carbon::Check