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, specializes};
13 use hir::def_id::DefId;
14 use traits::{self, Reveal};
15 use ty::{self, TyCtxt, TypeFoldable};
16 use ty::fast_reject::{self, SimplifiedType};
18 use syntax::ast::Name;
19 use util::nodemap::{DefIdMap, FxHashMap};
21 /// A per-trait graph of impls in specialization order. At the moment, this
22 /// graph forms a tree rooted with the trait itself, with all other nodes
23 /// representing impls, and parent-child relationships representing
26 /// The graph provides two key services:
28 /// - Construction, which implicitly checks for overlapping impls (i.e., impls
29 /// that overlap but where neither specializes the other -- an artifact of the
30 /// simple "chain" rule.
32 /// - Parent extraction. In particular, the graph can give you the *immediate*
33 /// parents of a given specializing impl, which is needed for extracting
34 /// default items amongst other thigns. In the simple "chain" rule, every impl
35 /// has at most one parent.
37 // all impls have a parent; the "root" impls have as their parent the def_id
39 parent: DefIdMap<DefId>,
41 // the "root" impls are found by looking up the trait's def_id.
42 children: DefIdMap<Children>,
45 /// Children of a given impl, grouped into blanket/non-blanket varieties as is
46 /// done in `TraitDef`.
48 // Impls of a trait (or specializations of a given impl). To allow for
49 // quicker lookup, the impls are indexed by a simplified version of their
50 // `Self` type: impls with a simplifiable `Self` are stored in
51 // `nonblanket_impls` keyed by it, while all other impls are stored in
54 // A similar division is used within `TraitDef`, but the lists there collect
55 // together *all* the impls for a trait, and are populated prior to building
56 // the specialization graph.
58 /// Impls of the trait.
59 nonblanket_impls: FxHashMap<fast_reject::SimplifiedType, Vec<DefId>>,
61 /// Blanket impls associated with the trait.
62 blanket_impls: Vec<DefId>,
65 /// The result of attempting to insert an impl into a group of children.
67 /// The impl was inserted as a new child in this group of children.
70 /// The impl replaced an existing impl that specializes it.
73 /// The impl is a specialization of an existing child.
74 ShouldRecurseOn(DefId),
77 impl<'a, 'gcx, 'tcx> Children {
78 fn new() -> Children {
80 nonblanket_impls: FxHashMap(),
81 blanket_impls: vec![],
85 /// Insert an impl into this set of children without comparing to any existing impls
86 fn insert_blindly(&mut self,
87 tcx: TyCtxt<'a, 'gcx, 'tcx>,
89 let trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap();
90 if let Some(sty) = fast_reject::simplify_type(tcx, trait_ref.self_ty(), false) {
91 self.nonblanket_impls.entry(sty).or_insert(vec![]).push(impl_def_id)
93 self.blanket_impls.push(impl_def_id)
97 /// Attempt to insert an impl into this set of children, while comparing for
98 /// specialiation relationships.
100 tcx: TyCtxt<'a, 'gcx, 'tcx>,
102 simplified_self: Option<SimplifiedType>)
103 -> Result<Inserted, OverlapError>
105 for slot in match simplified_self {
106 Some(sty) => self.filtered_mut(sty),
107 None => self.iter_mut(),
109 let possible_sibling = *slot;
111 let tcx = tcx.global_tcx();
112 let (le, ge) = tcx.infer_ctxt(Reveal::UserFacing).enter(|infcx| {
113 let overlap = traits::overlapping_impls(&infcx,
116 if let Some(impl_header) = overlap {
117 if tcx.impls_are_allowed_to_overlap(impl_def_id, possible_sibling) {
118 return Ok((false, false));
121 let le = specializes(tcx, impl_def_id, possible_sibling);
122 let ge = specializes(tcx, possible_sibling, impl_def_id);
125 // overlap, but no specialization; error out
126 let trait_ref = impl_header.trait_ref.unwrap();
127 let self_ty = trait_ref.self_ty();
129 with_impl: possible_sibling,
130 trait_desc: trait_ref.to_string(),
131 // only report the Self type if it has at least
132 // some outer concrete shell; otherwise, it's
133 // not adding much information.
134 self_desc: if self_ty.has_concrete_skeleton() {
135 Some(self_ty.to_string())
149 debug!("descending as child of TraitRef {:?}",
150 tcx.impl_trait_ref(possible_sibling).unwrap());
152 // the impl specializes possible_sibling
153 return Ok(Inserted::ShouldRecurseOn(possible_sibling));
154 } else if ge && !le {
155 debug!("placing as parent of TraitRef {:?}",
156 tcx.impl_trait_ref(possible_sibling).unwrap());
158 // possible_sibling specializes the impl
160 return Ok(Inserted::Replaced(possible_sibling));
162 // no overlap (error bailed already via ?)
166 // no overlap with any potential siblings, so add as a new sibling
167 debug!("placing as new sibling");
168 self.insert_blindly(tcx, impl_def_id);
169 Ok(Inserted::BecameNewSibling)
172 fn iter_mut(&'a mut self) -> Box<Iterator<Item = &'a mut DefId> + 'a> {
173 let nonblanket = self.nonblanket_impls.iter_mut().flat_map(|(_, v)| v.iter_mut());
174 Box::new(self.blanket_impls.iter_mut().chain(nonblanket))
177 fn filtered_mut(&'a mut self, sty: SimplifiedType)
178 -> Box<Iterator<Item = &'a mut DefId> + 'a> {
179 let nonblanket = self.nonblanket_impls.entry(sty).or_insert(vec![]).iter_mut();
180 Box::new(self.blanket_impls.iter_mut().chain(nonblanket))
184 impl<'a, 'gcx, 'tcx> Graph {
185 pub fn new() -> Graph {
187 parent: Default::default(),
188 children: Default::default(),
192 /// Insert a local impl into the specialization graph. If an existing impl
193 /// conflicts with it (has overlap, but neither specializes the other),
194 /// information about the area of overlap is returned in the `Err`.
195 pub fn insert(&mut self,
196 tcx: TyCtxt<'a, 'gcx, 'tcx>,
198 -> Result<(), OverlapError> {
199 assert!(impl_def_id.is_local());
201 let trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap();
202 let trait_def_id = trait_ref.def_id;
204 debug!("insert({:?}): inserting TraitRef {:?} into specialization graph",
205 impl_def_id, trait_ref);
207 // if the reference itself contains an earlier error (e.g., due to a
208 // resolution failure), then we just insert the impl at the top level of
209 // the graph and claim that there's no overlap (in order to supress
211 if trait_ref.references_error() {
212 debug!("insert: inserting dummy node for erroneous TraitRef {:?}, \
213 impl_def_id={:?}, trait_def_id={:?}",
214 trait_ref, impl_def_id, trait_def_id);
216 self.parent.insert(impl_def_id, trait_def_id);
217 self.children.entry(trait_def_id).or_insert(Children::new())
218 .insert_blindly(tcx, impl_def_id);
222 let mut parent = trait_def_id;
223 let simplified = fast_reject::simplify_type(tcx, trait_ref.self_ty(), false);
225 // Descend the specialization tree, where `parent` is the current parent node
227 use self::Inserted::*;
229 let insert_result = self.children.entry(parent).or_insert(Children::new())
230 .insert(tcx, impl_def_id, simplified)?;
232 match insert_result {
233 BecameNewSibling => {
236 Replaced(new_child) => {
237 self.parent.insert(new_child, impl_def_id);
238 let mut new_children = Children::new();
239 new_children.insert_blindly(tcx, new_child);
240 self.children.insert(impl_def_id, new_children);
243 ShouldRecurseOn(new_parent) => {
249 self.parent.insert(impl_def_id, parent);
253 /// Insert cached metadata mapping from a child impl back to its parent.
254 pub fn record_impl_from_cstore(&mut self,
255 tcx: TyCtxt<'a, 'gcx, 'tcx>,
258 if self.parent.insert(child, parent).is_some() {
259 bug!("When recording an impl from the crate store, information about its parent \
260 was already present.");
263 self.children.entry(parent).or_insert(Children::new()).insert_blindly(tcx, child);
266 /// The parent of a given impl, which is the def id of the trait when the
267 /// impl is a "specialization root".
268 pub fn parent(&self, child: DefId) -> DefId {
269 *self.parent.get(&child).unwrap()
273 /// A node in the specialization graph is either an impl or a trait
274 /// definition; either can serve as a source of item definitions.
275 /// There is always exactly one trait definition node: the root.
276 #[derive(Debug, Copy, Clone)]
282 impl<'a, 'gcx, 'tcx> Node {
283 pub fn is_from_trait(&self) -> bool {
285 Node::Trait(..) => true,
290 /// Iterate over the items defined directly by the given (impl or trait) node.
291 #[inline] // FIXME(#35870) Avoid closures being unexported due to impl Trait.
292 pub fn items(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>)
293 -> impl Iterator<Item = ty::AssociatedItem> + 'a {
294 tcx.associated_items(self.def_id())
297 pub fn def_id(&self) -> DefId {
299 Node::Impl(did) => did,
300 Node::Trait(did) => did,
305 pub struct Ancestors {
307 specialization_graph: Rc<Graph>,
308 current_source: Option<Node>,
311 impl Iterator for Ancestors {
313 fn next(&mut self) -> Option<Node> {
314 let cur = self.current_source.take();
315 if let Some(Node::Impl(cur_impl)) = cur {
316 let parent = self.specialization_graph.parent(cur_impl);
317 if parent == self.trait_def_id {
318 self.current_source = Some(Node::Trait(parent));
320 self.current_source = Some(Node::Impl(parent));
327 pub struct NodeItem<T> {
332 impl<T> NodeItem<T> {
333 pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> NodeItem<U> {
341 impl<'a, 'gcx, 'tcx> Ancestors {
342 /// Search the items from the given ancestors, returning each definition
343 /// with the given name and the given kind.
344 #[inline] // FIXME(#35870) Avoid closures being unexported due to impl Trait.
345 pub fn defs(self, tcx: TyCtxt<'a, 'gcx, 'tcx>, name: Name, kind: ty::AssociatedKind)
346 -> impl Iterator<Item = NodeItem<ty::AssociatedItem>> + 'a {
347 self.flat_map(move |node| {
348 node.items(tcx).filter(move |item| item.kind == kind && item.name == name)
349 .map(move |item| NodeItem { node: node, item: item })
354 /// Walk up the specialization ancestors of a given impl, starting with that
356 pub fn ancestors(tcx: TyCtxt,
358 start_from_impl: DefId)
360 let specialization_graph = tcx.specialization_graph_of(trait_def_id);
363 specialization_graph,
364 current_source: Some(Node::Impl(start_from_impl)),