1 //! Conditional compilation stripping.
3 use rustc_ast::ast::{self, AttrItem, Attribute, MetaItem};
4 use rustc_ast::attr::HasAttrs;
5 use rustc_ast::mut_visit::*;
7 use rustc_attr as attr;
8 use rustc_data_structures::fx::FxHashMap;
9 use rustc_data_structures::map_in_place::MapInPlace;
10 use rustc_errors::{error_code, struct_span_err, Applicability, Handler};
11 use rustc_feature::{Feature, Features, State as FeatureState};
13 ACCEPTED_FEATURES, ACTIVE_FEATURES, REMOVED_FEATURES, STABLE_REMOVED_FEATURES,
15 use rustc_parse::{parse_in, validate_attr};
16 use rustc_session::parse::{feature_err, ParseSess};
17 use rustc_span::edition::{Edition, ALL_EDITIONS};
18 use rustc_span::symbol::{sym, Symbol};
19 use rustc_span::{Span, DUMMY_SP};
21 use smallvec::SmallVec;
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>,
30 span_handler: &Handler,
31 krate_attrs: &[ast::Attribute],
32 crate_edition: Edition,
33 allow_features: &Option<Vec<String>>,
35 fn feature_removed(span_handler: &Handler, span: Span, reason: Option<&str>) {
36 let mut err = struct_span_err!(span_handler, span, E0557, "feature has been removed");
37 err.span_label(span, "feature has been removed");
38 if let Some(reason) = reason {
44 fn active_features_up_to(edition: Edition) -> impl Iterator<Item = &'static Feature> {
45 ACTIVE_FEATURES.iter().filter(move |feature| {
46 if let Some(feature_edition) = feature.edition {
47 feature_edition <= edition
54 let mut features = Features::default();
55 let mut edition_enabled_features = FxHashMap::default();
57 for &edition in ALL_EDITIONS {
58 if edition <= crate_edition {
59 // The `crate_edition` implies its respective umbrella feature-gate
60 // (i.e., `#![feature(rust_20XX_preview)]` isn't needed on edition 20XX).
61 edition_enabled_features.insert(edition.feature_name(), edition);
65 for feature in active_features_up_to(crate_edition) {
66 feature.set(&mut features, DUMMY_SP);
67 edition_enabled_features.insert(feature.name, crate_edition);
70 // Process the edition umbrella feature-gates first, to ensure
71 // `edition_enabled_features` is completed before it's queried.
72 for attr in krate_attrs {
73 if !attr.check_name(sym::feature) {
77 let list = match attr.meta_item_list() {
87 let name = mi.name_or_empty();
89 let edition = ALL_EDITIONS.iter().find(|e| name == e.feature_name()).copied();
90 if let Some(edition) = edition {
91 if edition <= crate_edition {
95 for feature in active_features_up_to(edition) {
96 // FIXME(Manishearth) there is currently no way to set
97 // lib features by edition
98 feature.set(&mut features, DUMMY_SP);
99 edition_enabled_features.insert(feature.name, edition);
105 for attr in krate_attrs {
106 if !attr.check_name(sym::feature) {
110 let list = match attr.meta_item_list() {
115 let bad_input = |span| {
116 struct_span_err!(span_handler, span, E0556, "malformed `feature` attribute input")
120 let name = match mi.ident() {
121 Some(ident) if mi.is_word() => ident.name,
126 "expected just one word",
127 format!("{}", ident.name),
128 Applicability::MaybeIncorrect,
134 bad_input(mi.span()).span_label(mi.span(), "expected just one word").emit();
139 if let Some(edition) = edition_enabled_features.get(&name) {
141 &format!("the feature `{}` is included in the Rust {} edition", name, edition);
142 span_handler.struct_span_warn_with_code(mi.span(), msg, error_code!(E0705)).emit();
146 if ALL_EDITIONS.iter().any(|e| name == e.feature_name()) {
147 // Handled in the separate loop above.
151 let removed = REMOVED_FEATURES.iter().find(|f| name == f.name);
152 let stable_removed = STABLE_REMOVED_FEATURES.iter().find(|f| name == f.name);
153 if let Some(Feature { state, .. }) = removed.or(stable_removed) {
154 if let FeatureState::Removed { reason } | FeatureState::Stabilized { reason } =
157 feature_removed(span_handler, mi.span(), *reason);
162 if let Some(Feature { since, .. }) = ACCEPTED_FEATURES.iter().find(|f| name == f.name) {
163 let since = Some(Symbol::intern(since));
164 features.declared_lang_features.push((name, mi.span(), since));
168 if let Some(allowed) = allow_features.as_ref() {
169 if allowed.iter().find(|&f| name.as_str() == *f).is_none() {
174 "the feature `{}` is not in the list of allowed features",
182 if let Some(f) = ACTIVE_FEATURES.iter().find(|f| name == f.name) {
183 f.set(&mut features, mi.span());
184 features.declared_lang_features.push((name, mi.span(), None));
188 features.declared_lib_features.push((name, mi.span()));
195 // `cfg_attr`-process the crate's attributes and compute the crate's features.
197 mut krate: ast::Crate,
200 allow_features: &Option<Vec<String>>,
201 ) -> (ast::Crate, Features) {
202 let mut strip_unconfigured = StripUnconfigured { sess, features: None };
204 let unconfigured_attrs = krate.attrs.clone();
205 let diag = &sess.span_diagnostic;
206 let err_count = diag.err_count();
207 let features = match strip_unconfigured.configure(krate.attrs) {
209 // The entire crate is unconfigured.
210 krate.attrs = Vec::new();
211 krate.module.items = Vec::new();
216 let features = get_features(diag, &krate.attrs, edition, allow_features);
217 if err_count == diag.err_count() {
218 // Avoid reconfiguring malformed `cfg_attr`s.
219 strip_unconfigured.features = Some(&features);
220 strip_unconfigured.configure(unconfigured_attrs);
229 macro_rules! configure {
230 ($this:ident, $node:ident) => {
231 match $this.configure($node) {
233 None => return Default::default(),
238 const CFG_ATTR_GRAMMAR_HELP: &str = "#[cfg_attr(condition, attribute, other_attribute, ...)]";
239 const CFG_ATTR_NOTE_REF: &str = "for more information, visit \
240 <https://doc.rust-lang.org/reference/conditional-compilation.html\
241 #the-cfg_attr-attribute>";
243 impl<'a> StripUnconfigured<'a> {
244 pub fn configure<T: HasAttrs>(&mut self, mut node: T) -> Option<T> {
245 self.process_cfg_attrs(&mut node);
246 self.in_cfg(node.attrs()).then_some(node)
249 /// Parse and expand all `cfg_attr` attributes into a list of attributes
250 /// that are within each `cfg_attr` that has a true configuration predicate.
252 /// Gives compiler warnings if any `cfg_attr` does not contain any
253 /// attributes and is in the original source code. Gives compiler errors if
254 /// the syntax of any `cfg_attr` is incorrect.
255 pub fn process_cfg_attrs<T: HasAttrs>(&mut self, node: &mut T) {
256 node.visit_attrs(|attrs| {
257 attrs.flat_map_in_place(|attr| self.process_cfg_attr(attr));
261 /// Parse and expand a single `cfg_attr` attribute into a list of attributes
262 /// when the configuration predicate is true, or otherwise expand into an
263 /// empty list of attributes.
265 /// Gives a compiler warning when the `cfg_attr` contains no attributes and
266 /// is in the original source file. Gives a compiler error if the syntax of
267 /// the attribute is incorrect.
268 fn process_cfg_attr(&mut self, attr: Attribute) -> Vec<Attribute> {
269 if !attr.has_name(sym::cfg_attr) {
273 let (cfg_predicate, expanded_attrs) = match self.parse_cfg_attr(&attr) {
274 None => return vec![],
278 // Lint on zero attributes in source.
279 if expanded_attrs.is_empty() {
283 // At this point we know the attribute is considered used.
284 attr::mark_used(&attr);
286 if !attr::cfg_matches(&cfg_predicate, self.sess, self.features) {
290 // We call `process_cfg_attr` recursively in case there's a
291 // `cfg_attr` inside of another `cfg_attr`. E.g.
292 // `#[cfg_attr(false, cfg_attr(true, some_attr))]`.
295 .flat_map(|(item, span)| {
296 let attr = attr::mk_attr_from_item(attr.style, item, span);
297 self.process_cfg_attr(attr)
302 fn parse_cfg_attr(&self, attr: &Attribute) -> Option<(MetaItem, Vec<(AttrItem, Span)>)> {
303 match attr.get_normal_item().args {
304 ast::MacArgs::Delimited(dspan, delim, ref tts) if !tts.is_empty() => {
305 let msg = "wrong `cfg_attr` delimiters";
306 validate_attr::check_meta_bad_delim(self.sess, dspan, delim, msg);
307 match parse_in(self.sess, tts.clone(), "`cfg_attr` input", |p| p.parse_cfg_attr()) {
308 Ok(r) => return Some(r),
310 e.help(&format!("the valid syntax is `{}`", CFG_ATTR_GRAMMAR_HELP))
311 .note(CFG_ATTR_NOTE_REF)
316 _ => self.error_malformed_cfg_attr_missing(attr.span),
321 fn error_malformed_cfg_attr_missing(&self, span: Span) {
324 .struct_span_err(span, "malformed `cfg_attr` attribute input")
327 "missing condition and attribute",
328 CFG_ATTR_GRAMMAR_HELP.to_string(),
329 Applicability::HasPlaceholders,
331 .note(CFG_ATTR_NOTE_REF)
335 /// Determines if a node with the given attributes should be included in this configuration.
336 pub fn in_cfg(&self, attrs: &[Attribute]) -> bool {
337 attrs.iter().all(|attr| {
341 let meta_item = match validate_attr::parse_meta(self.sess, attr) {
342 Ok(meta_item) => meta_item,
348 let error = |span, msg, suggestion: &str| {
349 let mut err = self.sess.span_diagnostic.struct_span_err(span, msg);
350 if !suggestion.is_empty() {
353 "expected syntax is",
355 Applicability::MaybeIncorrect,
361 let span = meta_item.span;
362 match meta_item.meta_item_list() {
363 None => error(span, "`cfg` is not followed by parentheses", "cfg(/* predicate */)"),
364 Some([]) => error(span, "`cfg` predicate is not specified", ""),
365 Some([_, .., l]) => error(l.span(), "multiple `cfg` predicates are specified", ""),
366 Some([single]) => match single.meta_item() {
367 Some(meta_item) => attr::cfg_matches(meta_item, self.sess, self.features),
368 None => error(single.span(), "`cfg` predicate key cannot be a literal", ""),
374 /// Visit attributes on expression and statements (but not attributes on items in blocks).
375 fn visit_expr_attrs(&mut self, attrs: &[Attribute]) {
376 // flag the offending attributes
377 for attr in attrs.iter() {
378 self.maybe_emit_expr_attr_err(attr);
382 /// If attributes are not allowed on expressions, emit an error for `attr`
383 pub fn maybe_emit_expr_attr_err(&self, attr: &Attribute) {
384 if !self.features.map(|features| features.stmt_expr_attributes).unwrap_or(true) {
385 let mut err = feature_err(
387 sym::stmt_expr_attributes,
389 "attributes on expressions are experimental",
392 if attr.is_doc_comment() {
393 err.help("`///` is for documentation comments. For a plain comment, use `//`.");
400 pub fn configure_foreign_mod(&mut self, foreign_mod: &mut ast::ForeignMod) {
401 let ast::ForeignMod { abi: _, items } = foreign_mod;
402 items.flat_map_in_place(|item| self.configure(item));
405 pub fn configure_generic_params(&mut self, params: &mut Vec<ast::GenericParam>) {
406 params.flat_map_in_place(|param| self.configure(param));
409 fn configure_variant_data(&mut self, vdata: &mut ast::VariantData) {
411 ast::VariantData::Struct(fields, ..) | ast::VariantData::Tuple(fields, _) => {
412 fields.flat_map_in_place(|field| self.configure(field))
414 ast::VariantData::Unit(_) => {}
418 pub fn configure_item_kind(&mut self, item: &mut ast::ItemKind) {
420 ast::ItemKind::Struct(def, _generics) | ast::ItemKind::Union(def, _generics) => {
421 self.configure_variant_data(def)
423 ast::ItemKind::Enum(ast::EnumDef { variants }, _generics) => {
424 variants.flat_map_in_place(|variant| self.configure(variant));
425 for variant in variants {
426 self.configure_variant_data(&mut variant.data);
433 pub fn configure_expr_kind(&mut self, expr_kind: &mut ast::ExprKind) {
435 ast::ExprKind::Match(_m, arms) => {
436 arms.flat_map_in_place(|arm| self.configure(arm));
438 ast::ExprKind::Struct(_path, fields, _base) => {
439 fields.flat_map_in_place(|field| self.configure(field));
445 pub fn configure_expr(&mut self, expr: &mut P<ast::Expr>) {
446 self.visit_expr_attrs(expr.attrs());
448 // If an expr is valid to cfg away it will have been removed by the
449 // outer stmt or expression folder before descending in here.
450 // Anything else is always required, and thus has to error out
451 // in case of a cfg attr.
453 // N.B., this is intentionally not part of the visit_expr() function
454 // in order for filter_map_expr() to be able to avoid this check
455 if let Some(attr) = expr.attrs().iter().find(|a| is_cfg(a)) {
456 let msg = "removing an expression is not supported in this position";
457 self.sess.span_diagnostic.span_err(attr.span, msg);
460 self.process_cfg_attrs(expr)
463 pub fn configure_pat(&mut self, pat: &mut P<ast::Pat>) {
464 if let ast::PatKind::Struct(_path, fields, _etc) = &mut pat.kind {
465 fields.flat_map_in_place(|field| self.configure(field));
469 pub fn configure_fn_decl(&mut self, fn_decl: &mut ast::FnDecl) {
470 fn_decl.inputs.flat_map_in_place(|arg| self.configure(arg));
474 impl<'a> MutVisitor for StripUnconfigured<'a> {
475 fn visit_foreign_mod(&mut self, foreign_mod: &mut ast::ForeignMod) {
476 self.configure_foreign_mod(foreign_mod);
477 noop_visit_foreign_mod(foreign_mod, self);
480 fn visit_item_kind(&mut self, item: &mut ast::ItemKind) {
481 self.configure_item_kind(item);
482 noop_visit_item_kind(item, self);
485 fn visit_expr(&mut self, expr: &mut P<ast::Expr>) {
486 self.configure_expr(expr);
487 self.configure_expr_kind(&mut expr.kind);
488 noop_visit_expr(expr, self);
491 fn filter_map_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
492 let mut expr = configure!(self, expr);
493 self.configure_expr_kind(&mut expr.kind);
494 noop_visit_expr(&mut expr, self);
498 fn flat_map_stmt(&mut self, stmt: ast::Stmt) -> SmallVec<[ast::Stmt; 1]> {
499 noop_flat_map_stmt(configure!(self, stmt), self)
502 fn flat_map_item(&mut self, item: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
503 noop_flat_map_item(configure!(self, item), self)
506 fn flat_map_impl_item(&mut self, item: P<ast::AssocItem>) -> SmallVec<[P<ast::AssocItem>; 1]> {
507 noop_flat_map_assoc_item(configure!(self, item), self)
510 fn flat_map_trait_item(&mut self, item: P<ast::AssocItem>) -> SmallVec<[P<ast::AssocItem>; 1]> {
511 noop_flat_map_assoc_item(configure!(self, item), self)
514 fn visit_mac(&mut self, _mac: &mut ast::MacCall) {
515 // Don't configure interpolated AST (cf. issue #34171).
516 // Interpolated AST will get configured once the surrounding tokens are parsed.
519 fn visit_pat(&mut self, pat: &mut P<ast::Pat>) {
520 self.configure_pat(pat);
521 noop_visit_pat(pat, self)
524 fn visit_fn_decl(&mut self, mut fn_decl: &mut P<ast::FnDecl>) {
525 self.configure_fn_decl(&mut fn_decl);
526 noop_visit_fn_decl(fn_decl, self);
530 fn is_cfg(attr: &Attribute) -> bool {
531 attr.check_name(sym::cfg)