1 use crate::attr::HasAttrs;
2 use crate::feature_gate::{
4 EXPLAIN_STMT_ATTR_SYNTAX,
11 use crate::edition::Edition;
12 use crate::errors::Applicability;
13 use crate::mut_visit::*;
14 use crate::parse::{token, ParseSess};
16 use crate::util::map_in_place::MapInPlace;
18 use smallvec::SmallVec;
20 /// A folder that strips out items that do not belong in the current configuration.
21 pub struct StripUnconfigured<'a> {
22 pub sess: &'a ParseSess,
23 pub features: Option<&'a Features>,
26 // `cfg_attr`-process the crate's attributes and compute the crate's features.
27 pub fn features(mut krate: ast::Crate, sess: &ParseSess, edition: Edition)
28 -> (ast::Crate, Features) {
31 let mut strip_unconfigured = StripUnconfigured {
36 let unconfigured_attrs = krate.attrs.clone();
37 let err_count = sess.span_diagnostic.err_count();
38 if let Some(attrs) = strip_unconfigured.configure(krate.attrs) {
40 } else { // the entire crate is unconfigured
41 krate.attrs = Vec::new();
42 krate.module.items = Vec::new();
43 return (krate, Features::new());
46 features = get_features(&sess.span_diagnostic, &krate.attrs, edition);
48 // Avoid reconfiguring malformed `cfg_attr`s
49 if err_count == sess.span_diagnostic.err_count() {
50 strip_unconfigured.features = Some(&features);
51 strip_unconfigured.configure(unconfigured_attrs);
58 macro_rules! configure {
59 ($this:ident, $node:ident) => {
60 match $this.configure($node) {
62 None => return Default::default(),
67 impl<'a> StripUnconfigured<'a> {
68 pub fn configure<T: HasAttrs>(&mut self, mut node: T) -> Option<T> {
69 self.process_cfg_attrs(&mut node);
70 if self.in_cfg(node.attrs()) { Some(node) } else { None }
73 /// Parse and expand all `cfg_attr` attributes into a list of attributes
74 /// that are within each `cfg_attr` that has a true configuration predicate.
76 /// Gives compiler warnigns if any `cfg_attr` does not contain any
77 /// attributes and is in the original source code. Gives compiler errors if
78 /// the syntax of any `cfg_attr` is incorrect.
79 pub fn process_cfg_attrs<T: HasAttrs>(&mut self, node: &mut T) {
80 node.visit_attrs(|attrs| {
81 attrs.flat_map_in_place(|attr| self.process_cfg_attr(attr));
85 /// Parse and expand a single `cfg_attr` attribute into a list of attributes
86 /// when the configuration predicate is true, or otherwise expand into an
87 /// empty list of attributes.
89 /// Gives a compiler warning when the `cfg_attr` contains no attributes and
90 /// is in the original source file. Gives a compiler error if the syntax of
91 /// the attribute is incorrect.
92 fn process_cfg_attr(&mut self, attr: ast::Attribute) -> Vec<ast::Attribute> {
93 if !attr.check_name("cfg_attr") {
97 let (cfg_predicate, expanded_attrs) = match attr.parse(self.sess, |parser| {
98 parser.expect(&token::OpenDelim(token::Paren))?;
100 let cfg_predicate = parser.parse_meta_item()?;
101 parser.expect(&token::Comma)?;
103 // Presumably, the majority of the time there will only be one attr.
104 let mut expanded_attrs = Vec::with_capacity(1);
106 while !parser.check(&token::CloseDelim(token::Paren)) {
107 let lo = parser.span.lo();
108 let (path, tokens) = parser.parse_meta_item_unrestricted()?;
109 expanded_attrs.push((path, tokens, parser.prev_span.with_lo(lo)));
110 parser.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Paren)])?;
113 parser.expect(&token::CloseDelim(token::Paren))?;
114 Ok((cfg_predicate, expanded_attrs))
116 Ok(result) => result,
123 // Check feature gate and lint on zero attributes in source. Even if the feature is gated,
124 // we still compute as if it wasn't, since the emitted error will stop compilation further
125 // along the compilation.
126 if expanded_attrs.len() == 0 {
127 // FIXME: Emit unused attribute lint here.
130 if attr::cfg_matches(&cfg_predicate, self.sess, self.features) {
131 // We call `process_cfg_attr` recursively in case there's a
132 // `cfg_attr` inside of another `cfg_attr`. E.g.
133 // `#[cfg_attr(false, cfg_attr(true, some_attr))]`.
134 expanded_attrs.into_iter()
135 .flat_map(|(path, tokens, span)| self.process_cfg_attr(ast::Attribute {
136 id: attr::mk_attr_id(),
140 is_sugared_doc: false,
149 /// Determines if a node with the given attributes should be included in this configuration.
150 pub fn in_cfg(&mut self, attrs: &[ast::Attribute]) -> bool {
151 attrs.iter().all(|attr| {
156 let error = |span, msg, suggestion: &str| {
157 let mut err = self.sess.span_diagnostic.struct_span_err(span, msg);
158 if !suggestion.is_empty() {
161 "expected syntax is",
163 Applicability::MaybeIncorrect,
170 let meta_item = match attr.parse_meta(self.sess) {
171 Ok(meta_item) => meta_item,
172 Err(mut err) => { err.emit(); return true; }
174 let nested_meta_items = if let Some(nested_meta_items) = meta_item.meta_item_list() {
177 return error(meta_item.span, "`cfg` is not followed by parentheses",
178 "cfg(/* predicate */)");
181 if nested_meta_items.is_empty() {
182 return error(meta_item.span, "`cfg` predicate is not specified", "");
183 } else if nested_meta_items.len() > 1 {
184 return error(nested_meta_items.last().unwrap().span,
185 "multiple `cfg` predicates are specified", "");
188 match nested_meta_items[0].meta_item() {
189 Some(meta_item) => attr::cfg_matches(meta_item, self.sess, self.features),
190 None => error(nested_meta_items[0].span,
191 "`cfg` predicate key cannot be a literal", ""),
196 /// Visit attributes on expression and statements (but not attributes on items in blocks).
197 fn visit_expr_attrs(&mut self, attrs: &[ast::Attribute]) {
198 // flag the offending attributes
199 for attr in attrs.iter() {
200 self.maybe_emit_expr_attr_err(attr);
204 /// If attributes are not allowed on expressions, emit an error for `attr`
205 pub fn maybe_emit_expr_attr_err(&self, attr: &ast::Attribute) {
206 if !self.features.map(|features| features.stmt_expr_attributes).unwrap_or(true) {
207 let mut err = feature_err(self.sess,
208 "stmt_expr_attributes",
211 EXPLAIN_STMT_ATTR_SYNTAX);
213 if attr.is_sugared_doc {
214 err.help("`///` is for documentation comments. For a plain comment, use `//`.");
221 pub fn configure_foreign_mod(&mut self, foreign_mod: &mut ast::ForeignMod) {
222 let ast::ForeignMod { abi: _, items } = foreign_mod;
223 items.flat_map_in_place(|item| self.configure(item));
226 fn configure_variant_data(&mut self, vdata: &mut ast::VariantData) {
228 ast::VariantData::Struct(fields, _id) |
229 ast::VariantData::Tuple(fields, _id) =>
230 fields.flat_map_in_place(|field| self.configure(field)),
231 ast::VariantData::Unit(_id) => {}
235 pub fn configure_item_kind(&mut self, item: &mut ast::ItemKind) {
237 ast::ItemKind::Struct(def, _generics) |
238 ast::ItemKind::Union(def, _generics) => self.configure_variant_data(def),
239 ast::ItemKind::Enum(ast::EnumDef { variants }, _generics) => {
240 variants.flat_map_in_place(|variant| self.configure(variant));
241 for variant in variants {
242 self.configure_variant_data(&mut variant.node.data);
249 pub fn configure_expr_kind(&mut self, expr_kind: &mut ast::ExprKind) {
251 ast::ExprKind::Match(_m, arms) => {
252 arms.flat_map_in_place(|arm| self.configure(arm));
254 ast::ExprKind::Struct(_path, fields, _base) => {
255 fields.flat_map_in_place(|field| self.configure(field));
261 pub fn configure_expr(&mut self, expr: &mut 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 // N.B., this is intentionally not part of the visit_expr() function
270 // in order for filter_map_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_pat(&mut self, pat: &mut P<ast::Pat>) {
280 if let ast::PatKind::Struct(_path, fields, _etc) = &mut pat.node {
281 fields.flat_map_in_place(|field| self.configure(field));
285 /// Denies `#[cfg]` on generic parameters until we decide what to do with it.
286 /// See issue #51279.
287 pub fn disallow_cfg_on_generic_param(&mut self, param: &ast::GenericParam) {
288 for attr in param.attrs() {
289 let offending_attr = if attr.check_name("cfg") {
291 } else if attr.check_name("cfg_attr") {
296 let msg = format!("#[{}] cannot be applied on a generic parameter", offending_attr);
297 self.sess.span_diagnostic.span_err(attr.span, &msg);
302 impl<'a> MutVisitor for StripUnconfigured<'a> {
303 fn visit_foreign_mod(&mut self, foreign_mod: &mut ast::ForeignMod) {
304 self.configure_foreign_mod(foreign_mod);
305 noop_visit_foreign_mod(foreign_mod, self);
308 fn visit_item_kind(&mut self, item: &mut ast::ItemKind) {
309 self.configure_item_kind(item);
310 noop_visit_item_kind(item, self);
313 fn visit_expr(&mut self, expr: &mut P<ast::Expr>) {
314 self.configure_expr(expr);
315 self.configure_expr_kind(&mut expr.node);
316 noop_visit_expr(expr, self);
319 fn filter_map_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
320 let mut expr = configure!(self, expr);
321 self.configure_expr_kind(&mut expr.node);
322 noop_visit_expr(&mut expr, self);
326 fn flat_map_stmt(&mut self, stmt: ast::Stmt) -> SmallVec<[ast::Stmt; 1]> {
327 noop_flat_map_stmt(configure!(self, stmt), self)
330 fn flat_map_item(&mut self, item: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
331 noop_flat_map_item(configure!(self, item), self)
334 fn flat_map_impl_item(&mut self, item: ast::ImplItem) -> SmallVec<[ast::ImplItem; 1]> {
335 noop_flat_map_impl_item(configure!(self, item), self)
338 fn flat_map_trait_item(&mut self, item: ast::TraitItem) -> SmallVec<[ast::TraitItem; 1]> {
339 noop_flat_map_trait_item(configure!(self, item), self)
342 fn visit_mac(&mut self, _mac: &mut ast::Mac) {
343 // Don't configure interpolated AST (cf. issue #34171).
344 // Interpolated AST will get configured once the surrounding tokens are parsed.
347 fn visit_pat(&mut self, pat: &mut P<ast::Pat>) {
348 self.configure_pat(pat);
349 noop_visit_pat(pat, self)
353 fn is_cfg(attr: &ast::Attribute) -> bool {
354 attr.check_name("cfg")