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