1 //! Conditional compilation stripping.
4 use rustc_ast::token::{DelimToken, Token, TokenKind};
5 use rustc_ast::tokenstream::{DelimSpan, LazyTokenStream, Spacing, TokenStream, TokenTree};
6 use rustc_ast::{self as ast, AstLike, AttrItem, Attribute, MetaItem};
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;
17 use rustc_session::Session;
18 use rustc_span::edition::{Edition, ALL_EDITIONS};
19 use rustc_span::symbol::{sym, Symbol};
20 use rustc_span::{Span, DUMMY_SP};
22 /// A folder that strips out items that do not belong in the current configuration.
23 pub struct StripUnconfigured<'a> {
24 pub sess: &'a Session,
25 pub features: Option<&'a Features>,
31 span_handler: &Handler,
32 krate_attrs: &[ast::Attribute],
34 fn feature_removed(span_handler: &Handler, span: Span, reason: Option<&str>) {
35 let mut err = struct_span_err!(span_handler, span, E0557, "feature has been removed");
36 err.span_label(span, "feature has been removed");
37 if let Some(reason) = reason {
43 fn active_features_up_to(edition: Edition) -> impl Iterator<Item = &'static Feature> {
44 ACTIVE_FEATURES.iter().filter(move |feature| {
45 if let Some(feature_edition) = feature.edition {
46 feature_edition <= edition
53 let mut features = Features::default();
54 let mut edition_enabled_features = FxHashMap::default();
55 let crate_edition = sess.edition();
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 !sess.check_name(attr, 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 !sess.check_name(attr, 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) = sess.opts.debugging_opts.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.
196 pub fn features(sess: &Session, mut krate: ast::Crate) -> (ast::Crate, Features) {
197 let mut strip_unconfigured = StripUnconfigured { sess, features: None, modified: false };
199 let unconfigured_attrs = krate.attrs.clone();
200 let diag = &sess.parse_sess.span_diagnostic;
201 let err_count = diag.err_count();
202 let features = match strip_unconfigured.configure_krate_attrs(krate.attrs) {
204 // The entire crate is unconfigured.
205 krate.attrs = Vec::new();
206 krate.items = Vec::new();
211 let features = get_features(sess, diag, &krate.attrs);
212 if err_count == diag.err_count() {
213 // Avoid reconfiguring malformed `cfg_attr`s.
214 strip_unconfigured.features = Some(&features);
215 // Run configuration again, this time with features available
216 // so that we can perform feature-gating.
217 strip_unconfigured.configure_krate_attrs(unconfigured_attrs);
226 macro_rules! configure {
227 ($this:ident, $node:ident) => {
228 match $this.configure($node) {
230 None => return Default::default(),
235 const CFG_ATTR_GRAMMAR_HELP: &str = "#[cfg_attr(condition, attribute, other_attribute, ...)]";
236 const CFG_ATTR_NOTE_REF: &str = "for more information, visit \
237 <https://doc.rust-lang.org/reference/conditional-compilation.html\
238 #the-cfg_attr-attribute>";
240 impl<'a> StripUnconfigured<'a> {
241 pub fn configure<T: AstLike>(&mut self, mut node: T) -> Option<T> {
242 self.process_cfg_attrs(&mut node);
243 if self.in_cfg(node.attrs()) {
246 self.modified = true;
251 fn configure_krate_attrs(
253 mut attrs: Vec<ast::Attribute>,
254 ) -> Option<Vec<ast::Attribute>> {
255 attrs.flat_map_in_place(|attr| self.process_cfg_attr(attr));
256 if self.in_cfg(&attrs) {
259 self.modified = true;
264 /// Parse and expand all `cfg_attr` attributes into a list of attributes
265 /// that are within each `cfg_attr` that has a true configuration predicate.
267 /// Gives compiler warnings if any `cfg_attr` does not contain any
268 /// attributes and is in the original source code. Gives compiler errors if
269 /// the syntax of any `cfg_attr` is incorrect.
270 fn process_cfg_attrs<T: AstLike>(&mut self, node: &mut T) {
271 node.visit_attrs(|attrs| {
272 attrs.flat_map_in_place(|attr| self.process_cfg_attr(attr));
276 /// Parse and expand a single `cfg_attr` attribute into a list of attributes
277 /// when the configuration predicate is true, or otherwise expand into an
278 /// empty list of attributes.
280 /// Gives a compiler warning when the `cfg_attr` contains no attributes and
281 /// is in the original source file. Gives a compiler error if the syntax of
282 /// the attribute is incorrect.
283 fn process_cfg_attr(&mut self, attr: Attribute) -> Vec<Attribute> {
284 if !attr.has_name(sym::cfg_attr) {
288 // A `#[cfg_attr]` either gets removed, or replaced with a new attribute
289 self.modified = true;
291 let (cfg_predicate, expanded_attrs) = match self.parse_cfg_attr(&attr) {
292 None => return vec![],
296 // Lint on zero attributes in source.
297 if expanded_attrs.is_empty() {
301 // At this point we know the attribute is considered used.
302 self.sess.mark_attr_used(&attr);
304 if !attr::cfg_matches(&cfg_predicate, &self.sess.parse_sess, self.features) {
308 // We call `process_cfg_attr` recursively in case there's a
309 // `cfg_attr` inside of another `cfg_attr`. E.g.
310 // `#[cfg_attr(false, cfg_attr(true, some_attr))]`.
313 .flat_map(|(item, span)| {
314 let orig_tokens = attr.tokens();
316 // We are taking an attribute of the form `#[cfg_attr(pred, attr)]`
317 // and producing an attribute of the form `#[attr]`. We
318 // have captured tokens for `attr` itself, but we need to
319 // synthesize tokens for the wrapper `#` and `[]`, which
322 // Use the `#` in `#[cfg_attr(pred, attr)]` as the `#` token
323 // for `attr` when we expand it to `#[attr]`
324 let pound_token = orig_tokens.trees().next().unwrap();
325 if !matches!(pound_token, TokenTree::Token(Token { kind: TokenKind::Pound, .. })) {
326 panic!("Bad tokens for attribute {:?}", attr);
328 // We don't really have a good span to use for the syntheized `[]`
329 // in `#[attr]`, so just use the span of the `#` token.
330 let bracket_group = TokenTree::Delimited(
331 DelimSpan::from_single(pound_token.span()),
335 .unwrap_or_else(|| panic!("Missing tokens for {:?}", item))
336 .create_token_stream(),
338 let tokens = Some(LazyTokenStream::new(TokenStream::new(vec![
339 (pound_token, Spacing::Alone),
340 (bracket_group, Spacing::Alone),
343 self.process_cfg_attr(attr::mk_attr_from_item(item, tokens, attr.style, span))
348 fn parse_cfg_attr(&self, attr: &Attribute) -> Option<(MetaItem, Vec<(AttrItem, Span)>)> {
349 match attr.get_normal_item().args {
350 ast::MacArgs::Delimited(dspan, delim, ref tts) if !tts.is_empty() => {
351 let msg = "wrong `cfg_attr` delimiters";
352 validate_attr::check_meta_bad_delim(&self.sess.parse_sess, dspan, delim, msg);
353 match parse_in(&self.sess.parse_sess, tts.clone(), "`cfg_attr` input", |p| {
356 Ok(r) => return Some(r),
358 e.help(&format!("the valid syntax is `{}`", CFG_ATTR_GRAMMAR_HELP))
359 .note(CFG_ATTR_NOTE_REF)
364 _ => self.error_malformed_cfg_attr_missing(attr.span),
369 fn error_malformed_cfg_attr_missing(&self, span: Span) {
373 .struct_span_err(span, "malformed `cfg_attr` attribute input")
376 "missing condition and attribute",
377 CFG_ATTR_GRAMMAR_HELP.to_string(),
378 Applicability::HasPlaceholders,
380 .note(CFG_ATTR_NOTE_REF)
384 /// Determines if a node with the given attributes should be included in this configuration.
385 fn in_cfg(&self, attrs: &[Attribute]) -> bool {
386 attrs.iter().all(|attr| {
387 if !is_cfg(self.sess, attr) {
390 let meta_item = match validate_attr::parse_meta(&self.sess.parse_sess, attr) {
391 Ok(meta_item) => meta_item,
397 let error = |span, msg, suggestion: &str| {
398 let mut err = self.sess.parse_sess.span_diagnostic.struct_span_err(span, msg);
399 if !suggestion.is_empty() {
402 "expected syntax is",
404 Applicability::MaybeIncorrect,
410 let span = meta_item.span;
411 match meta_item.meta_item_list() {
412 None => error(span, "`cfg` is not followed by parentheses", "cfg(/* predicate */)"),
413 Some([]) => error(span, "`cfg` predicate is not specified", ""),
414 Some([_, .., l]) => error(l.span(), "multiple `cfg` predicates are specified", ""),
415 Some([single]) => match single.meta_item() {
417 attr::cfg_matches(meta_item, &self.sess.parse_sess, self.features)
419 None => error(single.span(), "`cfg` predicate key cannot be a literal", ""),
425 /// If attributes are not allowed on expressions, emit an error for `attr`
426 crate fn maybe_emit_expr_attr_err(&self, attr: &Attribute) {
427 if !self.features.map_or(true, |features| features.stmt_expr_attributes) {
428 let mut err = feature_err(
429 &self.sess.parse_sess,
430 sym::stmt_expr_attributes,
432 "attributes on expressions are experimental",
435 if attr.is_doc_comment() {
436 err.help("`///` is for documentation comments. For a plain comment, use `//`.");
443 pub fn configure_expr(&mut self, expr: &mut P<ast::Expr>) {
444 for attr in expr.attrs.iter() {
445 self.maybe_emit_expr_attr_err(attr);
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(self.sess, a)) {
456 let msg = "removing an expression is not supported in this position";
457 self.sess.parse_sess.span_diagnostic.span_err(attr.span, msg);
460 self.process_cfg_attrs(expr)
464 fn is_cfg(sess: &Session, attr: &Attribute) -> bool {
465 sess.check_name(attr, sym::cfg)