]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/config.rs
auto merge of #17654 : gereeter/rust/no-unnecessary-cell, r=alexcrichton
[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::AttrMetaMethods;
12 use diagnostic::SpanHandler;
13 use fold::Folder;
14 use {ast, fold, attr};
15 use codemap::Spanned;
16 use ptr::P;
17
18 /// A folder that strips out items that do not belong in the current
19 /// configuration.
20 struct Context<'a> {
21     in_cfg: |attrs: &[ast::Attribute]|: 'a -> bool,
22 }
23
24 // Support conditional compilation by transforming the AST, stripping out
25 // any items that do not belong in the current configuration
26 pub fn strip_unconfigured_items(diagnostic: &SpanHandler, krate: ast::Crate) -> ast::Crate {
27     let config = krate.config.clone();
28     strip_items(krate, |attrs| in_cfg(diagnostic, config.as_slice(), attrs))
29 }
30
31 impl<'a> fold::Folder for Context<'a> {
32     fn fold_mod(&mut self, module: ast::Mod) -> ast::Mod {
33         fold_mod(self, module)
34     }
35     fn fold_block(&mut self, block: P<ast::Block>) -> P<ast::Block> {
36         fold_block(self, block)
37     }
38     fn fold_foreign_mod(&mut self, foreign_mod: ast::ForeignMod) -> ast::ForeignMod {
39         fold_foreign_mod(self, foreign_mod)
40     }
41     fn fold_item_underscore(&mut self, item: ast::Item_) -> ast::Item_ {
42         fold_item_underscore(self, item)
43     }
44     fn fold_expr(&mut self, expr: P<ast::Expr>) -> P<ast::Expr> {
45         fold_expr(self, expr)
46     }
47     fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
48         fold::noop_fold_mac(mac, self)
49     }
50 }
51
52 pub fn strip_items(krate: ast::Crate,
53                    in_cfg: |attrs: &[ast::Attribute]| -> bool)
54                    -> ast::Crate {
55     let mut ctxt = Context {
56         in_cfg: in_cfg,
57     };
58     ctxt.fold_crate(krate)
59 }
60
61 fn filter_view_item(cx: &mut Context, view_item: ast::ViewItem) -> Option<ast::ViewItem> {
62     if view_item_in_cfg(cx, &view_item) {
63         Some(view_item)
64     } else {
65         None
66     }
67 }
68
69 fn fold_mod(cx: &mut Context, ast::Mod {inner, view_items, items}: ast::Mod) -> ast::Mod {
70     ast::Mod {
71         inner: inner,
72         view_items: view_items.into_iter().filter_map(|a| {
73             filter_view_item(cx, a).map(|x| cx.fold_view_item(x))
74         }).collect(),
75         items: items.into_iter().filter_map(|a| {
76             if item_in_cfg(cx, &*a) {
77                 Some(cx.fold_item(a))
78             } else {
79                 None
80             }
81         }).flat_map(|x| x.into_iter()).collect()
82     }
83 }
84
85 fn filter_foreign_item(cx: &mut Context, item: P<ast::ForeignItem>)
86                        -> Option<P<ast::ForeignItem>> {
87     if foreign_item_in_cfg(cx, &*item) {
88         Some(item)
89     } else {
90         None
91     }
92 }
93
94 fn fold_foreign_mod(cx: &mut Context, ast::ForeignMod {abi, view_items, items}: ast::ForeignMod)
95                     -> ast::ForeignMod {
96     ast::ForeignMod {
97         abi: abi,
98         view_items: view_items.into_iter().filter_map(|a| {
99             filter_view_item(cx, a).map(|x| cx.fold_view_item(x))
100         }).collect(),
101         items: items.into_iter()
102                     .filter_map(|a| filter_foreign_item(cx, a))
103                     .collect()
104     }
105 }
106
107 fn fold_item_underscore(cx: &mut Context, item: ast::Item_) -> ast::Item_ {
108     let item = match item {
109         ast::ItemImpl(a, b, c, impl_items) => {
110             let impl_items = impl_items.into_iter()
111                                        .filter(|ii| impl_item_in_cfg(cx, ii))
112                                        .collect();
113             ast::ItemImpl(a, b, c, impl_items)
114         }
115         ast::ItemTrait(a, b, c, methods) => {
116             let methods = methods.into_iter()
117                                  .filter(|m| trait_method_in_cfg(cx, m))
118                                  .collect();
119             ast::ItemTrait(a, b, c, methods)
120         }
121         ast::ItemStruct(def, generics) => {
122             ast::ItemStruct(fold_struct(cx, def), generics)
123         }
124         ast::ItemEnum(def, generics) => {
125             let mut variants = def.variants.into_iter().filter_map(|v| {
126                 if !(cx.in_cfg)(v.node.attrs.as_slice()) {
127                     None
128                 } else {
129                     Some(v.map(|Spanned {node: ast::Variant_ {id, name, attrs, kind,
130                                                               disr_expr, vis}, span}| {
131                         Spanned {
132                             node: ast::Variant_ {
133                                 id: id,
134                                 name: name,
135                                 attrs: attrs,
136                                 kind: match kind {
137                                     ast::TupleVariantKind(..) => kind,
138                                     ast::StructVariantKind(def) => {
139                                         ast::StructVariantKind(fold_struct(cx, def))
140                                     }
141                                 },
142                                 disr_expr: disr_expr,
143                                 vis: vis
144                             },
145                             span: span
146                         }
147                     }))
148                 }
149             });
150             ast::ItemEnum(ast::EnumDef {
151                 variants: variants.collect(),
152             }, generics)
153         }
154         item => item,
155     };
156
157     fold::noop_fold_item_underscore(item, cx)
158 }
159
160 fn fold_struct(cx: &mut Context, def: P<ast::StructDef>) -> P<ast::StructDef> {
161     def.map(|ast::StructDef {fields, ctor_id, super_struct, is_virtual}| {
162         ast::StructDef {
163             fields: fields.into_iter().filter(|m| {
164                 (cx.in_cfg)(m.node.attrs.as_slice())
165             }).collect(),
166             ctor_id: ctor_id,
167             super_struct: super_struct,
168             is_virtual: is_virtual,
169         }
170     })
171 }
172
173 fn retain_stmt(cx: &mut Context, stmt: &ast::Stmt) -> bool {
174     match stmt.node {
175         ast::StmtDecl(ref decl, _) => {
176             match decl.node {
177                 ast::DeclItem(ref item) => {
178                     item_in_cfg(cx, &**item)
179                 }
180                 _ => true
181             }
182         }
183         _ => true
184     }
185 }
186
187 fn fold_block(cx: &mut Context, b: P<ast::Block>) -> P<ast::Block> {
188     b.map(|ast::Block {id, view_items, stmts, expr, rules, span}| {
189         let resulting_stmts: Vec<P<ast::Stmt>> =
190             stmts.into_iter().filter(|a| retain_stmt(cx, &**a)).collect();
191         let resulting_stmts = resulting_stmts.into_iter()
192             .flat_map(|stmt| cx.fold_stmt(stmt).into_iter())
193             .collect();
194         let filtered_view_items = view_items.into_iter().filter_map(|a| {
195             filter_view_item(cx, a).map(|x| cx.fold_view_item(x))
196         }).collect();
197         ast::Block {
198             id: id,
199             view_items: filtered_view_items,
200             stmts: resulting_stmts,
201             expr: expr.map(|x| cx.fold_expr(x)),
202             rules: rules,
203             span: span,
204         }
205     })
206 }
207
208 fn fold_expr(cx: &mut Context, expr: P<ast::Expr>) -> P<ast::Expr> {
209     expr.map(|ast::Expr {id, span, node}| {
210         fold::noop_fold_expr(ast::Expr {
211             id: id,
212             node: match node {
213                 ast::ExprMatch(m, arms, source) => {
214                     ast::ExprMatch(m, arms.into_iter()
215                                         .filter(|a| (cx.in_cfg)(a.attrs.as_slice()))
216                                         .collect(), source)
217                 }
218                 _ => node
219             },
220             span: span
221         }, cx)
222     })
223 }
224
225 fn item_in_cfg(cx: &mut Context, item: &ast::Item) -> bool {
226     return (cx.in_cfg)(item.attrs.as_slice());
227 }
228
229 fn foreign_item_in_cfg(cx: &mut Context, item: &ast::ForeignItem) -> bool {
230     return (cx.in_cfg)(item.attrs.as_slice());
231 }
232
233 fn view_item_in_cfg(cx: &mut Context, item: &ast::ViewItem) -> bool {
234     return (cx.in_cfg)(item.attrs.as_slice());
235 }
236
237 fn trait_method_in_cfg(cx: &mut Context, meth: &ast::TraitItem) -> bool {
238     match *meth {
239         ast::RequiredMethod(ref meth) => (cx.in_cfg)(meth.attrs.as_slice()),
240         ast::ProvidedMethod(ref meth) => (cx.in_cfg)(meth.attrs.as_slice()),
241         ast::TypeTraitItem(ref typ) => (cx.in_cfg)(typ.attrs.as_slice()),
242     }
243 }
244
245 fn impl_item_in_cfg(cx: &mut Context, impl_item: &ast::ImplItem) -> bool {
246     match *impl_item {
247         ast::MethodImplItem(ref meth) => (cx.in_cfg)(meth.attrs.as_slice()),
248         ast::TypeImplItem(ref typ) => (cx.in_cfg)(typ.attrs.as_slice()),
249     }
250 }
251
252 // Determine if an item should be translated in the current crate
253 // configuration based on the item's attributes
254 fn in_cfg(diagnostic: &SpanHandler, cfg: &[P<ast::MetaItem>], attrs: &[ast::Attribute]) -> bool {
255     let mut in_cfg = false;
256     let mut seen_cfg = false;
257     for attr in attrs.iter() {
258         let mis = match attr.node.value.node {
259             ast::MetaList(_, ref mis) if attr.check_name("cfg") => mis,
260             _ => continue
261         };
262
263         if mis.len() != 1 {
264             diagnostic.span_warn(attr.span, "The use of multiple cfgs in the top level of \
265                                              `#[cfg(..)]` is deprecated. Change `#[cfg(a, b)]` to \
266                                              `#[cfg(all(a, b))]`.");
267         }
268
269         if seen_cfg {
270             diagnostic.span_warn(attr.span, "The semantics of multiple `#[cfg(..)]` attributes on \
271                                              same item are changing from the union of the cfgs to \
272                                              the intersection of the cfgs. Change `#[cfg(a)] \
273                                              #[cfg(b)]` to `#[cfg(any(a, b))]`.");
274         }
275
276         seen_cfg = true;
277         in_cfg |= mis.iter().all(|mi| attr::cfg_matches(diagnostic, cfg, &**mi));
278     }
279     in_cfg | !seen_cfg
280 }
281