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_ {name, attrs, data,
146 node: ast::Variant_ {
149 data: fold_struct(cx, data),
150 disr_expr: disr_expr,
157 ast::ItemEnum(ast::EnumDef {
158 variants: variants.collect(),
164 fold::noop_fold_item_underscore(item, cx)
167 fn fold_struct<F>(cx: &mut Context<F>, def: P<ast::VariantData>) -> P<ast::VariantData> where
168 F: FnMut(&[ast::Attribute]) -> bool
172 ast::VariantData::Struct(fields, id) => {
173 ast::VariantData::Struct(fields.into_iter().filter(|m| {
174 (cx.in_cfg)(&m.node.attrs)
177 ast::VariantData::Tuple(fields, id) => {
178 ast::VariantData::Tuple(fields.into_iter().filter(|m| {
179 (cx.in_cfg)(&m.node.attrs)
182 ast::VariantData::Unit(id) => ast::VariantData::Unit(id)
187 fn retain_stmt<F>(cx: &mut Context<F>, stmt: &ast::Stmt) -> bool where
188 F: FnMut(&[ast::Attribute]) -> bool
191 ast::StmtDecl(ref decl, _) => {
193 ast::DeclItem(ref item) => {
194 item_in_cfg(cx, &**item)
203 fn fold_block<F>(cx: &mut Context<F>, b: P<ast::Block>) -> P<ast::Block> where
204 F: FnMut(&[ast::Attribute]) -> bool
206 b.map(|ast::Block {id, stmts, expr, rules, span}| {
207 let resulting_stmts: Vec<P<ast::Stmt>> =
208 stmts.into_iter().filter(|a| retain_stmt(cx, &**a)).collect();
209 let resulting_stmts = resulting_stmts.into_iter()
210 .flat_map(|stmt| cx.fold_stmt(stmt).into_iter())
214 stmts: resulting_stmts,
215 expr: expr.map(|x| cx.fold_expr(x)),
222 fn fold_expr<F>(cx: &mut Context<F>, expr: P<ast::Expr>) -> P<ast::Expr> where
223 F: FnMut(&[ast::Attribute]) -> bool
225 expr.map(|ast::Expr {id, span, node}| {
226 fold::noop_fold_expr(ast::Expr {
229 ast::ExprMatch(m, arms) => {
230 ast::ExprMatch(m, arms.into_iter()
231 .filter(|a| (cx.in_cfg)(&a.attrs))
241 fn item_in_cfg<F>(cx: &mut Context<F>, item: &ast::Item) -> bool where
242 F: FnMut(&[ast::Attribute]) -> bool
244 return (cx.in_cfg)(&item.attrs);
247 fn foreign_item_in_cfg<F>(cx: &mut Context<F>, item: &ast::ForeignItem) -> bool where
248 F: FnMut(&[ast::Attribute]) -> bool
250 return (cx.in_cfg)(&item.attrs);
253 // Determine if an item should be translated in the current crate
254 // configuration based on the item's attributes
255 fn in_cfg(diagnostic: &SpanHandler, cfg: &[P<ast::MetaItem>], attrs: &[ast::Attribute],
256 feature_gated_cfgs: &mut Vec<GatedCfg>) -> bool {
257 attrs.iter().all(|attr| {
258 let mis = match attr.node.value.node {
259 ast::MetaList(_, ref mis) if attr.check_name("cfg") => mis,
264 diagnostic.span_err(attr.span, "expected 1 cfg-pattern");
268 attr::cfg_matches(diagnostic, cfg, &*mis[0],
273 struct CfgAttrFolder<'a, 'b> {
274 diag: &'a SpanHandler,
275 config: ast::CrateConfig,
276 feature_gated_cfgs: &'b mut Vec<GatedCfg>
279 // Process `#[cfg_attr]`.
280 fn process_cfg_attr(diagnostic: &SpanHandler, krate: ast::Crate,
281 feature_gated_cfgs: &mut Vec<GatedCfg>) -> ast::Crate {
282 let mut fld = CfgAttrFolder {
284 config: krate.config.clone(),
285 feature_gated_cfgs: feature_gated_cfgs,
287 fld.fold_crate(krate)
290 impl<'a,'b> fold::Folder for CfgAttrFolder<'a,'b> {
291 fn fold_attribute(&mut self, attr: ast::Attribute) -> Option<ast::Attribute> {
292 if !attr.check_name("cfg_attr") {
293 return fold::noop_fold_attribute(attr, self);
296 let attr_list = match attr.meta_item_list() {
297 Some(attr_list) => attr_list,
299 self.diag.span_err(attr.span, "expected `#[cfg_attr(<cfg pattern>, <attr>)]`");
303 let (cfg, mi) = match (attr_list.len(), attr_list.get(0), attr_list.get(1)) {
304 (2, Some(cfg), Some(mi)) => (cfg, mi),
306 self.diag.span_err(attr.span, "expected `#[cfg_attr(<cfg pattern>, <attr>)]`");
311 if attr::cfg_matches(self.diag, &self.config[..], &cfg,
312 self.feature_gated_cfgs) {
313 Some(respan(mi.span, ast::Attribute_ {
314 id: attr::mk_attr_id(),
315 style: attr.node.style,
317 is_sugared_doc: false,
324 // Need the ability to run pre-expansion.
325 fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
326 fold::noop_fold_mac(mac, self)