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.
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.
11 use attr::AttrMetaMethods;
13 use feature_gate::GatedCfgAttr;
15 use {ast, fold, attr};
17 use codemap::{Spanned, respan};
20 use util::small_vector::SmallVector;
22 /// A folder that strips out items that do not belong in the current
24 struct Context<'a, F> where F: FnMut(&[ast::Attribute]) -> bool {
26 diagnostic: &'a Handler,
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>)
35 // Need to do this check here because cfg runs before feature_gates
36 check_for_gated_stmt_expr_attributes(&krate, feature_gated_cfgs);
38 let krate = process_cfg_attr(diagnostic, krate, feature_gated_cfgs);
39 let config = krate.config.clone();
40 strip_items(diagnostic,
43 let mut diag = CfgDiagReal {
45 feature_gated_cfgs: feature_gated_cfgs,
47 in_cfg(&config, attrs, &mut diag)
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)
55 fn fold_item_underscore(&mut self, item: ast::Item_) -> ast::Item_ {
56 fold_item_underscore(self, item)
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.
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");
72 fn fold_opt_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
73 fold_opt_expr(self, expr)
75 fn fold_stmt(&mut self, stmt: P<ast::Stmt>) -> SmallVector<P<ast::Stmt>> {
78 fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
79 fold::noop_fold_mac(mac, self)
81 fn fold_item(&mut self, item: P<ast::Item>) -> SmallVector<P<ast::Item>> {
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,
90 let mut ctxt = Context {
92 diagnostic: diagnostic,
94 ctxt.fold_crate(krate)
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
102 if foreign_item_in_cfg(cx, &item) {
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
116 items: items.into_iter()
117 .filter_map(|a| filter_foreign_item(cx, a))
122 fn fold_item<F>(cx: &mut Context<F>, item: P<ast::Item>) -> SmallVector<P<ast::Item>> where
123 F: FnMut(&[ast::Attribute]) -> bool
125 if item_in_cfg(cx, &item) {
126 SmallVector::one(item.map(|i| cx.fold_item_simple(i)))
132 fn fold_item_underscore<F>(cx: &mut Context<F>, item: ast::Item_) -> ast::Item_ where
133 F: FnMut(&[ast::Attribute]) -> bool
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))
140 ast::ItemImpl(u, o, a, b, c, impl_items)
142 ast::ItemTrait(u, a, b, methods) => {
143 let methods = methods.into_iter()
144 .filter(|ti| (cx.in_cfg)(&ti.attrs))
146 ast::ItemTrait(u, a, b, methods)
148 ast::ItemStruct(def, generics) => {
149 ast::ItemStruct(fold_struct(cx, def), generics)
151 ast::ItemEnum(def, generics) => {
152 let variants = def.variants.into_iter().filter_map(|v| {
153 if !(cx.in_cfg)(&v.node.attrs) {
156 Some(v.map(|Spanned {node: ast::Variant_ {name, attrs, data,
159 node: ast::Variant_ {
162 data: fold_struct(cx, data),
163 disr_expr: disr_expr,
170 ast::ItemEnum(ast::EnumDef {
171 variants: variants.collect(),
177 fold::noop_fold_item_underscore(item, cx)
180 fn fold_struct<F>(cx: &mut Context<F>, vdata: ast::VariantData) -> ast::VariantData where
181 F: FnMut(&[ast::Attribute]) -> bool
184 ast::VariantData::Struct(fields, id) => {
185 ast::VariantData::Struct(fields.into_iter().filter(|m| {
186 (cx.in_cfg)(&m.node.attrs)
189 ast::VariantData::Tuple(fields, id) => {
190 ast::VariantData::Tuple(fields.into_iter().filter(|m| {
191 (cx.in_cfg)(&m.node.attrs)
194 ast::VariantData::Unit(id) => ast::VariantData::Unit(id)
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
201 if expr_in_cfg(cx, &expr) {
202 Some(fold_expr(cx, expr))
208 fn fold_expr<F>(cx: &mut Context<F>, expr: P<ast::Expr>) -> P<ast::Expr> where
209 F: FnMut(&[ast::Attribute]) -> bool
211 expr.map(|ast::Expr {id, span, node, attrs}| {
212 fold::noop_fold_expr(ast::Expr {
215 ast::ExprKind::Match(m, arms) => {
216 ast::ExprKind::Match(m, arms.into_iter()
217 .filter(|a| (cx.in_cfg)(&a.attrs))
228 fn fold_stmt<F>(cx: &mut Context<F>, stmt: P<ast::Stmt>) -> SmallVector<P<ast::Stmt>>
229 where F: FnMut(&[ast::Attribute]) -> bool
231 if stmt_in_cfg(cx, &stmt) {
232 stmt.and_then(|s| fold::noop_fold_stmt(s, cx))
238 fn stmt_in_cfg<F>(cx: &mut Context<F>, stmt: &ast::Stmt) -> bool where
239 F: FnMut(&[ast::Attribute]) -> bool
241 (cx.in_cfg)(stmt.node.attrs())
244 fn expr_in_cfg<F>(cx: &mut Context<F>, expr: &ast::Expr) -> bool where
245 F: FnMut(&[ast::Attribute]) -> bool
247 (cx.in_cfg)(expr.attrs())
250 fn item_in_cfg<F>(cx: &mut Context<F>, item: &ast::Item) -> bool where
251 F: FnMut(&[ast::Attribute]) -> bool
253 return (cx.in_cfg)(&item.attrs);
256 fn foreign_item_in_cfg<F>(cx: &mut Context<F>, item: &ast::ForeignItem) -> bool where
257 F: FnMut(&[ast::Attribute]) -> bool
259 return (cx.in_cfg)(&item.attrs);
262 fn is_cfg(attr: &ast::Attribute) -> bool {
263 attr.check_name("cfg")
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,
278 diag.emit_error(|diagnostic| {
279 diagnostic.span_err(attr.span, "expected 1 cfg-pattern");
284 attr::cfg_matches(cfg, &mis[0], diag)
288 struct CfgAttrFolder<'a, T> {
290 config: &'a ast::CrateConfig,
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 {
299 feature_gated_cfgs: feature_gated_cfgs,
301 config: &krate.config.clone(),
303 fld.fold_crate(krate)
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);
312 let attr_list = match attr.meta_item_list() {
313 Some(attr_list) => attr_list,
315 self.diag.emit_error(|diag| {
316 diag.span_err(attr.span,
317 "expected `#[cfg_attr(<cfg pattern>, <attr>)]`");
322 let (cfg, mi) = match (attr_list.len(), attr_list.get(0), attr_list.get(1)) {
323 (2, Some(cfg), Some(mi)) => (cfg, mi),
325 self.diag.emit_error(|diag| {
326 diag.span_err(attr.span,
327 "expected `#[cfg_attr(<cfg pattern>, <attr>)]`");
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,
338 is_sugared_doc: false,
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)
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,
357 visit::walk_crate(&mut v, krate);
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>,
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);
382 // flag the offending attributes
383 for attr in stmt_attrs {
384 self.discovered.push(GatedCfgAttr::GatedAttr(attr.span));
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);
392 visit::walk_stmt(self, s);
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 {
401 // flag the offending attributes
402 for attr in expr_attrs {
403 self.discovered.push(GatedCfgAttr::GatedAttr(attr.span));
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);
411 visit::walk_expr(self, ex);
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);
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);
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);
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);
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);
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);
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);
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)
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>);
470 pub struct CfgDiagReal<'a, 'b> {
471 pub diag: &'a Handler,
472 pub feature_gated_cfgs: &'b mut Vec<GatedCfgAttr>,
475 impl<'a, 'b> CfgDiag for CfgDiagReal<'a, 'b> {
476 fn emit_error<F>(&mut self, mut f: F) where F: FnMut(&Handler) {
479 fn flag_gated<F>(&mut self, mut f: F) where F: FnMut(&mut Vec<GatedCfgAttr>) {
480 f(self.feature_gated_cfgs)
484 struct CfgDiagSilent {
488 impl CfgDiag for CfgDiagSilent {
489 fn emit_error<F>(&mut self, _: F) where F: FnMut(&Handler) {
492 fn flag_gated<F>(&mut self, _: F) where F: FnMut(&mut Vec<GatedCfgAttr>) {}
495 fn node_survives_cfg(attrs: &[ast::Attribute],
496 config: &ast::CrateConfig) -> bool {
497 let mut survives_cfg = true;
500 let mut fld = CfgAttrFolder {
501 diag: CfgDiagSilent { error: false },
504 let attr = fld.fold_attribute(attr.clone());
506 // In case of error we can just return true,
507 // since the actual cfg folders will end compilation anyway.
509 if fld.diag.error { return true; }
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; }