]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_expand/src/config.rs
Tweak move error
[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::{AttrAnnotatedTokenStream, AttrAnnotatedTokenTree};
6 use rustc_ast::tokenstream::{DelimSpan, Spacing};
7 use rustc_ast::tokenstream::{LazyTokenStream, TokenTree};
8 use rustc_ast::NodeId;
9 use rustc_ast::{self as ast, AstLike, AttrStyle, Attribute, 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};
15 use rustc_feature::{
16     ACCEPTED_FEATURES, ACTIVE_FEATURES, REMOVED_FEATURES, STABLE_REMOVED_FEATURES,
17 };
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};
24
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,
34 }
35
36 fn get_features(
37     sess: &Session,
38     span_handler: &Handler,
39     krate_attrs: &[ast::Attribute],
40 ) -> Features {
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 {
45             err.note(reason);
46         }
47         err.emit();
48     }
49
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
54             } else {
55                 false
56             }
57         })
58     }
59
60     let mut features = Features::default();
61     let mut edition_enabled_features = FxHashMap::default();
62     let crate_edition = sess.edition();
63
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);
69         }
70     }
71
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);
75     }
76
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) {
81             continue;
82         }
83
84         let Some(list) = attr.meta_item_list() else {
85             continue;
86         };
87
88         for mi in list {
89             if !mi.is_word() {
90                 continue;
91             }
92
93             let name = mi.name_or_empty();
94
95             let edition = ALL_EDITIONS.iter().find(|e| name == e.feature_name()).copied();
96             if let Some(edition) = edition {
97                 if edition <= crate_edition {
98                     continue;
99                 }
100
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);
106                 }
107             }
108         }
109     }
110
111     for attr in krate_attrs {
112         if !attr.has_name(sym::feature) {
113             continue;
114         }
115
116         let Some(list) = attr.meta_item_list() else {
117             continue;
118         };
119
120         let bad_input = |span| {
121             struct_span_err!(span_handler, span, E0556, "malformed `feature` attribute input")
122         };
123
124         for mi in list {
125             let name = match mi.ident() {
126                 Some(ident) if mi.is_word() => ident.name,
127                 Some(ident) => {
128                     bad_input(mi.span())
129                         .span_suggestion(
130                             mi.span(),
131                             "expected just one word",
132                             format!("{}", ident.name),
133                             Applicability::MaybeIncorrect,
134                         )
135                         .emit();
136                     continue;
137                 }
138                 None => {
139                     bad_input(mi.span()).span_label(mi.span(), "expected just one word").emit();
140                     continue;
141                 }
142             };
143
144             if let Some(edition) = edition_enabled_features.get(&name) {
145                 let msg =
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();
148                 continue;
149             }
150
151             if ALL_EDITIONS.iter().any(|e| name == e.feature_name()) {
152                 // Handled in the separate loop above.
153                 continue;
154             }
155
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 } =
160                     state
161                 {
162                     feature_removed(span_handler, mi.span(), *reason);
163                     continue;
164                 }
165             }
166
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                 continue;
171             }
172
173             if let Some(allowed) = sess.opts.debugging_opts.allow_features.as_ref() {
174                 if allowed.iter().all(|f| name.as_str() != f) {
175                     struct_span_err!(
176                         span_handler,
177                         mi.span(),
178                         E0725,
179                         "the feature `{}` is not in the list of allowed features",
180                         name
181                     )
182                     .emit();
183                     continue;
184                 }
185             }
186
187             if let Some(f) = ACTIVE_FEATURES.iter().find(|f| name == f.name) {
188                 f.set(&mut features, mi.span());
189                 features.declared_lang_features.push((name, mi.span(), None));
190                 continue;
191             }
192
193             features.declared_lib_features.push((name, mi.span()));
194         }
195     }
196
197     features
198 }
199
200 // `cfg_attr`-process the crate's attributes and compute the crate's features.
201 pub fn features(
202     sess: &Session,
203     mut krate: ast::Crate,
204     lint_node_id: NodeId,
205 ) -> (ast::Crate, Features) {
206     let mut strip_unconfigured =
207         StripUnconfigured { sess, features: None, config_tokens: false, lint_node_id };
208
209     let unconfigured_attrs = krate.attrs.clone();
210     let diag = &sess.parse_sess.span_diagnostic;
211     let err_count = diag.err_count();
212     let features = match strip_unconfigured.configure_krate_attrs(krate.attrs) {
213         None => {
214             // The entire crate is unconfigured.
215             krate.attrs = Vec::new();
216             krate.items = Vec::new();
217             Features::default()
218         }
219         Some(attrs) => {
220             krate.attrs = attrs;
221             let features = get_features(sess, diag, &krate.attrs);
222             if err_count == diag.err_count() {
223                 // Avoid reconfiguring malformed `cfg_attr`s.
224                 strip_unconfigured.features = Some(&features);
225                 // Run configuration again, this time with features available
226                 // so that we can perform feature-gating.
227                 strip_unconfigured.configure_krate_attrs(unconfigured_attrs);
228             }
229             features
230         }
231     };
232     (krate, features)
233 }
234
235 #[macro_export]
236 macro_rules! configure {
237     ($this:ident, $node:ident) => {
238         match $this.configure($node) {
239             Some(node) => node,
240             None => return Default::default(),
241         }
242     };
243 }
244
245 impl<'a> StripUnconfigured<'a> {
246     pub fn configure<T: AstLike>(&self, mut node: T) -> Option<T> {
247         self.process_cfg_attrs(&mut node);
248         if self.in_cfg(node.attrs()) {
249             self.try_configure_tokens(&mut node);
250             Some(node)
251         } else {
252             None
253         }
254     }
255
256     fn try_configure_tokens<T: AstLike>(&self, node: &mut T) {
257         if self.config_tokens {
258             if let Some(Some(tokens)) = node.tokens_mut() {
259                 let attr_annotated_tokens = tokens.create_token_stream();
260                 *tokens = LazyTokenStream::new(self.configure_tokens(&attr_annotated_tokens));
261             }
262         }
263     }
264
265     fn configure_krate_attrs(&self, mut attrs: Vec<ast::Attribute>) -> Option<Vec<ast::Attribute>> {
266         attrs.flat_map_in_place(|attr| self.process_cfg_attr(attr));
267         if self.in_cfg(&attrs) { Some(attrs) } else { None }
268     }
269
270     /// Performs cfg-expansion on `stream`, producing a new `AttrAnnotatedTokenStream`.
271     /// This is only used during the invocation of `derive` proc-macros,
272     /// which require that we cfg-expand their entire input.
273     /// Normal cfg-expansion operates on parsed AST nodes via the `configure` method
274     fn configure_tokens(&self, stream: &AttrAnnotatedTokenStream) -> AttrAnnotatedTokenStream {
275         fn can_skip(stream: &AttrAnnotatedTokenStream) -> bool {
276             stream.0.iter().all(|(tree, _spacing)| match tree {
277                 AttrAnnotatedTokenTree::Attributes(_) => false,
278                 AttrAnnotatedTokenTree::Token(_) => true,
279                 AttrAnnotatedTokenTree::Delimited(_, _, inner) => can_skip(inner),
280             })
281         }
282
283         if can_skip(stream) {
284             return stream.clone();
285         }
286
287         let trees: Vec<_> = stream
288             .0
289             .iter()
290             .flat_map(|(tree, spacing)| match tree.clone() {
291                 AttrAnnotatedTokenTree::Attributes(mut data) => {
292                     let mut attrs: Vec<_> = std::mem::take(&mut data.attrs).into();
293                     attrs.flat_map_in_place(|attr| self.process_cfg_attr(attr));
294                     data.attrs = attrs.into();
295
296                     if self.in_cfg(&data.attrs) {
297                         data.tokens = LazyTokenStream::new(
298                             self.configure_tokens(&data.tokens.create_token_stream()),
299                         );
300                         Some((AttrAnnotatedTokenTree::Attributes(data), *spacing)).into_iter()
301                     } else {
302                         None.into_iter()
303                     }
304                 }
305                 AttrAnnotatedTokenTree::Delimited(sp, delim, mut inner) => {
306                     inner = self.configure_tokens(&inner);
307                     Some((AttrAnnotatedTokenTree::Delimited(sp, delim, inner), *spacing))
308                         .into_iter()
309                 }
310                 AttrAnnotatedTokenTree::Token(ref token) if let TokenKind::Interpolated(ref nt) = token.kind => {
311                     panic!(
312                         "Nonterminal should have been flattened at {:?}: {:?}",
313                         token.span, nt
314                     );
315                 }
316                 AttrAnnotatedTokenTree::Token(token) => {
317                     Some((AttrAnnotatedTokenTree::Token(token), *spacing)).into_iter()
318                 }
319             })
320             .collect();
321         AttrAnnotatedTokenStream::new(trees)
322     }
323
324     /// Parse and expand all `cfg_attr` attributes into a list of attributes
325     /// that are within each `cfg_attr` that has a true configuration predicate.
326     ///
327     /// Gives compiler warnings if any `cfg_attr` does not contain any
328     /// attributes and is in the original source code. Gives compiler errors if
329     /// the syntax of any `cfg_attr` is incorrect.
330     fn process_cfg_attrs<T: AstLike>(&self, node: &mut T) {
331         node.visit_attrs(|attrs| {
332             attrs.flat_map_in_place(|attr| self.process_cfg_attr(attr));
333         });
334     }
335
336     fn process_cfg_attr(&self, attr: Attribute) -> Vec<Attribute> {
337         if attr.has_name(sym::cfg_attr) { self.expand_cfg_attr(attr, true) } else { vec![attr] }
338     }
339
340     /// Parse and expand a single `cfg_attr` attribute into a list of attributes
341     /// when the configuration predicate is true, or otherwise expand into an
342     /// empty list of attributes.
343     ///
344     /// Gives a compiler warning when the `cfg_attr` contains no attributes and
345     /// is in the original source file. Gives a compiler error if the syntax of
346     /// the attribute is incorrect.
347     crate fn expand_cfg_attr(&self, attr: Attribute, recursive: bool) -> Vec<Attribute> {
348         let Some((cfg_predicate, expanded_attrs)) =
349             rustc_parse::parse_cfg_attr(&attr, &self.sess.parse_sess) else {
350                 return vec![];
351             };
352
353         // Lint on zero attributes in source.
354         if expanded_attrs.is_empty() {
355             self.sess.parse_sess.buffer_lint(
356                 rustc_lint_defs::builtin::UNUSED_ATTRIBUTES,
357                 attr.span,
358                 ast::CRATE_NODE_ID,
359                 "`#[cfg_attr]` does not expand to any attributes",
360             );
361         }
362
363         if !attr::cfg_matches(
364             &cfg_predicate,
365             &self.sess.parse_sess,
366             self.lint_node_id,
367             self.features,
368         ) {
369             return vec![];
370         }
371
372         if recursive {
373             // We call `process_cfg_attr` recursively in case there's a
374             // `cfg_attr` inside of another `cfg_attr`. E.g.
375             //  `#[cfg_attr(false, cfg_attr(true, some_attr))]`.
376             expanded_attrs
377                 .into_iter()
378                 .flat_map(|item| self.process_cfg_attr(self.expand_cfg_attr_item(&attr, item)))
379                 .collect()
380         } else {
381             expanded_attrs.into_iter().map(|item| self.expand_cfg_attr_item(&attr, item)).collect()
382         }
383     }
384
385     fn expand_cfg_attr_item(
386         &self,
387         attr: &Attribute,
388         (item, item_span): (ast::AttrItem, Span),
389     ) -> Attribute {
390         let orig_tokens = attr.tokens().to_tokenstream();
391
392         // We are taking an attribute of the form `#[cfg_attr(pred, attr)]`
393         // and producing an attribute of the form `#[attr]`. We
394         // have captured tokens for `attr` itself, but we need to
395         // synthesize tokens for the wrapper `#` and `[]`, which
396         // we do below.
397
398         // Use the `#` in `#[cfg_attr(pred, attr)]` as the `#` token
399         // for `attr` when we expand it to `#[attr]`
400         let mut orig_trees = orig_tokens.trees();
401         let TokenTree::Token(pound_token @ Token { kind: TokenKind::Pound, .. }) = orig_trees.next().unwrap() else {
402             panic!("Bad tokens for attribute {:?}", attr);
403         };
404         let pound_span = pound_token.span;
405
406         let mut trees = vec![(AttrAnnotatedTokenTree::Token(pound_token), Spacing::Alone)];
407         if attr.style == AttrStyle::Inner {
408             // For inner attributes, we do the same thing for the `!` in `#![some_attr]`
409             let TokenTree::Token(bang_token @ Token { kind: TokenKind::Not, .. }) = orig_trees.next().unwrap() else {
410                 panic!("Bad tokens for attribute {:?}", attr);
411             };
412             trees.push((AttrAnnotatedTokenTree::Token(bang_token), Spacing::Alone));
413         }
414         // We don't really have a good span to use for the syntheized `[]`
415         // in `#[attr]`, so just use the span of the `#` token.
416         let bracket_group = AttrAnnotatedTokenTree::Delimited(
417             DelimSpan::from_single(pound_span),
418             DelimToken::Bracket,
419             item.tokens
420                 .as_ref()
421                 .unwrap_or_else(|| panic!("Missing tokens for {:?}", item))
422                 .create_token_stream(),
423         );
424         trees.push((bracket_group, Spacing::Alone));
425         let tokens = Some(LazyTokenStream::new(AttrAnnotatedTokenStream::new(trees)));
426         let attr = attr::mk_attr_from_item(item, tokens, attr.style, item_span);
427         if attr.has_name(sym::crate_type) {
428             self.sess.parse_sess.buffer_lint(
429                 rustc_lint_defs::builtin::DEPRECATED_CFG_ATTR_CRATE_TYPE_NAME,
430                 attr.span,
431                 ast::CRATE_NODE_ID,
432                 "`crate_type` within an `#![cfg_attr] attribute is deprecated`",
433             );
434         }
435         if attr.has_name(sym::crate_name) {
436             self.sess.parse_sess.buffer_lint(
437                 rustc_lint_defs::builtin::DEPRECATED_CFG_ATTR_CRATE_TYPE_NAME,
438                 attr.span,
439                 ast::CRATE_NODE_ID,
440                 "`crate_name` within an `#![cfg_attr] attribute is deprecated`",
441             );
442         }
443         attr
444     }
445
446     /// Determines if a node with the given attributes should be included in this configuration.
447     fn in_cfg(&self, attrs: &[Attribute]) -> bool {
448         attrs.iter().all(|attr| !is_cfg(attr) || self.cfg_true(attr))
449     }
450
451     crate fn cfg_true(&self, attr: &Attribute) -> bool {
452         let meta_item = match validate_attr::parse_meta(&self.sess.parse_sess, attr) {
453             Ok(meta_item) => meta_item,
454             Err(mut err) => {
455                 err.emit();
456                 return true;
457             }
458         };
459         parse_cfg(&meta_item, &self.sess).map_or(true, |meta_item| {
460             attr::cfg_matches(&meta_item, &self.sess.parse_sess, self.lint_node_id, self.features)
461         })
462     }
463
464     /// If attributes are not allowed on expressions, emit an error for `attr`
465     crate fn maybe_emit_expr_attr_err(&self, attr: &Attribute) {
466         if !self.features.map_or(true, |features| features.stmt_expr_attributes) {
467             let mut err = feature_err(
468                 &self.sess.parse_sess,
469                 sym::stmt_expr_attributes,
470                 attr.span,
471                 "attributes on expressions are experimental",
472             );
473
474             if attr.is_doc_comment() {
475                 err.help("`///` is for documentation comments. For a plain comment, use `//`.");
476             }
477
478             err.emit();
479         }
480     }
481
482     pub fn configure_expr(&self, expr: &mut P<ast::Expr>) {
483         for attr in expr.attrs.iter() {
484             self.maybe_emit_expr_attr_err(attr);
485         }
486
487         // If an expr is valid to cfg away it will have been removed by the
488         // outer stmt or expression folder before descending in here.
489         // Anything else is always required, and thus has to error out
490         // in case of a cfg attr.
491         //
492         // N.B., this is intentionally not part of the visit_expr() function
493         //     in order for filter_map_expr() to be able to avoid this check
494         if let Some(attr) = expr.attrs().iter().find(|a| is_cfg(*a)) {
495             let msg = "removing an expression is not supported in this position";
496             self.sess.parse_sess.span_diagnostic.span_err(attr.span, msg);
497         }
498
499         self.process_cfg_attrs(expr);
500         self.try_configure_tokens(&mut *expr);
501     }
502 }
503
504 pub fn parse_cfg<'a>(meta_item: &'a MetaItem, sess: &Session) -> Option<&'a MetaItem> {
505     let error = |span, msg, suggestion: &str| {
506         let mut err = sess.parse_sess.span_diagnostic.struct_span_err(span, msg);
507         if !suggestion.is_empty() {
508             err.span_suggestion(
509                 span,
510                 "expected syntax is",
511                 suggestion.into(),
512                 Applicability::HasPlaceholders,
513             );
514         }
515         err.emit();
516         None
517     };
518     let span = meta_item.span;
519     match meta_item.meta_item_list() {
520         None => error(span, "`cfg` is not followed by parentheses", "cfg(/* predicate */)"),
521         Some([]) => error(span, "`cfg` predicate is not specified", ""),
522         Some([_, .., l]) => error(l.span(), "multiple `cfg` predicates are specified", ""),
523         Some([single]) => match single.meta_item() {
524             Some(meta_item) => Some(meta_item),
525             None => error(single.span(), "`cfg` predicate key cannot be a literal", ""),
526         },
527     }
528 }
529
530 fn is_cfg(attr: &Attribute) -> bool {
531     attr.has_name(sym::cfg)
532 }