]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_expand/src/config.rs
Rollup merge of #83277 - spastorino:early_otherwise-opt-unsound, r=oli-obk
[rust.git] / compiler / rustc_expand / src / config.rs
1 //! Conditional compilation stripping.
2
3 use rustc_ast::ptr::P;
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};
12 use rustc_feature::{
13     ACCEPTED_FEATURES, ACTIVE_FEATURES, REMOVED_FEATURES, STABLE_REMOVED_FEATURES,
14 };
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};
21
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>,
26     pub modified: bool,
27 }
28
29 fn get_features(
30     sess: &Session,
31     span_handler: &Handler,
32     krate_attrs: &[ast::Attribute],
33 ) -> Features {
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 {
38             err.note(reason);
39         }
40         err.emit();
41     }
42
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
47             } else {
48                 false
49             }
50         })
51     }
52
53     let mut features = Features::default();
54     let mut edition_enabled_features = FxHashMap::default();
55     let crate_edition = sess.edition();
56
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);
62         }
63     }
64
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);
68     }
69
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) {
74             continue;
75         }
76
77         let list = match attr.meta_item_list() {
78             Some(list) => list,
79             None => continue,
80         };
81
82         for mi in list {
83             if !mi.is_word() {
84                 continue;
85             }
86
87             let name = mi.name_or_empty();
88
89             let edition = ALL_EDITIONS.iter().find(|e| name == e.feature_name()).copied();
90             if let Some(edition) = edition {
91                 if edition <= crate_edition {
92                     continue;
93                 }
94
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);
100                 }
101             }
102         }
103     }
104
105     for attr in krate_attrs {
106         if !sess.check_name(attr, sym::feature) {
107             continue;
108         }
109
110         let list = match attr.meta_item_list() {
111             Some(list) => list,
112             None => continue,
113         };
114
115         let bad_input = |span| {
116             struct_span_err!(span_handler, span, E0556, "malformed `feature` attribute input")
117         };
118
119         for mi in list {
120             let name = match mi.ident() {
121                 Some(ident) if mi.is_word() => ident.name,
122                 Some(ident) => {
123                     bad_input(mi.span())
124                         .span_suggestion(
125                             mi.span(),
126                             "expected just one word",
127                             format!("{}", ident.name),
128                             Applicability::MaybeIncorrect,
129                         )
130                         .emit();
131                     continue;
132                 }
133                 None => {
134                     bad_input(mi.span()).span_label(mi.span(), "expected just one word").emit();
135                     continue;
136                 }
137             };
138
139             if let Some(edition) = edition_enabled_features.get(&name) {
140                 let msg =
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();
143                 continue;
144             }
145
146             if ALL_EDITIONS.iter().any(|e| name == e.feature_name()) {
147                 // Handled in the separate loop above.
148                 continue;
149             }
150
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 } =
155                     state
156                 {
157                     feature_removed(span_handler, mi.span(), *reason);
158                     continue;
159                 }
160             }
161
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));
165                 continue;
166             }
167
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() {
170                     struct_span_err!(
171                         span_handler,
172                         mi.span(),
173                         E0725,
174                         "the feature `{}` is not in the list of allowed features",
175                         name
176                     )
177                     .emit();
178                     continue;
179                 }
180             }
181
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));
185                 continue;
186             }
187
188             features.declared_lib_features.push((name, mi.span()));
189         }
190     }
191
192     features
193 }
194
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 };
198
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) {
203         None => {
204             // The entire crate is unconfigured.
205             krate.attrs = Vec::new();
206             krate.items = Vec::new();
207             Features::default()
208         }
209         Some(attrs) => {
210             krate.attrs = attrs;
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);
218             }
219             features
220         }
221     };
222     (krate, features)
223 }
224
225 #[macro_export]
226 macro_rules! configure {
227     ($this:ident, $node:ident) => {
228         match $this.configure($node) {
229             Some(node) => node,
230             None => return Default::default(),
231         }
232     };
233 }
234
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>";
239
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()) {
244             Some(node)
245         } else {
246             self.modified = true;
247             None
248         }
249     }
250
251     fn configure_krate_attrs(
252         &mut self,
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) {
257             Some(attrs)
258         } else {
259             self.modified = true;
260             None
261         }
262     }
263
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.
266     ///
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));
273         });
274     }
275
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.
279     ///
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) {
285             return vec![attr];
286         }
287
288         // A `#[cfg_attr]` either gets removed, or replaced with a new attribute
289         self.modified = true;
290
291         let (cfg_predicate, expanded_attrs) = match self.parse_cfg_attr(&attr) {
292             None => return vec![],
293             Some(r) => r,
294         };
295
296         // Lint on zero attributes in source.
297         if expanded_attrs.is_empty() {
298             return vec![attr];
299         }
300
301         // At this point we know the attribute is considered used.
302         self.sess.mark_attr_used(&attr);
303
304         if !attr::cfg_matches(&cfg_predicate, &self.sess.parse_sess, self.features) {
305             return vec![];
306         }
307
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))]`.
311         expanded_attrs
312             .into_iter()
313             .flat_map(|(item, span)| {
314                 let orig_tokens = attr.tokens();
315
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
320                 // we do below.
321
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);
327                 }
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()),
332                     DelimToken::Bracket,
333                     item.tokens
334                         .as_ref()
335                         .unwrap_or_else(|| panic!("Missing tokens for {:?}", item))
336                         .create_token_stream(),
337                 );
338                 let tokens = Some(LazyTokenStream::new(TokenStream::new(vec![
339                     (pound_token, Spacing::Alone),
340                     (bracket_group, Spacing::Alone),
341                 ])));
342
343                 self.process_cfg_attr(attr::mk_attr_from_item(item, tokens, attr.style, span))
344             })
345             .collect()
346     }
347
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| {
354                     p.parse_cfg_attr()
355                 }) {
356                     Ok(r) => return Some(r),
357                     Err(mut e) => {
358                         e.help(&format!("the valid syntax is `{}`", CFG_ATTR_GRAMMAR_HELP))
359                             .note(CFG_ATTR_NOTE_REF)
360                             .emit();
361                     }
362                 }
363             }
364             _ => self.error_malformed_cfg_attr_missing(attr.span),
365         }
366         None
367     }
368
369     fn error_malformed_cfg_attr_missing(&self, span: Span) {
370         self.sess
371             .parse_sess
372             .span_diagnostic
373             .struct_span_err(span, "malformed `cfg_attr` attribute input")
374             .span_suggestion(
375                 span,
376                 "missing condition and attribute",
377                 CFG_ATTR_GRAMMAR_HELP.to_string(),
378                 Applicability::HasPlaceholders,
379             )
380             .note(CFG_ATTR_NOTE_REF)
381             .emit();
382     }
383
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) {
388                 return true;
389             }
390             let meta_item = match validate_attr::parse_meta(&self.sess.parse_sess, attr) {
391                 Ok(meta_item) => meta_item,
392                 Err(mut err) => {
393                     err.emit();
394                     return true;
395                 }
396             };
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() {
400                     err.span_suggestion(
401                         span,
402                         "expected syntax is",
403                         suggestion.into(),
404                         Applicability::MaybeIncorrect,
405                     );
406                 }
407                 err.emit();
408                 true
409             };
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() {
416                     Some(meta_item) => {
417                         attr::cfg_matches(meta_item, &self.sess.parse_sess, self.features)
418                     }
419                     None => error(single.span(), "`cfg` predicate key cannot be a literal", ""),
420                 },
421             }
422         })
423     }
424
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,
431                 attr.span,
432                 "attributes on expressions are experimental",
433             );
434
435             if attr.is_doc_comment() {
436                 err.help("`///` is for documentation comments. For a plain comment, use `//`.");
437             }
438
439             err.emit();
440         }
441     }
442
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);
446         }
447
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.
452         //
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);
458         }
459
460         self.process_cfg_attrs(expr)
461     }
462 }
463
464 fn is_cfg(sess: &Session, attr: &Attribute) -> bool {
465     sess.check_name(attr, sym::cfg)
466 }