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};
15 use source_map::Spanned;
17 use parse::{token, ParseSess};
19 use errors::Applicability;
23 /// A folder that strips out items that do not belong in the current configuration.
24 pub struct StripUnconfigured<'a> {
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, edition: Edition)
31 -> (ast::Crate, Features) {
34 let mut strip_unconfigured = StripUnconfigured {
39 let unconfigured_attrs = krate.attrs.clone();
40 let err_count = sess.span_diagnostic.err_count();
41 if let Some(attrs) = strip_unconfigured.configure(krate.attrs) {
43 } else { // the entire crate is unconfigured
44 krate.attrs = Vec::new();
45 krate.module.items = Vec::new();
46 return (krate, Features::new());
49 features = get_features(&sess.span_diagnostic, &krate.attrs, edition);
51 // Avoid reconfiguring malformed `cfg_attr`s
52 if err_count == sess.span_diagnostic.err_count() {
53 strip_unconfigured.features = Some(&features);
54 strip_unconfigured.configure(unconfigured_attrs);
61 macro_rules! configure {
62 ($this:ident, $node:ident) => {
63 match $this.configure($node) {
65 None => return Default::default(),
70 impl<'a> StripUnconfigured<'a> {
71 pub fn configure<T: HasAttrs>(&mut self, node: T) -> Option<T> {
72 let node = self.process_cfg_attrs(node);
73 if self.in_cfg(node.attrs()) { Some(node) } else { None }
76 pub fn process_cfg_attrs<T: HasAttrs>(&mut self, node: T) -> T {
77 node.map_attrs(|attrs| {
78 attrs.into_iter().filter_map(|attr| self.process_cfg_attr(attr)).collect()
82 fn process_cfg_attr(&mut self, attr: ast::Attribute) -> Option<ast::Attribute> {
83 if !attr.check_name("cfg_attr") {
87 let (cfg, path, tokens, span) = match attr.parse(self.sess, |parser| {
88 parser.expect(&token::OpenDelim(token::Paren))?;
89 let cfg = parser.parse_meta_item()?;
90 parser.expect(&token::Comma)?;
91 let lo = parser.span.lo();
92 let (path, tokens) = parser.parse_meta_item_unrestricted()?;
93 parser.expect(&token::CloseDelim(token::Paren))?;
94 Ok((cfg, path, tokens, parser.prev_span.with_lo(lo)))
103 if attr::cfg_matches(&cfg, self.sess, self.features) {
104 self.process_cfg_attr(ast::Attribute {
105 id: attr::mk_attr_id(),
109 is_sugared_doc: false,
117 // Determine if a node with the given attributes should be included in this configuration.
118 pub fn in_cfg(&mut self, attrs: &[ast::Attribute]) -> bool {
119 attrs.iter().all(|attr| {
124 let error = |span, msg, suggestion: &str| {
125 let mut err = self.sess.span_diagnostic.struct_span_err(span, msg);
126 if !suggestion.is_empty() {
127 err.span_suggestion_with_applicability(
129 "expected syntax is",
131 Applicability::MaybeIncorrect,
138 let meta_item = if let Some(meta_item) = attr.meta() {
141 // Not a well-formed meta-item. Why? We don't know.
142 return error(attr.span, "`cfg` is not a well-formed meta-item",
143 "#[cfg(/* predicate */)]");
145 let nested_meta_items = if let Some(nested_meta_items) = meta_item.meta_item_list() {
148 return error(meta_item.span, "`cfg` is not followed by parentheses",
149 "cfg(/* predicate */)");
152 if nested_meta_items.is_empty() {
153 return error(meta_item.span, "`cfg` predicate is not specified", "");
154 } else if nested_meta_items.len() > 1 {
155 return error(nested_meta_items.last().unwrap().span,
156 "multiple `cfg` predicates are specified", "");
159 match nested_meta_items[0].meta_item() {
160 Some(meta_item) => attr::cfg_matches(meta_item, self.sess, self.features),
161 None => error(nested_meta_items[0].span,
162 "`cfg` predicate key cannot be a literal", ""),
167 // Visit attributes on expression and statements (but not attributes on items in blocks).
168 fn visit_expr_attrs(&mut self, attrs: &[ast::Attribute]) {
169 // flag the offending attributes
170 for attr in attrs.iter() {
171 self.maybe_emit_expr_attr_err(attr);
175 /// If attributes are not allowed on expressions, emit an error for `attr`
176 pub fn maybe_emit_expr_attr_err(&self, attr: &ast::Attribute) {
177 if !self.features.map(|features| features.stmt_expr_attributes).unwrap_or(true) {
178 let mut err = feature_err(self.sess,
179 "stmt_expr_attributes",
182 EXPLAIN_STMT_ATTR_SYNTAX);
184 if attr.is_sugared_doc {
185 err.help("`///` is for documentation comments. For a plain comment, use `//`.");
192 pub fn configure_foreign_mod(&mut self, foreign_mod: ast::ForeignMod) -> ast::ForeignMod {
194 abi: foreign_mod.abi,
195 items: foreign_mod.items.into_iter().filter_map(|item| self.configure(item)).collect(),
199 fn configure_variant_data(&mut self, vdata: ast::VariantData) -> ast::VariantData {
201 ast::VariantData::Struct(fields, id) => {
202 let fields = fields.into_iter().filter_map(|field| self.configure(field));
203 ast::VariantData::Struct(fields.collect(), id)
205 ast::VariantData::Tuple(fields, id) => {
206 let fields = fields.into_iter().filter_map(|field| self.configure(field));
207 ast::VariantData::Tuple(fields.collect(), id)
209 ast::VariantData::Unit(id) => ast::VariantData::Unit(id)
213 pub fn configure_item_kind(&mut self, item: ast::ItemKind) -> ast::ItemKind {
215 ast::ItemKind::Struct(def, generics) => {
216 ast::ItemKind::Struct(self.configure_variant_data(def), generics)
218 ast::ItemKind::Union(def, generics) => {
219 ast::ItemKind::Union(self.configure_variant_data(def), generics)
221 ast::ItemKind::Enum(def, generics) => {
222 let variants = def.variants.into_iter().filter_map(|v| {
223 self.configure(v).map(|v| {
225 node: ast::Variant_ {
228 data: self.configure_variant_data(v.node.data),
229 disr_expr: v.node.disr_expr,
235 ast::ItemKind::Enum(ast::EnumDef {
236 variants: variants.collect(),
243 pub fn configure_expr_kind(&mut self, expr_kind: ast::ExprKind) -> ast::ExprKind {
245 ast::ExprKind::Match(m, arms) => {
246 let arms = arms.into_iter().filter_map(|a| self.configure(a)).collect();
247 ast::ExprKind::Match(m, arms)
249 ast::ExprKind::Struct(path, fields, base) => {
250 let fields = fields.into_iter()
251 .filter_map(|field| {
252 self.configure(field)
255 ast::ExprKind::Struct(path, fields, base)
261 pub fn configure_expr(&mut self, expr: P<ast::Expr>) -> P<ast::Expr> {
262 self.visit_expr_attrs(expr.attrs());
264 // If an expr is valid to cfg away it will have been removed by the
265 // outer stmt or expression folder before descending in here.
266 // Anything else is always required, and thus has to error out
267 // in case of a cfg attr.
269 // NB: This is intentionally not part of the fold_expr() function
270 // in order for fold_opt_expr() to be able to avoid this check
271 if let Some(attr) = expr.attrs().iter().find(|a| is_cfg(a)) {
272 let msg = "removing an expression is not supported in this position";
273 self.sess.span_diagnostic.span_err(attr.span, msg);
276 self.process_cfg_attrs(expr)
279 pub fn configure_stmt(&mut self, stmt: ast::Stmt) -> Option<ast::Stmt> {
283 pub fn configure_struct_expr_field(&mut self, field: ast::Field) -> Option<ast::Field> {
284 self.configure(field)
287 pub fn configure_pat(&mut self, pattern: P<ast::Pat>) -> P<ast::Pat> {
288 pattern.map(|mut pattern| {
289 if let ast::PatKind::Struct(path, fields, etc) = pattern.node {
290 let fields = fields.into_iter()
291 .filter_map(|field| {
292 self.configure(field)
295 pattern.node = ast::PatKind::Struct(path, fields, etc);
301 // deny #[cfg] on generic parameters until we decide what to do with it.
303 pub fn disallow_cfg_on_generic_param(&mut self, param: &ast::GenericParam) {
304 for attr in param.attrs() {
305 let offending_attr = if attr.check_name("cfg") {
307 } else if attr.check_name("cfg_attr") {
312 let msg = format!("#[{}] cannot be applied on a generic parameter", offending_attr);
313 self.sess.span_diagnostic.span_err(attr.span, &msg);
318 impl<'a> fold::Folder for StripUnconfigured<'a> {
319 fn fold_foreign_mod(&mut self, foreign_mod: ast::ForeignMod) -> ast::ForeignMod {
320 let foreign_mod = self.configure_foreign_mod(foreign_mod);
321 fold::noop_fold_foreign_mod(foreign_mod, self)
324 fn fold_item_kind(&mut self, item: ast::ItemKind) -> ast::ItemKind {
325 let item = self.configure_item_kind(item);
326 fold::noop_fold_item_kind(item, self)
329 fn fold_expr(&mut self, expr: P<ast::Expr>) -> P<ast::Expr> {
330 let mut expr = self.configure_expr(expr).into_inner();
331 expr.node = self.configure_expr_kind(expr.node);
332 P(fold::noop_fold_expr(expr, self))
335 fn fold_opt_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
336 let mut expr = configure!(self, expr).into_inner();
337 expr.node = self.configure_expr_kind(expr.node);
338 Some(P(fold::noop_fold_expr(expr, self)))
341 fn fold_stmt(&mut self, stmt: ast::Stmt) -> OneVector<ast::Stmt> {
342 match self.configure_stmt(stmt) {
343 Some(stmt) => fold::noop_fold_stmt(stmt, self),
344 None => return OneVector::new(),
348 fn fold_item(&mut self, item: P<ast::Item>) -> OneVector<P<ast::Item>> {
349 fold::noop_fold_item(configure!(self, item), self)
352 fn fold_impl_item(&mut self, item: ast::ImplItem) -> OneVector<ast::ImplItem> {
353 fold::noop_fold_impl_item(configure!(self, item), self)
356 fn fold_trait_item(&mut self, item: ast::TraitItem) -> OneVector<ast::TraitItem> {
357 fold::noop_fold_trait_item(configure!(self, item), self)
360 fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
361 // Don't configure interpolated AST (c.f. #34171).
362 // Interpolated AST will get configured once the surrounding tokens are parsed.
366 fn fold_pat(&mut self, pattern: P<ast::Pat>) -> P<ast::Pat> {
367 fold::noop_fold_pat(self.configure_pat(pattern), self)
371 fn is_cfg(attr: &ast::Attribute) -> bool {
372 attr.check_name("cfg")