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