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