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