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