1 //! Process the potential `cfg` attributes on a module.
2 //! Also determine if the module should be included in this configuration.
4 //! This module properly belongs in syntax_expand, but for now it's tied into
5 //! parsing, so we leave it here to avoid complicated out-of-line dependencies.
7 //! A principled solution to this wrong location would be to implement [#64197].
9 //! [#64197]: https://github.com/rust-lang/rust/issues/64197
11 use crate::{parse_in, validate_attr};
12 use rustc_errors::Applicability;
13 use rustc_feature::Features;
14 use syntax::ast::{self, AttrItem, Attribute, MetaItem};
16 use syntax::attr::HasAttrs;
17 use syntax::edition::Edition;
18 use syntax::feature_gate::{feature_err, get_features};
19 use syntax::mut_visit::*;
21 use syntax::sess::ParseSess;
22 use syntax::util::map_in_place::MapInPlace;
23 use syntax_pos::symbol::sym;
26 use smallvec::SmallVec;
28 /// A folder that strips out items that do not belong in the current configuration.
29 pub struct StripUnconfigured<'a> {
30 pub sess: &'a ParseSess,
31 pub features: Option<&'a Features>,
34 // `cfg_attr`-process the crate's attributes and compute the crate's features.
36 mut krate: ast::Crate,
39 allow_features: &Option<Vec<String>>,
40 ) -> (ast::Crate, Features) {
43 let mut strip_unconfigured = StripUnconfigured { sess, features: None };
45 let unconfigured_attrs = krate.attrs.clone();
46 let err_count = sess.span_diagnostic.err_count();
47 if let Some(attrs) = strip_unconfigured.configure(krate.attrs) {
50 // the entire crate is unconfigured
51 krate.attrs = Vec::new();
52 krate.module.items = Vec::new();
53 return (krate, Features::default());
56 features = get_features(&sess.span_diagnostic, &krate.attrs, edition, allow_features);
58 // Avoid reconfiguring malformed `cfg_attr`s
59 if err_count == sess.span_diagnostic.err_count() {
60 strip_unconfigured.features = Some(&features);
61 strip_unconfigured.configure(unconfigured_attrs);
69 macro_rules! configure {
70 ($this:ident, $node:ident) => {
71 match $this.configure($node) {
73 None => return Default::default(),
78 const CFG_ATTR_GRAMMAR_HELP: &str = "#[cfg_attr(condition, attribute, other_attribute, ...)]";
79 const CFG_ATTR_NOTE_REF: &str = "for more information, visit \
80 <https://doc.rust-lang.org/reference/conditional-compilation.html\
81 #the-cfg_attr-attribute>";
83 impl<'a> StripUnconfigured<'a> {
84 pub fn configure<T: HasAttrs>(&mut self, mut node: T) -> Option<T> {
85 self.process_cfg_attrs(&mut node);
86 self.in_cfg(node.attrs()).then_some(node)
89 /// Parse and expand all `cfg_attr` attributes into a list of attributes
90 /// that are within each `cfg_attr` that has a true configuration predicate.
92 /// Gives compiler warnigns if any `cfg_attr` does not contain any
93 /// attributes and is in the original source code. Gives compiler errors if
94 /// the syntax of any `cfg_attr` is incorrect.
95 pub fn process_cfg_attrs<T: HasAttrs>(&mut self, node: &mut T) {
96 node.visit_attrs(|attrs| {
97 attrs.flat_map_in_place(|attr| self.process_cfg_attr(attr));
101 /// Parse and expand a single `cfg_attr` attribute into a list of attributes
102 /// when the configuration predicate is true, or otherwise expand into an
103 /// empty list of attributes.
105 /// Gives a compiler warning when the `cfg_attr` contains no attributes and
106 /// is in the original source file. Gives a compiler error if the syntax of
107 /// the attribute is incorrect.
108 fn process_cfg_attr(&mut self, attr: Attribute) -> Vec<Attribute> {
109 if !attr.has_name(sym::cfg_attr) {
113 let (cfg_predicate, expanded_attrs) = match self.parse_cfg_attr(&attr) {
114 None => return vec![],
118 // Lint on zero attributes in source.
119 if expanded_attrs.is_empty() {
123 // At this point we know the attribute is considered used.
124 attr::mark_used(&attr);
126 if !attr::cfg_matches(&cfg_predicate, self.sess, self.features) {
130 // We call `process_cfg_attr` recursively in case there's a
131 // `cfg_attr` inside of another `cfg_attr`. E.g.
132 // `#[cfg_attr(false, cfg_attr(true, some_attr))]`.
135 .flat_map(|(item, span)| {
136 let attr = attr::mk_attr_from_item(attr.style, item, span);
137 self.process_cfg_attr(attr)
142 fn parse_cfg_attr(&self, attr: &Attribute) -> Option<(MetaItem, Vec<(AttrItem, Span)>)> {
143 match attr.get_normal_item().args {
144 ast::MacArgs::Delimited(dspan, delim, ref tts) if !tts.is_empty() => {
145 let msg = "wrong `cfg_attr` delimiters";
146 validate_attr::check_meta_bad_delim(self.sess, dspan, delim, msg);
147 match parse_in(self.sess, tts.clone(), "`cfg_attr` input", |p| p.parse_cfg_attr()) {
148 Ok(r) => return Some(r),
150 .help(&format!("the valid syntax is `{}`", CFG_ATTR_GRAMMAR_HELP))
151 .note(CFG_ATTR_NOTE_REF)
155 _ => self.error_malformed_cfg_attr_missing(attr.span),
160 fn error_malformed_cfg_attr_missing(&self, span: Span) {
163 .struct_span_err(span, "malformed `cfg_attr` attribute input")
166 "missing condition and attribute",
167 CFG_ATTR_GRAMMAR_HELP.to_string(),
168 Applicability::HasPlaceholders,
170 .note(CFG_ATTR_NOTE_REF)
174 /// Determines if a node with the given attributes should be included in this configuration.
175 pub fn in_cfg(&self, attrs: &[Attribute]) -> bool {
176 attrs.iter().all(|attr| {
181 let error = |span, msg, suggestion: &str| {
182 let mut err = self.sess.span_diagnostic.struct_span_err(span, msg);
183 if !suggestion.is_empty() {
186 "expected syntax is",
188 Applicability::MaybeIncorrect,
195 let meta_item = match validate_attr::parse_meta(self.sess, attr) {
196 Ok(meta_item) => meta_item,
202 let nested_meta_items = if let Some(nested_meta_items) = meta_item.meta_item_list() {
207 "`cfg` is not followed by parentheses",
208 "cfg(/* predicate */)",
212 if nested_meta_items.is_empty() {
213 return error(meta_item.span, "`cfg` predicate is not specified", "");
214 } else if nested_meta_items.len() > 1 {
216 nested_meta_items.last().unwrap().span(),
217 "multiple `cfg` predicates are specified",
222 match nested_meta_items[0].meta_item() {
223 Some(meta_item) => attr::cfg_matches(meta_item, self.sess, self.features),
225 nested_meta_items[0].span(),
226 "`cfg` predicate key cannot be a literal",
233 /// Visit attributes on expression and statements (but not attributes on items in blocks).
234 fn visit_expr_attrs(&mut self, attrs: &[Attribute]) {
235 // flag the offending attributes
236 for attr in attrs.iter() {
237 self.maybe_emit_expr_attr_err(attr);
241 /// If attributes are not allowed on expressions, emit an error for `attr`
242 pub fn maybe_emit_expr_attr_err(&self, attr: &Attribute) {
243 if !self.features.map(|features| features.stmt_expr_attributes).unwrap_or(true) {
244 let mut err = feature_err(
246 sym::stmt_expr_attributes,
248 "attributes on expressions are experimental",
251 if attr.is_doc_comment() {
252 err.help("`///` is for documentation comments. For a plain comment, use `//`.");
259 pub fn configure_foreign_mod(&mut self, foreign_mod: &mut ast::ForeignMod) {
260 let ast::ForeignMod { abi: _, items } = foreign_mod;
261 items.flat_map_in_place(|item| self.configure(item));
264 pub fn configure_generic_params(&mut self, params: &mut Vec<ast::GenericParam>) {
265 params.flat_map_in_place(|param| self.configure(param));
268 fn configure_variant_data(&mut self, vdata: &mut ast::VariantData) {
270 ast::VariantData::Struct(fields, ..) | ast::VariantData::Tuple(fields, _) => {
271 fields.flat_map_in_place(|field| self.configure(field))
273 ast::VariantData::Unit(_) => {}
277 pub fn configure_item_kind(&mut self, item: &mut ast::ItemKind) {
279 ast::ItemKind::Struct(def, _generics) | ast::ItemKind::Union(def, _generics) => {
280 self.configure_variant_data(def)
282 ast::ItemKind::Enum(ast::EnumDef { variants }, _generics) => {
283 variants.flat_map_in_place(|variant| self.configure(variant));
284 for variant in variants {
285 self.configure_variant_data(&mut variant.data);
292 pub fn configure_expr_kind(&mut self, expr_kind: &mut ast::ExprKind) {
294 ast::ExprKind::Match(_m, arms) => {
295 arms.flat_map_in_place(|arm| self.configure(arm));
297 ast::ExprKind::Struct(_path, fields, _base) => {
298 fields.flat_map_in_place(|field| self.configure(field));
304 pub fn configure_expr(&mut self, expr: &mut P<ast::Expr>) {
305 self.visit_expr_attrs(expr.attrs());
307 // If an expr is valid to cfg away it will have been removed by the
308 // outer stmt or expression folder before descending in here.
309 // Anything else is always required, and thus has to error out
310 // in case of a cfg attr.
312 // N.B., this is intentionally not part of the visit_expr() function
313 // in order for filter_map_expr() to be able to avoid this check
314 if let Some(attr) = expr.attrs().iter().find(|a| is_cfg(a)) {
315 let msg = "removing an expression is not supported in this position";
316 self.sess.span_diagnostic.span_err(attr.span, msg);
319 self.process_cfg_attrs(expr)
322 pub fn configure_pat(&mut self, pat: &mut P<ast::Pat>) {
323 if let ast::PatKind::Struct(_path, fields, _etc) = &mut pat.kind {
324 fields.flat_map_in_place(|field| self.configure(field));
328 pub fn configure_fn_decl(&mut self, fn_decl: &mut ast::FnDecl) {
329 fn_decl.inputs.flat_map_in_place(|arg| self.configure(arg));
333 impl<'a> MutVisitor for StripUnconfigured<'a> {
334 fn visit_foreign_mod(&mut self, foreign_mod: &mut ast::ForeignMod) {
335 self.configure_foreign_mod(foreign_mod);
336 noop_visit_foreign_mod(foreign_mod, self);
339 fn visit_item_kind(&mut self, item: &mut ast::ItemKind) {
340 self.configure_item_kind(item);
341 noop_visit_item_kind(item, self);
344 fn visit_expr(&mut self, expr: &mut P<ast::Expr>) {
345 self.configure_expr(expr);
346 self.configure_expr_kind(&mut expr.kind);
347 noop_visit_expr(expr, self);
350 fn filter_map_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
351 let mut expr = configure!(self, expr);
352 self.configure_expr_kind(&mut expr.kind);
353 noop_visit_expr(&mut expr, self);
357 fn flat_map_stmt(&mut self, stmt: ast::Stmt) -> SmallVec<[ast::Stmt; 1]> {
358 noop_flat_map_stmt(configure!(self, stmt), self)
361 fn flat_map_item(&mut self, item: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
362 noop_flat_map_item(configure!(self, item), self)
365 fn flat_map_impl_item(&mut self, item: ast::AssocItem) -> SmallVec<[ast::AssocItem; 1]> {
366 noop_flat_map_assoc_item(configure!(self, item), self)
369 fn flat_map_trait_item(&mut self, item: ast::AssocItem) -> SmallVec<[ast::AssocItem; 1]> {
370 noop_flat_map_assoc_item(configure!(self, item), self)
373 fn visit_mac(&mut self, _mac: &mut ast::Mac) {
374 // Don't configure interpolated AST (cf. issue #34171).
375 // Interpolated AST will get configured once the surrounding tokens are parsed.
378 fn visit_pat(&mut self, pat: &mut P<ast::Pat>) {
379 self.configure_pat(pat);
380 noop_visit_pat(pat, self)
383 fn visit_fn_decl(&mut self, mut fn_decl: &mut P<ast::FnDecl>) {
384 self.configure_fn_decl(&mut fn_decl);
385 noop_visit_fn_decl(fn_decl, self);
389 fn is_cfg(attr: &Attribute) -> bool {
390 attr.check_name(sym::cfg)
393 /// Process the potential `cfg` attributes on a module.
394 /// Also determine if the module should be included in this configuration.
395 pub fn process_configure_mod(
399 ) -> (bool, Vec<Attribute>) {
400 // Don't perform gated feature checking.
401 let mut strip_unconfigured = StripUnconfigured { sess, features: None };
402 let mut attrs = attrs.to_owned();
403 strip_unconfigured.process_cfg_attrs(&mut attrs);
404 (!cfg_mods || strip_unconfigured.in_cfg(&attrs), attrs)