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