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.
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.
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
18 use front::map as ast_map;
20 use middle::def_id::DefId;
24 use util::nodemap::NodeSet;
26 use std::collections::HashSet;
31 use rustc_front::visit::Visitor;
32 use rustc_front::visit;
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()
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) {
49 hir::ItemImpl(_, _, ref generics, _, _, _) |
50 hir::ItemFn(_, _, _, _, ref generics, _) => {
51 generics_require_inlining(generics)
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) {
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),
69 tcx.sess.span_bug(impl_item.span, "impl did is not an item")
72 tcx.sess.span_bug(impl_item.span, "found a foreign impl as a parent of a local method")
76 // Information needed while computing reachability.
77 struct ReachableContext<'a, 'tcx: 'a> {
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
89 impl<'a, 'tcx, 'v> Visitor<'v> for ReachableContext<'a, 'tcx> {
91 fn visit_expr(&mut self, expr: &hir::Expr) {
94 hir::ExprPath(..) => {
95 let def = match self.tcx.def_map.borrow().get(&expr.id) {
96 Some(d) => d.full_def(),
98 self.tcx.sess.span_bug(expr.span,
99 "def ID not in def map?!")
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);
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);
116 // If this wasn't a static, then the destination is
119 self.reachable_symbols.insert(node_id);
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;
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)
135 self.reachable_symbols.insert(node_id);
141 visit::walk_expr(self, expr)
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.
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
158 reachable_symbols: NodeSet(),
159 worklist: Vec::new(),
160 any_library: any_library,
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; }
172 match self.tcx.map.find(node_id) {
173 Some(ast_map::NodeItem(item)) => {
175 hir::ItemFn(..) => item_might_be_inlined(&*item),
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,
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) {
194 let impl_did = self.tcx
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
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)
209 hir::TypeImplItem(_) => false,
213 None => false // This will happen for default methods.
217 // Step 2: Mark all symbols that the symbols on the worklist touch.
218 fn propagate(&mut self) {
219 let mut scanned = HashSet::new();
221 let search_item = match self.worklist.pop() {
225 if !scanned.insert(search_item) {
229 if let Some(ref item) = self.tcx.map.find(search_item) {
230 self.propagate_node(item, search_item);
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);
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);
259 ast_map::NodeItem(item) => {
261 hir::ItemFn(_, _, _, _, _, ref search_block) => {
262 if item_might_be_inlined(&*item) {
263 visit::walk_block(self, &**search_block)
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);
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(..) => {}
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
291 hir::ConstTraitItem(_, Some(ref expr)) => {
292 self.visit_expr(&*expr);
294 hir::MethodTraitItem(_, Some(ref body)) => {
295 visit::walk_block(self, body);
297 hir::TypeTraitItem(..) => {}
300 ast_map::NodeImplItem(impl_item) => {
301 match impl_item.node {
302 hir::ConstImplItem(_, ref expr) => {
303 self.visit_expr(&*expr);
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)
311 hir::TypeImplItem(_) => {}
314 // Nothing to recurse on for these
315 ast_map::NodeForeignItem(_) |
316 ast_map::NodeVariant(_) |
317 ast_map::NodeStructCtor(_) => {}
321 .bug(&format!("found unexpected thingy in worklist: {}",
324 .node_to_string(search_item)))
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>,
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);
354 visit::walk_item(self, item);
358 pub fn find_reachable(tcx: &ty::ctxt,
359 exported_items: &privacy::ExportedItems)
362 let mut reachable_context = ReachableContext::new(tcx);
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
369 for id in exported_items {
370 reachable_context.worklist.push(*id);
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);
380 let mut collect_private_impl_items = CollectPrivateImplItemsVisitor {
381 exported_items: exported_items,
382 worklist: &mut reachable_context.worklist,
385 visit::walk_crate(&mut collect_private_impl_items, tcx.map.krate());
388 // Step 2: Mark all symbols that the symbols on the worklist touch.
389 reachable_context.propagate();
391 // Return the set of reachable symbols.
392 reachable_context.reachable_symbols