]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/reachable.rs
rustc: desugar `use a::{b,c};` into `use a::b; use a::c;` in HIR.
[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 ast_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;
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.map.as_local_node_id(impl_src) {
67         match tcx.map.find(impl_node_id) {
68             Some(ast_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     // The set of items which must be exported in the linkage sense.
83     reachable_symbols: NodeSet,
84     // A worklist of item IDs. Each item ID in this worklist will be inlined
85     // and will be scanned for further references.
86     worklist: Vec<ast::NodeId>,
87     // Whether any output of this compilation is a library
88     any_library: bool,
89 }
90
91 impl<'a, 'tcx, 'v> Visitor<'v> for ReachableContext<'a, 'tcx> {
92     fn visit_expr(&mut self, expr: &hir::Expr) {
93         match expr.node {
94             hir::ExprPath(_) => {
95                 let def = self.tcx.expect_def(expr.id);
96                 let def_id = def.def_id();
97                 if let Some(node_id) = self.tcx.map.as_local_node_id(def_id) {
98                     if self.def_id_represents_local_inlined_item(def_id) {
99                         self.worklist.push(node_id);
100                     } else {
101                         match def {
102                             // If this path leads to a constant, then we need to
103                             // recurse into the constant to continue finding
104                             // items that are reachable.
105                             Def::Const(..) | Def::AssociatedConst(..) => {
106                                 self.worklist.push(node_id);
107                             }
108
109                             // If this wasn't a static, then the destination is
110                             // surely reachable.
111                             _ => {
112                                 self.reachable_symbols.insert(node_id);
113                             }
114                         }
115                     }
116                 }
117             }
118             hir::ExprMethodCall(..) => {
119                 let method_call = ty::MethodCall::expr(expr.id);
120                 let def_id = self.tcx.tables().method_map[&method_call].def_id;
121
122                 // Mark the trait item (and, possibly, its default impl) as reachable
123                 // Or mark inherent impl item as reachable
124                 if let Some(node_id) = self.tcx.map.as_local_node_id(def_id) {
125                     if self.def_id_represents_local_inlined_item(def_id) {
126                         self.worklist.push(node_id)
127                     }
128                     self.reachable_symbols.insert(node_id);
129                 }
130             }
131             _ => {}
132         }
133
134         intravisit::walk_expr(self, expr)
135     }
136 }
137
138 impl<'a, 'tcx> ReachableContext<'a, 'tcx> {
139     // Creates a new reachability computation context.
140     fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> ReachableContext<'a, 'tcx> {
141         let any_library = tcx.sess.crate_types.borrow().iter().any(|ty| {
142             *ty == config::CrateTypeRlib || *ty == config::CrateTypeDylib ||
143             *ty == config::CrateTypeProcMacro || *ty == config::CrateTypeMetadata
144         });
145         ReachableContext {
146             tcx: tcx,
147             reachable_symbols: NodeSet(),
148             worklist: Vec::new(),
149             any_library: any_library,
150         }
151     }
152
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.map.as_local_node_id(def_id) {
157             Some(node_id) => node_id,
158             None => { return false; }
159         };
160
161         match self.tcx.map.find(node_id) {
162             Some(ast_map::NodeItem(item)) => {
163                 match item.node {
164                     hir::ItemFn(..) => item_might_be_inlined(&item),
165                     _ => false,
166                 }
167             }
168             Some(ast_map::NodeTraitItem(trait_method)) => {
169                 match trait_method.node {
170                     hir::ConstTraitItem(_, ref default) => default.is_some(),
171                     hir::MethodTraitItem(_, ref body) => body.is_some(),
172                     hir::TypeTraitItem(..) => false,
173                 }
174             }
175             Some(ast_map::NodeImplItem(impl_item)) => {
176                 match impl_item.node {
177                     hir::ImplItemKind::Const(..) => true,
178                     hir::ImplItemKind::Method(ref sig, _) => {
179                         if generics_require_inlining(&sig.generics) ||
180                                 attr::requests_inline(&impl_item.attrs) {
181                             true
182                         } else {
183                             let impl_did = self.tcx
184                                                .map
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.map.as_local_node_id(impl_did).unwrap();
190                             match self.tcx.map.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.map.find(search_item) {
219                 self.propagate_node(item, search_item);
220             }
221         }
222     }
223
224     fn propagate_node(&mut self, node: &ast_map::Node,
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 ast_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 is_extern = attr::contains_extern_indicator(&self.tcx.sess.diagnostic(),
236                                                                 &item.attrs);
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             ast_map::NodeItem(item) => {
251                 match item.node {
252                     hir::ItemFn(.., ref body) => {
253                         if item_might_be_inlined(&item) {
254                             self.visit_expr(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(_, ref init) => {
262                         self.visit_expr(&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(..) |
272                     hir::ItemStruct(..) | hir::ItemEnum(..) |
273                     hir::ItemUnion(..) | hir::ItemDefaultImpl(..) => {}
274                 }
275             }
276             ast_map::NodeTraitItem(trait_method) => {
277                 match trait_method.node {
278                     hir::ConstTraitItem(_, None) |
279                     hir::MethodTraitItem(_, None) => {
280                         // Keep going, nothing to get exported
281                     }
282                     hir::ConstTraitItem(_, Some(ref body)) |
283                     hir::MethodTraitItem(_, Some(ref body)) => {
284                         self.visit_expr(body);
285                     }
286                     hir::TypeTraitItem(..) => {}
287                 }
288             }
289             ast_map::NodeImplItem(impl_item) => {
290                 match impl_item.node {
291                     hir::ImplItemKind::Const(_, ref expr) => {
292                         self.visit_expr(&expr);
293                     }
294                     hir::ImplItemKind::Method(ref sig, ref body) => {
295                         let did = self.tcx.map.get_parent_did(search_item);
296                         if method_might_be_inlined(self.tcx, sig, impl_item, did) {
297                             self.visit_expr(body)
298                         }
299                     }
300                     hir::ImplItemKind::Type(_) => {}
301                 }
302             }
303             // Nothing to recurse on for these
304             ast_map::NodeForeignItem(_) |
305             ast_map::NodeVariant(_) |
306             ast_map::NodeStructCtor(_) => {}
307             _ => {
308                 bug!("found unexpected thingy in worklist: {}",
309                      self.tcx.map.node_to_string(search_item))
310             }
311         }
312     }
313 }
314
315 // Some methods from non-exported (completely private) trait impls still have to be
316 // reachable if they are called from inlinable code. Generally, it's not known until
317 // monomorphization if a specific trait impl item can be reachable or not. So, we
318 // conservatively mark all of them as reachable.
319 // FIXME: One possible strategy for pruning the reachable set is to avoid marking impl
320 // items of non-exported traits (or maybe all local traits?) unless their respective
321 // trait items are used from inlinable code through method call syntax or UFCS, or their
322 // trait is a lang item.
323 struct CollectPrivateImplItemsVisitor<'a> {
324     access_levels: &'a privacy::AccessLevels,
325     worklist: &'a mut Vec<ast::NodeId>,
326 }
327
328 impl<'a, 'v> ItemLikeVisitor<'v> for CollectPrivateImplItemsVisitor<'a> {
329     fn visit_item(&mut self, item: &hir::Item) {
330         // We need only trait impls here, not inherent impls, and only non-exported ones
331         if let hir::ItemImpl(.., Some(_), _, ref impl_item_refs) = item.node {
332             if !self.access_levels.is_reachable(item.id) {
333                 for impl_item_ref in impl_item_refs {
334                     self.worklist.push(impl_item_ref.id.node_id);
335                 }
336             }
337         }
338     }
339
340     fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem) {
341         // processed in visit_item above
342     }
343 }
344
345 pub fn find_reachable<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
346                                 access_levels: &privacy::AccessLevels)
347                                 -> NodeSet {
348     let _task = tcx.dep_graph.in_task(DepNode::Reachability);
349
350     let mut reachable_context = ReachableContext::new(tcx);
351
352     // Step 1: Seed the worklist with all nodes which were found to be public as
353     //         a result of the privacy pass along with all local lang items and impl items.
354     //         If other crates link to us, they're going to expect to be able to
355     //         use the lang items, so we need to be sure to mark them as
356     //         exported.
357     for (id, _) in &access_levels.map {
358         reachable_context.worklist.push(*id);
359     }
360     for item in tcx.lang_items.items().iter() {
361         if let Some(did) = *item {
362             if let Some(node_id) = tcx.map.as_local_node_id(did) {
363                 reachable_context.worklist.push(node_id);
364             }
365         }
366     }
367     {
368         let mut collect_private_impl_items = CollectPrivateImplItemsVisitor {
369             access_levels: access_levels,
370             worklist: &mut reachable_context.worklist,
371         };
372         tcx.map.krate().visit_all_item_likes(&mut collect_private_impl_items);
373     }
374
375     // Step 2: Mark all symbols that the symbols on the worklist touch.
376     reachable_context.propagate();
377
378     // Return the set of reachable symbols.
379     reachable_context.reachable_symbols
380 }