1 use crate::attr::HasAttrs;
2 use crate::feature_gate::{
4 EXPLAIN_STMT_ATTR_SYNTAX,
11 use crate::edition::Edition;
12 use crate::mut_visit::*;
13 use crate::parse::{token, ParseSess};
15 use crate::symbol::sym;
16 use crate::util::map_in_place::MapInPlace;
18 use errors::Applicability;
19 use smallvec::SmallVec;
21 /// A folder that strips out items that do not belong in the current configuration.
22 pub struct StripUnconfigured<'a> {
23 pub sess: &'a ParseSess,
24 pub features: Option<&'a Features>,
27 // `cfg_attr`-process the crate's attributes and compute the crate's features.
28 pub fn features(mut krate: ast::Crate, sess: &ParseSess, edition: Edition,
29 allow_features: &Option<Vec<String>>) -> (ast::Crate, Features) {
32 let mut strip_unconfigured = StripUnconfigured {
37 let unconfigured_attrs = krate.attrs.clone();
38 let err_count = sess.span_diagnostic.err_count();
39 if let Some(attrs) = strip_unconfigured.configure(krate.attrs) {
41 } else { // the entire crate is unconfigured
42 krate.attrs = Vec::new();
43 krate.module.items = Vec::new();
44 return (krate, Features::new());
47 features = get_features(&sess.span_diagnostic, &krate.attrs, edition, allow_features);
49 // Avoid reconfiguring malformed `cfg_attr`s
50 if err_count == sess.span_diagnostic.err_count() {
51 strip_unconfigured.features = Some(&features);
52 strip_unconfigured.configure(unconfigured_attrs);
59 macro_rules! configure {
60 ($this:ident, $node:ident) => {
61 match $this.configure($node) {
63 None => return Default::default(),
68 impl<'a> StripUnconfigured<'a> {
69 pub fn configure<T: HasAttrs>(&mut self, mut node: T) -> Option<T> {
70 self.process_cfg_attrs(&mut node);
71 if self.in_cfg(node.attrs()) { Some(node) } else { None }
74 /// Parse and expand all `cfg_attr` attributes into a list of attributes
75 /// that are within each `cfg_attr` that has a true configuration predicate.
77 /// Gives compiler warnigns if any `cfg_attr` does not contain any
78 /// attributes and is in the original source code. Gives compiler errors if
79 /// the syntax of any `cfg_attr` is incorrect.
80 pub fn process_cfg_attrs<T: HasAttrs>(&mut self, node: &mut T) {
81 node.visit_attrs(|attrs| {
82 attrs.flat_map_in_place(|attr| self.process_cfg_attr(attr));
86 /// Parse and expand a single `cfg_attr` attribute into a list of attributes
87 /// when the configuration predicate is true, or otherwise expand into an
88 /// empty list of attributes.
90 /// Gives a compiler warning when the `cfg_attr` contains no attributes and
91 /// is in the original source file. Gives a compiler error if the syntax of
92 /// the attribute is incorrect.
93 fn process_cfg_attr(&mut self, attr: ast::Attribute) -> Vec<ast::Attribute> {
94 if attr.path != sym::cfg_attr {
97 if attr.tokens.is_empty() {
98 self.sess.span_diagnostic
101 "malformed `cfg_attr` attribute input",
104 "missing condition and attribute",
105 "#[cfg_attr(condition, attribute, other_attribute, ...)]".to_owned(),
106 Applicability::HasPlaceholders,
107 ).note("for more information, visit \
108 <https://doc.rust-lang.org/reference/conditional-compilation.html\
109 #the-cfg_attr-attribute>")
114 let (cfg_predicate, expanded_attrs) = match attr.parse(self.sess, |parser| {
115 parser.expect(&token::OpenDelim(token::Paren))?;
117 let cfg_predicate = parser.parse_meta_item()?;
118 parser.expect(&token::Comma)?;
120 // Presumably, the majority of the time there will only be one attr.
121 let mut expanded_attrs = Vec::with_capacity(1);
123 while !parser.check(&token::CloseDelim(token::Paren)) {
124 let lo = parser.token.span.lo();
125 let (path, tokens) = parser.parse_meta_item_unrestricted()?;
126 expanded_attrs.push((path, tokens, parser.prev_span.with_lo(lo)));
127 parser.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Paren)])?;
130 parser.expect(&token::CloseDelim(token::Paren))?;
131 Ok((cfg_predicate, expanded_attrs))
133 Ok(result) => result,
140 // Lint on zero attributes in source.
141 if expanded_attrs.is_empty() {
145 // At this point we know the attribute is considered used.
146 attr::mark_used(&attr);
148 if attr::cfg_matches(&cfg_predicate, self.sess, self.features) {
149 // We call `process_cfg_attr` recursively in case there's a
150 // `cfg_attr` inside of another `cfg_attr`. E.g.
151 // `#[cfg_attr(false, cfg_attr(true, some_attr))]`.
152 expanded_attrs.into_iter()
153 .flat_map(|(path, tokens, span)| self.process_cfg_attr(ast::Attribute {
154 id: attr::mk_attr_id(),
158 is_sugared_doc: false,
167 /// Determines if a node with the given attributes should be included in this configuration.
168 pub fn in_cfg(&mut self, attrs: &[ast::Attribute]) -> bool {
169 attrs.iter().all(|attr| {
174 let error = |span, msg, suggestion: &str| {
175 let mut err = self.sess.span_diagnostic.struct_span_err(span, msg);
176 if !suggestion.is_empty() {
179 "expected syntax is",
181 Applicability::MaybeIncorrect,
188 let meta_item = match attr.parse_meta(self.sess) {
189 Ok(meta_item) => meta_item,
190 Err(mut err) => { err.emit(); return true; }
192 let nested_meta_items = if let Some(nested_meta_items) = meta_item.meta_item_list() {
195 return error(meta_item.span, "`cfg` is not followed by parentheses",
196 "cfg(/* predicate */)");
199 if nested_meta_items.is_empty() {
200 return error(meta_item.span, "`cfg` predicate is not specified", "");
201 } else if nested_meta_items.len() > 1 {
202 return error(nested_meta_items.last().unwrap().span(),
203 "multiple `cfg` predicates are specified", "");
206 match nested_meta_items[0].meta_item() {
207 Some(meta_item) => attr::cfg_matches(meta_item, self.sess, self.features),
208 None => error(nested_meta_items[0].span(),
209 "`cfg` predicate key cannot be a literal", ""),
214 /// Visit attributes on expression and statements (but not attributes on items in blocks).
215 fn visit_expr_attrs(&mut self, attrs: &[ast::Attribute]) {
216 // flag the offending attributes
217 for attr in attrs.iter() {
218 self.maybe_emit_expr_attr_err(attr);
222 /// If attributes are not allowed on expressions, emit an error for `attr`
223 pub fn maybe_emit_expr_attr_err(&self, attr: &ast::Attribute) {
224 if !self.features.map(|features| features.stmt_expr_attributes).unwrap_or(true) {
225 let mut err = feature_err(self.sess,
226 sym::stmt_expr_attributes,
229 EXPLAIN_STMT_ATTR_SYNTAX);
231 if attr.is_sugared_doc {
232 err.help("`///` is for documentation comments. For a plain comment, use `//`.");
239 pub fn configure_foreign_mod(&mut self, foreign_mod: &mut ast::ForeignMod) {
240 let ast::ForeignMod { abi: _, items } = foreign_mod;
241 items.flat_map_in_place(|item| self.configure(item));
244 pub fn configure_generic_params(&mut self, params: &mut Vec<ast::GenericParam>) {
245 params.flat_map_in_place(|param| self.configure(param));
248 fn configure_variant_data(&mut self, vdata: &mut ast::VariantData) {
250 ast::VariantData::Struct(fields, ..) | ast::VariantData::Tuple(fields, _) =>
251 fields.flat_map_in_place(|field| self.configure(field)),
252 ast::VariantData::Unit(_) => {}
256 pub fn configure_item_kind(&mut self, item: &mut ast::ItemKind) {
258 ast::ItemKind::Struct(def, _generics) |
259 ast::ItemKind::Union(def, _generics) => self.configure_variant_data(def),
260 ast::ItemKind::Enum(ast::EnumDef { variants }, _generics) => {
261 variants.flat_map_in_place(|variant| self.configure(variant));
262 for variant in variants {
263 self.configure_variant_data(&mut variant.data);
270 pub fn configure_expr_kind(&mut self, expr_kind: &mut ast::ExprKind) {
272 ast::ExprKind::Match(_m, arms) => {
273 arms.flat_map_in_place(|arm| self.configure(arm));
275 ast::ExprKind::Struct(_path, fields, _base) => {
276 fields.flat_map_in_place(|field| self.configure(field));
282 pub fn configure_expr(&mut self, expr: &mut P<ast::Expr>) {
283 self.visit_expr_attrs(expr.attrs());
285 // If an expr is valid to cfg away it will have been removed by the
286 // outer stmt or expression folder before descending in here.
287 // Anything else is always required, and thus has to error out
288 // in case of a cfg attr.
290 // N.B., this is intentionally not part of the visit_expr() function
291 // in order for filter_map_expr() to be able to avoid this check
292 if let Some(attr) = expr.attrs().iter().find(|a| is_cfg(a)) {
293 let msg = "removing an expression is not supported in this position";
294 self.sess.span_diagnostic.span_err(attr.span, msg);
297 self.process_cfg_attrs(expr)
300 pub fn configure_pat(&mut self, pat: &mut P<ast::Pat>) {
301 if let ast::PatKind::Struct(_path, fields, _etc) = &mut pat.node {
302 fields.flat_map_in_place(|field| self.configure(field));
306 pub fn configure_fn_decl(&mut self, fn_decl: &mut ast::FnDecl) {
307 fn_decl.inputs.flat_map_in_place(|arg| self.configure(arg));
311 impl<'a> MutVisitor for StripUnconfigured<'a> {
312 fn visit_foreign_mod(&mut self, foreign_mod: &mut ast::ForeignMod) {
313 self.configure_foreign_mod(foreign_mod);
314 noop_visit_foreign_mod(foreign_mod, self);
317 fn visit_item_kind(&mut self, item: &mut ast::ItemKind) {
318 self.configure_item_kind(item);
319 noop_visit_item_kind(item, self);
322 fn visit_expr(&mut self, expr: &mut P<ast::Expr>) {
323 self.configure_expr(expr);
324 self.configure_expr_kind(&mut expr.node);
325 noop_visit_expr(expr, self);
328 fn filter_map_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
329 let mut expr = configure!(self, expr);
330 self.configure_expr_kind(&mut expr.node);
331 noop_visit_expr(&mut expr, self);
335 fn flat_map_stmt(&mut self, stmt: ast::Stmt) -> SmallVec<[ast::Stmt; 1]> {
336 noop_flat_map_stmt(configure!(self, stmt), self)
339 fn flat_map_item(&mut self, item: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
340 noop_flat_map_item(configure!(self, item), self)
343 fn flat_map_impl_item(&mut self, item: ast::ImplItem) -> SmallVec<[ast::ImplItem; 1]> {
344 noop_flat_map_impl_item(configure!(self, item), self)
347 fn flat_map_trait_item(&mut self, item: ast::TraitItem) -> SmallVec<[ast::TraitItem; 1]> {
348 noop_flat_map_trait_item(configure!(self, item), self)
351 fn visit_mac(&mut self, _mac: &mut ast::Mac) {
352 // Don't configure interpolated AST (cf. issue #34171).
353 // Interpolated AST will get configured once the surrounding tokens are parsed.
356 fn visit_pat(&mut self, pat: &mut P<ast::Pat>) {
357 self.configure_pat(pat);
358 noop_visit_pat(pat, self)
361 fn visit_fn_decl(&mut self, mut fn_decl: &mut P<ast::FnDecl>) {
362 self.configure_fn_decl(&mut fn_decl);
363 noop_visit_fn_decl(fn_decl, self);
367 fn is_cfg(attr: &ast::Attribute) -> bool {
368 attr.check_name(sym::cfg)