]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/config.rs
840acff73ada49a5921b62b589a5111b5c7ba1d0
[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 errors::Handler;
13 use feature_gate::GatedCfgAttr;
14 use fold::Folder;
15 use {ast, fold, attr};
16 use visit;
17 use codemap::{Spanned, respan};
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
23 /// configuration.
24 struct Context<'a, F> where F: FnMut(&[ast::Attribute]) -> bool {
25     in_cfg: F,
26     diagnostic: &'a Handler,
27 }
28
29 // Support conditional compilation by transforming the AST, stripping out
30 // any items that do not belong in the current configuration
31 pub fn strip_unconfigured_items(diagnostic: &Handler, krate: ast::Crate,
32                                 feature_gated_cfgs: &mut Vec<GatedCfgAttr>)
33                                 -> ast::Crate
34 {
35     // Need to do this check here because cfg runs before feature_gates
36     check_for_gated_stmt_expr_attributes(&krate, feature_gated_cfgs);
37
38     let krate = process_cfg_attr(diagnostic, krate, feature_gated_cfgs);
39     let config = krate.config.clone();
40     strip_items(diagnostic,
41                 krate,
42                 |attrs| {
43                     let mut diag = CfgDiagReal {
44                         diag: diagnostic,
45                         feature_gated_cfgs: feature_gated_cfgs,
46                     };
47                     in_cfg(&config, attrs, &mut diag)
48                 })
49 }
50
51 impl<'a, F> fold::Folder for Context<'a, F> where F: FnMut(&[ast::Attribute]) -> bool {
52     fn fold_foreign_mod(&mut self, foreign_mod: ast::ForeignMod) -> ast::ForeignMod {
53         fold_foreign_mod(self, foreign_mod)
54     }
55     fn fold_item_underscore(&mut self, item: ast::Item_) -> ast::Item_ {
56         fold_item_underscore(self, item)
57     }
58     fn fold_expr(&mut self, expr: P<ast::Expr>) -> P<ast::Expr> {
59         // If an expr is valid to cfg away it will have been removed by the
60         // outer stmt or expression folder before descending in here.
61         // Anything else is always required, and thus has to error out
62         // in case of a cfg attr.
63         //
64         // NB: This is intentionally not part of the fold_expr() function
65         //     in order for fold_opt_expr() to be able to avoid this check
66         if let Some(attr) = expr.attrs().iter().find(|a| is_cfg(a)) {
67             self.diagnostic.span_err(attr.span,
68                 "removing an expression is not supported in this position");
69         }
70         fold_expr(self, expr)
71     }
72     fn fold_opt_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
73         fold_opt_expr(self, expr)
74     }
75     fn fold_stmt(&mut self, stmt: P<ast::Stmt>) -> SmallVector<P<ast::Stmt>> {
76         fold_stmt(self, stmt)
77     }
78     fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
79         fold::noop_fold_mac(mac, self)
80     }
81     fn fold_item(&mut self, item: P<ast::Item>) -> SmallVector<P<ast::Item>> {
82         fold_item(self, item)
83     }
84 }
85
86 pub fn strip_items<'a, F>(diagnostic: &'a Handler,
87                           krate: ast::Crate, in_cfg: F) -> ast::Crate where
88     F: FnMut(&[ast::Attribute]) -> bool,
89 {
90     let mut ctxt = Context {
91         in_cfg: in_cfg,
92         diagnostic: diagnostic,
93     };
94     ctxt.fold_crate(krate)
95 }
96
97 fn filter_foreign_item<F>(cx: &mut Context<F>,
98                           item: P<ast::ForeignItem>)
99                           -> Option<P<ast::ForeignItem>> where
100     F: FnMut(&[ast::Attribute]) -> bool
101 {
102     if foreign_item_in_cfg(cx, &item) {
103         Some(item)
104     } else {
105         None
106     }
107 }
108
109 fn fold_foreign_mod<F>(cx: &mut Context<F>,
110                        ast::ForeignMod {abi, items}: ast::ForeignMod)
111                        -> ast::ForeignMod where
112     F: FnMut(&[ast::Attribute]) -> bool
113 {
114     ast::ForeignMod {
115         abi: abi,
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, o, a, b, c, impl_items) => {
137             let impl_items = impl_items.into_iter()
138                                        .filter(|ii| (cx.in_cfg)(&ii.attrs))
139                                        .collect();
140             ast::ItemImpl(u, o, a, b, c, impl_items)
141         }
142         ast::ItemTrait(u, a, b, methods) => {
143             let methods = methods.into_iter()
144                                  .filter(|ti| (cx.in_cfg)(&ti.attrs))
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) {
154                     None
155                 } else {
156                     Some(v.map(|Spanned {node: ast::Variant_ {name, attrs, data,
157                                                               disr_expr}, span}| {
158                         Spanned {
159                             node: ast::Variant_ {
160                                 name: name,
161                                 attrs: attrs,
162                                 data: fold_struct(cx, data),
163                                 disr_expr: disr_expr,
164                             },
165                             span: span
166                         }
167                     }))
168                 }
169             });
170             ast::ItemEnum(ast::EnumDef {
171                 variants: variants.collect(),
172             }, generics)
173         }
174         item => item,
175     };
176
177     fold::noop_fold_item_underscore(item, cx)
178 }
179
180 fn fold_struct<F>(cx: &mut Context<F>, vdata: ast::VariantData) -> ast::VariantData where
181     F: FnMut(&[ast::Attribute]) -> bool
182 {
183     match vdata {
184         ast::VariantData::Struct(fields, id) => {
185             ast::VariantData::Struct(fields.into_iter().filter(|m| {
186                 (cx.in_cfg)(&m.node.attrs)
187             }).collect(), id)
188         }
189         ast::VariantData::Tuple(fields, id) => {
190             ast::VariantData::Tuple(fields.into_iter().filter(|m| {
191                 (cx.in_cfg)(&m.node.attrs)
192             }).collect(), id)
193         }
194         ast::VariantData::Unit(id) => ast::VariantData::Unit(id)
195     }
196 }
197
198 fn fold_opt_expr<F>(cx: &mut Context<F>, expr: P<ast::Expr>) -> Option<P<ast::Expr>>
199     where F: FnMut(&[ast::Attribute]) -> bool
200 {
201     if expr_in_cfg(cx, &expr) {
202         Some(fold_expr(cx, expr))
203     } else {
204         None
205     }
206 }
207
208 fn fold_expr<F>(cx: &mut Context<F>, expr: P<ast::Expr>) -> P<ast::Expr> where
209     F: FnMut(&[ast::Attribute]) -> bool
210 {
211     expr.map(|ast::Expr {id, span, node, attrs}| {
212         fold::noop_fold_expr(ast::Expr {
213             id: id,
214             node: match node {
215                 ast::ExprKind::Match(m, arms) => {
216                     ast::ExprKind::Match(m, arms.into_iter()
217                                         .filter(|a| (cx.in_cfg)(&a.attrs))
218                                         .collect())
219                 }
220                 _ => node
221             },
222             span: span,
223             attrs: attrs,
224         }, cx)
225     })
226 }
227
228 fn fold_stmt<F>(cx: &mut Context<F>, stmt: P<ast::Stmt>) -> SmallVector<P<ast::Stmt>>
229     where F: FnMut(&[ast::Attribute]) -> bool
230 {
231     if stmt_in_cfg(cx, &stmt) {
232         stmt.and_then(|s| fold::noop_fold_stmt(s, cx))
233     } else {
234         SmallVector::zero()
235     }
236 }
237
238 fn stmt_in_cfg<F>(cx: &mut Context<F>, stmt: &ast::Stmt) -> bool where
239     F: FnMut(&[ast::Attribute]) -> bool
240 {
241     (cx.in_cfg)(stmt.node.attrs())
242 }
243
244 fn expr_in_cfg<F>(cx: &mut Context<F>, expr: &ast::Expr) -> bool where
245     F: FnMut(&[ast::Attribute]) -> bool
246 {
247     (cx.in_cfg)(expr.attrs())
248 }
249
250 fn item_in_cfg<F>(cx: &mut Context<F>, item: &ast::Item) -> bool where
251     F: FnMut(&[ast::Attribute]) -> bool
252 {
253     return (cx.in_cfg)(&item.attrs);
254 }
255
256 fn foreign_item_in_cfg<F>(cx: &mut Context<F>, item: &ast::ForeignItem) -> bool where
257     F: FnMut(&[ast::Attribute]) -> bool
258 {
259     return (cx.in_cfg)(&item.attrs);
260 }
261
262 fn is_cfg(attr: &ast::Attribute) -> bool {
263     attr.check_name("cfg")
264 }
265
266 // Determine if an item should be translated in the current crate
267 // configuration based on the item's attributes
268 fn in_cfg<T: CfgDiag>(cfg: &[P<ast::MetaItem>],
269                       attrs: &[ast::Attribute],
270                       diag: &mut T) -> bool {
271     attrs.iter().all(|attr| {
272         let mis = match attr.node.value.node {
273             ast::MetaList(_, ref mis) if is_cfg(&attr) => mis,
274             _ => return true
275         };
276
277         if mis.len() != 1 {
278             diag.emit_error(|diagnostic| {
279                 diagnostic.span_err(attr.span, "expected 1 cfg-pattern");
280             });
281             return true;
282         }
283
284         attr::cfg_matches(cfg, &mis[0], diag)
285     })
286 }
287
288 struct CfgAttrFolder<'a, T> {
289     diag: T,
290     config: &'a ast::CrateConfig,
291 }
292
293 // Process `#[cfg_attr]`.
294 fn process_cfg_attr(diagnostic: &Handler, krate: ast::Crate,
295                     feature_gated_cfgs: &mut Vec<GatedCfgAttr>) -> ast::Crate {
296     let mut fld = CfgAttrFolder {
297         diag: CfgDiagReal {
298             diag: diagnostic,
299             feature_gated_cfgs: feature_gated_cfgs,
300         },
301         config: &krate.config.clone(),
302     };
303     fld.fold_crate(krate)
304 }
305
306 impl<'a, T: CfgDiag> fold::Folder for CfgAttrFolder<'a, T> {
307     fn fold_attribute(&mut self, attr: ast::Attribute) -> Option<ast::Attribute> {
308         if !attr.check_name("cfg_attr") {
309             return fold::noop_fold_attribute(attr, self);
310         }
311
312         let attr_list = match attr.meta_item_list() {
313             Some(attr_list) => attr_list,
314             None => {
315                 self.diag.emit_error(|diag| {
316                     diag.span_err(attr.span,
317                         "expected `#[cfg_attr(<cfg pattern>, <attr>)]`");
318                 });
319                 return None;
320             }
321         };
322         let (cfg, mi) = match (attr_list.len(), attr_list.get(0), attr_list.get(1)) {
323             (2, Some(cfg), Some(mi)) => (cfg, mi),
324             _ => {
325                 self.diag.emit_error(|diag| {
326                     diag.span_err(attr.span,
327                         "expected `#[cfg_attr(<cfg pattern>, <attr>)]`");
328                 });
329                 return None;
330             }
331         };
332
333         if attr::cfg_matches(&self.config[..], &cfg, &mut self.diag) {
334             Some(respan(mi.span, ast::Attribute_ {
335                 id: attr::mk_attr_id(),
336                 style: attr.node.style,
337                 value: mi.clone(),
338                 is_sugared_doc: false,
339             }))
340         } else {
341             None
342         }
343     }
344
345     // Need the ability to run pre-expansion.
346     fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
347         fold::noop_fold_mac(mac, self)
348     }
349 }
350
351 fn check_for_gated_stmt_expr_attributes(krate: &ast::Crate,
352                                         discovered: &mut Vec<GatedCfgAttr>) {
353     let mut v = StmtExprAttrFeatureVisitor {
354         config: &krate.config,
355         discovered: discovered,
356     };
357     visit::walk_crate(&mut v, krate);
358 }
359
360 /// To cover this feature, we need to discover all attributes
361 /// so we need to run before cfg.
362 struct StmtExprAttrFeatureVisitor<'a, 'b> {
363     config: &'a ast::CrateConfig,
364     discovered: &'b mut Vec<GatedCfgAttr>,
365 }
366
367 // Runs the cfg_attr and cfg folders locally in "silent" mode
368 // to discover attribute use on stmts or expressions ahead of time
369 impl<'v, 'a, 'b> visit::Visitor<'v> for StmtExprAttrFeatureVisitor<'a, 'b> {
370     fn visit_stmt(&mut self, s: &'v ast::Stmt) {
371         // check if there even are any attributes on this node
372         let stmt_attrs = s.node.attrs();
373         if stmt_attrs.len() > 0 {
374             // attributes on items are fine
375             if let ast::StmtKind::Decl(ref decl, _) = s.node {
376                 if let ast::DeclKind::Item(_) = decl.node {
377                     visit::walk_stmt(self, s);
378                     return;
379                 }
380             }
381
382             // flag the offending attributes
383             for attr in stmt_attrs {
384                 self.discovered.push(GatedCfgAttr::GatedAttr(attr.span));
385             }
386
387             // if the node does not end up being cfg-d away, walk down
388             if node_survives_cfg(stmt_attrs, self.config) {
389                 visit::walk_stmt(self, s);
390             }
391         } else {
392             visit::walk_stmt(self, s);
393         }
394     }
395
396     fn visit_expr(&mut self, ex: &'v ast::Expr) {
397         // check if there even are any attributes on this node
398         let expr_attrs = ex.attrs();
399         if expr_attrs.len() > 0 {
400
401             // flag the offending attributes
402             for attr in expr_attrs {
403                 self.discovered.push(GatedCfgAttr::GatedAttr(attr.span));
404             }
405
406             // if the node does not end up being cfg-d away, walk down
407             if node_survives_cfg(expr_attrs, self.config) {
408                 visit::walk_expr(self, ex);
409             }
410         } else {
411             visit::walk_expr(self, ex);
412         }
413     }
414
415     fn visit_foreign_item(&mut self, i: &'v ast::ForeignItem) {
416         if node_survives_cfg(&i.attrs, self.config) {
417             visit::walk_foreign_item(self, i);
418         }
419     }
420
421     fn visit_item(&mut self, i: &'v ast::Item) {
422         if node_survives_cfg(&i.attrs, self.config) {
423             visit::walk_item(self, i);
424         }
425     }
426
427     fn visit_impl_item(&mut self, ii: &'v ast::ImplItem) {
428         if node_survives_cfg(&ii.attrs, self.config) {
429             visit::walk_impl_item(self, ii);
430         }
431     }
432
433     fn visit_trait_item(&mut self, ti: &'v ast::TraitItem) {
434         if node_survives_cfg(&ti.attrs, self.config) {
435             visit::walk_trait_item(self, ti);
436         }
437     }
438
439     fn visit_struct_field(&mut self, s: &'v ast::StructField) {
440         if node_survives_cfg(&s.node.attrs, self.config) {
441             visit::walk_struct_field(self, s);
442         }
443     }
444
445     fn visit_variant(&mut self, v: &'v ast::Variant,
446                      g: &'v ast::Generics, item_id: ast::NodeId) {
447         if node_survives_cfg(&v.node.attrs, self.config) {
448             visit::walk_variant(self, v, g, item_id);
449         }
450     }
451
452     fn visit_arm(&mut self, a: &'v ast::Arm) {
453         if node_survives_cfg(&a.attrs, self.config) {
454             visit::walk_arm(self, a);
455         }
456     }
457
458     // This visitor runs pre expansion, so we need to prevent
459     // the default panic here
460     fn visit_mac(&mut self, mac: &'v ast::Mac) {
461         visit::walk_mac(self, mac)
462     }
463 }
464
465 pub trait CfgDiag {
466     fn emit_error<F>(&mut self, f: F) where F: FnMut(&Handler);
467     fn flag_gated<F>(&mut self, f: F) where F: FnMut(&mut Vec<GatedCfgAttr>);
468 }
469
470 pub struct CfgDiagReal<'a, 'b> {
471     pub diag: &'a Handler,
472     pub feature_gated_cfgs: &'b mut Vec<GatedCfgAttr>,
473 }
474
475 impl<'a, 'b> CfgDiag for CfgDiagReal<'a, 'b> {
476     fn emit_error<F>(&mut self, mut f: F) where F: FnMut(&Handler) {
477         f(self.diag)
478     }
479     fn flag_gated<F>(&mut self, mut f: F) where F: FnMut(&mut Vec<GatedCfgAttr>) {
480         f(self.feature_gated_cfgs)
481     }
482 }
483
484 struct CfgDiagSilent {
485     error: bool,
486 }
487
488 impl CfgDiag for CfgDiagSilent {
489     fn emit_error<F>(&mut self, _: F) where F: FnMut(&Handler) {
490         self.error = true;
491     }
492     fn flag_gated<F>(&mut self, _: F) where F: FnMut(&mut Vec<GatedCfgAttr>) {}
493 }
494
495 fn node_survives_cfg(attrs: &[ast::Attribute],
496                      config: &ast::CrateConfig) -> bool {
497     let mut survives_cfg = true;
498
499     for attr in attrs {
500         let mut fld = CfgAttrFolder {
501             diag: CfgDiagSilent { error: false },
502             config: config,
503         };
504         let attr = fld.fold_attribute(attr.clone());
505
506         // In case of error we can just return true,
507         // since the actual cfg folders will end compilation anyway.
508
509         if fld.diag.error { return true; }
510
511         survives_cfg &= attr.map(|attr| {
512             let mut diag = CfgDiagSilent { error: false };
513             let r = in_cfg(config, &[attr], &mut diag);
514             if diag.error { return true; }
515             r
516         }).unwrap_or(true)
517     }
518
519     survives_cfg
520 }