]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/stability.rs
rollup merge of #20518: nagisa/weighted-bool
[rust.git] / src / librustc / middle / stability.rs
1 // Copyright 2014 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 //! A pass that annotates every item and method with its stability level,
12 //! propagating default levels lexically from parent to children ast nodes.
13
14 use middle::ty;
15 use metadata::csearch;
16 use syntax::codemap::Span;
17 use syntax::{attr, visit};
18 use syntax::ast;
19 use syntax::ast::{Attribute, Block, Crate, DefId, FnDecl, NodeId, Variant};
20 use syntax::ast::{Item, RequiredMethod, ProvidedMethod, TraitItem};
21 use syntax::ast::{TypeMethod, Method, Generics, StructField, TypeTraitItem};
22 use syntax::ast_util::is_local;
23 use syntax::attr::Stability;
24 use syntax::visit::{FnKind, FkMethod, Visitor};
25 use util::nodemap::{NodeMap, DefIdMap};
26 use util::ppaux::Repr;
27
28 use std::mem::replace;
29
30 /// A stability index, giving the stability level for items and methods.
31 pub struct Index {
32     // stability for crate-local items; unmarked stability == no entry
33     local: NodeMap<Stability>,
34     // cache for extern-crate items; unmarked stability == entry with None
35     extern_cache: DefIdMap<Option<Stability>>
36 }
37
38 // A private tree-walker for producing an Index.
39 struct Annotator {
40     index: Index,
41     parent: Option<Stability>
42 }
43
44 impl Annotator {
45     // Determine the stability for a node based on its attributes and inherited
46     // stability. The stability is recorded in the index and used as the parent.
47     fn annotate<F>(&mut self, id: NodeId, use_parent: bool,
48                    attrs: &Vec<Attribute>, f: F) where
49         F: FnOnce(&mut Annotator),
50     {
51         match attr::find_stability(attrs.as_slice()) {
52             Some(stab) => {
53                 self.index.local.insert(id, stab.clone());
54
55                 // Don't inherit #[stable]
56                 if stab.level != attr::Stable {
57                     let parent = replace(&mut self.parent, Some(stab));
58                     f(self);
59                     self.parent = parent;
60                 } else {
61                     f(self);
62                 }
63             }
64             None => {
65                 if use_parent {
66                     self.parent.clone().map(|stab| self.index.local.insert(id, stab));
67                 }
68                 f(self);
69             }
70         }
71     }
72 }
73
74 impl<'v> Visitor<'v> for Annotator {
75     fn visit_item(&mut self, i: &Item) {
76         // FIXME (#18969): the following is a hack around the fact
77         // that we cannot currently annotate the stability of
78         // `deriving`.  Basically, we do *not* allow stability
79         // inheritance on trait implementations, so that derived
80         // implementations appear to be unannotated. This then allows
81         // derived implementations to be automatically tagged with the
82         // stability of the trait. This is WRONG, but expedient to get
83         // libstd stabilized for the 1.0 release.
84         let use_parent = match i.node {
85             ast::ItemImpl(_, _, _, Some(_), _, _) => false,
86             _ => true,
87         };
88
89         self.annotate(i.id, use_parent, &i.attrs, |v| visit::walk_item(v, i));
90
91         if let ast::ItemStruct(ref sd, _) = i.node {
92             sd.ctor_id.map(|id| {
93                 self.annotate(id, true, &i.attrs, |_| {})
94             });
95         }
96     }
97
98     fn visit_fn(&mut self, fk: FnKind<'v>, _: &'v FnDecl,
99                 _: &'v Block, _: Span, _: NodeId) {
100         if let FkMethod(_, _, meth) = fk {
101             // Methods are not already annotated, so we annotate it
102             self.annotate(meth.id, true, &meth.attrs, |_| {});
103         }
104         // Items defined in a function body have no reason to have
105         // a stability attribute, so we don't recurse.
106     }
107
108     fn visit_trait_item(&mut self, t: &TraitItem) {
109         let (id, attrs) = match *t {
110             RequiredMethod(TypeMethod {id, ref attrs, ..}) => (id, attrs),
111
112             // work around lack of pattern matching for @ types
113             ProvidedMethod(ref method) => {
114                 match **method {
115                     Method {ref attrs, id, ..} => (id, attrs),
116                 }
117             }
118
119             TypeTraitItem(ref typedef) => (typedef.ty_param.id, &typedef.attrs),
120         };
121         self.annotate(id, true, attrs, |v| visit::walk_trait_item(v, t));
122     }
123
124     fn visit_variant(&mut self, var: &Variant, g: &'v Generics) {
125         self.annotate(var.node.id, true, &var.node.attrs,
126                       |v| visit::walk_variant(v, var, g))
127     }
128
129     fn visit_struct_field(&mut self, s: &StructField) {
130         self.annotate(s.node.id, true, &s.node.attrs,
131                       |v| visit::walk_struct_field(v, s));
132     }
133
134     fn visit_foreign_item(&mut self, i: &ast::ForeignItem) {
135         self.annotate(i.id, true, &i.attrs, |_| {});
136     }
137 }
138
139 impl Index {
140     /// Construct the stability index for a crate being compiled.
141     pub fn build(krate: &Crate) -> Index {
142         let mut annotator = Annotator {
143             index: Index {
144                 local: NodeMap::new(),
145                 extern_cache: DefIdMap::new()
146             },
147             parent: None
148         };
149         annotator.annotate(ast::CRATE_NODE_ID, true, &krate.attrs,
150                            |v| visit::walk_crate(v, krate));
151         annotator.index
152     }
153 }
154
155 /// Lookup the stability for a node, loading external crate
156 /// metadata as necessary.
157 pub fn lookup(tcx: &ty::ctxt, id: DefId) -> Option<Stability> {
158     debug!("lookup(id={})",
159            id.repr(tcx));
160
161     // is this definition the implementation of a trait method?
162     match ty::trait_item_of_item(tcx, id) {
163         Some(ty::MethodTraitItemId(trait_method_id)) if trait_method_id != id => {
164             debug!("lookup: trait_method_id={}", trait_method_id);
165             return lookup(tcx, trait_method_id)
166         }
167         _ => {}
168     }
169
170     let item_stab = if is_local(id) {
171         tcx.stability.borrow().local.get(&id.node).cloned()
172     } else {
173         let stab = csearch::get_stability(&tcx.sess.cstore, id);
174         let mut index = tcx.stability.borrow_mut();
175         (*index).extern_cache.insert(id, stab.clone());
176         stab
177     };
178
179     item_stab.or_else(|| {
180         if let Some(trait_id) = ty::trait_id_of_impl(tcx, id) {
181             // FIXME (#18969): for the time being, simply use the
182             // stability of the trait to determine the stability of any
183             // unmarked impls for it. See FIXME above for more details.
184
185             debug!("lookup: trait_id={}", trait_id);
186             lookup(tcx, trait_id)
187         } else {
188             None
189         }
190     })
191 }