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