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.
12 use feature_gate::{emit_feature_err, EXPLAIN_STMT_ATTR_SYNTAX, Features, get_features, GateIssue};
16 use codemap::{Spanned, respan};
17 use parse::{ParseSess, token};
20 use util::small_vector::SmallVector;
22 /// A folder that strips out items that do not belong in the current configuration.
23 pub struct StripUnconfigured<'a> {
24 pub config: &'a ast::CrateConfig,
25 pub should_test: bool,
26 pub sess: &'a ParseSess,
27 pub features: Option<&'a Features>,
30 impl<'a> StripUnconfigured<'a> {
31 fn configure<T: HasAttrs>(&mut self, node: T) -> Option<T> {
32 let node = self.process_cfg_attrs(node);
33 if self.in_cfg(node.attrs()) { Some(node) } else { None }
36 pub fn process_cfg_attrs<T: HasAttrs>(&mut self, node: T) -> T {
37 node.map_attrs(|attrs| {
38 attrs.into_iter().filter_map(|attr| self.process_cfg_attr(attr)).collect()
42 fn process_cfg_attr(&mut self, attr: ast::Attribute) -> Option<ast::Attribute> {
43 if !attr.check_name("cfg_attr") {
47 let attr_list = match attr.meta_item_list() {
48 Some(attr_list) => attr_list,
50 let msg = "expected `#[cfg_attr(<cfg pattern>, <attr>)]`";
51 self.sess.span_diagnostic.span_err(attr.span, msg);
56 let (cfg, mi) = match (attr_list.len(), attr_list.get(0), attr_list.get(1)) {
57 (2, Some(cfg), Some(mi)) => (cfg, mi),
59 let msg = "expected `#[cfg_attr(<cfg pattern>, <attr>)]`";
60 self.sess.span_diagnostic.span_err(attr.span, msg);
65 use attr::cfg_matches;
66 match (cfg.meta_item(), mi.meta_item()) {
67 (Some(cfg), Some(mi)) =>
68 if cfg_matches(self.config, &cfg, self.sess, self.features) {
69 self.process_cfg_attr(respan(mi.span, ast::Attribute_ {
70 id: attr::mk_attr_id(),
71 style: attr.node.style,
73 is_sugared_doc: false,
79 let msg = "unexpected literal(s) in `#[cfg_attr(<cfg pattern>, <attr>)]`";
80 self.sess.span_diagnostic.span_err(attr.span, msg);
86 // Determine if a node with the given attributes should be included in this configuation.
87 fn in_cfg(&mut self, attrs: &[ast::Attribute]) -> bool {
88 attrs.iter().all(|attr| {
89 // When not compiling with --test we should not compile the #[test] functions
90 if !self.should_test && is_test_or_bench(attr) {
94 let mis = match attr.node.value.node {
95 ast::MetaItemKind::List(_, ref mis) if is_cfg(&attr) => mis,
100 self.sess.span_diagnostic.span_err(attr.span, "expected 1 cfg-pattern");
104 if !mis[0].is_meta_item() {
105 self.sess.span_diagnostic.span_err(mis[0].span, "unexpected literal");
109 attr::cfg_matches(self.config, mis[0].meta_item().unwrap(), self.sess, self.features)
113 // Visit attributes on expression and statements (but not attributes on items in blocks).
114 fn visit_stmt_or_expr_attrs(&mut self, attrs: &[ast::Attribute]) {
115 // flag the offending attributes
116 for attr in attrs.iter() {
117 if !self.features.map(|features| features.stmt_expr_attributes).unwrap_or(true) {
118 emit_feature_err(&self.sess.span_diagnostic,
119 "stmt_expr_attributes",
122 EXPLAIN_STMT_ATTR_SYNTAX);
128 // Support conditional compilation by transforming the AST, stripping out
129 // any items that do not belong in the current configuration
130 pub fn strip_unconfigured_items(mut krate: ast::Crate, sess: &ParseSess, should_test: bool)
131 -> (ast::Crate, Features) {
134 let mut strip_unconfigured = StripUnconfigured {
135 config: &krate.config.clone(),
136 should_test: should_test,
141 let err_count = sess.span_diagnostic.err_count();
142 let krate_attrs = strip_unconfigured.configure(krate.attrs.clone()).unwrap_or_default();
143 features = get_features(&sess.span_diagnostic, &krate_attrs);
144 if err_count < sess.span_diagnostic.err_count() {
145 krate.attrs = krate_attrs.clone(); // Avoid reconfiguring malformed `cfg_attr`s
148 strip_unconfigured.features = Some(&features);
149 krate = strip_unconfigured.fold_crate(krate);
150 krate.attrs = krate_attrs;
156 impl<'a> fold::Folder for StripUnconfigured<'a> {
157 fn fold_foreign_mod(&mut self, foreign_mod: ast::ForeignMod) -> ast::ForeignMod {
159 abi: foreign_mod.abi,
160 items: foreign_mod.items.into_iter().filter_map(|item| {
161 self.configure(item).map(|item| fold::noop_fold_foreign_item(item, self))
166 fn fold_item_kind(&mut self, item: ast::ItemKind) -> ast::ItemKind {
167 let fold_struct = |this: &mut Self, vdata| match vdata {
168 ast::VariantData::Struct(fields, id) => {
169 let fields = fields.into_iter().filter_map(|field| this.configure(field));
170 ast::VariantData::Struct(fields.collect(), id)
172 ast::VariantData::Tuple(fields, id) => {
173 let fields = fields.into_iter().filter_map(|field| this.configure(field));
174 ast::VariantData::Tuple(fields.collect(), id)
176 ast::VariantData::Unit(id) => ast::VariantData::Unit(id)
179 let item = match item {
180 ast::ItemKind::Struct(def, generics) => {
181 ast::ItemKind::Struct(fold_struct(self, def), generics)
183 ast::ItemKind::Enum(def, generics) => {
184 let variants = def.variants.into_iter().filter_map(|v| {
185 self.configure(v).map(|v| {
187 node: ast::Variant_ {
190 data: fold_struct(self, v.node.data),
191 disr_expr: v.node.disr_expr,
197 ast::ItemKind::Enum(ast::EnumDef {
198 variants: variants.collect(),
204 fold::noop_fold_item_kind(item, self)
207 fn fold_expr(&mut self, expr: P<ast::Expr>) -> P<ast::Expr> {
208 self.visit_stmt_or_expr_attrs(expr.attrs());
210 // If an expr is valid to cfg away it will have been removed by the
211 // outer stmt or expression folder before descending in here.
212 // Anything else is always required, and thus has to error out
213 // in case of a cfg attr.
215 // NB: This is intentionally not part of the fold_expr() function
216 // in order for fold_opt_expr() to be able to avoid this check
217 if let Some(attr) = expr.attrs().iter().find(|a| is_cfg(a) || is_test_or_bench(a)) {
218 let msg = "removing an expression is not supported in this position";
219 self.sess.span_diagnostic.span_err(attr.span, msg);
222 let expr = self.process_cfg_attrs(expr);
223 fold_expr(self, expr)
226 fn fold_opt_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
227 self.configure(expr).map(|expr| fold_expr(self, expr))
230 fn fold_stmt(&mut self, stmt: ast::Stmt) -> SmallVector<ast::Stmt> {
231 self.visit_stmt_or_expr_attrs(stmt.attrs());
232 self.configure(stmt).map(|stmt| fold::noop_fold_stmt(stmt, self))
233 .unwrap_or(SmallVector::zero())
236 fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
237 fold::noop_fold_mac(mac, self)
240 fn fold_item(&mut self, item: P<ast::Item>) -> SmallVector<P<ast::Item>> {
241 self.configure(item).map(|item| fold::noop_fold_item(item, self))
242 .unwrap_or(SmallVector::zero())
245 fn fold_impl_item(&mut self, item: ast::ImplItem) -> SmallVector<ast::ImplItem> {
246 self.configure(item).map(|item| fold::noop_fold_impl_item(item, self))
247 .unwrap_or(SmallVector::zero())
250 fn fold_trait_item(&mut self, item: ast::TraitItem) -> SmallVector<ast::TraitItem> {
251 self.configure(item).map(|item| fold::noop_fold_trait_item(item, self))
252 .unwrap_or(SmallVector::zero())
255 fn fold_interpolated(&mut self, nt: token::Nonterminal) -> token::Nonterminal {
256 // Don't configure interpolated AST (c.f. #34171).
257 // Interpolated AST will get configured once the surrounding tokens are parsed.
262 fn fold_expr(folder: &mut StripUnconfigured, expr: P<ast::Expr>) -> P<ast::Expr> {
263 expr.map(|ast::Expr {id, span, node, attrs}| {
264 fold::noop_fold_expr(ast::Expr {
267 ast::ExprKind::Match(m, arms) => {
268 ast::ExprKind::Match(m, arms.into_iter()
269 .filter_map(|a| folder.configure(a))
280 fn is_cfg(attr: &ast::Attribute) -> bool {
281 attr.check_name("cfg")
284 fn is_test_or_bench(attr: &ast::Attribute) -> bool {
285 attr.check_name("test") || attr.check_name("bench")