]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/config.rs
add inline attributes to stage 0 methods
[rust.git] / src / libsyntax / config.rs
1 // Copyright 2012-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 use attr::HasAttrs;
12 use feature_gate::{feature_err, EXPLAIN_STMT_ATTR_SYNTAX, Features, get_features, GateIssue};
13 use {fold, attr};
14 use ast;
15 use codemap::Spanned;
16 use parse::ParseSess;
17 use ptr::P;
18
19 use util::small_vector::SmallVector;
20
21 /// A folder that strips out items that do not belong in the current configuration.
22 pub struct StripUnconfigured<'a> {
23     pub should_test: bool,
24     pub sess: &'a ParseSess,
25     pub features: Option<&'a Features>,
26 }
27
28 // `cfg_attr`-process the crate's attributes and compute the crate's features.
29 pub fn features(mut krate: ast::Crate, sess: &ParseSess, should_test: bool)
30                 -> (ast::Crate, Features) {
31     let features;
32     {
33         let mut strip_unconfigured = StripUnconfigured {
34             should_test: should_test,
35             sess: sess,
36             features: None,
37         };
38
39         let unconfigured_attrs = krate.attrs.clone();
40         let err_count = sess.span_diagnostic.err_count();
41         if let Some(attrs) = strip_unconfigured.configure(krate.attrs) {
42             krate.attrs = attrs;
43         } else { // the entire crate is unconfigured
44             krate.attrs = Vec::new();
45             krate.module.items = Vec::new();
46             return (krate, Features::new());
47         }
48
49         features = get_features(&sess.span_diagnostic, &krate.attrs);
50
51         // Avoid reconfiguring malformed `cfg_attr`s
52         if err_count == sess.span_diagnostic.err_count() {
53             strip_unconfigured.features = Some(&features);
54             strip_unconfigured.configure(unconfigured_attrs);
55         }
56     }
57
58     (krate, features)
59 }
60
61 macro_rules! configure {
62     ($this:ident, $node:ident) => {
63         match $this.configure($node) {
64             Some(node) => node,
65             None => return Default::default(),
66         }
67     }
68 }
69
70 impl<'a> StripUnconfigured<'a> {
71     pub fn configure<T: HasAttrs>(&mut self, node: T) -> Option<T> {
72         let node = self.process_cfg_attrs(node);
73         if self.in_cfg(node.attrs()) { Some(node) } else { None }
74     }
75
76     pub fn process_cfg_attrs<T: HasAttrs>(&mut self, node: T) -> T {
77         node.map_attrs(|attrs| {
78             attrs.into_iter().filter_map(|attr| self.process_cfg_attr(attr)).collect()
79         })
80     }
81
82     fn process_cfg_attr(&mut self, attr: ast::Attribute) -> Option<ast::Attribute> {
83         if !attr.check_name("cfg_attr") {
84             return Some(attr);
85         }
86
87         let attr_list = match attr.meta_item_list() {
88             Some(attr_list) => attr_list,
89             None => {
90                 let msg = "expected `#[cfg_attr(<cfg pattern>, <attr>)]`";
91                 self.sess.span_diagnostic.span_err(attr.span, msg);
92                 return None;
93             }
94         };
95
96         let (cfg, mi) = match (attr_list.len(), attr_list.get(0), attr_list.get(1)) {
97             (2, Some(cfg), Some(mi)) => (cfg, mi),
98             _ => {
99                 let msg = "expected `#[cfg_attr(<cfg pattern>, <attr>)]`";
100                 self.sess.span_diagnostic.span_err(attr.span, msg);
101                 return None;
102             }
103         };
104
105         use attr::cfg_matches;
106         match (cfg.meta_item(), mi.meta_item()) {
107             (Some(cfg), Some(mi)) =>
108                 if cfg_matches(&cfg, self.sess, self.features) {
109                     self.process_cfg_attr(ast::Attribute {
110                         id: attr::mk_attr_id(),
111                         style: attr.style,
112                         value: mi.clone(),
113                         is_sugared_doc: false,
114                         span: mi.span,
115                     })
116                 } else {
117                     None
118                 },
119             _ => {
120                 let msg = "unexpected literal(s) in `#[cfg_attr(<cfg pattern>, <attr>)]`";
121                 self.sess.span_diagnostic.span_err(attr.span, msg);
122                 None
123             }
124         }
125     }
126
127     // Determine if a node with the given attributes should be included in this configuation.
128     pub fn in_cfg(&mut self, attrs: &[ast::Attribute]) -> bool {
129         attrs.iter().all(|attr| {
130             // When not compiling with --test we should not compile the #[test] functions
131             if !self.should_test && is_test_or_bench(attr) {
132                 return false;
133             }
134
135             let mis = match attr.value.node {
136                 ast::MetaItemKind::List(ref mis) if is_cfg(&attr) => mis,
137                 _ => return true
138             };
139
140             if mis.len() != 1 {
141                 self.sess.span_diagnostic.span_err(attr.span, "expected 1 cfg-pattern");
142                 return true;
143             }
144
145             if !mis[0].is_meta_item() {
146                 self.sess.span_diagnostic.span_err(mis[0].span, "unexpected literal");
147                 return true;
148             }
149
150             attr::cfg_matches(mis[0].meta_item().unwrap(), self.sess, self.features)
151         })
152     }
153
154     // Visit attributes on expression and statements (but not attributes on items in blocks).
155     fn visit_expr_attrs(&mut self, attrs: &[ast::Attribute]) {
156         // flag the offending attributes
157         for attr in attrs.iter() {
158             if !self.features.map(|features| features.stmt_expr_attributes).unwrap_or(true) {
159                 let mut err = feature_err(&self.sess,
160                                           "stmt_expr_attributes",
161                                           attr.span,
162                                           GateIssue::Language,
163                                           EXPLAIN_STMT_ATTR_SYNTAX);
164                 if attr.is_sugared_doc {
165                     err.help("`///` is for documentation comments. For a plain comment, use `//`.");
166                 }
167                 err.emit();
168             }
169         }
170     }
171
172     pub fn configure_foreign_mod(&mut self, foreign_mod: ast::ForeignMod) -> ast::ForeignMod {
173         ast::ForeignMod {
174             abi: foreign_mod.abi,
175             items: foreign_mod.items.into_iter().filter_map(|item| self.configure(item)).collect(),
176         }
177     }
178
179     fn configure_variant_data(&mut self, vdata: ast::VariantData) -> ast::VariantData {
180         match vdata {
181             ast::VariantData::Struct(fields, id) => {
182                 let fields = fields.into_iter().filter_map(|field| self.configure(field));
183                 ast::VariantData::Struct(fields.collect(), id)
184             }
185             ast::VariantData::Tuple(fields, id) => {
186                 let fields = fields.into_iter().filter_map(|field| self.configure(field));
187                 ast::VariantData::Tuple(fields.collect(), id)
188             }
189             ast::VariantData::Unit(id) => ast::VariantData::Unit(id)
190         }
191     }
192
193     pub fn configure_item_kind(&mut self, item: ast::ItemKind) -> ast::ItemKind {
194         match item {
195             ast::ItemKind::Struct(def, generics) => {
196                 ast::ItemKind::Struct(self.configure_variant_data(def), generics)
197             }
198             ast::ItemKind::Union(def, generics) => {
199                 ast::ItemKind::Union(self.configure_variant_data(def), generics)
200             }
201             ast::ItemKind::Enum(def, generics) => {
202                 let variants = def.variants.into_iter().filter_map(|v| {
203                     self.configure(v).map(|v| {
204                         Spanned {
205                             node: ast::Variant_ {
206                                 name: v.node.name,
207                                 attrs: v.node.attrs,
208                                 data: self.configure_variant_data(v.node.data),
209                                 disr_expr: v.node.disr_expr,
210                             },
211                             span: v.span
212                         }
213                     })
214                 });
215                 ast::ItemKind::Enum(ast::EnumDef {
216                     variants: variants.collect(),
217                 }, generics)
218             }
219             item => item,
220         }
221     }
222
223     pub fn configure_expr_kind(&mut self, expr_kind: ast::ExprKind) -> ast::ExprKind {
224         match expr_kind {
225             ast::ExprKind::Match(m, arms) => {
226                 let arms = arms.into_iter().filter_map(|a| self.configure(a)).collect();
227                 ast::ExprKind::Match(m, arms)
228             }
229             ast::ExprKind::Struct(path, fields, base) => {
230                 let fields = fields.into_iter()
231                     .filter_map(|field| {
232                         self.visit_struct_field_attrs(field.attrs());
233                         self.configure(field)
234                     })
235                     .collect();
236                 ast::ExprKind::Struct(path, fields, base)
237             }
238             _ => expr_kind,
239         }
240     }
241
242     pub fn configure_expr(&mut self, expr: P<ast::Expr>) -> P<ast::Expr> {
243         self.visit_expr_attrs(expr.attrs());
244
245         // If an expr is valid to cfg away it will have been removed by the
246         // outer stmt or expression folder before descending in here.
247         // Anything else is always required, and thus has to error out
248         // in case of a cfg attr.
249         //
250         // NB: This is intentionally not part of the fold_expr() function
251         //     in order for fold_opt_expr() to be able to avoid this check
252         if let Some(attr) = expr.attrs().iter().find(|a| is_cfg(a) || is_test_or_bench(a)) {
253             let msg = "removing an expression is not supported in this position";
254             self.sess.span_diagnostic.span_err(attr.span, msg);
255         }
256
257         self.process_cfg_attrs(expr)
258     }
259
260     pub fn configure_stmt(&mut self, stmt: ast::Stmt) -> Option<ast::Stmt> {
261         self.configure(stmt)
262     }
263
264     pub fn configure_struct_expr_field(&mut self, field: ast::Field) -> Option<ast::Field> {
265         if !self.features.map(|features| features.struct_field_attributes).unwrap_or(true) {
266             if !field.attrs.is_empty() {
267                 let mut err = feature_err(&self.sess,
268                                           "struct_field_attributes",
269                                           field.span,
270                                           GateIssue::Language,
271                                           "attributes on struct literal fields are unstable");
272                 err.emit();
273             }
274         }
275
276         self.configure(field)
277     }
278
279     pub fn configure_pat(&mut self, pattern: P<ast::Pat>) -> P<ast::Pat> {
280         pattern.map(|mut pattern| {
281             if let ast::PatKind::Struct(path, fields, etc) = pattern.node {
282                 let fields = fields.into_iter()
283                     .filter_map(|field| {
284                         self.visit_struct_field_attrs(field.attrs());
285                         self.configure(field)
286                     })
287                     .collect();
288                 pattern.node = ast::PatKind::Struct(path, fields, etc);
289             }
290             pattern
291         })
292     }
293
294     fn visit_struct_field_attrs(&mut self, attrs: &[ast::Attribute]) {
295         // flag the offending attributes
296         for attr in attrs.iter() {
297             if !self.features.map(|features| features.struct_field_attributes).unwrap_or(true) {
298                 let mut err = feature_err(
299                     &self.sess,
300                     "struct_field_attributes",
301                     attr.span,
302                     GateIssue::Language,
303                     "attributes on struct pattern or literal fields are unstable");
304                 err.emit();
305             }
306         }
307     }
308 }
309
310 impl<'a> fold::Folder for StripUnconfigured<'a> {
311     fn fold_foreign_mod(&mut self, foreign_mod: ast::ForeignMod) -> ast::ForeignMod {
312         let foreign_mod = self.configure_foreign_mod(foreign_mod);
313         fold::noop_fold_foreign_mod(foreign_mod, self)
314     }
315
316     fn fold_item_kind(&mut self, item: ast::ItemKind) -> ast::ItemKind {
317         let item = self.configure_item_kind(item);
318         fold::noop_fold_item_kind(item, self)
319     }
320
321     fn fold_expr(&mut self, expr: P<ast::Expr>) -> P<ast::Expr> {
322         let mut expr = self.configure_expr(expr).unwrap();
323         expr.node = self.configure_expr_kind(expr.node);
324         P(fold::noop_fold_expr(expr, self))
325     }
326
327     fn fold_opt_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
328         let mut expr = configure!(self, expr).unwrap();
329         expr.node = self.configure_expr_kind(expr.node);
330         Some(P(fold::noop_fold_expr(expr, self)))
331     }
332
333     fn fold_stmt(&mut self, stmt: ast::Stmt) -> SmallVector<ast::Stmt> {
334         match self.configure_stmt(stmt) {
335             Some(stmt) => fold::noop_fold_stmt(stmt, self),
336             None => return SmallVector::new(),
337         }
338     }
339
340     fn fold_item(&mut self, item: P<ast::Item>) -> SmallVector<P<ast::Item>> {
341         fold::noop_fold_item(configure!(self, item), self)
342     }
343
344     fn fold_impl_item(&mut self, item: ast::ImplItem) -> SmallVector<ast::ImplItem> {
345         fold::noop_fold_impl_item(configure!(self, item), self)
346     }
347
348     fn fold_trait_item(&mut self, item: ast::TraitItem) -> SmallVector<ast::TraitItem> {
349         fold::noop_fold_trait_item(configure!(self, item), self)
350     }
351
352     fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
353         // Don't configure interpolated AST (c.f. #34171).
354         // Interpolated AST will get configured once the surrounding tokens are parsed.
355         mac
356     }
357
358     fn fold_pat(&mut self, pattern: P<ast::Pat>) -> P<ast::Pat> {
359         fold::noop_fold_pat(self.configure_pat(pattern), self)
360     }
361 }
362
363 fn is_cfg(attr: &ast::Attribute) -> bool {
364     attr.check_name("cfg")
365 }
366
367 pub fn is_test_or_bench(attr: &ast::Attribute) -> bool {
368     attr.check_name("test") || attr.check_name("bench")
369 }