1 use super::OverlapError;
4 use rustc_hir::def_id::DefId;
5 use rustc_middle::ty::fast_reject::{self, SimplifiedType, SimplifyParams, StripReferences};
6 use rustc_middle::ty::print::with_no_trimmed_paths;
7 use rustc_middle::ty::{self, TyCtxt, TypeFoldable};
9 pub use rustc_middle::traits::specialization_graph::*;
11 #[derive(Copy, Clone, Debug)]
12 pub enum FutureCompatOverlapErrorKind {
18 pub struct FutureCompatOverlapError {
19 pub error: OverlapError,
20 pub kind: FutureCompatOverlapErrorKind,
23 /// The result of attempting to insert an impl into a group of children.
25 /// The impl was inserted as a new child in this group of children.
26 BecameNewSibling(Option<FutureCompatOverlapError>),
28 /// The impl should replace existing impls [X1, ..], because the impl specializes X1, X2, etc.
29 ReplaceChildren(Vec<DefId>),
31 /// The impl is a specialization of an existing child.
32 ShouldRecurseOn(DefId),
35 trait ChildrenExt<'tcx> {
36 fn insert_blindly(&mut self, tcx: TyCtxt<'tcx>, impl_def_id: DefId);
37 fn remove_existing(&mut self, tcx: TyCtxt<'tcx>, impl_def_id: DefId);
43 simplified_self: Option<SimplifiedType>,
44 overlap_mode: OverlapMode,
45 ) -> Result<Inserted, OverlapError>;
48 impl ChildrenExt<'_> for Children {
49 /// Insert an impl into this set of children without comparing to any existing impls.
50 fn insert_blindly(&mut self, tcx: TyCtxt<'_>, impl_def_id: DefId) {
51 let trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap();
52 if let Some(st) = fast_reject::simplify_type(
58 debug!("insert_blindly: impl_def_id={:?} st={:?}", impl_def_id, st);
59 self.non_blanket_impls.entry(st).or_default().push(impl_def_id)
61 debug!("insert_blindly: impl_def_id={:?} st=None", impl_def_id);
62 self.blanket_impls.push(impl_def_id)
66 /// Removes an impl from this set of children. Used when replacing
67 /// an impl with a parent. The impl must be present in the list of
69 fn remove_existing(&mut self, tcx: TyCtxt<'_>, impl_def_id: DefId) {
70 let trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap();
71 let vec: &mut Vec<DefId>;
72 if let Some(st) = fast_reject::simplify_type(
78 debug!("remove_existing: impl_def_id={:?} st={:?}", impl_def_id, st);
79 vec = self.non_blanket_impls.get_mut(&st).unwrap();
81 debug!("remove_existing: impl_def_id={:?} st=None", impl_def_id);
82 vec = &mut self.blanket_impls;
85 let index = vec.iter().position(|d| *d == impl_def_id).unwrap();
89 /// Attempt to insert an impl into this set of children, while comparing for
90 /// specialization relationships.
95 simplified_self: Option<SimplifiedType>,
96 overlap_mode: OverlapMode,
97 ) -> Result<Inserted, OverlapError> {
98 let mut last_lint = None;
99 let mut replace_children = Vec::new();
101 debug!("insert(impl_def_id={:?}, simplified_self={:?})", impl_def_id, simplified_self,);
103 let possible_siblings = match simplified_self {
104 Some(st) => PotentialSiblings::Filtered(filtered_children(self, st)),
105 None => PotentialSiblings::Unfiltered(iter_children(self)),
108 for possible_sibling in possible_siblings {
110 "insert: impl_def_id={:?}, simplified_self={:?}, possible_sibling={:?}",
111 impl_def_id, simplified_self, possible_sibling,
114 let create_overlap_error = |overlap: traits::coherence::OverlapResult<'_>| {
115 let trait_ref = overlap.impl_header.trait_ref.unwrap();
116 let self_ty = trait_ref.self_ty();
118 // FIXME: should postpone string formatting until we decide to actually emit.
119 with_no_trimmed_paths(|| {
121 with_impl: possible_sibling,
122 trait_desc: trait_ref.print_only_trait_path().to_string(),
123 // Only report the `Self` type if it has at least
124 // some outer concrete shell; otherwise, it's
125 // not adding much information.
126 self_desc: if self_ty.has_concrete_skeleton() {
127 Some(self_ty.to_string())
131 intercrate_ambiguity_causes: overlap.intercrate_ambiguity_causes,
132 involves_placeholder: overlap.involves_placeholder,
137 let report_overlap_error = |overlap: traits::coherence::OverlapResult<'_>,
139 // Found overlap, but no specialization; error out or report future-compat warning.
141 // Do we *still* get overlap if we disable the future-incompatible modes?
142 let should_err = traits::overlapping_impls(
146 traits::SkipLeakCheck::default(),
152 let error = create_overlap_error(overlap);
157 *last_lint = Some(FutureCompatOverlapError {
159 kind: FutureCompatOverlapErrorKind::LeakCheck,
166 let last_lint_mut = &mut last_lint;
167 let (le, ge) = traits::overlapping_impls(
171 traits::SkipLeakCheck::Yes,
174 if let Some(overlap_kind) =
175 tcx.impls_are_allowed_to_overlap(impl_def_id, possible_sibling)
178 ty::ImplOverlapKind::Permitted { marker: _ } => {}
179 ty::ImplOverlapKind::Issue33140 => {
180 *last_lint_mut = Some(FutureCompatOverlapError {
181 error: create_overlap_error(overlap),
182 kind: FutureCompatOverlapErrorKind::Issue33140,
187 return Ok((false, false));
190 let le = tcx.specializes((impl_def_id, possible_sibling));
191 let ge = tcx.specializes((possible_sibling, impl_def_id));
194 report_overlap_error(overlap, last_lint_mut)
199 || Ok((false, false)),
204 "descending as child of TraitRef {:?}",
205 tcx.impl_trait_ref(possible_sibling).unwrap()
208 // The impl specializes `possible_sibling`.
209 return Ok(Inserted::ShouldRecurseOn(possible_sibling));
210 } else if ge && !le {
212 "placing as parent of TraitRef {:?}",
213 tcx.impl_trait_ref(possible_sibling).unwrap()
216 replace_children.push(possible_sibling);
218 // Either there's no overlap, or the overlap was already reported by
223 if !replace_children.is_empty() {
224 return Ok(Inserted::ReplaceChildren(replace_children));
227 // No overlap with any potential siblings, so add as a new sibling.
228 debug!("placing as new sibling");
229 self.insert_blindly(tcx, impl_def_id);
230 Ok(Inserted::BecameNewSibling(last_lint))
234 fn iter_children(children: &mut Children) -> impl Iterator<Item = DefId> + '_ {
235 let nonblanket = children.non_blanket_impls.iter().flat_map(|(_, v)| v.iter());
236 children.blanket_impls.iter().chain(nonblanket).cloned()
239 fn filtered_children(
240 children: &mut Children,
242 ) -> impl Iterator<Item = DefId> + '_ {
243 let nonblanket = children.non_blanket_impls.entry(st).or_default().iter();
244 children.blanket_impls.iter().chain(nonblanket).cloned()
247 // A custom iterator used by Children::insert
248 enum PotentialSiblings<I, J>
250 I: Iterator<Item = DefId>,
251 J: Iterator<Item = DefId>,
257 impl<I, J> Iterator for PotentialSiblings<I, J>
259 I: Iterator<Item = DefId>,
260 J: Iterator<Item = DefId>,
264 fn next(&mut self) -> Option<Self::Item> {
266 PotentialSiblings::Unfiltered(ref mut iter) => iter.next(),
267 PotentialSiblings::Filtered(ref mut iter) => iter.next(),
273 /// Insert a local impl into the specialization graph. If an existing impl
274 /// conflicts with it (has overlap, but neither specializes the other),
275 /// information about the area of overlap is returned in the `Err`.
280 overlap_mode: OverlapMode,
281 ) -> Result<Option<FutureCompatOverlapError>, OverlapError>;
283 /// Insert cached metadata mapping from a child impl back to its parent.
284 fn record_impl_from_cstore(&mut self, tcx: TyCtxt<'_>, parent: DefId, child: DefId);
287 impl GraphExt for Graph {
288 /// Insert a local impl into the specialization graph. If an existing impl
289 /// conflicts with it (has overlap, but neither specializes the other),
290 /// information about the area of overlap is returned in the `Err`.
295 overlap_mode: OverlapMode,
296 ) -> Result<Option<FutureCompatOverlapError>, OverlapError> {
297 assert!(impl_def_id.is_local());
299 let trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap();
300 let trait_def_id = trait_ref.def_id;
303 "insert({:?}): inserting TraitRef {:?} into specialization graph",
304 impl_def_id, trait_ref
307 // If the reference itself contains an earlier error (e.g., due to a
308 // resolution failure), then we just insert the impl at the top level of
309 // the graph and claim that there's no overlap (in order to suppress
311 if trait_ref.references_error() {
313 "insert: inserting dummy node for erroneous TraitRef {:?}, \
314 impl_def_id={:?}, trait_def_id={:?}",
315 trait_ref, impl_def_id, trait_def_id
318 self.parent.insert(impl_def_id, trait_def_id);
319 self.children.entry(trait_def_id).or_default().insert_blindly(tcx, impl_def_id);
323 let mut parent = trait_def_id;
324 let mut last_lint = None;
325 let simplified = fast_reject::simplify_type(
332 // Descend the specialization tree, where `parent` is the current parent node.
334 use self::Inserted::*;
336 let insert_result = self.children.entry(parent).or_default().insert(
343 match insert_result {
344 BecameNewSibling(opt_lint) => {
345 last_lint = opt_lint;
348 ReplaceChildren(grand_children_to_be) => {
355 // and we are inserting the impl N. We want to make it:
363 // Adjust P's list of children: remove G and then add N.
365 let siblings = self.children.get_mut(&parent).unwrap();
366 for &grand_child_to_be in &grand_children_to_be {
367 siblings.remove_existing(tcx, grand_child_to_be);
369 siblings.insert_blindly(tcx, impl_def_id);
372 // Set G's parent to N and N's parent to P.
373 for &grand_child_to_be in &grand_children_to_be {
374 self.parent.insert(grand_child_to_be, impl_def_id);
376 self.parent.insert(impl_def_id, parent);
378 // Add G as N's child.
379 for &grand_child_to_be in &grand_children_to_be {
383 .insert_blindly(tcx, grand_child_to_be);
387 ShouldRecurseOn(new_parent) => {
393 self.parent.insert(impl_def_id, parent);
397 /// Insert cached metadata mapping from a child impl back to its parent.
398 fn record_impl_from_cstore(&mut self, tcx: TyCtxt<'_>, parent: DefId, child: DefId) {
399 if self.parent.insert(child, parent).is_some() {
401 "When recording an impl from the crate store, information about its parent \
402 was already present."
406 self.children.entry(parent).or_default().insert_blindly(tcx, child);