facet_type.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  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 "toolchain/check/convert.h"
  6. #include "toolchain/check/diagnostic_helpers.h"
  7. #include "toolchain/check/generic.h"
  8. #include "toolchain/check/import_ref.h"
  9. #include "toolchain/check/inst.h"
  10. #include "toolchain/check/interface.h"
  11. #include "toolchain/check/subst.h"
  12. #include "toolchain/check/type.h"
  13. #include "toolchain/check/type_completion.h"
  14. #include "toolchain/sem_ir/ids.h"
  15. #include "toolchain/sem_ir/typed_insts.h"
  16. namespace Carbon::Check {
  17. auto FacetTypeFromInterface(Context& context, SemIR::InterfaceId interface_id,
  18. SemIR::SpecificId specific_id) -> SemIR::FacetType {
  19. SemIR::FacetTypeId facet_type_id = context.facet_types().Add(
  20. SemIR::FacetTypeInfo{.extend_constraints = {{interface_id, specific_id}},
  21. .other_requirements = false});
  22. return {.type_id = SemIR::TypeType::TypeId, .facet_type_id = facet_type_id};
  23. }
  24. // Returns whether the `LookupImplWitness` of `witness_id` matches `interface`.
  25. static auto WitnessQueryMatchesInterface(
  26. Context& context, SemIR::InstId witness_id,
  27. const SemIR::SpecificInterface& interface) -> bool {
  28. auto lookup = context.insts().GetAs<SemIR::LookupImplWitness>(witness_id);
  29. return interface ==
  30. context.specific_interfaces().Get(lookup.query_specific_interface_id);
  31. }
  32. static auto IncompleteFacetTypeDiagnosticBuilder(
  33. Context& context, SemIR::LocId loc_id, SemIR::TypeInstId facet_type_inst_id,
  34. bool is_definition) -> DiagnosticBuilder {
  35. if (is_definition) {
  36. CARBON_DIAGNOSTIC(ImplAsIncompleteFacetTypeDefinition, Error,
  37. "definition of impl as incomplete facet type {0}",
  38. InstIdAsType);
  39. return context.emitter().Build(loc_id, ImplAsIncompleteFacetTypeDefinition,
  40. facet_type_inst_id);
  41. } else {
  42. CARBON_DIAGNOSTIC(
  43. ImplAsIncompleteFacetTypeRewrites, Error,
  44. "declaration of impl as incomplete facet type {0} with rewrites",
  45. InstIdAsType);
  46. return context.emitter().Build(loc_id, ImplAsIncompleteFacetTypeRewrites,
  47. facet_type_inst_id);
  48. }
  49. }
  50. auto InitialFacetTypeImplWitness(
  51. Context& context, SemIR::LocId witness_loc_id,
  52. SemIR::TypeInstId facet_type_inst_id, SemIR::TypeInstId self_type_inst_id,
  53. const SemIR::SpecificInterface& interface_to_witness,
  54. SemIR::SpecificId self_specific_id, bool is_definition) -> SemIR::InstId {
  55. // TODO: Finish facet type resolution. This code currently only handles
  56. // rewrite constraints that set associated constants to a concrete value.
  57. // Need logic to topologically sort rewrites to respect dependencies, and
  58. // afterwards reject duplicates that are not identical.
  59. auto facet_type_id =
  60. context.types().GetTypeIdForTypeInstId(facet_type_inst_id);
  61. CARBON_CHECK(facet_type_id != SemIR::ErrorInst::TypeId);
  62. auto facet_type = context.types().GetAs<SemIR::FacetType>(facet_type_id);
  63. // TODO: This is currently a copy because I'm not sure whether anything could
  64. // cause the facet type store to resize before we are done with it.
  65. auto facet_type_info = context.facet_types().Get(facet_type.facet_type_id);
  66. if (!is_definition && facet_type_info.rewrite_constraints.empty()) {
  67. auto witness_table_inst_id = AddInst<SemIR::ImplWitnessTable>(
  68. context, witness_loc_id,
  69. {.elements_id = context.inst_blocks().AddPlaceholder(),
  70. .impl_id = SemIR::ImplId::None});
  71. return AddInst<SemIR::ImplWitness>(
  72. context, witness_loc_id,
  73. {.type_id = GetSingletonType(context, SemIR::WitnessType::TypeInstId),
  74. .witness_table_id = witness_table_inst_id,
  75. .specific_id = self_specific_id});
  76. }
  77. if (!RequireCompleteType(
  78. context, facet_type_id, SemIR::LocId(facet_type_inst_id), [&] {
  79. return IncompleteFacetTypeDiagnosticBuilder(
  80. context, witness_loc_id, facet_type_inst_id, is_definition);
  81. })) {
  82. return SemIR::ErrorInst::InstId;
  83. }
  84. const auto& interface =
  85. context.interfaces().Get(interface_to_witness.interface_id);
  86. auto assoc_entities =
  87. context.inst_blocks().Get(interface.associated_entities_id);
  88. // TODO: When this function is used for things other than just impls, may want
  89. // to only load the specific associated entities that are mentioned in rewrite
  90. // rules.
  91. for (auto decl_id : assoc_entities) {
  92. LoadImportRef(context, decl_id);
  93. }
  94. SemIR::InstId witness_inst_id = SemIR::InstId::None;
  95. llvm::MutableArrayRef<SemIR::InstId> table;
  96. {
  97. auto elements_id =
  98. context.inst_blocks().AddUninitialized(assoc_entities.size());
  99. table = context.inst_blocks().GetMutable(elements_id);
  100. for (auto& uninit : table) {
  101. uninit = SemIR::ImplWitnessTablePlaceholder::TypeInstId;
  102. }
  103. auto witness_table_inst_id = AddInst<SemIR::ImplWitnessTable>(
  104. context, witness_loc_id,
  105. {.elements_id = elements_id, .impl_id = SemIR::ImplId::None});
  106. witness_inst_id = AddInst<SemIR::ImplWitness>(
  107. context, witness_loc_id,
  108. {.type_id = GetSingletonType(context, SemIR::WitnessType::TypeInstId),
  109. .witness_table_id = witness_table_inst_id,
  110. .specific_id = self_specific_id});
  111. }
  112. for (auto rewrite : facet_type_info.rewrite_constraints) {
  113. auto access =
  114. context.insts().GetAs<SemIR::ImplWitnessAccess>(rewrite.lhs_id);
  115. if (!WitnessQueryMatchesInterface(context, access.witness_id,
  116. interface_to_witness)) {
  117. continue;
  118. }
  119. auto& table_entry = table[access.index.index];
  120. if (table_entry == SemIR::ErrorInst::InstId) {
  121. // Don't overwrite an error value. This prioritizes not generating
  122. // multiple errors for one associated constant over picking a value
  123. // for it to use to attempt recovery.
  124. continue;
  125. }
  126. auto rewrite_inst_id = rewrite.rhs_id;
  127. if (rewrite_inst_id == SemIR::ErrorInst::InstId) {
  128. table_entry = SemIR::ErrorInst::InstId;
  129. continue;
  130. }
  131. auto decl_id = context.constant_values().GetConstantInstId(
  132. assoc_entities[access.index.index]);
  133. CARBON_CHECK(decl_id.has_value(), "Non-constant associated entity");
  134. if (decl_id == SemIR::ErrorInst::InstId) {
  135. table_entry = SemIR::ErrorInst::InstId;
  136. continue;
  137. }
  138. auto assoc_constant_decl =
  139. context.insts().TryGetAs<SemIR::AssociatedConstantDecl>(decl_id);
  140. if (!assoc_constant_decl) {
  141. auto type_id = context.insts().Get(decl_id).type_id();
  142. auto type_inst = context.types().GetAsInst(type_id);
  143. auto fn_type = type_inst.As<SemIR::FunctionType>();
  144. const auto& fn = context.functions().Get(fn_type.function_id);
  145. CARBON_DIAGNOSTIC(RewriteForAssociatedFunction, Error,
  146. "rewrite specified for associated function {0}",
  147. SemIR::NameId);
  148. context.emitter().Emit(facet_type_inst_id, RewriteForAssociatedFunction,
  149. fn.name_id);
  150. table_entry = SemIR::ErrorInst::InstId;
  151. continue;
  152. }
  153. // FacetTypes resolution disallows two rewrites to the same associated
  154. // constant, so we won't ever have a facet write twice to the same position
  155. // in the witness table.
  156. CARBON_CHECK(table_entry == SemIR::ImplWitnessTablePlaceholder::TypeInstId);
  157. // If the associated constant has a symbolic type, convert the rewrite
  158. // value to that type now we know the value of `Self`.
  159. SemIR::TypeId assoc_const_type_id = assoc_constant_decl->type_id;
  160. if (assoc_const_type_id.is_symbolic()) {
  161. // Get the type of the associated constant in this interface with this
  162. // value for `Self`.
  163. assoc_const_type_id = GetTypeForSpecificAssociatedEntity(
  164. context, SemIR::LocId(facet_type_inst_id),
  165. interface_to_witness.specific_id, decl_id,
  166. context.types().GetTypeIdForTypeInstId(self_type_inst_id),
  167. witness_inst_id);
  168. // Perform the conversion of the value to the type. We skipped this when
  169. // forming the facet type because the type of the associated constant
  170. // was symbolic.
  171. auto converted_inst_id =
  172. ConvertToValueOfType(context, SemIR::LocId(facet_type_inst_id),
  173. rewrite_inst_id, assoc_const_type_id);
  174. // Canonicalize the converted constant value.
  175. converted_inst_id =
  176. context.constant_values().GetConstantInstId(converted_inst_id);
  177. // The result of conversion can be non-constant even if the original
  178. // value was constant.
  179. if (converted_inst_id.has_value()) {
  180. rewrite_inst_id = converted_inst_id;
  181. } else {
  182. const auto& assoc_const = context.associated_constants().Get(
  183. assoc_constant_decl->assoc_const_id);
  184. CARBON_DIAGNOSTIC(
  185. AssociatedConstantNotConstantAfterConversion, Error,
  186. "associated constant {0} given value {1} that is not constant "
  187. "after conversion to {2}",
  188. SemIR::NameId, InstIdAsConstant, SemIR::TypeId);
  189. context.emitter().Emit(
  190. facet_type_inst_id, AssociatedConstantNotConstantAfterConversion,
  191. assoc_const.name_id, rewrite_inst_id, assoc_const_type_id);
  192. rewrite_inst_id = SemIR::ErrorInst::InstId;
  193. }
  194. }
  195. CARBON_CHECK(rewrite_inst_id == context.constant_values().GetConstantInstId(
  196. rewrite_inst_id),
  197. "Rewritten value for associated constant is not canonical.");
  198. table_entry = AddInst<SemIR::ImplWitnessAssociatedConstant>(
  199. context, witness_loc_id,
  200. {.type_id = context.insts().Get(rewrite_inst_id).type_id(),
  201. .inst_id = rewrite_inst_id});
  202. }
  203. return witness_inst_id;
  204. }
  205. auto RequireCompleteFacetTypeForImplDefinition(
  206. Context& context, SemIR::LocId loc_id, SemIR::TypeInstId facet_type_inst_id)
  207. -> bool {
  208. auto facet_type_id =
  209. context.types().GetTypeIdForTypeInstId(facet_type_inst_id);
  210. return RequireCompleteType(
  211. context, facet_type_id, SemIR::LocId(facet_type_inst_id), [&] {
  212. return IncompleteFacetTypeDiagnosticBuilder(context, loc_id,
  213. facet_type_inst_id,
  214. /*is_definition=*/true);
  215. });
  216. }
  217. auto AllocateFacetTypeImplWitness(Context& context,
  218. SemIR::InterfaceId interface_id,
  219. SemIR::InstBlockId witness_id) -> void {
  220. const auto& interface = context.interfaces().Get(interface_id);
  221. CARBON_CHECK(interface.is_complete());
  222. auto assoc_entities =
  223. context.inst_blocks().Get(interface.associated_entities_id);
  224. for (auto decl_id : assoc_entities) {
  225. LoadImportRef(context, decl_id);
  226. }
  227. llvm::SmallVector<SemIR::InstId> empty_table(
  228. assoc_entities.size(), SemIR::ImplWitnessTablePlaceholder::TypeInstId);
  229. context.inst_blocks().ReplacePlaceholder(witness_id, empty_table);
  230. }
  231. auto IsPeriodSelf(Context& context, SemIR::ConstantId const_id) -> bool {
  232. // This also rejects the singleton Error value as it's concrete.
  233. if (!const_id.is_symbolic()) {
  234. return false;
  235. }
  236. const auto& symbolic =
  237. context.constant_values().GetSymbolicConstant(const_id);
  238. // Fast early reject before doing more expensive operations.
  239. if (symbolic.dependence != SemIR::ConstantDependence::PeriodSelf) {
  240. return false;
  241. }
  242. return IsPeriodSelf(context, symbolic.inst_id);
  243. }
  244. auto IsPeriodSelf(Context& context, SemIR::InstId inst_id) -> bool {
  245. // Unwrap the `FacetAccessType` instruction, which we get when the `.Self` is
  246. // converted to `type`.
  247. if (auto facet_access_type =
  248. context.insts().TryGetAs<SemIR::FacetAccessType>(inst_id)) {
  249. inst_id = facet_access_type->facet_value_inst_id;
  250. }
  251. if (auto bind_symbolic_name =
  252. context.insts().TryGetAs<SemIR::BindSymbolicName>(inst_id)) {
  253. const auto& bind_name =
  254. context.entity_names().Get(bind_symbolic_name->entity_name_id);
  255. return bind_name.name_id == SemIR::NameId::PeriodSelf;
  256. }
  257. return false;
  258. }
  259. // If `inst_id` is the ID of an `ImplWitnessAccess` into `.Self`, return it.
  260. // Otherwise, returns `nullopt`.
  261. static auto TryGetImplWitnessAccessOfPeriodSelf(Context& context,
  262. SemIR::InstId inst_id)
  263. -> std::optional<SemIR::ImplWitnessAccess> {
  264. auto lhs_access = context.insts().TryGetAs<SemIR::ImplWitnessAccess>(inst_id);
  265. if (!lhs_access) {
  266. return std::nullopt;
  267. }
  268. auto lhs_lookup = context.insts().TryGetAs<SemIR::LookupImplWitness>(
  269. lhs_access->witness_id);
  270. if (!lhs_lookup) {
  271. return std::nullopt;
  272. }
  273. if (!IsPeriodSelf(context, lhs_lookup->query_self_inst_id)) {
  274. return std::nullopt;
  275. }
  276. return lhs_access;
  277. }
  278. // To be used for substituting into the RHS of a rewrite constraint.
  279. //
  280. // It will substitute any `ImplWitnessAccess` into `.Self` (a reference to an
  281. // associated constant) with the RHS of another rewrite constraint that writes
  282. // to the same associated constant. For example:
  283. // ```
  284. // Z where .X = () and .Y = .X
  285. // ```
  286. // Here the second `.X` is an `ImplWitnessAccess` which would be substituted by
  287. // finding the first rewrite constraint, where the LHS is for the same
  288. // associated constant and using its RHS. So the substitution would produce:
  289. // ```
  290. // Z where .X = () and .Y = ()
  291. // ```
  292. //
  293. // This additionally diagnoses cycles when the `ImplWitnessAccess` is reading
  294. // from the same rewrite constraint, and is thus assigning to the associated
  295. // constant a value that refers to the same associated constant, such as with
  296. // `Z where .X = C(.X)`. In the event of a cycle, the `ImplWitnessAccess` is
  297. // replaced with `ErrorInst` so that further evaluation of the
  298. // `ImplWitnessAccess` will not loop infinitely.
  299. class SubstImplWitnessAccessCallbacks : public SubstInstCallbacks {
  300. public:
  301. // The `facet_type_info` is for the facet whose rewrite constraints are being
  302. // substituted, and where it looks for rewritten values to substitute from.
  303. //
  304. // The `substituting_constraint` is the rewrite constraint for which the RHS
  305. // is being substituted with the value from another rewrite constraint, if
  306. // possible. That is, `.Y = .X` in the example in the class docs.
  307. explicit SubstImplWitnessAccessCallbacks(
  308. Context* context, SemIR::LocId loc_id,
  309. const SemIR::FacetTypeInfo* facet_type_info,
  310. const SemIR::FacetTypeInfo::RewriteConstraint* substituting_constraint)
  311. : SubstInstCallbacks(context),
  312. loc_id_(loc_id),
  313. facet_type_info_(*facet_type_info),
  314. substituting_constraint_(substituting_constraint) {}
  315. auto Subst(SemIR::InstId& rhs_inst_id) const -> bool override {
  316. if (context().constant_values().Get(rhs_inst_id).is_concrete()) {
  317. return true;
  318. }
  319. auto rhs_access =
  320. TryGetImplWitnessAccessOfPeriodSelf(context(), rhs_inst_id);
  321. if (!rhs_access) {
  322. return false;
  323. }
  324. // TODO: We could consider replacing this loop, which makes for an O(N^2)
  325. // algorithm with something more efficient for searching, such as a map.
  326. // However that would probably require heap allocations which may be worse
  327. // overall since the number of rewrite constraints is generally low.
  328. for (const auto& search_constraint : facet_type_info_.rewrite_constraints) {
  329. auto search_lhs_access = TryGetImplWitnessAccessOfPeriodSelf(
  330. context(), search_constraint.lhs_id);
  331. if (!search_lhs_access) {
  332. continue;
  333. }
  334. if (search_lhs_access->witness_id == rhs_access->witness_id &&
  335. search_lhs_access->index == rhs_access->index) {
  336. if (&search_constraint == substituting_constraint_) {
  337. if (search_constraint.rhs_id != SemIR::ErrorInst::InstId) {
  338. CARBON_DIAGNOSTIC(FacetTypeConstraintCycle, Error,
  339. "found cycle in facet type constraint for {0}",
  340. InstIdAsConstant);
  341. // TODO: It would be nice to note the places where the values are
  342. // assigned but rewrite constraint instructions are from canonical
  343. // constant values, and have no locations. We'd need to store a
  344. // location along with them in the rewrite constraints, and track
  345. // propagation of locations here, which may imply heap allocations.
  346. context().emitter().Emit(loc_id_, FacetTypeConstraintCycle,
  347. substituting_constraint_->lhs_id);
  348. rhs_inst_id = SemIR::ErrorInst::InstId;
  349. }
  350. } else {
  351. rhs_inst_id = search_constraint.rhs_id;
  352. }
  353. return true;
  354. }
  355. }
  356. return false;
  357. }
  358. auto Rebuild(SemIR::InstId /*orig_inst_id*/, SemIR::Inst new_inst) const
  359. -> SemIR::InstId override {
  360. return RebuildNewInst(loc_id_, new_inst);
  361. }
  362. private:
  363. SemIR::LocId loc_id_;
  364. const SemIR::FacetTypeInfo& facet_type_info_;
  365. const SemIR::FacetTypeInfo::RewriteConstraint* substituting_constraint_;
  366. };
  367. auto ResolveRewriteConstraintsAndCanonicalize(
  368. Context& context, SemIR::LocId loc_id,
  369. SemIR::FacetTypeInfo& facet_type_info) -> bool {
  370. // This operation sorts and dedupes the rewrite constraints. They are sorted
  371. // primarily by the `lhs_id`, then by the `rhs_id`.
  372. facet_type_info.Canonicalize();
  373. bool success = true;
  374. if (facet_type_info.rewrite_constraints.empty()) {
  375. return success;
  376. }
  377. for (size_t i = 0; i < facet_type_info.rewrite_constraints.size() - 1; ++i) {
  378. auto& constraint = facet_type_info.rewrite_constraints[i];
  379. if (constraint.lhs_id == SemIR::ErrorInst::InstId ||
  380. constraint.rhs_id == SemIR::ErrorInst::InstId) {
  381. continue;
  382. }
  383. auto lhs_access =
  384. TryGetImplWitnessAccessOfPeriodSelf(context, constraint.lhs_id);
  385. if (!lhs_access) {
  386. continue;
  387. }
  388. // This loop moves `i` to the last position with the same LHS value, so that
  389. // we don't diagnose more than once within the same contiguous range of
  390. // assignments to a single LHS value.
  391. for (; i < facet_type_info.rewrite_constraints.size() - 1; ++i) {
  392. auto& next = facet_type_info.rewrite_constraints[i + 1];
  393. if (constraint.lhs_id != next.lhs_id) {
  394. break;
  395. }
  396. // `constraint.lhs_id == next.lhs_id` so only check for `ErrorInst` in the
  397. // RHS. On the first error, `constraint.rhs_id` is set to `ErrorInst`
  398. // which prevents further diagnostics for the same LHS value due to this
  399. // condition.
  400. if (constraint.rhs_id != SemIR::ErrorInst::InstId &&
  401. next.rhs_id != SemIR::ErrorInst::InstId) {
  402. CARBON_DIAGNOSTIC(
  403. AssociatedConstantWithDifferentValues, Error,
  404. "associated constant {0} given two different values {1} and {2}",
  405. InstIdAsConstant, InstIdAsConstant, InstIdAsConstant);
  406. // TODO: It would be nice to note the places where the values are
  407. // assigned but rewrite constraint instructions are from canonical
  408. // constant values, and have no locations. We'd need to store a location
  409. // along with them in the rewrite constraints.
  410. context.emitter().Emit(loc_id, AssociatedConstantWithDifferentValues,
  411. constraint.lhs_id, constraint.rhs_id,
  412. next.rhs_id);
  413. }
  414. constraint.rhs_id = SemIR::ErrorInst::InstId;
  415. next.rhs_id = SemIR::ErrorInst::InstId;
  416. success = false;
  417. }
  418. }
  419. while (true) {
  420. bool applied_rewrite = false;
  421. for (auto& constraint : facet_type_info.rewrite_constraints) {
  422. if (constraint.lhs_id == SemIR::ErrorInst::InstId ||
  423. constraint.rhs_id == SemIR::ErrorInst::InstId) {
  424. continue;
  425. }
  426. auto lhs_access =
  427. TryGetImplWitnessAccessOfPeriodSelf(context, constraint.lhs_id);
  428. if (!lhs_access) {
  429. continue;
  430. }
  431. // Replace any `ImplWitnessAccess` in the RHS of this constraint with the
  432. // RHS of another constraint that sets the value of the associated
  433. // constant being accessed in the RHS.
  434. auto subst_inst_id =
  435. SubstInst(context, constraint.rhs_id,
  436. SubstImplWitnessAccessCallbacks(
  437. &context, loc_id, &facet_type_info, &constraint));
  438. if (subst_inst_id != constraint.rhs_id) {
  439. constraint.rhs_id = subst_inst_id;
  440. if (constraint.rhs_id != SemIR::ErrorInst::InstId) {
  441. // If the RHS is replaced with a non-error value, we need to do
  442. // another pass so that the new RHS value can continue to propagate.
  443. applied_rewrite = true;
  444. }
  445. }
  446. }
  447. if (!applied_rewrite) {
  448. break;
  449. }
  450. }
  451. // Canonicalize again, as we may have inserted errors into the rewrite
  452. // constraints, and these could change sorting order and need to be deduped.
  453. facet_type_info.Canonicalize();
  454. return success;
  455. }
  456. } // namespace Carbon::Check