rustc_trait_selection/traits/specialize/
specialization_graph.rs

1use rustc_errors::ErrorGuaranteed;
2use rustc_hir::def_id::DefId;
3use rustc_macros::extension;
4use rustc_middle::bug;
5pub use rustc_middle::traits::specialization_graph::*;
6use rustc_middle::ty::fast_reject::{self, SimplifiedType, TreatParams};
7use rustc_middle::ty::{self, TyCtxt, TypeVisitableExt};
8use tracing::{debug, instrument};
9
10use super::OverlapError;
11use crate::traits;
12
13#[derive(Copy, Clone, Debug)]
14pub enum FutureCompatOverlapErrorKind {
15    OrderDepTraitObjects,
16    LeakCheck,
17}
18
19#[derive(Debug)]
20pub struct FutureCompatOverlapError<'tcx> {
21    pub error: OverlapError<'tcx>,
22    pub kind: FutureCompatOverlapErrorKind,
23}
24
25/// The result of attempting to insert an impl into a group of children.
26#[derive(Debug)]
27enum Inserted<'tcx> {
28    /// The impl was inserted as a new child in this group of children.
29    BecameNewSibling(Option<FutureCompatOverlapError<'tcx>>),
30
31    /// The impl should replace existing impls [X1, ..], because the impl specializes X1, X2, etc.
32    ReplaceChildren(Vec<DefId>),
33
34    /// The impl is a specialization of an existing child.
35    ShouldRecurseOn(DefId),
36}
37
38#[extension(trait ChildrenExt<'tcx>)]
39impl<'tcx> Children {
40    /// Insert an impl into this set of children without comparing to any existing impls.
41    fn insert_blindly(&mut self, tcx: TyCtxt<'tcx>, impl_def_id: DefId) {
42        let trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap().skip_binder();
43        if let Some(st) =
44            fast_reject::simplify_type(tcx, trait_ref.self_ty(), TreatParams::InstantiateWithInfer)
45        {
46            debug!("insert_blindly: impl_def_id={:?} st={:?}", impl_def_id, st);
47            self.non_blanket_impls.entry(st).or_default().push(impl_def_id)
48        } else {
49            debug!("insert_blindly: impl_def_id={:?} st=None", impl_def_id);
50            self.blanket_impls.push(impl_def_id)
51        }
52    }
53
54    /// Removes an impl from this set of children. Used when replacing
55    /// an impl with a parent. The impl must be present in the list of
56    /// children already.
57    fn remove_existing(&mut self, tcx: TyCtxt<'tcx>, impl_def_id: DefId) {
58        let trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap().skip_binder();
59        let vec: &mut Vec<DefId>;
60        if let Some(st) =
61            fast_reject::simplify_type(tcx, trait_ref.self_ty(), TreatParams::InstantiateWithInfer)
62        {
63            debug!("remove_existing: impl_def_id={:?} st={:?}", impl_def_id, st);
64            vec = self.non_blanket_impls.get_mut(&st).unwrap();
65        } else {
66            debug!("remove_existing: impl_def_id={:?} st=None", impl_def_id);
67            vec = &mut self.blanket_impls;
68        }
69
70        let index = vec.iter().position(|d| *d == impl_def_id).unwrap();
71        vec.remove(index);
72    }
73
74    /// Attempt to insert an impl into this set of children, while comparing for
75    /// specialization relationships.
76    #[instrument(level = "debug", skip(self, tcx), ret)]
77    fn insert(
78        &mut self,
79        tcx: TyCtxt<'tcx>,
80        impl_def_id: DefId,
81        simplified_self: Option<SimplifiedType>,
82        overlap_mode: OverlapMode,
83    ) -> Result<Inserted<'tcx>, OverlapError<'tcx>> {
84        let mut last_lint = None;
85        let mut replace_children = Vec::new();
86
87        let possible_siblings = match simplified_self {
88            Some(st) => PotentialSiblings::Filtered(filtered_children(self, st)),
89            None => PotentialSiblings::Unfiltered(iter_children(self)),
90        };
91
92        for possible_sibling in possible_siblings {
93            debug!(?possible_sibling);
94
95            let create_overlap_error = |overlap: traits::coherence::OverlapResult<'tcx>| {
96                let trait_ref = overlap.impl_header.trait_ref.unwrap();
97                let self_ty = trait_ref.self_ty();
98
99                OverlapError {
100                    with_impl: possible_sibling,
101                    trait_ref,
102                    // Only report the `Self` type if it has at least
103                    // some outer concrete shell; otherwise, it's
104                    // not adding much information.
105                    self_ty: self_ty.has_concrete_skeleton().then_some(self_ty),
106                    intercrate_ambiguity_causes: overlap.intercrate_ambiguity_causes,
107                    involves_placeholder: overlap.involves_placeholder,
108                    overflowing_predicates: overlap.overflowing_predicates,
109                }
110            };
111
112            let report_overlap_error = |overlap: traits::coherence::OverlapResult<'tcx>,
113                                        last_lint: &mut _| {
114                // Found overlap, but no specialization; error out or report future-compat warning.
115
116                // Do we *still* get overlap if we disable the future-incompatible modes?
117                let should_err = traits::overlapping_impls(
118                    tcx,
119                    possible_sibling,
120                    impl_def_id,
121                    traits::SkipLeakCheck::default(),
122                    overlap_mode,
123                )
124                .is_some();
125
126                let error = create_overlap_error(overlap);
127
128                if should_err {
129                    Err(error)
130                } else {
131                    *last_lint = Some(FutureCompatOverlapError {
132                        error,
133                        kind: FutureCompatOverlapErrorKind::LeakCheck,
134                    });
135
136                    Ok((false, false))
137                }
138            };
139
140            let last_lint_mut = &mut last_lint;
141            let (le, ge) = traits::overlapping_impls(
142                tcx,
143                possible_sibling,
144                impl_def_id,
145                traits::SkipLeakCheck::Yes,
146                overlap_mode,
147            )
148            .map_or(Ok((false, false)), |overlap| {
149                if let Some(overlap_kind) =
150                    tcx.impls_are_allowed_to_overlap(impl_def_id, possible_sibling)
151                {
152                    match overlap_kind {
153                        ty::ImplOverlapKind::Permitted { marker: _ } => {}
154                        ty::ImplOverlapKind::FutureCompatOrderDepTraitObjects => {
155                            *last_lint_mut = Some(FutureCompatOverlapError {
156                                error: create_overlap_error(overlap),
157                                kind: FutureCompatOverlapErrorKind::OrderDepTraitObjects,
158                            });
159                        }
160                    }
161
162                    return Ok((false, false));
163                }
164
165                let le = tcx.specializes((impl_def_id, possible_sibling));
166                let ge = tcx.specializes((possible_sibling, impl_def_id));
167
168                if le == ge { report_overlap_error(overlap, last_lint_mut) } else { Ok((le, ge)) }
169            })?;
170
171            if le && !ge {
172                debug!(
173                    "descending as child of TraitRef {:?}",
174                    tcx.impl_trait_ref(possible_sibling).unwrap().instantiate_identity()
175                );
176
177                // The impl specializes `possible_sibling`.
178                return Ok(Inserted::ShouldRecurseOn(possible_sibling));
179            } else if ge && !le {
180                debug!(
181                    "placing as parent of TraitRef {:?}",
182                    tcx.impl_trait_ref(possible_sibling).unwrap().instantiate_identity()
183                );
184
185                replace_children.push(possible_sibling);
186            } else {
187                // Either there's no overlap, or the overlap was already reported by
188                // `overlap_error`.
189            }
190        }
191
192        if !replace_children.is_empty() {
193            return Ok(Inserted::ReplaceChildren(replace_children));
194        }
195
196        // No overlap with any potential siblings, so add as a new sibling.
197        debug!("placing as new sibling");
198        self.insert_blindly(tcx, impl_def_id);
199        Ok(Inserted::BecameNewSibling(last_lint))
200    }
201}
202
203fn iter_children(children: &Children) -> impl Iterator<Item = DefId> + '_ {
204    let nonblanket = children.non_blanket_impls.iter().flat_map(|(_, v)| v.iter());
205    children.blanket_impls.iter().chain(nonblanket).cloned()
206}
207
208fn filtered_children(
209    children: &mut Children,
210    st: SimplifiedType,
211) -> impl Iterator<Item = DefId> + '_ {
212    let nonblanket = children.non_blanket_impls.entry(st).or_default().iter();
213    children.blanket_impls.iter().chain(nonblanket).cloned()
214}
215
216// A custom iterator used by Children::insert
217enum PotentialSiblings<I, J>
218where
219    I: Iterator<Item = DefId>,
220    J: Iterator<Item = DefId>,
221{
222    Unfiltered(I),
223    Filtered(J),
224}
225
226impl<I, J> Iterator for PotentialSiblings<I, J>
227where
228    I: Iterator<Item = DefId>,
229    J: Iterator<Item = DefId>,
230{
231    type Item = DefId;
232
233    fn next(&mut self) -> Option<Self::Item> {
234        match *self {
235            PotentialSiblings::Unfiltered(ref mut iter) => iter.next(),
236            PotentialSiblings::Filtered(ref mut iter) => iter.next(),
237        }
238    }
239}
240
241#[extension(pub trait GraphExt<'tcx>)]
242impl<'tcx> Graph {
243    /// Insert a local impl into the specialization graph. If an existing impl
244    /// conflicts with it (has overlap, but neither specializes the other),
245    /// information about the area of overlap is returned in the `Err`.
246    fn insert(
247        &mut self,
248        tcx: TyCtxt<'tcx>,
249        impl_def_id: DefId,
250        overlap_mode: OverlapMode,
251    ) -> Result<Option<FutureCompatOverlapError<'tcx>>, OverlapError<'tcx>> {
252        assert!(impl_def_id.is_local());
253
254        // FIXME: use `EarlyBinder` in `self.children`
255        let trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap().skip_binder();
256        let trait_def_id = trait_ref.def_id;
257
258        debug!(
259            "insert({:?}): inserting TraitRef {:?} into specialization graph",
260            impl_def_id, trait_ref
261        );
262
263        // If the reference itself contains an earlier error (e.g., due to a
264        // resolution failure), then we just insert the impl at the top level of
265        // the graph and claim that there's no overlap (in order to suppress
266        // bogus errors).
267        if trait_ref.references_error() {
268            debug!(
269                "insert: inserting dummy node for erroneous TraitRef {:?}, \
270                 impl_def_id={:?}, trait_def_id={:?}",
271                trait_ref, impl_def_id, trait_def_id
272            );
273
274            self.parent.insert(impl_def_id, trait_def_id);
275            self.children.entry(trait_def_id).or_default().insert_blindly(tcx, impl_def_id);
276            return Ok(None);
277        }
278
279        let mut parent = trait_def_id;
280        let mut last_lint = None;
281        let simplified =
282            fast_reject::simplify_type(tcx, trait_ref.self_ty(), TreatParams::InstantiateWithInfer);
283
284        // Descend the specialization tree, where `parent` is the current parent node.
285        loop {
286            use self::Inserted::*;
287
288            let insert_result = self.children.entry(parent).or_default().insert(
289                tcx,
290                impl_def_id,
291                simplified,
292                overlap_mode,
293            )?;
294
295            match insert_result {
296                BecameNewSibling(opt_lint) => {
297                    last_lint = opt_lint;
298                    break;
299                }
300                ReplaceChildren(grand_children_to_be) => {
301                    // We currently have
302                    //
303                    //     P
304                    //     |
305                    //     G
306                    //
307                    // and we are inserting the impl N. We want to make it:
308                    //
309                    //     P
310                    //     |
311                    //     N
312                    //     |
313                    //     G
314
315                    // Adjust P's list of children: remove G and then add N.
316                    {
317                        let siblings = self.children.get_mut(&parent).unwrap();
318                        for &grand_child_to_be in &grand_children_to_be {
319                            siblings.remove_existing(tcx, grand_child_to_be);
320                        }
321                        siblings.insert_blindly(tcx, impl_def_id);
322                    }
323
324                    // Set G's parent to N and N's parent to P.
325                    for &grand_child_to_be in &grand_children_to_be {
326                        self.parent.insert(grand_child_to_be, impl_def_id);
327                    }
328                    self.parent.insert(impl_def_id, parent);
329
330                    // Add G as N's child.
331                    for &grand_child_to_be in &grand_children_to_be {
332                        self.children
333                            .entry(impl_def_id)
334                            .or_default()
335                            .insert_blindly(tcx, grand_child_to_be);
336                    }
337                    break;
338                }
339                ShouldRecurseOn(new_parent) => {
340                    parent = new_parent;
341                }
342            }
343        }
344
345        self.parent.insert(impl_def_id, parent);
346        Ok(last_lint)
347    }
348
349    /// Insert cached metadata mapping from a child impl back to its parent.
350    fn record_impl_from_cstore(&mut self, tcx: TyCtxt<'tcx>, parent: DefId, child: DefId) {
351        if self.parent.insert(child, parent).is_some() {
352            bug!(
353                "When recording an impl from the crate store, information about its parent \
354                 was already present."
355            );
356        }
357
358        self.children.entry(parent).or_default().insert_blindly(tcx, child);
359    }
360}
361
362/// Locate the definition of an associated type in the specialization hierarchy,
363/// starting from the given impl.
364pub(crate) fn assoc_def(
365    tcx: TyCtxt<'_>,
366    impl_def_id: DefId,
367    assoc_def_id: DefId,
368) -> Result<LeafDef, ErrorGuaranteed> {
369    let trait_def_id = tcx.trait_id_of_impl(impl_def_id).unwrap();
370    let trait_def = tcx.trait_def(trait_def_id);
371
372    // This function may be called while we are still building the
373    // specialization graph that is queried below (via TraitDef::ancestors()),
374    // so, in order to avoid unnecessary infinite recursion, we manually look
375    // for the associated item at the given impl.
376    // If there is no such item in that impl, this function will fail with a
377    // cycle error if the specialization graph is currently being built.
378    if let Some(&impl_item_id) = tcx.impl_item_implementor_ids(impl_def_id).get(&assoc_def_id) {
379        // Ensure that the impl is constrained, otherwise projection may give us
380        // bad unconstrained infer vars.
381        if let Some(impl_def_id) = impl_def_id.as_local() {
382            tcx.ensure_ok().enforce_impl_non_lifetime_params_are_constrained(impl_def_id)?;
383        }
384
385        let item = tcx.associated_item(impl_item_id);
386        let impl_node = Node::Impl(impl_def_id);
387        return Ok(LeafDef {
388            item,
389            defining_node: impl_node,
390            finalizing_node: if item.defaultness(tcx).is_default() {
391                None
392            } else {
393                Some(impl_node)
394            },
395        });
396    }
397
398    let ancestors = trait_def.ancestors(tcx, impl_def_id)?;
399    if let Some(assoc_item) = ancestors.leaf_def(tcx, assoc_def_id) {
400        // Ensure that the impl is constrained, otherwise projection may give us
401        // bad unconstrained infer vars.
402        if assoc_item.item.container == ty::AssocItemContainer::Impl
403            && let Some(impl_def_id) = assoc_item.item.container_id(tcx).as_local()
404        {
405            tcx.ensure_ok().enforce_impl_non_lifetime_params_are_constrained(impl_def_id)?;
406        }
407
408        Ok(assoc_item)
409    } else {
410        // This is saying that neither the trait nor
411        // the impl contain a definition for this
412        // associated type. Normally this situation
413        // could only arise through a compiler bug --
414        // if the user wrote a bad item name, it
415        // should have failed during HIR ty lowering.
416        bug!(
417            "No associated type `{}` for {}",
418            tcx.item_name(assoc_def_id),
419            tcx.def_path_str(impl_def_id)
420        )
421    }
422}