facet_type.cpp 26 KB

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