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;
12 use diagnostic::SpanHandler;
13 use feature_gate::GatedCfg;
15 use {ast, fold, attr};
16 use codemap::{Spanned, respan};
19 use util::small_vector::SmallVector;
21 /// A folder that strips out items that do not belong in the current
23 struct Context<F> where F: FnMut(&[ast::Attribute]) -> bool {
27 // Support conditional compilation by transforming the AST, stripping out
28 // any items that do not belong in the current configuration
29 pub fn strip_unconfigured_items(diagnostic: &SpanHandler, krate: ast::Crate,
30 feature_gated_cfgs: &mut Vec<GatedCfg>)
33 let krate = process_cfg_attr(diagnostic, krate, feature_gated_cfgs);
34 let config = krate.config.clone();
35 strip_items(krate, |attrs| in_cfg(diagnostic, &config, attrs, feature_gated_cfgs))
38 impl<F> fold::Folder for Context<F> where F: FnMut(&[ast::Attribute]) -> bool {
39 fn fold_mod(&mut self, module: ast::Mod) -> ast::Mod {
40 fold_mod(self, module)
42 fn fold_block(&mut self, block: P<ast::Block>) -> P<ast::Block> {
43 fold_block(self, block)
45 fn fold_foreign_mod(&mut self, foreign_mod: ast::ForeignMod) -> ast::ForeignMod {
46 fold_foreign_mod(self, foreign_mod)
48 fn fold_item_underscore(&mut self, item: ast::Item_) -> ast::Item_ {
49 fold_item_underscore(self, item)
51 fn fold_expr(&mut self, expr: P<ast::Expr>) -> P<ast::Expr> {
54 fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
55 fold::noop_fold_mac(mac, self)
57 fn fold_item(&mut self, item: P<ast::Item>) -> SmallVector<P<ast::Item>> {
62 pub fn strip_items<F>(krate: ast::Crate, in_cfg: F) -> ast::Crate where
63 F: FnMut(&[ast::Attribute]) -> bool,
65 let mut ctxt = Context {
68 ctxt.fold_crate(krate)
71 fn fold_mod<F>(cx: &mut Context<F>,
72 ast::Mod {inner, items}: ast::Mod)
74 F: FnMut(&[ast::Attribute]) -> bool
78 items: items.into_iter().flat_map(|a| {
79 cx.fold_item(a).into_iter()
84 fn filter_foreign_item<F>(cx: &mut Context<F>,
85 item: P<ast::ForeignItem>)
86 -> Option<P<ast::ForeignItem>> where
87 F: FnMut(&[ast::Attribute]) -> bool
89 if foreign_item_in_cfg(cx, &*item) {
96 fn fold_foreign_mod<F>(cx: &mut Context<F>,
97 ast::ForeignMod {abi, items}: ast::ForeignMod)
98 -> ast::ForeignMod where
99 F: FnMut(&[ast::Attribute]) -> bool
103 items: items.into_iter()
104 .filter_map(|a| filter_foreign_item(cx, a))
109 fn fold_item<F>(cx: &mut Context<F>, item: P<ast::Item>) -> SmallVector<P<ast::Item>> where
110 F: FnMut(&[ast::Attribute]) -> bool
112 if item_in_cfg(cx, &*item) {
113 SmallVector::one(item.map(|i| cx.fold_item_simple(i)))
119 fn fold_item_underscore<F>(cx: &mut Context<F>, item: ast::Item_) -> ast::Item_ where
120 F: FnMut(&[ast::Attribute]) -> bool
122 let item = match item {
123 ast::ItemImpl(u, o, a, b, c, impl_items) => {
124 let impl_items = impl_items.into_iter()
125 .filter(|ii| (cx.in_cfg)(&ii.attrs))
127 ast::ItemImpl(u, o, a, b, c, impl_items)
129 ast::ItemTrait(u, a, b, methods) => {
130 let methods = methods.into_iter()
131 .filter(|ti| (cx.in_cfg)(&ti.attrs))
133 ast::ItemTrait(u, a, b, methods)
135 ast::ItemStruct(def, generics) => {
136 ast::ItemStruct(fold_struct(cx, def), generics)
138 ast::ItemEnum(def, generics) => {
139 let variants = def.variants.into_iter().filter_map(|v| {
140 if !(cx.in_cfg)(&v.node.attrs) {
143 Some(v.map(|Spanned {node: ast::Variant_ {id, name, attrs, kind,
146 node: ast::Variant_ {
151 ast::TupleVariantKind(..) => kind,
152 ast::StructVariantKind(def) => {
153 ast::StructVariantKind(fold_struct(cx, def))
156 disr_expr: disr_expr,
163 ast::ItemEnum(ast::EnumDef {
164 variants: variants.collect(),
170 fold::noop_fold_item_underscore(item, cx)
173 fn fold_struct<F>(cx: &mut Context<F>, def: P<ast::StructDef>) -> P<ast::StructDef> where
174 F: FnMut(&[ast::Attribute]) -> bool
176 def.map(|ast::StructDef { fields, ctor_id }| {
178 fields: fields.into_iter().filter(|m| {
179 (cx.in_cfg)(&m.node.attrs)
186 fn retain_stmt<F>(cx: &mut Context<F>, stmt: &ast::Stmt) -> bool where
187 F: FnMut(&[ast::Attribute]) -> bool
190 ast::StmtDecl(ref decl, _) => {
192 ast::DeclItem(ref item) => {
193 item_in_cfg(cx, &**item)
202 fn fold_block<F>(cx: &mut Context<F>, b: P<ast::Block>) -> P<ast::Block> where
203 F: FnMut(&[ast::Attribute]) -> bool
205 b.map(|ast::Block {id, stmts, expr, rules, span}| {
206 let resulting_stmts: Vec<P<ast::Stmt>> =
207 stmts.into_iter().filter(|a| retain_stmt(cx, &**a)).collect();
208 let resulting_stmts = resulting_stmts.into_iter()
209 .flat_map(|stmt| cx.fold_stmt(stmt).into_iter())
213 stmts: resulting_stmts,
214 expr: expr.map(|x| cx.fold_expr(x)),
221 fn fold_expr<F>(cx: &mut Context<F>, expr: P<ast::Expr>) -> P<ast::Expr> where
222 F: FnMut(&[ast::Attribute]) -> bool
224 expr.map(|ast::Expr {id, span, node}| {
225 fold::noop_fold_expr(ast::Expr {
228 ast::ExprMatch(m, arms) => {
229 ast::ExprMatch(m, arms.into_iter()
230 .filter(|a| (cx.in_cfg)(&a.attrs))
240 fn item_in_cfg<F>(cx: &mut Context<F>, item: &ast::Item) -> bool where
241 F: FnMut(&[ast::Attribute]) -> bool
243 return (cx.in_cfg)(&item.attrs);
246 fn foreign_item_in_cfg<F>(cx: &mut Context<F>, item: &ast::ForeignItem) -> bool where
247 F: FnMut(&[ast::Attribute]) -> bool
249 return (cx.in_cfg)(&item.attrs);
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],
255 feature_gated_cfgs: &mut Vec<GatedCfg>) -> bool {
256 attrs.iter().all(|attr| {
257 let mis = match attr.node.value.node {
258 ast::MetaList(_, ref mis) if attr.check_name("cfg") => mis,
263 diagnostic.span_err(attr.span, "expected 1 cfg-pattern");
267 attr::cfg_matches(diagnostic, cfg, &*mis[0],
272 struct CfgAttrFolder<'a, 'b> {
273 diag: &'a SpanHandler,
274 config: ast::CrateConfig,
275 feature_gated_cfgs: &'b mut Vec<GatedCfg>
278 // Process `#[cfg_attr]`.
279 fn process_cfg_attr(diagnostic: &SpanHandler, krate: ast::Crate,
280 feature_gated_cfgs: &mut Vec<GatedCfg>) -> ast::Crate {
281 let mut fld = CfgAttrFolder {
283 config: krate.config.clone(),
284 feature_gated_cfgs: feature_gated_cfgs,
286 fld.fold_crate(krate)
289 impl<'a,'b> fold::Folder for CfgAttrFolder<'a,'b> {
290 fn fold_attribute(&mut self, attr: ast::Attribute) -> Option<ast::Attribute> {
291 if !attr.check_name("cfg_attr") {
292 return fold::noop_fold_attribute(attr, self);
295 let attr_list = match attr.meta_item_list() {
296 Some(attr_list) => attr_list,
298 self.diag.span_err(attr.span, "expected `#[cfg_attr(<cfg pattern>, <attr>)]`");
302 let (cfg, mi) = match (attr_list.len(), attr_list.get(0), attr_list.get(1)) {
303 (2, Some(cfg), Some(mi)) => (cfg, mi),
305 self.diag.span_err(attr.span, "expected `#[cfg_attr(<cfg pattern>, <attr>)]`");
310 if attr::cfg_matches(self.diag, &self.config[..], &cfg,
311 self.feature_gated_cfgs) {
312 Some(respan(mi.span, ast::Attribute_ {
313 id: attr::mk_attr_id(),
314 style: attr.node.style,
316 is_sugared_doc: false,
323 // Need the ability to run pre-expansion.
324 fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
325 fold::noop_fold_mac(mac, self)