facet_type.cpp 26 KB

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