]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/config.rs
Rollup merge of #36099 - skade:better-try-documentation, r=steveklabnik
[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::{emit_feature_err, EXPLAIN_STMT_ATTR_SYNTAX, Features, get_features, GateIssue};
13 use fold::Folder;
14 use {fold, attr};
15 use ast;
16 use codemap::{Spanned, respan};
17 use parse::{ParseSess, token};
18 use ptr::P;
19
20 use util::small_vector::SmallVector;
21
22 /// A folder that strips out items that do not belong in the current configuration.
23 pub struct StripUnconfigured<'a> {
24     pub config: &'a ast::CrateConfig,
25     pub should_test: bool,
26     pub sess: &'a ParseSess,
27     pub features: Option<&'a Features>,
28 }
29
30 impl<'a> StripUnconfigured<'a> {
31     fn configure<T: HasAttrs>(&mut self, node: T) -> Option<T> {
32         let node = self.process_cfg_attrs(node);
33         if self.in_cfg(node.attrs()) { Some(node) } else { None }
34     }
35
36     pub fn process_cfg_attrs<T: HasAttrs>(&mut self, node: T) -> T {
37         node.map_attrs(|attrs| {
38             attrs.into_iter().filter_map(|attr| self.process_cfg_attr(attr)).collect()
39         })
40     }
41
42     fn process_cfg_attr(&mut self, attr: ast::Attribute) -> Option<ast::Attribute> {
43         if !attr.check_name("cfg_attr") {
44             return Some(attr);
45         }
46
47         let attr_list = match attr.meta_item_list() {
48             Some(attr_list) => attr_list,
49             None => {
50                 let msg = "expected `#[cfg_attr(<cfg pattern>, <attr>)]`";
51                 self.sess.span_diagnostic.span_err(attr.span, msg);
52                 return None;
53             }
54         };
55
56         let (cfg, mi) = match (attr_list.len(), attr_list.get(0), attr_list.get(1)) {
57             (2, Some(cfg), Some(mi)) => (cfg, mi),
58             _ => {
59                 let msg = "expected `#[cfg_attr(<cfg pattern>, <attr>)]`";
60                 self.sess.span_diagnostic.span_err(attr.span, msg);
61                 return None;
62             }
63         };
64
65         use attr::cfg_matches;
66         match (cfg.meta_item(), mi.meta_item()) {
67             (Some(cfg), Some(mi)) =>
68                 if cfg_matches(self.config, &cfg, self.sess, self.features) {
69                     self.process_cfg_attr(respan(mi.span, ast::Attribute_ {
70                         id: attr::mk_attr_id(),
71                         style: attr.node.style,
72                         value: mi.clone(),
73                         is_sugared_doc: false,
74                     }))
75                 } else {
76                     None
77                 },
78             _ => {
79                 let msg = "unexpected literal(s) in `#[cfg_attr(<cfg pattern>, <attr>)]`";
80                 self.sess.span_diagnostic.span_err(attr.span, msg);
81                 None
82             }
83         }
84     }
85
86     // Determine if a node with the given attributes should be included in this configuation.
87     fn in_cfg(&mut self, attrs: &[ast::Attribute]) -> bool {
88         attrs.iter().all(|attr| {
89             // When not compiling with --test we should not compile the #[test] functions
90             if !self.should_test && is_test_or_bench(attr) {
91                 return false;
92             }
93
94             let mis = match attr.node.value.node {
95                 ast::MetaItemKind::List(_, ref mis) if is_cfg(&attr) => mis,
96                 _ => return true
97             };
98
99             if mis.len() != 1 {
100                 self.sess.span_diagnostic.span_err(attr.span, "expected 1 cfg-pattern");
101                 return true;
102             }
103
104             if !mis[0].is_meta_item() {
105                 self.sess.span_diagnostic.span_err(mis[0].span, "unexpected literal");
106                 return true;
107             }
108
109             attr::cfg_matches(self.config, mis[0].meta_item().unwrap(), self.sess, self.features)
110         })
111     }
112
113     // Visit attributes on expression and statements (but not attributes on items in blocks).
114     fn visit_stmt_or_expr_attrs(&mut self, attrs: &[ast::Attribute]) {
115         // flag the offending attributes
116         for attr in attrs.iter() {
117             if !self.features.map(|features| features.stmt_expr_attributes).unwrap_or(true) {
118                 emit_feature_err(&self.sess.span_diagnostic,
119                                  "stmt_expr_attributes",
120                                  attr.span,
121                                  GateIssue::Language,
122                                  EXPLAIN_STMT_ATTR_SYNTAX);
123             }
124         }
125     }
126 }
127
128 // Support conditional compilation by transforming the AST, stripping out
129 // any items that do not belong in the current configuration
130 pub fn strip_unconfigured_items(mut krate: ast::Crate, sess: &ParseSess, should_test: bool)
131                                 -> (ast::Crate, Features) {
132     let features;
133     {
134         let mut strip_unconfigured = StripUnconfigured {
135             config: &krate.config.clone(),
136             should_test: should_test,
137             sess: sess,
138             features: None,
139         };
140
141         let err_count = sess.span_diagnostic.err_count();
142         let krate_attrs = strip_unconfigured.configure(krate.attrs.clone()).unwrap_or_default();
143         features = get_features(&sess.span_diagnostic, &krate_attrs);
144         if err_count < sess.span_diagnostic.err_count() {
145             krate.attrs = krate_attrs.clone(); // Avoid reconfiguring malformed `cfg_attr`s
146         }
147
148         strip_unconfigured.features = Some(&features);
149         krate = strip_unconfigured.fold_crate(krate);
150         krate.attrs = krate_attrs;
151     }
152
153     (krate, features)
154 }
155
156 impl<'a> fold::Folder for StripUnconfigured<'a> {
157     fn fold_foreign_mod(&mut self, foreign_mod: ast::ForeignMod) -> ast::ForeignMod {
158         ast::ForeignMod {
159             abi: foreign_mod.abi,
160             items: foreign_mod.items.into_iter().filter_map(|item| {
161                 self.configure(item).map(|item| fold::noop_fold_foreign_item(item, self))
162             }).collect(),
163         }
164     }
165
166     fn fold_item_kind(&mut self, item: ast::ItemKind) -> ast::ItemKind {
167         let fold_struct = |this: &mut Self, vdata| match vdata {
168             ast::VariantData::Struct(fields, id) => {
169                 let fields = fields.into_iter().filter_map(|field| this.configure(field));
170                 ast::VariantData::Struct(fields.collect(), id)
171             }
172             ast::VariantData::Tuple(fields, id) => {
173                 let fields = fields.into_iter().filter_map(|field| this.configure(field));
174                 ast::VariantData::Tuple(fields.collect(), id)
175             }
176             ast::VariantData::Unit(id) => ast::VariantData::Unit(id)
177         };
178
179         let item = match item {
180             ast::ItemKind::Struct(def, generics) => {
181                 ast::ItemKind::Struct(fold_struct(self, def), generics)
182             }
183             ast::ItemKind::Union(def, generics) => {
184                 ast::ItemKind::Union(fold_struct(self, def), generics)
185             }
186             ast::ItemKind::Enum(def, generics) => {
187                 let variants = def.variants.into_iter().filter_map(|v| {
188                     self.configure(v).map(|v| {
189                         Spanned {
190                             node: ast::Variant_ {
191                                 name: v.node.name,
192                                 attrs: v.node.attrs,
193                                 data: fold_struct(self, v.node.data),
194                                 disr_expr: v.node.disr_expr,
195                             },
196                             span: v.span
197                         }
198                     })
199                 });
200                 ast::ItemKind::Enum(ast::EnumDef {
201                     variants: variants.collect(),
202                 }, generics)
203             }
204             item => item,
205         };
206
207         fold::noop_fold_item_kind(item, self)
208     }
209
210     fn fold_expr(&mut self, expr: P<ast::Expr>) -> P<ast::Expr> {
211         self.visit_stmt_or_expr_attrs(expr.attrs());
212
213         // If an expr is valid to cfg away it will have been removed by the
214         // outer stmt or expression folder before descending in here.
215         // Anything else is always required, and thus has to error out
216         // in case of a cfg attr.
217         //
218         // NB: This is intentionally not part of the fold_expr() function
219         //     in order for fold_opt_expr() to be able to avoid this check
220         if let Some(attr) = expr.attrs().iter().find(|a| is_cfg(a) || is_test_or_bench(a)) {
221             let msg = "removing an expression is not supported in this position";
222             self.sess.span_diagnostic.span_err(attr.span, msg);
223         }
224
225         let expr = self.process_cfg_attrs(expr);
226         fold_expr(self, expr)
227     }
228
229     fn fold_opt_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
230         self.configure(expr).map(|expr| fold_expr(self, expr))
231     }
232
233     fn fold_stmt(&mut self, stmt: ast::Stmt) -> SmallVector<ast::Stmt> {
234         self.visit_stmt_or_expr_attrs(stmt.attrs());
235         self.configure(stmt).map(|stmt| fold::noop_fold_stmt(stmt, self))
236                             .unwrap_or(SmallVector::zero())
237     }
238
239     fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
240         fold::noop_fold_mac(mac, self)
241     }
242
243     fn fold_item(&mut self, item: P<ast::Item>) -> SmallVector<P<ast::Item>> {
244         self.configure(item).map(|item| fold::noop_fold_item(item, self))
245                             .unwrap_or(SmallVector::zero())
246     }
247
248     fn fold_impl_item(&mut self, item: ast::ImplItem) -> SmallVector<ast::ImplItem> {
249         self.configure(item).map(|item| fold::noop_fold_impl_item(item, self))
250                             .unwrap_or(SmallVector::zero())
251     }
252
253     fn fold_trait_item(&mut self, item: ast::TraitItem) -> SmallVector<ast::TraitItem> {
254         self.configure(item).map(|item| fold::noop_fold_trait_item(item, self))
255                             .unwrap_or(SmallVector::zero())
256     }
257
258     fn fold_interpolated(&mut self, nt: token::Nonterminal) -> token::Nonterminal {
259         // Don't configure interpolated AST (c.f. #34171).
260         // Interpolated AST will get configured once the surrounding tokens are parsed.
261         nt
262     }
263 }
264
265 fn fold_expr(folder: &mut StripUnconfigured, expr: P<ast::Expr>) -> P<ast::Expr> {
266     expr.map(|ast::Expr {id, span, node, attrs}| {
267         fold::noop_fold_expr(ast::Expr {
268             id: id,
269             node: match node {
270                 ast::ExprKind::Match(m, arms) => {
271                     ast::ExprKind::Match(m, arms.into_iter()
272                                         .filter_map(|a| folder.configure(a))
273                                         .collect())
274                 }
275                 _ => node
276             },
277             span: span,
278             attrs: attrs,
279         }, folder)
280     })
281 }
282
283 fn is_cfg(attr: &ast::Attribute) -> bool {
284     attr.check_name("cfg")
285 }
286
287 fn is_test_or_bench(attr: &ast::Attribute) -> bool {
288     attr.check_name("test") || attr.check_name("bench")
289 }