1 use crate::error::StrictCoherenceNeedsNegativeCoherence;
2 use crate::ty::fast_reject::SimplifiedType;
3 use crate::ty::visit::TypeVisitable;
4 use crate::ty::{self, TyCtxt};
5 use rustc_data_structures::fx::FxIndexMap;
6 use rustc_errors::ErrorGuaranteed;
7 use rustc_hir::def_id::{DefId, DefIdMap};
8 use rustc_span::symbol::sym;
10 /// A per-trait graph of impls in specialization order. At the moment, this
11 /// graph forms a tree rooted with the trait itself, with all other nodes
12 /// representing impls, and parent-child relationships representing
15 /// The graph provides two key services:
17 /// - Construction. This implicitly checks for overlapping impls (i.e., impls
18 /// that overlap but where neither specializes the other -- an artifact of the
19 /// simple "chain" rule.
21 /// - Parent extraction. In particular, the graph can give you the *immediate*
22 /// parents of a given specializing impl, which is needed for extracting
23 /// default items amongst other things. In the simple "chain" rule, every impl
24 /// has at most one parent.
25 #[derive(TyEncodable, TyDecodable, HashStable, Debug)]
27 /// All impls have a parent; the "root" impls have as their parent the `def_id`
29 pub parent: DefIdMap<DefId>,
31 /// The "root" impls are found by looking up the trait's def_id.
32 pub children: DefIdMap<Children>,
34 /// Whether an error was emitted while constructing the graph.
35 pub has_errored: Option<ErrorGuaranteed>,
39 pub fn new() -> Graph {
40 Graph { parent: Default::default(), children: Default::default(), has_errored: None }
43 /// The parent of a given impl, which is the `DefId` of the trait when the
44 /// impl is a "specialization root".
45 pub fn parent(&self, child: DefId) -> DefId {
46 *self.parent.get(&child).unwrap_or_else(|| panic!("Failed to get parent for {:?}", child))
50 /// What kind of overlap check are we doing -- this exists just for testing and feature-gating
52 #[derive(Copy, Clone, PartialEq, Eq, Hash, HashStable, Debug, TyEncodable, TyDecodable)]
53 pub enum OverlapMode {
54 /// The 1.0 rules (either types fail to unify, or where clauses are not implemented for crate-local types)
56 /// Feature-gated test: Stable, *or* there is an explicit negative impl that rules out one of the where-clauses.
58 /// Just check for negative impls, not for "where clause not implemented": used for testing.
63 pub fn get<'tcx>(tcx: TyCtxt<'tcx>, trait_id: DefId) -> OverlapMode {
64 let with_negative_coherence = tcx.features().with_negative_coherence;
65 let strict_coherence = tcx.has_attr(trait_id, sym::rustc_strict_coherence);
67 if with_negative_coherence {
68 if strict_coherence { OverlapMode::Strict } else { OverlapMode::WithNegative }
71 let attr_span = trait_id
74 .flat_map(|local_def_id| {
75 tcx.hir().attrs(tcx.hir().local_def_id_to_hir_id(local_def_id))
77 .find(|attr| attr.has_name(sym::rustc_strict_coherence))
78 .map(|attr| attr.span);
79 tcx.sess.emit_err(StrictCoherenceNeedsNegativeCoherence {
80 span: tcx.def_span(trait_id),
88 pub fn use_negative_impl(&self) -> bool {
89 *self == OverlapMode::Strict || *self == OverlapMode::WithNegative
92 pub fn use_implicit_negative(&self) -> bool {
93 *self == OverlapMode::Stable || *self == OverlapMode::WithNegative
97 /// Children of a given impl, grouped into blanket/non-blanket varieties as is
98 /// done in `TraitDef`.
99 #[derive(Default, TyEncodable, TyDecodable, Debug, HashStable)]
100 pub struct Children {
101 // Impls of a trait (or specializations of a given impl). To allow for
102 // quicker lookup, the impls are indexed by a simplified version of their
103 // `Self` type: impls with a simplifiable `Self` are stored in
104 // `non_blanket_impls` keyed by it, while all other impls are stored in
107 // A similar division is used within `TraitDef`, but the lists there collect
108 // together *all* the impls for a trait, and are populated prior to building
109 // the specialization graph.
110 /// Impls of the trait.
111 pub non_blanket_impls: FxIndexMap<SimplifiedType, Vec<DefId>>,
113 /// Blanket impls associated with the trait.
114 pub blanket_impls: Vec<DefId>,
117 /// A node in the specialization graph is either an impl or a trait
118 /// definition; either can serve as a source of item definitions.
119 /// There is always exactly one trait definition node: the root.
120 #[derive(Debug, Copy, Clone)]
127 pub fn is_from_trait(&self) -> bool {
128 matches!(self, Node::Trait(..))
131 /// Tries to find the associated item that implements `trait_item_def_id`
132 /// defined in this node.
134 /// If this returns `None`, the item can potentially still be found in
135 /// parents of this node.
139 trait_item_def_id: DefId,
140 ) -> Option<&'tcx ty::AssocItem> {
142 Node::Trait(_) => Some(tcx.associated_item(trait_item_def_id)),
143 Node::Impl(impl_def_id) => {
144 let id = tcx.impl_item_implementor_ids(impl_def_id).get(&trait_item_def_id)?;
145 Some(tcx.associated_item(*id))
150 pub fn def_id(&self) -> DefId {
152 Node::Impl(did) => did,
153 Node::Trait(did) => did,
158 #[derive(Copy, Clone)]
159 pub struct Ancestors<'tcx> {
161 specialization_graph: &'tcx Graph,
162 current_source: Option<Node>,
165 impl Iterator for Ancestors<'_> {
167 fn next(&mut self) -> Option<Node> {
168 let cur = self.current_source.take();
169 if let Some(Node::Impl(cur_impl)) = cur {
170 let parent = self.specialization_graph.parent(cur_impl);
172 self.current_source = if parent == self.trait_def_id {
173 Some(Node::Trait(parent))
175 Some(Node::Impl(parent))
182 /// Information about the most specialized definition of an associated item.
184 /// The associated item described by this `LeafDef`.
185 pub item: ty::AssocItem,
187 /// The node in the specialization graph containing the definition of `item`.
188 pub defining_node: Node,
190 /// The "top-most" (ie. least specialized) specialization graph node that finalized the
191 /// definition of `item`.
196 /// #![feature(specialization)]
201 /// impl<T> Tr for T {
202 /// default fn assoc(&self) {}
205 /// impl Tr for u8 {}
208 /// If we start the leaf definition search at `impl Tr for u8`, that impl will be the
209 /// `finalizing_node`, while `defining_node` will be the generic impl.
211 /// If the leaf definition search is started at the generic impl, `finalizing_node` will be
212 /// `None`, since the most specialized impl we found still allows overriding the method
213 /// (doesn't finalize it).
214 pub finalizing_node: Option<Node>,
218 /// Returns whether this definition is known to not be further specializable.
219 pub fn is_final(&self) -> bool {
220 self.finalizing_node.is_some()
224 impl<'tcx> Ancestors<'tcx> {
225 /// Finds the bottom-most (ie. most specialized) definition of an associated
227 pub fn leaf_def(mut self, tcx: TyCtxt<'tcx>, trait_item_def_id: DefId) -> Option<LeafDef> {
228 let mut finalizing_node = None;
230 self.find_map(|node| {
231 if let Some(item) = node.item(tcx, trait_item_def_id) {
232 if finalizing_node.is_none() {
233 let is_specializable = item.defaultness(tcx).is_default()
234 || tcx.impl_defaultness(node.def_id()).is_default();
236 if !is_specializable {
237 finalizing_node = Some(node);
241 Some(LeafDef { item: *item, defining_node: node, finalizing_node })
243 // Item not mentioned. This "finalizes" any defaulted item provided by an ancestor.
244 finalizing_node = Some(node);
251 /// Walk up the specialization ancestors of a given impl, starting with that
254 /// Returns `Err` if an error was reported while building the specialization
256 pub fn ancestors<'tcx>(
259 start_from_impl: DefId,
260 ) -> Result<Ancestors<'tcx>, ErrorGuaranteed> {
261 let specialization_graph = tcx.specialization_graph_of(trait_def_id);
263 if let Some(reported) = specialization_graph.has_errored {
265 } else if let Err(reported) = tcx.type_of(start_from_impl).error_reported() {
270 specialization_graph,
271 current_source: Some(Node::Impl(start_from_impl)),