1 //! Conditional compilation stripping.
4 use rustc_ast::token::{Delimiter, Token, TokenKind};
5 use rustc_ast::tokenstream::{AttrTokenStream, AttrTokenTree};
6 use rustc_ast::tokenstream::{DelimSpan, Spacing};
7 use rustc_ast::tokenstream::{LazyAttrTokenStream, TokenTree};
9 use rustc_ast::{self as ast, AttrStyle, Attribute, HasAttrs, HasTokens, MetaItem};
10 use rustc_attr as attr;
11 use rustc_data_structures::fx::FxHashMap;
12 use rustc_data_structures::map_in_place::MapInPlace;
13 use rustc_errors::{error_code, struct_span_err, Applicability, Handler};
14 use rustc_feature::{Feature, Features, State as FeatureState};
16 ACCEPTED_FEATURES, ACTIVE_FEATURES, REMOVED_FEATURES, STABLE_REMOVED_FEATURES,
18 use rustc_parse::validate_attr;
19 use rustc_session::parse::feature_err;
20 use rustc_session::Session;
21 use rustc_span::edition::{Edition, ALL_EDITIONS};
22 use rustc_span::symbol::{sym, Symbol};
23 use rustc_span::{Span, DUMMY_SP};
25 /// A folder that strips out items that do not belong in the current configuration.
26 pub struct StripUnconfigured<'a> {
27 pub sess: &'a Session,
28 pub features: Option<&'a Features>,
29 /// If `true`, perform cfg-stripping on attached tokens.
30 /// This is only used for the input to derive macros,
31 /// which needs eager expansion of `cfg` and `cfg_attr`
32 pub config_tokens: bool,
33 pub lint_node_id: NodeId,
38 span_handler: &Handler,
39 krate_attrs: &[ast::Attribute],
41 fn feature_removed(span_handler: &Handler, span: Span, reason: Option<&str>) {
42 let mut err = struct_span_err!(span_handler, span, E0557, "feature has been removed");
43 err.span_label(span, "feature has been removed");
44 if let Some(reason) = reason {
50 fn active_features_up_to(edition: Edition) -> impl Iterator<Item = &'static Feature> {
51 ACTIVE_FEATURES.iter().filter(move |feature| {
52 if let Some(feature_edition) = feature.edition {
53 feature_edition <= edition
60 let mut features = Features::default();
61 let mut edition_enabled_features = FxHashMap::default();
62 let crate_edition = sess.edition();
64 for &edition in ALL_EDITIONS {
65 if edition <= crate_edition {
66 // The `crate_edition` implies its respective umbrella feature-gate
67 // (i.e., `#![feature(rust_20XX_preview)]` isn't needed on edition 20XX).
68 edition_enabled_features.insert(edition.feature_name(), edition);
72 for feature in active_features_up_to(crate_edition) {
73 feature.set(&mut features, DUMMY_SP);
74 edition_enabled_features.insert(feature.name, crate_edition);
77 // Process the edition umbrella feature-gates first, to ensure
78 // `edition_enabled_features` is completed before it's queried.
79 for attr in krate_attrs {
80 if !attr.has_name(sym::feature) {
84 let Some(list) = attr.meta_item_list() else {
93 let name = mi.name_or_empty();
95 let edition = ALL_EDITIONS.iter().find(|e| name == e.feature_name()).copied();
96 if let Some(edition) = edition {
97 if edition <= crate_edition {
101 for feature in active_features_up_to(edition) {
102 // FIXME(Manishearth) there is currently no way to set
103 // lib features by edition
104 feature.set(&mut features, DUMMY_SP);
105 edition_enabled_features.insert(feature.name, edition);
111 for attr in krate_attrs {
112 if !attr.has_name(sym::feature) {
116 let Some(list) = attr.meta_item_list() else {
120 let bad_input = |span| {
121 struct_span_err!(span_handler, span, E0556, "malformed `feature` attribute input")
125 let name = match mi.ident() {
126 Some(ident) if mi.is_word() => ident.name,
131 "expected just one word",
133 Applicability::MaybeIncorrect,
139 bad_input(mi.span()).span_label(mi.span(), "expected just one word").emit();
144 if let Some(edition) = edition_enabled_features.get(&name) {
146 &format!("the feature `{}` is included in the Rust {} edition", name, edition);
147 span_handler.struct_span_warn_with_code(mi.span(), msg, error_code!(E0705)).emit();
151 if ALL_EDITIONS.iter().any(|e| name == e.feature_name()) {
152 // Handled in the separate loop above.
156 let removed = REMOVED_FEATURES.iter().find(|f| name == f.name);
157 let stable_removed = STABLE_REMOVED_FEATURES.iter().find(|f| name == f.name);
158 if let Some(Feature { state, .. }) = removed.or(stable_removed) {
159 if let FeatureState::Removed { reason } | FeatureState::Stabilized { reason } =
162 feature_removed(span_handler, mi.span(), *reason);
167 if let Some(Feature { since, .. }) = ACCEPTED_FEATURES.iter().find(|f| name == f.name) {
168 let since = Some(Symbol::intern(since));
169 features.declared_lang_features.push((name, mi.span(), since));
170 features.active_features.insert(name);
174 if let Some(allowed) = sess.opts.unstable_opts.allow_features.as_ref() {
175 if allowed.iter().all(|f| name.as_str() != f) {
180 "the feature `{}` is not in the list of allowed features",
188 if let Some(f) = ACTIVE_FEATURES.iter().find(|f| name == f.name) {
189 f.set(&mut features, mi.span());
190 features.declared_lang_features.push((name, mi.span(), None));
191 features.active_features.insert(name);
195 features.declared_lib_features.push((name, mi.span()));
196 features.active_features.insert(name);
203 // `cfg_attr`-process the crate's attributes and compute the crate's features.
206 mut krate: ast::Crate,
207 lint_node_id: NodeId,
208 ) -> (ast::Crate, Features) {
209 let mut strip_unconfigured =
210 StripUnconfigured { sess, features: None, config_tokens: false, lint_node_id };
212 let unconfigured_attrs = krate.attrs.clone();
213 let diag = &sess.parse_sess.span_diagnostic;
214 let err_count = diag.err_count();
215 let features = match strip_unconfigured.configure_krate_attrs(krate.attrs) {
217 // The entire crate is unconfigured.
218 krate.attrs = ast::AttrVec::new();
219 krate.items = Vec::new();
224 let features = get_features(sess, diag, &krate.attrs);
225 if err_count == diag.err_count() {
226 // Avoid reconfiguring malformed `cfg_attr`s.
227 strip_unconfigured.features = Some(&features);
228 // Run configuration again, this time with features available
229 // so that we can perform feature-gating.
230 strip_unconfigured.configure_krate_attrs(unconfigured_attrs);
239 macro_rules! configure {
240 ($this:ident, $node:ident) => {
241 match $this.configure($node) {
243 None => return Default::default(),
248 impl<'a> StripUnconfigured<'a> {
249 pub fn configure<T: HasAttrs + HasTokens>(&self, mut node: T) -> Option<T> {
250 self.process_cfg_attrs(&mut node);
251 if self.in_cfg(node.attrs()) {
252 self.try_configure_tokens(&mut node);
259 fn try_configure_tokens<T: HasTokens>(&self, node: &mut T) {
260 if self.config_tokens {
261 if let Some(Some(tokens)) = node.tokens_mut() {
262 let attr_stream = tokens.to_attr_token_stream();
263 *tokens = LazyAttrTokenStream::new(self.configure_tokens(&attr_stream));
268 fn configure_krate_attrs(&self, mut attrs: ast::AttrVec) -> Option<ast::AttrVec> {
269 attrs.flat_map_in_place(|attr| self.process_cfg_attr(attr));
270 if self.in_cfg(&attrs) { Some(attrs) } else { None }
273 /// Performs cfg-expansion on `stream`, producing a new `AttrTokenStream`.
274 /// This is only used during the invocation of `derive` proc-macros,
275 /// which require that we cfg-expand their entire input.
276 /// Normal cfg-expansion operates on parsed AST nodes via the `configure` method
277 fn configure_tokens(&self, stream: &AttrTokenStream) -> AttrTokenStream {
278 fn can_skip(stream: &AttrTokenStream) -> bool {
279 stream.0.iter().all(|tree| match tree {
280 AttrTokenTree::Attributes(_) => false,
281 AttrTokenTree::Token(..) => true,
282 AttrTokenTree::Delimited(_, _, inner) => can_skip(inner),
286 if can_skip(stream) {
287 return stream.clone();
290 let trees: Vec<_> = stream
293 .flat_map(|tree| match tree.clone() {
294 AttrTokenTree::Attributes(mut data) => {
295 data.attrs.flat_map_in_place(|attr| self.process_cfg_attr(attr));
297 if self.in_cfg(&data.attrs) {
298 data.tokens = LazyAttrTokenStream::new(
299 self.configure_tokens(&data.tokens.to_attr_token_stream()),
301 Some(AttrTokenTree::Attributes(data)).into_iter()
306 AttrTokenTree::Delimited(sp, delim, mut inner) => {
307 inner = self.configure_tokens(&inner);
308 Some(AttrTokenTree::Delimited(sp, delim, inner))
311 AttrTokenTree::Token(ref token, _) if let TokenKind::Interpolated(ref nt) = token.kind => {
313 "Nonterminal should have been flattened at {:?}: {:?}",
317 AttrTokenTree::Token(token, spacing) => {
318 Some(AttrTokenTree::Token(token, spacing)).into_iter()
322 AttrTokenStream::new(trees)
325 /// Parse and expand all `cfg_attr` attributes into a list of attributes
326 /// that are within each `cfg_attr` that has a true configuration predicate.
328 /// Gives compiler warnings if any `cfg_attr` does not contain any
329 /// attributes and is in the original source code. Gives compiler errors if
330 /// the syntax of any `cfg_attr` is incorrect.
331 fn process_cfg_attrs<T: HasAttrs>(&self, node: &mut T) {
332 node.visit_attrs(|attrs| {
333 attrs.flat_map_in_place(|attr| self.process_cfg_attr(attr));
337 fn process_cfg_attr(&self, attr: Attribute) -> Vec<Attribute> {
338 if attr.has_name(sym::cfg_attr) { self.expand_cfg_attr(attr, true) } else { vec![attr] }
341 /// Parse and expand a single `cfg_attr` attribute into a list of attributes
342 /// when the configuration predicate is true, or otherwise expand into an
343 /// empty list of attributes.
345 /// Gives a compiler warning when the `cfg_attr` contains no attributes and
346 /// is in the original source file. Gives a compiler error if the syntax of
347 /// the attribute is incorrect.
348 pub(crate) fn expand_cfg_attr(&self, attr: Attribute, recursive: bool) -> Vec<Attribute> {
349 let Some((cfg_predicate, expanded_attrs)) =
350 rustc_parse::parse_cfg_attr(&attr, &self.sess.parse_sess) else {
354 // Lint on zero attributes in source.
355 if expanded_attrs.is_empty() {
356 self.sess.parse_sess.buffer_lint(
357 rustc_lint_defs::builtin::UNUSED_ATTRIBUTES,
360 "`#[cfg_attr]` does not expand to any attributes",
364 if !attr::cfg_matches(
366 &self.sess.parse_sess,
374 // We call `process_cfg_attr` recursively in case there's a
375 // `cfg_attr` inside of another `cfg_attr`. E.g.
376 // `#[cfg_attr(false, cfg_attr(true, some_attr))]`.
379 .flat_map(|item| self.process_cfg_attr(self.expand_cfg_attr_item(&attr, item)))
382 expanded_attrs.into_iter().map(|item| self.expand_cfg_attr_item(&attr, item)).collect()
386 fn expand_cfg_attr_item(
389 (item, item_span): (ast::AttrItem, Span),
391 let orig_tokens = attr.tokens();
393 // We are taking an attribute of the form `#[cfg_attr(pred, attr)]`
394 // and producing an attribute of the form `#[attr]`. We
395 // have captured tokens for `attr` itself, but we need to
396 // synthesize tokens for the wrapper `#` and `[]`, which
399 // Use the `#` in `#[cfg_attr(pred, attr)]` as the `#` token
400 // for `attr` when we expand it to `#[attr]`
401 let mut orig_trees = orig_tokens.into_trees();
402 let TokenTree::Token(pound_token @ Token { kind: TokenKind::Pound, .. }, _) = orig_trees.next().unwrap() else {
403 panic!("Bad tokens for attribute {:?}", attr);
405 let pound_span = pound_token.span;
407 let mut trees = vec![AttrTokenTree::Token(pound_token, Spacing::Alone)];
408 if attr.style == AttrStyle::Inner {
409 // For inner attributes, we do the same thing for the `!` in `#![some_attr]`
410 let TokenTree::Token(bang_token @ Token { kind: TokenKind::Not, .. }, _) = orig_trees.next().unwrap() else {
411 panic!("Bad tokens for attribute {:?}", attr);
413 trees.push(AttrTokenTree::Token(bang_token, Spacing::Alone));
415 // We don't really have a good span to use for the synthesized `[]`
416 // in `#[attr]`, so just use the span of the `#` token.
417 let bracket_group = AttrTokenTree::Delimited(
418 DelimSpan::from_single(pound_span),
422 .unwrap_or_else(|| panic!("Missing tokens for {:?}", item))
423 .to_attr_token_stream(),
425 trees.push(bracket_group);
426 let tokens = Some(LazyAttrTokenStream::new(AttrTokenStream::new(trees)));
427 let attr = attr::mk_attr_from_item(
428 &self.sess.parse_sess.attr_id_generator,
434 if attr.has_name(sym::crate_type) {
435 self.sess.parse_sess.buffer_lint(
436 rustc_lint_defs::builtin::DEPRECATED_CFG_ATTR_CRATE_TYPE_NAME,
439 "`crate_type` within an `#![cfg_attr] attribute is deprecated`",
442 if attr.has_name(sym::crate_name) {
443 self.sess.parse_sess.buffer_lint(
444 rustc_lint_defs::builtin::DEPRECATED_CFG_ATTR_CRATE_TYPE_NAME,
447 "`crate_name` within an `#![cfg_attr] attribute is deprecated`",
453 /// Determines if a node with the given attributes should be included in this configuration.
454 fn in_cfg(&self, attrs: &[Attribute]) -> bool {
455 attrs.iter().all(|attr| !is_cfg(attr) || self.cfg_true(attr))
458 pub(crate) fn cfg_true(&self, attr: &Attribute) -> bool {
459 let meta_item = match validate_attr::parse_meta(&self.sess.parse_sess, attr) {
460 Ok(meta_item) => meta_item,
466 parse_cfg(&meta_item, &self.sess).map_or(true, |meta_item| {
467 attr::cfg_matches(&meta_item, &self.sess.parse_sess, self.lint_node_id, self.features)
471 /// If attributes are not allowed on expressions, emit an error for `attr`
472 pub(crate) fn maybe_emit_expr_attr_err(&self, attr: &Attribute) {
473 if !self.features.map_or(true, |features| features.stmt_expr_attributes) {
474 let mut err = feature_err(
475 &self.sess.parse_sess,
476 sym::stmt_expr_attributes,
478 "attributes on expressions are experimental",
481 if attr.is_doc_comment() {
482 err.help("`///` is for documentation comments. For a plain comment, use `//`.");
489 pub fn configure_expr(&self, expr: &mut P<ast::Expr>) {
490 for attr in expr.attrs.iter() {
491 self.maybe_emit_expr_attr_err(attr);
494 // If an expr is valid to cfg away it will have been removed by the
495 // outer stmt or expression folder before descending in here.
496 // Anything else is always required, and thus has to error out
497 // in case of a cfg attr.
499 // N.B., this is intentionally not part of the visit_expr() function
500 // in order for filter_map_expr() to be able to avoid this check
501 if let Some(attr) = expr.attrs().iter().find(|a| is_cfg(*a)) {
502 let msg = "removing an expression is not supported in this position";
503 self.sess.parse_sess.span_diagnostic.span_err(attr.span, msg);
506 self.process_cfg_attrs(expr);
507 self.try_configure_tokens(&mut *expr);
511 pub fn parse_cfg<'a>(meta_item: &'a MetaItem, sess: &Session) -> Option<&'a MetaItem> {
512 let error = |span, msg, suggestion: &str| {
513 let mut err = sess.parse_sess.span_diagnostic.struct_span_err(span, msg);
514 if !suggestion.is_empty() {
517 "expected syntax is",
519 Applicability::HasPlaceholders,
525 let span = meta_item.span;
526 match meta_item.meta_item_list() {
527 None => error(span, "`cfg` is not followed by parentheses", "cfg(/* predicate */)"),
528 Some([]) => error(span, "`cfg` predicate is not specified", ""),
529 Some([_, .., l]) => error(l.span(), "multiple `cfg` predicates are specified", ""),
530 Some([single]) => match single.meta_item() {
531 Some(meta_item) => Some(meta_item),
532 None => error(single.span(), "`cfg` predicate key cannot be a literal", ""),
537 fn is_cfg(attr: &Attribute) -> bool {
538 attr.has_name(sym::cfg)