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::{feature_err, EXPLAIN_STMT_ATTR_SYNTAX, Features, get_features, GateIssue};
17 use parse::{token, ParseSess};
22 /// A folder that strips out items that do not belong in the current configuration.
23 pub struct StripUnconfigured<'a> {
24 pub should_test: bool,
25 pub sess: &'a ParseSess,
26 pub features: Option<&'a Features>,
29 // `cfg_attr`-process the crate's attributes and compute the crate's features.
30 pub fn features(mut krate: ast::Crate, sess: &ParseSess, should_test: bool, edition: Edition)
31 -> (ast::Crate, Features) {
34 let mut strip_unconfigured = StripUnconfigured {
40 let unconfigured_attrs = krate.attrs.clone();
41 let err_count = sess.span_diagnostic.err_count();
42 if let Some(attrs) = strip_unconfigured.configure(krate.attrs) {
44 } else { // the entire crate is unconfigured
45 krate.attrs = Vec::new();
46 krate.module.items = Vec::new();
47 return (krate, Features::new());
50 features = get_features(&sess.span_diagnostic, &krate.attrs, edition);
52 // Avoid reconfiguring malformed `cfg_attr`s
53 if err_count == sess.span_diagnostic.err_count() {
54 strip_unconfigured.features = Some(&features);
55 strip_unconfigured.configure(unconfigured_attrs);
62 macro_rules! configure {
63 ($this:ident, $node:ident) => {
64 match $this.configure($node) {
66 None => return Default::default(),
71 impl<'a> StripUnconfigured<'a> {
72 pub fn configure<T: HasAttrs>(&mut self, node: T) -> Option<T> {
73 let node = self.process_cfg_attrs(node);
74 if self.in_cfg(node.attrs()) { Some(node) } else { None }
77 pub fn process_cfg_attrs<T: HasAttrs>(&mut self, node: T) -> T {
78 node.map_attrs(|attrs| {
79 attrs.into_iter().filter_map(|attr| self.process_cfg_attr(attr)).collect()
83 fn process_cfg_attr(&mut self, attr: ast::Attribute) -> Option<ast::Attribute> {
84 if !attr.check_name("cfg_attr") {
88 let (cfg, path, tokens, span) = match attr.parse(self.sess, |parser| {
89 parser.expect(&token::OpenDelim(token::Paren))?;
90 let cfg = parser.parse_meta_item()?;
91 parser.expect(&token::Comma)?;
92 let lo = parser.span.lo();
93 let (path, tokens) = parser.parse_path_and_tokens()?;
94 parser.expect(&token::CloseDelim(token::Paren))?;
95 Ok((cfg, path, tokens, parser.prev_span.with_lo(lo)))
104 if attr::cfg_matches(&cfg, self.sess, self.features) {
105 self.process_cfg_attr(ast::Attribute {
106 id: attr::mk_attr_id(),
110 is_sugared_doc: false,
118 // Determine if a node with the given attributes should be included in this configuration.
119 pub fn in_cfg(&mut self, attrs: &[ast::Attribute]) -> bool {
120 attrs.iter().all(|attr| {
121 // When not compiling with --test we should not compile the #[test] functions
122 if !self.should_test && is_test_or_bench(attr) {
126 let mis = if !is_cfg(attr) {
128 } else if let Some(mis) = attr.meta_item_list() {
135 self.sess.span_diagnostic.span_err(attr.span, "expected 1 cfg-pattern");
139 if !mis[0].is_meta_item() {
140 self.sess.span_diagnostic.span_err(mis[0].span, "unexpected literal");
144 attr::cfg_matches(mis[0].meta_item().unwrap(), self.sess, self.features)
148 // Visit attributes on expression and statements (but not attributes on items in blocks).
149 fn visit_expr_attrs(&mut self, attrs: &[ast::Attribute]) {
150 // flag the offending attributes
151 for attr in attrs.iter() {
152 self.maybe_emit_expr_attr_err(attr);
156 /// If attributes are not allowed on expressions, emit an error for `attr`
157 pub fn maybe_emit_expr_attr_err(&self, attr: &ast::Attribute) {
158 if !self.features.map(|features| features.stmt_expr_attributes).unwrap_or(true) {
159 let mut err = feature_err(self.sess,
160 "stmt_expr_attributes",
163 EXPLAIN_STMT_ATTR_SYNTAX);
165 if attr.is_sugared_doc {
166 err.help("`///` is for documentation comments. For a plain comment, use `//`.");
173 pub fn configure_foreign_mod(&mut self, foreign_mod: ast::ForeignMod) -> ast::ForeignMod {
175 abi: foreign_mod.abi,
176 items: foreign_mod.items.into_iter().filter_map(|item| self.configure(item)).collect(),
180 fn configure_variant_data(&mut self, vdata: ast::VariantData) -> ast::VariantData {
182 ast::VariantData::Struct(fields, id) => {
183 let fields = fields.into_iter().filter_map(|field| self.configure(field));
184 ast::VariantData::Struct(fields.collect(), id)
186 ast::VariantData::Tuple(fields, id) => {
187 let fields = fields.into_iter().filter_map(|field| self.configure(field));
188 ast::VariantData::Tuple(fields.collect(), id)
190 ast::VariantData::Unit(id) => ast::VariantData::Unit(id)
194 pub fn configure_item_kind(&mut self, item: ast::ItemKind) -> ast::ItemKind {
196 ast::ItemKind::Struct(def, generics) => {
197 ast::ItemKind::Struct(self.configure_variant_data(def), generics)
199 ast::ItemKind::Union(def, generics) => {
200 ast::ItemKind::Union(self.configure_variant_data(def), generics)
202 ast::ItemKind::Enum(def, generics) => {
203 let variants = def.variants.into_iter().filter_map(|v| {
204 self.configure(v).map(|v| {
206 node: ast::Variant_ {
209 data: self.configure_variant_data(v.node.data),
210 disr_expr: v.node.disr_expr,
216 ast::ItemKind::Enum(ast::EnumDef {
217 variants: variants.collect(),
224 pub fn configure_expr_kind(&mut self, expr_kind: ast::ExprKind) -> ast::ExprKind {
226 ast::ExprKind::Match(m, arms) => {
227 let arms = arms.into_iter().filter_map(|a| self.configure(a)).collect();
228 ast::ExprKind::Match(m, arms)
230 ast::ExprKind::Struct(path, fields, base) => {
231 let fields = fields.into_iter()
232 .filter_map(|field| {
233 self.configure(field)
236 ast::ExprKind::Struct(path, fields, base)
242 pub fn configure_expr(&mut self, expr: P<ast::Expr>) -> P<ast::Expr> {
243 self.visit_expr_attrs(expr.attrs());
245 // If an expr is valid to cfg away it will have been removed by the
246 // outer stmt or expression folder before descending in here.
247 // Anything else is always required, and thus has to error out
248 // in case of a cfg attr.
250 // NB: This is intentionally not part of the fold_expr() function
251 // in order for fold_opt_expr() to be able to avoid this check
252 if let Some(attr) = expr.attrs().iter().find(|a| is_cfg(a) || is_test_or_bench(a)) {
253 let msg = "removing an expression is not supported in this position";
254 self.sess.span_diagnostic.span_err(attr.span, msg);
257 self.process_cfg_attrs(expr)
260 pub fn configure_stmt(&mut self, stmt: ast::Stmt) -> Option<ast::Stmt> {
264 pub fn configure_struct_expr_field(&mut self, field: ast::Field) -> Option<ast::Field> {
265 self.configure(field)
268 pub fn configure_pat(&mut self, pattern: P<ast::Pat>) -> P<ast::Pat> {
269 pattern.map(|mut pattern| {
270 if let ast::PatKind::Struct(path, fields, etc) = pattern.node {
271 let fields = fields.into_iter()
272 .filter_map(|field| {
273 self.configure(field)
276 pattern.node = ast::PatKind::Struct(path, fields, etc);
282 // deny #[cfg] on generic parameters until we decide what to do with it.
284 pub fn disallow_cfg_on_generic_param(&mut self, param: &ast::GenericParam) {
285 for attr in param.attrs() {
286 let offending_attr = if attr.check_name("cfg") {
288 } else if attr.check_name("cfg_attr") {
293 let msg = format!("#[{}] cannot be applied on a generic parameter", offending_attr);
294 self.sess.span_diagnostic.span_err(attr.span, &msg);
299 impl<'a> fold::Folder for StripUnconfigured<'a> {
300 fn fold_foreign_mod(&mut self, foreign_mod: ast::ForeignMod) -> ast::ForeignMod {
301 let foreign_mod = self.configure_foreign_mod(foreign_mod);
302 fold::noop_fold_foreign_mod(foreign_mod, self)
305 fn fold_item_kind(&mut self, item: ast::ItemKind) -> ast::ItemKind {
306 let item = self.configure_item_kind(item);
307 fold::noop_fold_item_kind(item, self)
310 fn fold_expr(&mut self, expr: P<ast::Expr>) -> P<ast::Expr> {
311 let mut expr = self.configure_expr(expr).into_inner();
312 expr.node = self.configure_expr_kind(expr.node);
313 P(fold::noop_fold_expr(expr, self))
316 fn fold_opt_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
317 let mut expr = configure!(self, expr).into_inner();
318 expr.node = self.configure_expr_kind(expr.node);
319 Some(P(fold::noop_fold_expr(expr, self)))
322 fn fold_stmt(&mut self, stmt: ast::Stmt) -> OneVector<ast::Stmt> {
323 match self.configure_stmt(stmt) {
324 Some(stmt) => fold::noop_fold_stmt(stmt, self),
325 None => return OneVector::new(),
329 fn fold_item(&mut self, item: P<ast::Item>) -> OneVector<P<ast::Item>> {
330 fold::noop_fold_item(configure!(self, item), self)
333 fn fold_impl_item(&mut self, item: ast::ImplItem) -> OneVector<ast::ImplItem> {
334 fold::noop_fold_impl_item(configure!(self, item), self)
337 fn fold_trait_item(&mut self, item: ast::TraitItem) -> OneVector<ast::TraitItem> {
338 fold::noop_fold_trait_item(configure!(self, item), self)
341 fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
342 // Don't configure interpolated AST (c.f. #34171).
343 // Interpolated AST will get configured once the surrounding tokens are parsed.
347 fn fold_pat(&mut self, pattern: P<ast::Pat>) -> P<ast::Pat> {
348 fold::noop_fold_pat(self.configure_pat(pattern), self)
352 fn is_cfg(attr: &ast::Attribute) -> bool {
353 attr.check_name("cfg")
356 pub fn is_test_or_bench(attr: &ast::Attribute) -> bool {
357 attr.check_name("test") || attr.check_name("bench")