facet_type.cpp 27 KB

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