]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/config.rs
rollup merge of #18407 : thestinger/arena
[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 }| {
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         }
168     })
169 }
170
171 fn retain_stmt(cx: &mut Context, stmt: &ast::Stmt) -> bool {
172     match stmt.node {
173         ast::StmtDecl(ref decl, _) => {
174             match decl.node {
175                 ast::DeclItem(ref item) => {
176                     item_in_cfg(cx, &**item)
177                 }
178                 _ => true
179             }
180         }
181         _ => true
182     }
183 }
184
185 fn fold_block(cx: &mut Context, b: P<ast::Block>) -> P<ast::Block> {
186     b.map(|ast::Block {id, view_items, stmts, expr, rules, span}| {
187         let resulting_stmts: Vec<P<ast::Stmt>> =
188             stmts.into_iter().filter(|a| retain_stmt(cx, &**a)).collect();
189         let resulting_stmts = resulting_stmts.into_iter()
190             .flat_map(|stmt| cx.fold_stmt(stmt).into_iter())
191             .collect();
192         let filtered_view_items = view_items.into_iter().filter_map(|a| {
193             filter_view_item(cx, a).map(|x| cx.fold_view_item(x))
194         }).collect();
195         ast::Block {
196             id: id,
197             view_items: filtered_view_items,
198             stmts: resulting_stmts,
199             expr: expr.map(|x| cx.fold_expr(x)),
200             rules: rules,
201             span: span,
202         }
203     })
204 }
205
206 fn fold_expr(cx: &mut Context, expr: P<ast::Expr>) -> P<ast::Expr> {
207     expr.map(|ast::Expr {id, span, node}| {
208         fold::noop_fold_expr(ast::Expr {
209             id: id,
210             node: match node {
211                 ast::ExprMatch(m, arms, source) => {
212                     ast::ExprMatch(m, arms.into_iter()
213                                         .filter(|a| (cx.in_cfg)(a.attrs.as_slice()))
214                                         .collect(), source)
215                 }
216                 _ => node
217             },
218             span: span
219         }, cx)
220     })
221 }
222
223 fn item_in_cfg(cx: &mut Context, item: &ast::Item) -> bool {
224     return (cx.in_cfg)(item.attrs.as_slice());
225 }
226
227 fn foreign_item_in_cfg(cx: &mut Context, item: &ast::ForeignItem) -> bool {
228     return (cx.in_cfg)(item.attrs.as_slice());
229 }
230
231 fn view_item_in_cfg(cx: &mut Context, item: &ast::ViewItem) -> bool {
232     return (cx.in_cfg)(item.attrs.as_slice());
233 }
234
235 fn trait_method_in_cfg(cx: &mut Context, meth: &ast::TraitItem) -> bool {
236     match *meth {
237         ast::RequiredMethod(ref meth) => (cx.in_cfg)(meth.attrs.as_slice()),
238         ast::ProvidedMethod(ref meth) => (cx.in_cfg)(meth.attrs.as_slice()),
239         ast::TypeTraitItem(ref typ) => (cx.in_cfg)(typ.attrs.as_slice()),
240     }
241 }
242
243 fn impl_item_in_cfg(cx: &mut Context, impl_item: &ast::ImplItem) -> bool {
244     match *impl_item {
245         ast::MethodImplItem(ref meth) => (cx.in_cfg)(meth.attrs.as_slice()),
246         ast::TypeImplItem(ref typ) => (cx.in_cfg)(typ.attrs.as_slice()),
247     }
248 }
249
250 // Determine if an item should be translated in the current crate
251 // configuration based on the item's attributes
252 fn in_cfg(diagnostic: &SpanHandler, cfg: &[P<ast::MetaItem>], attrs: &[ast::Attribute]) -> bool {
253     attrs.iter().all(|attr| {
254         let mis = match attr.node.value.node {
255             ast::MetaList(_, ref mis) if attr.check_name("cfg") => mis,
256             _ => return true
257         };
258
259         if mis.len() != 1 {
260             diagnostic.span_err(attr.span, "expected 1 cfg-pattern");
261             return true;
262         }
263
264         attr::cfg_matches(diagnostic, cfg, &*mis[0])
265     })
266 }
267