]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/reachable.rs
Refactor away `inferred_obligations` from the trait selector
[rust.git] / src / librustc / middle / reachable.rs
1 // Copyright 2012-2013 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 // Finds items that are externally reachable, to determine which items
12 // need to have their metadata (and possibly their AST) serialized.
13 // All items that can be referred to through an exported name are
14 // reachable, and when a reachable thing is inline or generic, it
15 // makes all other generics or inline functions that it references
16 // reachable as well.
17
18 use hir::map as hir_map;
19 use hir::def::Def;
20 use hir::def_id::{DefId, CrateNum};
21 use rustc_data_structures::sync::Lrc;
22 use ty::{self, TyCtxt};
23 use ty::maps::Providers;
24 use middle::privacy;
25 use session::config;
26 use util::nodemap::{NodeSet, FxHashSet};
27
28 use syntax::abi::Abi;
29 use syntax::ast;
30 use syntax::attr;
31 use hir;
32 use hir::def_id::LOCAL_CRATE;
33 use hir::intravisit::{Visitor, NestedVisitorMap};
34 use hir::itemlikevisit::ItemLikeVisitor;
35 use hir::intravisit;
36
37 // Returns true if the given set of generics implies that the item it's
38 // associated with must be inlined.
39 fn generics_require_inlining(generics: &hir::Generics) -> bool {
40     generics.params.iter().any(|param| param.is_type_param())
41 }
42
43 // Returns true if the given item must be inlined because it may be
44 // monomorphized or it was marked with `#[inline]`. This will only return
45 // true for functions.
46 fn item_might_be_inlined(item: &hir::Item) -> bool {
47     if attr::requests_inline(&item.attrs) {
48         return true
49     }
50
51     match item.node {
52         hir::ItemImpl(_, _, _, ref generics, ..) |
53         hir::ItemFn(.., ref generics, _) => {
54             generics_require_inlining(generics)
55         }
56         _ => false,
57     }
58 }
59
60 fn method_might_be_inlined<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
61                                      impl_item: &hir::ImplItem,
62                                      impl_src: DefId) -> bool {
63     if attr::requests_inline(&impl_item.attrs) ||
64         generics_require_inlining(&impl_item.generics) {
65         return true
66     }
67     if let Some(impl_node_id) = tcx.hir.as_local_node_id(impl_src) {
68         match tcx.hir.find(impl_node_id) {
69             Some(hir_map::NodeItem(item)) =>
70                 item_might_be_inlined(&item),
71             Some(..) | None =>
72                 span_bug!(impl_item.span, "impl did is not an item")
73         }
74     } else {
75         span_bug!(impl_item.span, "found a foreign impl as a parent of a local method")
76     }
77 }
78
79 // Information needed while computing reachability.
80 struct ReachableContext<'a, 'tcx: 'a> {
81     // The type context.
82     tcx: TyCtxt<'a, 'tcx, 'tcx>,
83     tables: &'a ty::TypeckTables<'tcx>,
84     // The set of items which must be exported in the linkage sense.
85     reachable_symbols: NodeSet,
86     // A worklist of item IDs. Each item ID in this worklist will be inlined
87     // and will be scanned for further references.
88     worklist: Vec<ast::NodeId>,
89     // Whether any output of this compilation is a library
90     any_library: bool,
91 }
92
93 impl<'a, 'tcx> Visitor<'tcx> for ReachableContext<'a, 'tcx> {
94     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
95         NestedVisitorMap::None
96     }
97
98     fn visit_nested_body(&mut self, body: hir::BodyId) {
99         let old_tables = self.tables;
100         self.tables = self.tcx.body_tables(body);
101         let body = self.tcx.hir.body(body);
102         self.visit_body(body);
103         self.tables = old_tables;
104     }
105
106     fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
107         let def = match expr.node {
108             hir::ExprPath(ref qpath) => {
109                 Some(self.tables.qpath_def(qpath, expr.hir_id))
110             }
111             hir::ExprMethodCall(..) => {
112                 Some(self.tables.type_dependent_defs()[expr.hir_id])
113             }
114             _ => None
115         };
116
117         match def {
118             Some(Def::Local(node_id)) | Some(Def::Upvar(node_id, ..)) => {
119                 self.reachable_symbols.insert(node_id);
120             }
121             Some(def) => {
122                 let def_id = def.def_id();
123                 if let Some(node_id) = self.tcx.hir.as_local_node_id(def_id) {
124                     if self.def_id_represents_local_inlined_item(def_id) {
125                         self.worklist.push(node_id);
126                     } else {
127                         match def {
128                             // If this path leads to a constant, then we need to
129                             // recurse into the constant to continue finding
130                             // items that are reachable.
131                             Def::Const(..) | Def::AssociatedConst(..) => {
132                                 self.worklist.push(node_id);
133                             }
134
135                             // If this wasn't a static, then the destination is
136                             // surely reachable.
137                             _ => {
138                                 self.reachable_symbols.insert(node_id);
139                             }
140                         }
141                     }
142                 }
143             }
144             _ => {}
145         }
146
147         intravisit::walk_expr(self, expr)
148     }
149 }
150
151 impl<'a, 'tcx> ReachableContext<'a, 'tcx> {
152     // Returns true if the given def ID represents a local item that is
153     // eligible for inlining and false otherwise.
154     fn def_id_represents_local_inlined_item(&self, def_id: DefId) -> bool {
155         let node_id = match self.tcx.hir.as_local_node_id(def_id) {
156             Some(node_id) => node_id,
157             None => { return false; }
158         };
159
160         match self.tcx.hir.find(node_id) {
161             Some(hir_map::NodeItem(item)) => {
162                 match item.node {
163                     hir::ItemFn(..) => item_might_be_inlined(&item),
164                     _ => false,
165                 }
166             }
167             Some(hir_map::NodeTraitItem(trait_method)) => {
168                 match trait_method.node {
169                     hir::TraitItemKind::Const(_, ref default) => default.is_some(),
170                     hir::TraitItemKind::Method(_, hir::TraitMethod::Provided(_)) => true,
171                     hir::TraitItemKind::Method(_, hir::TraitMethod::Required(_)) |
172                     hir::TraitItemKind::Type(..) => false,
173                 }
174             }
175             Some(hir_map::NodeImplItem(impl_item)) => {
176                 match impl_item.node {
177                     hir::ImplItemKind::Const(..) => true,
178                     hir::ImplItemKind::Method(..) => {
179                         if generics_require_inlining(&impl_item.generics) ||
180                                 attr::requests_inline(&impl_item.attrs) {
181                             true
182                         } else {
183                             let impl_did = self.tcx
184                                                .hir
185                                                .get_parent_did(node_id);
186                             // Check the impl. If the generics on the self
187                             // type of the impl require inlining, this method
188                             // does too.
189                             let impl_node_id = self.tcx.hir.as_local_node_id(impl_did).unwrap();
190                             match self.tcx.hir.expect_item(impl_node_id).node {
191                                 hir::ItemImpl(_, _, _, ref generics, ..) => {
192                                     generics_require_inlining(generics)
193                                 }
194                                 _ => false
195                             }
196                         }
197                     }
198                     hir::ImplItemKind::Type(_) => false,
199                 }
200             }
201             Some(_) => false,
202             None => false   // This will happen for default methods.
203         }
204     }
205
206     // Step 2: Mark all symbols that the symbols on the worklist touch.
207     fn propagate(&mut self) {
208         let mut scanned = FxHashSet();
209         loop {
210             let search_item = match self.worklist.pop() {
211                 Some(item) => item,
212                 None => break,
213             };
214             if !scanned.insert(search_item) {
215                 continue
216             }
217
218             if let Some(ref item) = self.tcx.hir.find(search_item) {
219                 self.propagate_node(item, search_item);
220             }
221         }
222     }
223
224     fn propagate_node(&mut self, node: &hir_map::Node<'tcx>,
225                       search_item: ast::NodeId) {
226         if !self.any_library {
227             // If we are building an executable, only explicitly extern
228             // types need to be exported.
229             if let hir_map::NodeItem(item) = *node {
230                 let reachable = if let hir::ItemFn(.., abi, _, _) = item.node {
231                     abi != Abi::Rust
232                 } else {
233                     false
234                 };
235                 let def_id = self.tcx.hir.local_def_id(item.id);
236                 let is_extern = self.tcx.contains_extern_indicator(def_id);
237                 if reachable || is_extern {
238                     self.reachable_symbols.insert(search_item);
239                 }
240             }
241         } else {
242             // If we are building a library, then reachable symbols will
243             // continue to participate in linkage after this product is
244             // produced. In this case, we traverse the ast node, recursing on
245             // all reachable nodes from this one.
246             self.reachable_symbols.insert(search_item);
247         }
248
249         match *node {
250             hir_map::NodeItem(item) => {
251                 match item.node {
252                     hir::ItemFn(.., body) => {
253                         if item_might_be_inlined(&item) {
254                             self.visit_nested_body(body);
255                         }
256                     }
257
258                     // Reachable constants will be inlined into other crates
259                     // unconditionally, so we need to make sure that their
260                     // contents are also reachable.
261                     hir::ItemConst(_, init) => {
262                         self.visit_nested_body(init);
263                     }
264
265                     // These are normal, nothing reachable about these
266                     // inherently and their children are already in the
267                     // worklist, as determined by the privacy pass
268                     hir::ItemExternCrate(_) | hir::ItemUse(..) |
269                     hir::ItemTy(..) | hir::ItemStatic(..) |
270                     hir::ItemMod(..) | hir::ItemForeignMod(..) |
271                     hir::ItemImpl(..) | hir::ItemTrait(..) | hir::ItemTraitAlias(..) |
272                     hir::ItemStruct(..) | hir::ItemEnum(..) |
273                     hir::ItemUnion(..) |  hir::ItemGlobalAsm(..) => {}
274                 }
275             }
276             hir_map::NodeTraitItem(trait_method) => {
277                 match trait_method.node {
278                     hir::TraitItemKind::Const(_, None) |
279                     hir::TraitItemKind::Method(_, hir::TraitMethod::Required(_)) => {
280                         // Keep going, nothing to get exported
281                     }
282                     hir::TraitItemKind::Const(_, Some(body_id)) |
283                     hir::TraitItemKind::Method(_, hir::TraitMethod::Provided(body_id)) => {
284                         self.visit_nested_body(body_id);
285                     }
286                     hir::TraitItemKind::Type(..) => {}
287                 }
288             }
289             hir_map::NodeImplItem(impl_item) => {
290                 match impl_item.node {
291                     hir::ImplItemKind::Const(_, body) => {
292                         self.visit_nested_body(body);
293                     }
294                     hir::ImplItemKind::Method(_, body) => {
295                         let did = self.tcx.hir.get_parent_did(search_item);
296                         if method_might_be_inlined(self.tcx, impl_item, did) {
297                             self.visit_nested_body(body)
298                         }
299                     }
300                     hir::ImplItemKind::Type(_) => {}
301                 }
302             }
303             hir_map::NodeExpr(&hir::Expr { node: hir::ExprClosure(.., body, _, _), .. }) => {
304                 self.visit_nested_body(body);
305             }
306             // Nothing to recurse on for these
307             hir_map::NodeForeignItem(_) |
308             hir_map::NodeVariant(_) |
309             hir_map::NodeStructCtor(_) |
310             hir_map::NodeField(_) |
311             hir_map::NodeTy(_) |
312             hir_map::NodeMacroDef(_) => {}
313             _ => {
314                 bug!("found unexpected thingy in worklist: {}",
315                      self.tcx.hir.node_to_string(search_item))
316             }
317         }
318     }
319 }
320
321 // Some methods from non-exported (completely private) trait impls still have to be
322 // reachable if they are called from inlinable code. Generally, it's not known until
323 // monomorphization if a specific trait impl item can be reachable or not. So, we
324 // conservatively mark all of them as reachable.
325 // FIXME: One possible strategy for pruning the reachable set is to avoid marking impl
326 // items of non-exported traits (or maybe all local traits?) unless their respective
327 // trait items are used from inlinable code through method call syntax or UFCS, or their
328 // trait is a lang item.
329 struct CollectPrivateImplItemsVisitor<'a, 'tcx: 'a> {
330     tcx: TyCtxt<'a, 'tcx, 'tcx>,
331     access_levels: &'a privacy::AccessLevels,
332     worklist: &'a mut Vec<ast::NodeId>,
333 }
334
335 impl<'a, 'tcx: 'a> ItemLikeVisitor<'tcx> for CollectPrivateImplItemsVisitor<'a, 'tcx> {
336     fn visit_item(&mut self, item: &hir::Item) {
337         // Anything which has custom linkage gets thrown on the worklist no
338         // matter where it is in the crate.
339         if attr::contains_name(&item.attrs, "linkage") {
340             self.worklist.push(item.id);
341         }
342
343         // We need only trait impls here, not inherent impls, and only non-exported ones
344         if let hir::ItemImpl(.., Some(ref trait_ref), _, ref impl_item_refs) = item.node {
345             if !self.access_levels.is_reachable(item.id) {
346                 for impl_item_ref in impl_item_refs {
347                     self.worklist.push(impl_item_ref.id.node_id);
348                 }
349
350                 let trait_def_id = match trait_ref.path.def {
351                     Def::Trait(def_id) => def_id,
352                     _ => unreachable!()
353                 };
354
355                 if !trait_def_id.is_local() {
356                     return
357                 }
358
359                 for default_method in self.tcx.provided_trait_methods(trait_def_id) {
360                     let node_id = self.tcx
361                                       .hir
362                                       .as_local_node_id(default_method.def_id)
363                                       .unwrap();
364                     self.worklist.push(node_id);
365                 }
366             }
367         }
368     }
369
370     fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem) {}
371
372     fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem) {
373         // processed in visit_item above
374     }
375 }
376
377 // We introduce a new-type here, so we can have a specialized HashStable
378 // implementation for it.
379 #[derive(Clone)]
380 pub struct ReachableSet(pub Lrc<NodeSet>);
381
382
383 fn reachable_set<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, crate_num: CrateNum) -> ReachableSet {
384     debug_assert!(crate_num == LOCAL_CRATE);
385
386     let access_levels = &tcx.privacy_access_levels(LOCAL_CRATE);
387
388     let any_library = tcx.sess.crate_types.borrow().iter().any(|ty| {
389         *ty == config::CrateTypeRlib || *ty == config::CrateTypeDylib ||
390         *ty == config::CrateTypeProcMacro
391     });
392     let mut reachable_context = ReachableContext {
393         tcx,
394         tables: &ty::TypeckTables::empty(None),
395         reachable_symbols: NodeSet(),
396         worklist: Vec::new(),
397         any_library,
398     };
399
400     // Step 1: Seed the worklist with all nodes which were found to be public as
401     //         a result of the privacy pass along with all local lang items and impl items.
402     //         If other crates link to us, they're going to expect to be able to
403     //         use the lang items, so we need to be sure to mark them as
404     //         exported.
405     for (id, _) in &access_levels.map {
406         reachable_context.worklist.push(*id);
407     }
408     for item in tcx.lang_items().items().iter() {
409         if let Some(did) = *item {
410             if let Some(node_id) = tcx.hir.as_local_node_id(did) {
411                 reachable_context.worklist.push(node_id);
412             }
413         }
414     }
415     {
416         let mut collect_private_impl_items = CollectPrivateImplItemsVisitor {
417             tcx,
418             access_levels,
419             worklist: &mut reachable_context.worklist,
420         };
421         tcx.hir.krate().visit_all_item_likes(&mut collect_private_impl_items);
422     }
423
424     // Step 2: Mark all symbols that the symbols on the worklist touch.
425     reachable_context.propagate();
426
427     // Return the set of reachable symbols.
428     ReachableSet(Lrc::new(reachable_context.reachable_symbols))
429 }
430
431 pub fn provide(providers: &mut Providers) {
432     *providers = Providers {
433         reachable_set,
434         ..*providers
435     };
436 }