facet_type.cpp 27 KB

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