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.
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.
11 use super::OverlapError;
13 use hir::def_id::DefId;
14 use ich::{self, StableHashingContext};
15 use rustc_data_structures::stable_hasher::{HashStable, StableHasher,
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};
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
30 /// The graph provides two key services:
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.
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)]
42 // all impls have a parent; the "root" impls have as their parent the def_id
44 parent: DefIdMap<DefId>,
46 // the "root" impls are found by looking up the trait's def_id.
47 children: DefIdMap<Children>,
50 /// Children of a given impl, grouped into blanket/non-blanket varieties as is
51 /// done in `TraitDef`.
52 #[derive(Default, RustcEncodable, RustcDecodable)]
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
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.
64 /// Impls of the trait.
65 nonblanket_impls: FxHashMap<fast_reject::SimplifiedType, Vec<DefId>>,
67 /// Blanket impls associated with the trait.
68 blanket_impls: Vec<DefId>,
71 /// The result of attempting to insert an impl into a group of children.
73 /// The impl was inserted as a new child in this group of children.
74 BecameNewSibling(Option<OverlapError>),
76 /// The impl should replace an existing impl X, because the impl specializes X.
79 /// The impl is a specialization of an existing child.
80 ShouldRecurseOn(DefId),
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>,
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)
93 debug!("insert_blindly: impl_def_id={:?} sty=None", impl_def_id);
94 self.blanket_impls.push(impl_def_id)
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();
110 debug!("remove_existing: impl_def_id={:?} sty=None", impl_def_id);
111 vec = &mut self.blanket_impls;
114 let index = vec.iter().position(|d| *d == impl_def_id).unwrap();
118 /// Attempt to insert an impl into this set of children, while comparing for
119 /// specialization relationships.
121 tcx: TyCtxt<'a, 'gcx, 'tcx>,
123 simplified_self: Option<SimplifiedType>)
124 -> Result<Inserted, OverlapError>
126 let mut last_lint = None;
129 "insert(impl_def_id={:?}, simplified_self={:?})",
134 for possible_sibling in match simplified_self {
135 Some(sty) => self.filtered(sty),
139 "insert: impl_def_id={:?}, simplified_self={:?}, possible_sibling={:?}",
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();
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())
160 intercrate_ambiguity_causes: overlap.intercrate_ambiguity_causes,
164 let tcx = tcx.global_tcx();
165 let (le, ge) = traits::overlapping_impls(
169 traits::IntercrateMode::Issue43355,
171 if tcx.impls_are_allowed_to_overlap(impl_def_id, possible_sibling) {
172 return Ok((false, false));
175 let le = tcx.specializes((impl_def_id, possible_sibling));
176 let ge = tcx.specializes((possible_sibling, impl_def_id));
179 Err(overlap_error(overlap))
184 || Ok((false, false)),
188 debug!("descending as child of TraitRef {:?}",
189 tcx.impl_trait_ref(possible_sibling).unwrap());
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());
197 return Ok(Inserted::ReplaceChild(possible_sibling));
199 if !tcx.impls_are_allowed_to_overlap(impl_def_id, possible_sibling) {
200 traits::overlapping_impls(
204 traits::IntercrateMode::Fixed,
205 |overlap| last_lint = Some(overlap_error(overlap)),
210 // no overlap (error bailed already via ?)
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))
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())
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())
231 impl<'a, 'gcx, 'tcx> Graph {
232 pub fn new() -> Graph {
234 parent: Default::default(),
235 children: Default::default(),
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>,
245 -> Result<Option<OverlapError>, OverlapError> {
246 assert!(impl_def_id.is_local());
248 let trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap();
249 let trait_def_id = trait_ref.def_id;
251 debug!("insert({:?}): inserting TraitRef {:?} into specialization graph",
252 impl_def_id, trait_ref);
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
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);
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);
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);
273 // Descend the specialization tree, where `parent` is the current parent node
275 use self::Inserted::*;
277 let insert_result = self.children.entry(parent).or_default()
278 .insert(tcx, impl_def_id, simplified)?;
280 match insert_result {
281 BecameNewSibling(opt_lint) => {
282 last_lint = opt_lint;
285 ReplaceChild(grand_child_to_be) => {
292 // and we are inserting the impl N. We want to make it:
300 // Adjust P's list of children: remove G and then add N.
302 let siblings = self.children
305 siblings.remove_existing(tcx, grand_child_to_be);
306 siblings.insert_blindly(tcx, impl_def_id);
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);
313 // Add G as N's child.
314 self.children.entry(impl_def_id).or_default()
315 .insert_blindly(tcx, grand_child_to_be);
318 ShouldRecurseOn(new_parent) => {
324 self.parent.insert(impl_def_id, parent);
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>,
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.");
338 self.children.entry(parent).or_default().insert_blindly(tcx, child);
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()
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)]
357 impl<'a, 'gcx, 'tcx> Node {
358 pub fn is_from_trait(&self) -> bool {
360 Node::Trait(..) => true,
365 /// Iterate over the items defined directly by the given (impl or trait) node.
368 tcx: TyCtxt<'a, 'gcx, 'tcx>,
369 ) -> ty::AssociatedItemsIterator<'a, 'gcx, 'tcx> {
370 tcx.associated_items(self.def_id())
373 pub fn def_id(&self) -> DefId {
375 Node::Impl(did) => did,
376 Node::Trait(did) => did,
381 pub struct Ancestors {
383 specialization_graph: Lrc<Graph>,
384 current_source: Option<Node>,
387 impl Iterator for Ancestors {
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);
394 self.current_source = if parent == self.trait_def_id {
395 Some(Node::Trait(parent))
397 Some(Node::Impl(parent))
404 pub struct NodeItem<T> {
409 impl<T> NodeItem<T> {
410 pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> NodeItem<U> {
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.
424 tcx: TyCtxt<'a, 'gcx, 'tcx>,
425 trait_item_name: Ident,
426 trait_item_kind: ty::AssociatedKind,
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) {
435 | (Type, Existential)
436 => tcx.hygienic_eq(impl_item.ident, trait_item_name, trait_def_id),
443 }).map(move |item| NodeItem { node: node, item: item })
448 /// Walk up the specialization ancestors of a given impl, starting with that
450 pub fn ancestors(tcx: TyCtxt<'_, '_, '_>,
452 start_from_impl: DefId)
454 let specialization_graph = tcx.specialization_graph_of(trait_def_id);
457 specialization_graph,
458 current_source: Some(Node::Impl(start_from_impl)),
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>) {
467 ref nonblanket_impls,
471 ich::hash_stable_trait_impls(hcx, hasher, blanket_impls, nonblanket_impls);
475 impl_stable_hash_for!(struct self::Graph {