]> git.lizzy.rs Git - rust.git/blob - src/librustc/traits/specialize/specialization_graph.rs
Rollup merge of #54921 - GuillaumeGomez:line-numbers, r=QuietMisdreavus
[rust.git] / src / librustc / traits / specialize / specialization_graph.rs
1 // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use super::OverlapError;
12
13 use hir::def_id::DefId;
14 use ich::{self, StableHashingContext};
15 use rustc_data_structures::stable_hasher::{HashStable, StableHasher,
16                                            StableHasherResult};
17 use traits;
18 use ty::{self, TyCtxt, TypeFoldable};
19 use ty::fast_reject::{self, SimplifiedType};
20 use rustc_data_structures::sync::Lrc;
21 use syntax::ast::Ident;
22 use util::captures::Captures;
23 use util::nodemap::{DefIdMap, FxHashMap};
24
25 /// A per-trait graph of impls in specialization order. At the moment, this
26 /// graph forms a tree rooted with the trait itself, with all other nodes
27 /// representing impls, and parent-child relationships representing
28 /// specializations.
29 ///
30 /// The graph provides two key services:
31 ///
32 /// - Construction, which implicitly checks for overlapping impls (i.e., impls
33 ///   that overlap but where neither specializes the other -- an artifact of the
34 ///   simple "chain" rule.
35 ///
36 /// - Parent extraction. In particular, the graph can give you the *immediate*
37 ///   parents of a given specializing impl, which is needed for extracting
38 ///   default items amongst other things. In the simple "chain" rule, every impl
39 ///   has at most one parent.
40 #[derive(RustcEncodable, RustcDecodable)]
41 pub struct Graph {
42     // all impls have a parent; the "root" impls have as their parent the def_id
43     // of the trait
44     parent: DefIdMap<DefId>,
45
46     // the "root" impls are found by looking up the trait's def_id.
47     children: DefIdMap<Children>,
48 }
49
50 /// Children of a given impl, grouped into blanket/non-blanket varieties as is
51 /// done in `TraitDef`.
52 #[derive(Default, RustcEncodable, RustcDecodable)]
53 struct Children {
54     // Impls of a trait (or specializations of a given impl). To allow for
55     // quicker lookup, the impls are indexed by a simplified version of their
56     // `Self` type: impls with a simplifiable `Self` are stored in
57     // `nonblanket_impls` keyed by it, while all other impls are stored in
58     // `blanket_impls`.
59     //
60     // A similar division is used within `TraitDef`, but the lists there collect
61     // together *all* the impls for a trait, and are populated prior to building
62     // the specialization graph.
63
64     /// Impls of the trait.
65     nonblanket_impls: FxHashMap<fast_reject::SimplifiedType, Vec<DefId>>,
66
67     /// Blanket impls associated with the trait.
68     blanket_impls: Vec<DefId>,
69 }
70
71 /// The result of attempting to insert an impl into a group of children.
72 enum Inserted {
73     /// The impl was inserted as a new child in this group of children.
74     BecameNewSibling(Option<OverlapError>),
75
76     /// The impl should replace an existing impl X, because the impl specializes X.
77     ReplaceChild(DefId),
78
79     /// The impl is a specialization of an existing child.
80     ShouldRecurseOn(DefId),
81 }
82
83 impl<'a, 'gcx, 'tcx> Children {
84     /// Insert an impl into this set of children without comparing to any existing impls
85     fn insert_blindly(&mut self,
86                       tcx: TyCtxt<'a, 'gcx, 'tcx>,
87                       impl_def_id: DefId) {
88         let trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap();
89         if let Some(sty) = fast_reject::simplify_type(tcx, trait_ref.self_ty(), false) {
90             debug!("insert_blindly: impl_def_id={:?} sty={:?}", impl_def_id, sty);
91             self.nonblanket_impls.entry(sty).or_default().push(impl_def_id)
92         } else {
93             debug!("insert_blindly: impl_def_id={:?} sty=None", impl_def_id);
94             self.blanket_impls.push(impl_def_id)
95         }
96     }
97
98     /// Remove an impl from this set of children. Used when replacing
99     /// an impl with a parent. The impl must be present in the list of
100     /// children already.
101     fn remove_existing(&mut self,
102                       tcx: TyCtxt<'a, 'gcx, 'tcx>,
103                       impl_def_id: DefId) {
104         let trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap();
105         let vec: &mut Vec<DefId>;
106         if let Some(sty) = fast_reject::simplify_type(tcx, trait_ref.self_ty(), false) {
107             debug!("remove_existing: impl_def_id={:?} sty={:?}", impl_def_id, sty);
108             vec = self.nonblanket_impls.get_mut(&sty).unwrap();
109         } else {
110             debug!("remove_existing: impl_def_id={:?} sty=None", impl_def_id);
111             vec = &mut self.blanket_impls;
112         }
113
114         let index = vec.iter().position(|d| *d == impl_def_id).unwrap();
115         vec.remove(index);
116     }
117
118     /// Attempt to insert an impl into this set of children, while comparing for
119     /// specialization relationships.
120     fn insert(&mut self,
121               tcx: TyCtxt<'a, 'gcx, 'tcx>,
122               impl_def_id: DefId,
123               simplified_self: Option<SimplifiedType>)
124               -> Result<Inserted, OverlapError>
125     {
126         let mut last_lint = None;
127
128         debug!(
129             "insert(impl_def_id={:?}, simplified_self={:?})",
130             impl_def_id,
131             simplified_self,
132         );
133
134         for possible_sibling in match simplified_self {
135             Some(sty) => self.filtered(sty),
136             None => self.iter(),
137         } {
138             debug!(
139                 "insert: impl_def_id={:?}, simplified_self={:?}, possible_sibling={:?}",
140                 impl_def_id,
141                 simplified_self,
142                 possible_sibling,
143             );
144
145             let overlap_error = |overlap: traits::coherence::OverlapResult<'_>| {
146                 // overlap, but no specialization; error out
147                 let trait_ref = overlap.impl_header.trait_ref.unwrap();
148                 let self_ty = trait_ref.self_ty();
149                 OverlapError {
150                     with_impl: possible_sibling,
151                     trait_desc: trait_ref.to_string(),
152                     // only report the Self type if it has at least
153                     // some outer concrete shell; otherwise, it's
154                     // not adding much information.
155                     self_desc: if self_ty.has_concrete_skeleton() {
156                         Some(self_ty.to_string())
157                     } else {
158                         None
159                     },
160                     intercrate_ambiguity_causes: overlap.intercrate_ambiguity_causes,
161                 }
162             };
163
164             let tcx = tcx.global_tcx();
165             let (le, ge) = traits::overlapping_impls(
166                 tcx,
167                 possible_sibling,
168                 impl_def_id,
169                 traits::IntercrateMode::Issue43355,
170                 |overlap| {
171                     if tcx.impls_are_allowed_to_overlap(impl_def_id, possible_sibling) {
172                         return Ok((false, false));
173                     }
174
175                     let le = tcx.specializes((impl_def_id, possible_sibling));
176                     let ge = tcx.specializes((possible_sibling, impl_def_id));
177
178                     if le == ge {
179                         Err(overlap_error(overlap))
180                     } else {
181                         Ok((le, ge))
182                     }
183                 },
184                 || Ok((false, false)),
185             )?;
186
187             if le && !ge {
188                 debug!("descending as child of TraitRef {:?}",
189                        tcx.impl_trait_ref(possible_sibling).unwrap());
190
191                 // the impl specializes possible_sibling
192                 return Ok(Inserted::ShouldRecurseOn(possible_sibling));
193             } else if ge && !le {
194                 debug!("placing as parent of TraitRef {:?}",
195                        tcx.impl_trait_ref(possible_sibling).unwrap());
196
197                 return Ok(Inserted::ReplaceChild(possible_sibling));
198             } else {
199                 if !tcx.impls_are_allowed_to_overlap(impl_def_id, possible_sibling) {
200                     traits::overlapping_impls(
201                         tcx,
202                         possible_sibling,
203                         impl_def_id,
204                         traits::IntercrateMode::Fixed,
205                         |overlap| last_lint = Some(overlap_error(overlap)),
206                         || (),
207                     );
208                 }
209
210                 // no overlap (error bailed already via ?)
211             }
212         }
213
214         // no overlap with any potential siblings, so add as a new sibling
215         debug!("placing as new sibling");
216         self.insert_blindly(tcx, impl_def_id);
217         Ok(Inserted::BecameNewSibling(last_lint))
218     }
219
220     fn iter(&mut self) -> Box<dyn Iterator<Item = DefId> + '_> {
221         let nonblanket = self.nonblanket_impls.iter_mut().flat_map(|(_, v)| v.iter());
222         Box::new(self.blanket_impls.iter().chain(nonblanket).cloned())
223     }
224
225     fn filtered(&mut self, sty: SimplifiedType) -> Box<dyn Iterator<Item = DefId> + '_> {
226         let nonblanket = self.nonblanket_impls.entry(sty).or_default().iter();
227         Box::new(self.blanket_impls.iter().chain(nonblanket).cloned())
228     }
229 }
230
231 impl<'a, 'gcx, 'tcx> Graph {
232     pub fn new() -> Graph {
233         Graph {
234             parent: Default::default(),
235             children: Default::default(),
236         }
237     }
238
239     /// Insert a local impl into the specialization graph. If an existing impl
240     /// conflicts with it (has overlap, but neither specializes the other),
241     /// information about the area of overlap is returned in the `Err`.
242     pub fn insert(&mut self,
243                   tcx: TyCtxt<'a, 'gcx, 'tcx>,
244                   impl_def_id: DefId)
245                   -> Result<Option<OverlapError>, OverlapError> {
246         assert!(impl_def_id.is_local());
247
248         let trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap();
249         let trait_def_id = trait_ref.def_id;
250
251         debug!("insert({:?}): inserting TraitRef {:?} into specialization graph",
252                impl_def_id, trait_ref);
253
254         // if the reference itself contains an earlier error (e.g., due to a
255         // resolution failure), then we just insert the impl at the top level of
256         // the graph and claim that there's no overlap (in order to suppress
257         // bogus errors).
258         if trait_ref.references_error() {
259             debug!("insert: inserting dummy node for erroneous TraitRef {:?}, \
260                     impl_def_id={:?}, trait_def_id={:?}",
261                    trait_ref, impl_def_id, trait_def_id);
262
263             self.parent.insert(impl_def_id, trait_def_id);
264             self.children.entry(trait_def_id).or_default()
265                 .insert_blindly(tcx, impl_def_id);
266             return Ok(None);
267         }
268
269         let mut parent = trait_def_id;
270         let mut last_lint = None;
271         let simplified = fast_reject::simplify_type(tcx, trait_ref.self_ty(), false);
272
273         // Descend the specialization tree, where `parent` is the current parent node
274         loop {
275             use self::Inserted::*;
276
277             let insert_result = self.children.entry(parent).or_default()
278                 .insert(tcx, impl_def_id, simplified)?;
279
280             match insert_result {
281                 BecameNewSibling(opt_lint) => {
282                     last_lint = opt_lint;
283                     break;
284                 }
285                 ReplaceChild(grand_child_to_be) => {
286                     // We currently have
287                     //
288                     //     P
289                     //     |
290                     //     G
291                     //
292                     // and we are inserting the impl N. We want to make it:
293                     //
294                     //     P
295                     //     |
296                     //     N
297                     //     |
298                     //     G
299
300                     // Adjust P's list of children: remove G and then add N.
301                     {
302                         let siblings = self.children
303                             .get_mut(&parent)
304                             .unwrap();
305                         siblings.remove_existing(tcx, grand_child_to_be);
306                         siblings.insert_blindly(tcx, impl_def_id);
307                     }
308
309                     // Set G's parent to N and N's parent to P
310                     self.parent.insert(grand_child_to_be, impl_def_id);
311                     self.parent.insert(impl_def_id, parent);
312
313                     // Add G as N's child.
314                     self.children.entry(impl_def_id).or_default()
315                         .insert_blindly(tcx, grand_child_to_be);
316                     break;
317                 }
318                 ShouldRecurseOn(new_parent) => {
319                     parent = new_parent;
320                 }
321             }
322         }
323
324         self.parent.insert(impl_def_id, parent);
325         Ok(last_lint)
326     }
327
328     /// Insert cached metadata mapping from a child impl back to its parent.
329     pub fn record_impl_from_cstore(&mut self,
330                                    tcx: TyCtxt<'a, 'gcx, 'tcx>,
331                                    parent: DefId,
332                                    child: DefId) {
333         if self.parent.insert(child, parent).is_some() {
334             bug!("When recording an impl from the crate store, information about its parent \
335                   was already present.");
336         }
337
338         self.children.entry(parent).or_default().insert_blindly(tcx, child);
339     }
340
341     /// The parent of a given impl, which is the def id of the trait when the
342     /// impl is a "specialization root".
343     pub fn parent(&self, child: DefId) -> DefId {
344         *self.parent.get(&child).unwrap()
345     }
346 }
347
348 /// A node in the specialization graph is either an impl or a trait
349 /// definition; either can serve as a source of item definitions.
350 /// There is always exactly one trait definition node: the root.
351 #[derive(Debug, Copy, Clone)]
352 pub enum Node {
353     Impl(DefId),
354     Trait(DefId),
355 }
356
357 impl<'a, 'gcx, 'tcx> Node {
358     pub fn is_from_trait(&self) -> bool {
359         match *self {
360             Node::Trait(..) => true,
361             _ => false,
362         }
363     }
364
365     /// Iterate over the items defined directly by the given (impl or trait) node.
366     pub fn items(
367         &self,
368         tcx: TyCtxt<'a, 'gcx, 'tcx>,
369     ) -> impl Iterator<Item = ty::AssociatedItem> + 'a {
370         tcx.associated_items(self.def_id())
371     }
372
373     pub fn def_id(&self) -> DefId {
374         match *self {
375             Node::Impl(did) => did,
376             Node::Trait(did) => did,
377         }
378     }
379 }
380
381 pub struct Ancestors {
382     trait_def_id: DefId,
383     specialization_graph: Lrc<Graph>,
384     current_source: Option<Node>,
385 }
386
387 impl Iterator for Ancestors {
388     type Item = Node;
389     fn next(&mut self) -> Option<Node> {
390         let cur = self.current_source.take();
391         if let Some(Node::Impl(cur_impl)) = cur {
392             let parent = self.specialization_graph.parent(cur_impl);
393
394             self.current_source = if parent == self.trait_def_id {
395                 Some(Node::Trait(parent))
396             } else {
397                 Some(Node::Impl(parent))
398             };
399         }
400         cur
401     }
402 }
403
404 pub struct NodeItem<T> {
405     pub node: Node,
406     pub item: T,
407 }
408
409 impl<T> NodeItem<T> {
410     pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> NodeItem<U> {
411         NodeItem {
412             node: self.node,
413             item: f(self.item),
414         }
415     }
416 }
417
418 impl<'a, 'gcx, 'tcx> Ancestors {
419     /// Search the items from the given ancestors, returning each definition
420     /// with the given name and the given kind.
421     #[inline] // FIXME(#35870) Avoid closures being unexported due to impl Trait.
422     pub fn defs(
423         self,
424         tcx: TyCtxt<'a, 'gcx, 'tcx>,
425         trait_item_name: Ident,
426         trait_item_kind: ty::AssociatedKind,
427         trait_def_id: DefId,
428     ) -> impl Iterator<Item = NodeItem<ty::AssociatedItem>> + Captures<'gcx> + Captures<'tcx> + 'a {
429         self.flat_map(move |node| {
430             use ty::AssociatedKind::*;
431             node.items(tcx).filter(move |impl_item| match (trait_item_kind, impl_item.kind) {
432                 | (Const, Const)
433                 | (Method, Method)
434                 | (Type, Type)
435                 | (Type, Existential)
436                 => tcx.hygienic_eq(impl_item.ident, trait_item_name, trait_def_id),
437
438                 | (Const, _)
439                 | (Method, _)
440                 | (Type, _)
441                 | (Existential, _)
442                 => false,
443             }).map(move |item| NodeItem { node: node, item: item })
444         })
445     }
446 }
447
448 /// Walk up the specialization ancestors of a given impl, starting with that
449 /// impl itself.
450 pub fn ancestors(tcx: TyCtxt<'_, '_, '_>,
451                  trait_def_id: DefId,
452                  start_from_impl: DefId)
453                  -> Ancestors {
454     let specialization_graph = tcx.specialization_graph_of(trait_def_id);
455     Ancestors {
456         trait_def_id,
457         specialization_graph,
458         current_source: Some(Node::Impl(start_from_impl)),
459     }
460 }
461
462 impl<'a> HashStable<StableHashingContext<'a>> for Children {
463     fn hash_stable<W: StableHasherResult>(&self,
464                                           hcx: &mut StableHashingContext<'a>,
465                                           hasher: &mut StableHasher<W>) {
466         let Children {
467             ref nonblanket_impls,
468             ref blanket_impls,
469         } = *self;
470
471         ich::hash_stable_trait_impls(hcx, hasher, blanket_impls, nonblanket_impls);
472     }
473 }
474
475 impl_stable_hash_for!(struct self::Graph {
476     parent,
477     children
478 });