]> git.proxmox.com Git - rustc.git/blob - vendor/rustc-ap-rustc_expand/src/config.rs
New upstream version 1.49.0+dfsg1
[rustc.git] / vendor / rustc-ap-rustc_expand / src / config.rs
1 //! Conditional compilation stripping.
2
3 use rustc_ast::attr::HasAttrs;
4 use rustc_ast::mut_visit::*;
5 use rustc_ast::ptr::P;
6 use rustc_ast::token::{DelimToken, Token, TokenKind};
7 use rustc_ast::tokenstream::{DelimSpan, LazyTokenStreamInner, Spacing, TokenStream, TokenTree};
8 use rustc_ast::{self as ast, AttrItem, Attribute, MetaItem};
9 use rustc_attr as attr;
10 use rustc_data_structures::fx::FxHashMap;
11 use rustc_data_structures::map_in_place::MapInPlace;
12 use rustc_data_structures::sync::Lrc;
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::{parse_in, 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 use smallvec::SmallVec;
26
27 /// A folder that strips out items that do not belong in the current configuration.
28 pub struct StripUnconfigured<'a> {
29 pub sess: &'a Session,
30 pub features: Option<&'a Features>,
31 }
32
33 fn get_features(
34 sess: &Session,
35 span_handler: &Handler,
36 krate_attrs: &[ast::Attribute],
37 ) -> Features {
38 fn feature_removed(span_handler: &Handler, span: Span, reason: Option<&str>) {
39 let mut err = struct_span_err!(span_handler, span, E0557, "feature has been removed");
40 err.span_label(span, "feature has been removed");
41 if let Some(reason) = reason {
42 err.note(reason);
43 }
44 err.emit();
45 }
46
47 fn active_features_up_to(edition: Edition) -> impl Iterator<Item = &'static Feature> {
48 ACTIVE_FEATURES.iter().filter(move |feature| {
49 if let Some(feature_edition) = feature.edition {
50 feature_edition <= edition
51 } else {
52 false
53 }
54 })
55 }
56
57 let mut features = Features::default();
58 let mut edition_enabled_features = FxHashMap::default();
59 let crate_edition = sess.edition();
60
61 for &edition in ALL_EDITIONS {
62 if edition <= crate_edition {
63 // The `crate_edition` implies its respective umbrella feature-gate
64 // (i.e., `#![feature(rust_20XX_preview)]` isn't needed on edition 20XX).
65 edition_enabled_features.insert(edition.feature_name(), edition);
66 }
67 }
68
69 for feature in active_features_up_to(crate_edition) {
70 feature.set(&mut features, DUMMY_SP);
71 edition_enabled_features.insert(feature.name, crate_edition);
72 }
73
74 // Process the edition umbrella feature-gates first, to ensure
75 // `edition_enabled_features` is completed before it's queried.
76 for attr in krate_attrs {
77 if !sess.check_name(attr, sym::feature) {
78 continue;
79 }
80
81 let list = match attr.meta_item_list() {
82 Some(list) => list,
83 None => continue,
84 };
85
86 for mi in list {
87 if !mi.is_word() {
88 continue;
89 }
90
91 let name = mi.name_or_empty();
92
93 let edition = ALL_EDITIONS.iter().find(|e| name == e.feature_name()).copied();
94 if let Some(edition) = edition {
95 if edition <= crate_edition {
96 continue;
97 }
98
99 for feature in active_features_up_to(edition) {
100 // FIXME(Manishearth) there is currently no way to set
101 // lib features by edition
102 feature.set(&mut features, DUMMY_SP);
103 edition_enabled_features.insert(feature.name, edition);
104 }
105 }
106 }
107 }
108
109 for attr in krate_attrs {
110 if !sess.check_name(attr, sym::feature) {
111 continue;
112 }
113
114 let list = match attr.meta_item_list() {
115 Some(list) => list,
116 None => continue,
117 };
118
119 let bad_input = |span| {
120 struct_span_err!(span_handler, span, E0556, "malformed `feature` attribute input")
121 };
122
123 for mi in list {
124 let name = match mi.ident() {
125 Some(ident) if mi.is_word() => ident.name,
126 Some(ident) => {
127 bad_input(mi.span())
128 .span_suggestion(
129 mi.span(),
130 "expected just one word",
131 format!("{}", ident.name),
132 Applicability::MaybeIncorrect,
133 )
134 .emit();
135 continue;
136 }
137 None => {
138 bad_input(mi.span()).span_label(mi.span(), "expected just one word").emit();
139 continue;
140 }
141 };
142
143 if let Some(edition) = edition_enabled_features.get(&name) {
144 let msg =
145 &format!("the feature `{}` is included in the Rust {} edition", name, edition);
146 span_handler.struct_span_warn_with_code(mi.span(), msg, error_code!(E0705)).emit();
147 continue;
148 }
149
150 if ALL_EDITIONS.iter().any(|e| name == e.feature_name()) {
151 // Handled in the separate loop above.
152 continue;
153 }
154
155 let removed = REMOVED_FEATURES.iter().find(|f| name == f.name);
156 let stable_removed = STABLE_REMOVED_FEATURES.iter().find(|f| name == f.name);
157 if let Some(Feature { state, .. }) = removed.or(stable_removed) {
158 if let FeatureState::Removed { reason } | FeatureState::Stabilized { reason } =
159 state
160 {
161 feature_removed(span_handler, mi.span(), *reason);
162 continue;
163 }
164 }
165
166 if let Some(Feature { since, .. }) = ACCEPTED_FEATURES.iter().find(|f| name == f.name) {
167 let since = Some(Symbol::intern(since));
168 features.declared_lang_features.push((name, mi.span(), since));
169 continue;
170 }
171
172 if let Some(allowed) = sess.opts.debugging_opts.allow_features.as_ref() {
173 if allowed.iter().find(|&f| name.as_str() == *f).is_none() {
174 struct_span_err!(
175 span_handler,
176 mi.span(),
177 E0725,
178 "the feature `{}` is not in the list of allowed features",
179 name
180 )
181 .emit();
182 continue;
183 }
184 }
185
186 if let Some(f) = ACTIVE_FEATURES.iter().find(|f| name == f.name) {
187 f.set(&mut features, mi.span());
188 features.declared_lang_features.push((name, mi.span(), None));
189 continue;
190 }
191
192 features.declared_lib_features.push((name, mi.span()));
193 }
194 }
195
196 features
197 }
198
199 // `cfg_attr`-process the crate's attributes and compute the crate's features.
200 pub fn features(sess: &Session, mut krate: ast::Crate) -> (ast::Crate, Features) {
201 let mut strip_unconfigured = StripUnconfigured { sess, features: None };
202
203 let unconfigured_attrs = krate.attrs.clone();
204 let diag = &sess.parse_sess.span_diagnostic;
205 let err_count = diag.err_count();
206 let features = match strip_unconfigured.configure(krate.attrs) {
207 None => {
208 // The entire crate is unconfigured.
209 krate.attrs = Vec::new();
210 krate.module.items = Vec::new();
211 Features::default()
212 }
213 Some(attrs) => {
214 krate.attrs = attrs;
215 let features = get_features(sess, diag, &krate.attrs);
216 if err_count == diag.err_count() {
217 // Avoid reconfiguring malformed `cfg_attr`s.
218 strip_unconfigured.features = Some(&features);
219 strip_unconfigured.configure(unconfigured_attrs);
220 }
221 features
222 }
223 };
224 (krate, features)
225 }
226
227 #[macro_export]
228 macro_rules! configure {
229 ($this:ident, $node:ident) => {
230 match $this.configure($node) {
231 Some(node) => node,
232 None => return Default::default(),
233 }
234 };
235 }
236
237 const CFG_ATTR_GRAMMAR_HELP: &str = "#[cfg_attr(condition, attribute, other_attribute, ...)]";
238 const CFG_ATTR_NOTE_REF: &str = "for more information, visit \
239 <https://doc.rust-lang.org/reference/conditional-compilation.html\
240 #the-cfg_attr-attribute>";
241
242 impl<'a> StripUnconfigured<'a> {
243 pub fn configure<T: HasAttrs>(&mut self, mut node: T) -> Option<T> {
244 self.process_cfg_attrs(&mut node);
245 self.in_cfg(node.attrs()).then_some(node)
246 }
247
248 /// Parse and expand all `cfg_attr` attributes into a list of attributes
249 /// that are within each `cfg_attr` that has a true configuration predicate.
250 ///
251 /// Gives compiler warnings if any `cfg_attr` does not contain any
252 /// attributes and is in the original source code. Gives compiler errors if
253 /// the syntax of any `cfg_attr` is incorrect.
254 pub fn process_cfg_attrs<T: HasAttrs>(&mut self, node: &mut T) {
255 node.visit_attrs(|attrs| {
256 attrs.flat_map_in_place(|attr| self.process_cfg_attr(attr));
257 });
258 }
259
260 /// Parse and expand a single `cfg_attr` attribute into a list of attributes
261 /// when the configuration predicate is true, or otherwise expand into an
262 /// empty list of attributes.
263 ///
264 /// Gives a compiler warning when the `cfg_attr` contains no attributes and
265 /// is in the original source file. Gives a compiler error if the syntax of
266 /// the attribute is incorrect.
267 fn process_cfg_attr(&mut self, attr: Attribute) -> Vec<Attribute> {
268 if !attr.has_name(sym::cfg_attr) {
269 return vec![attr];
270 }
271
272 let (cfg_predicate, expanded_attrs) = match self.parse_cfg_attr(&attr) {
273 None => return vec![],
274 Some(r) => r,
275 };
276
277 // Lint on zero attributes in source.
278 if expanded_attrs.is_empty() {
279 return vec![attr];
280 }
281
282 // At this point we know the attribute is considered used.
283 self.sess.mark_attr_used(&attr);
284
285 if !attr::cfg_matches(&cfg_predicate, &self.sess.parse_sess, self.features) {
286 return vec![];
287 }
288
289 // We call `process_cfg_attr` recursively in case there's a
290 // `cfg_attr` inside of another `cfg_attr`. E.g.
291 // `#[cfg_attr(false, cfg_attr(true, some_attr))]`.
292 expanded_attrs
293 .into_iter()
294 .flat_map(|(item, span)| {
295 let orig_tokens =
296 attr.tokens.as_ref().unwrap_or_else(|| panic!("Missing tokens for {:?}", attr));
297
298 // We are taking an attribute of the form `#[cfg_attr(pred, attr)]`
299 // and producing an attribute of the form `#[attr]`. We
300 // have captured tokens for `attr` itself, but we need to
301 // synthesize tokens for the wrapper `#` and `[]`, which
302 // we do below.
303
304 // Use the `#` in `#[cfg_attr(pred, attr)]` as the `#` token
305 // for `attr` when we expand it to `#[attr]`
306 let pound_token = orig_tokens.into_token_stream().trees().next().unwrap();
307 if !matches!(pound_token, TokenTree::Token(Token { kind: TokenKind::Pound, .. })) {
308 panic!("Bad tokens for attribute {:?}", attr);
309 }
310 // We don't really have a good span to use for the syntheized `[]`
311 // in `#[attr]`, so just use the span of the `#` token.
312 let bracket_group = TokenTree::Delimited(
313 DelimSpan::from_single(pound_token.span()),
314 DelimToken::Bracket,
315 item.tokens
316 .clone()
317 .unwrap_or_else(|| panic!("Missing tokens for {:?}", item))
318 .into_token_stream(),
319 );
320
321 let mut attr = attr::mk_attr_from_item(attr.style, item, span);
322 attr.tokens = Some(Lrc::new(LazyTokenStreamInner::Ready(TokenStream::new(vec![
323 (pound_token, Spacing::Alone),
324 (bracket_group, Spacing::Alone),
325 ]))));
326 self.process_cfg_attr(attr)
327 })
328 .collect()
329 }
330
331 fn parse_cfg_attr(&self, attr: &Attribute) -> Option<(MetaItem, Vec<(AttrItem, Span)>)> {
332 match attr.get_normal_item().args {
333 ast::MacArgs::Delimited(dspan, delim, ref tts) if !tts.is_empty() => {
334 let msg = "wrong `cfg_attr` delimiters";
335 validate_attr::check_meta_bad_delim(&self.sess.parse_sess, dspan, delim, msg);
336 match parse_in(&self.sess.parse_sess, tts.clone(), "`cfg_attr` input", |p| {
337 p.parse_cfg_attr()
338 }) {
339 Ok(r) => return Some(r),
340 Err(mut e) => {
341 e.help(&format!("the valid syntax is `{}`", CFG_ATTR_GRAMMAR_HELP))
342 .note(CFG_ATTR_NOTE_REF)
343 .emit();
344 }
345 }
346 }
347 _ => self.error_malformed_cfg_attr_missing(attr.span),
348 }
349 None
350 }
351
352 fn error_malformed_cfg_attr_missing(&self, span: Span) {
353 self.sess
354 .parse_sess
355 .span_diagnostic
356 .struct_span_err(span, "malformed `cfg_attr` attribute input")
357 .span_suggestion(
358 span,
359 "missing condition and attribute",
360 CFG_ATTR_GRAMMAR_HELP.to_string(),
361 Applicability::HasPlaceholders,
362 )
363 .note(CFG_ATTR_NOTE_REF)
364 .emit();
365 }
366
367 /// Determines if a node with the given attributes should be included in this configuration.
368 pub fn in_cfg(&self, attrs: &[Attribute]) -> bool {
369 attrs.iter().all(|attr| {
370 if !is_cfg(self.sess, attr) {
371 return true;
372 }
373 let meta_item = match validate_attr::parse_meta(&self.sess.parse_sess, attr) {
374 Ok(meta_item) => meta_item,
375 Err(mut err) => {
376 err.emit();
377 return true;
378 }
379 };
380 let error = |span, msg, suggestion: &str| {
381 let mut err = self.sess.parse_sess.span_diagnostic.struct_span_err(span, msg);
382 if !suggestion.is_empty() {
383 err.span_suggestion(
384 span,
385 "expected syntax is",
386 suggestion.into(),
387 Applicability::MaybeIncorrect,
388 );
389 }
390 err.emit();
391 true
392 };
393 let span = meta_item.span;
394 match meta_item.meta_item_list() {
395 None => error(span, "`cfg` is not followed by parentheses", "cfg(/* predicate */)"),
396 Some([]) => error(span, "`cfg` predicate is not specified", ""),
397 Some([_, .., l]) => error(l.span(), "multiple `cfg` predicates are specified", ""),
398 Some([single]) => match single.meta_item() {
399 Some(meta_item) => {
400 attr::cfg_matches(meta_item, &self.sess.parse_sess, self.features)
401 }
402 None => error(single.span(), "`cfg` predicate key cannot be a literal", ""),
403 },
404 }
405 })
406 }
407
408 /// Visit attributes on expression and statements (but not attributes on items in blocks).
409 fn visit_expr_attrs(&mut self, attrs: &[Attribute]) {
410 // flag the offending attributes
411 for attr in attrs.iter() {
412 self.maybe_emit_expr_attr_err(attr);
413 }
414 }
415
416 /// If attributes are not allowed on expressions, emit an error for `attr`
417 pub fn maybe_emit_expr_attr_err(&self, attr: &Attribute) {
418 if !self.features.map(|features| features.stmt_expr_attributes).unwrap_or(true) {
419 let mut err = feature_err(
420 &self.sess.parse_sess,
421 sym::stmt_expr_attributes,
422 attr.span,
423 "attributes on expressions are experimental",
424 );
425
426 if attr.is_doc_comment() {
427 err.help("`///` is for documentation comments. For a plain comment, use `//`.");
428 }
429
430 err.emit();
431 }
432 }
433
434 pub fn configure_foreign_mod(&mut self, foreign_mod: &mut ast::ForeignMod) {
435 let ast::ForeignMod { unsafety: _, abi: _, items } = foreign_mod;
436 items.flat_map_in_place(|item| self.configure(item));
437 }
438
439 fn configure_variant_data(&mut self, vdata: &mut ast::VariantData) {
440 match vdata {
441 ast::VariantData::Struct(fields, ..) | ast::VariantData::Tuple(fields, _) => {
442 fields.flat_map_in_place(|field| self.configure(field))
443 }
444 ast::VariantData::Unit(_) => {}
445 }
446 }
447
448 pub fn configure_item_kind(&mut self, item: &mut ast::ItemKind) {
449 match item {
450 ast::ItemKind::Struct(def, _generics) | ast::ItemKind::Union(def, _generics) => {
451 self.configure_variant_data(def)
452 }
453 ast::ItemKind::Enum(ast::EnumDef { variants }, _generics) => {
454 variants.flat_map_in_place(|variant| self.configure(variant));
455 for variant in variants {
456 self.configure_variant_data(&mut variant.data);
457 }
458 }
459 _ => {}
460 }
461 }
462
463 pub fn configure_expr_kind(&mut self, expr_kind: &mut ast::ExprKind) {
464 match expr_kind {
465 ast::ExprKind::Match(_m, arms) => {
466 arms.flat_map_in_place(|arm| self.configure(arm));
467 }
468 ast::ExprKind::Struct(_path, fields, _base) => {
469 fields.flat_map_in_place(|field| self.configure(field));
470 }
471 _ => {}
472 }
473 }
474
475 pub fn configure_expr(&mut self, expr: &mut P<ast::Expr>) {
476 self.visit_expr_attrs(expr.attrs());
477
478 // If an expr is valid to cfg away it will have been removed by the
479 // outer stmt or expression folder before descending in here.
480 // Anything else is always required, and thus has to error out
481 // in case of a cfg attr.
482 //
483 // N.B., this is intentionally not part of the visit_expr() function
484 // in order for filter_map_expr() to be able to avoid this check
485 if let Some(attr) = expr.attrs().iter().find(|a| is_cfg(self.sess, a)) {
486 let msg = "removing an expression is not supported in this position";
487 self.sess.parse_sess.span_diagnostic.span_err(attr.span, msg);
488 }
489
490 self.process_cfg_attrs(expr)
491 }
492
493 pub fn configure_pat(&mut self, pat: &mut P<ast::Pat>) {
494 if let ast::PatKind::Struct(_path, fields, _etc) = &mut pat.kind {
495 fields.flat_map_in_place(|field| self.configure(field));
496 }
497 }
498
499 pub fn configure_fn_decl(&mut self, fn_decl: &mut ast::FnDecl) {
500 fn_decl.inputs.flat_map_in_place(|arg| self.configure(arg));
501 }
502 }
503
504 impl<'a> MutVisitor for StripUnconfigured<'a> {
505 fn visit_foreign_mod(&mut self, foreign_mod: &mut ast::ForeignMod) {
506 self.configure_foreign_mod(foreign_mod);
507 noop_visit_foreign_mod(foreign_mod, self);
508 }
509
510 fn visit_item_kind(&mut self, item: &mut ast::ItemKind) {
511 self.configure_item_kind(item);
512 noop_visit_item_kind(item, self);
513 }
514
515 fn visit_expr(&mut self, expr: &mut P<ast::Expr>) {
516 self.configure_expr(expr);
517 self.configure_expr_kind(&mut expr.kind);
518 noop_visit_expr(expr, self);
519 }
520
521 fn filter_map_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
522 let mut expr = configure!(self, expr);
523 self.configure_expr_kind(&mut expr.kind);
524 noop_visit_expr(&mut expr, self);
525 Some(expr)
526 }
527
528 fn flat_map_generic_param(
529 &mut self,
530 param: ast::GenericParam,
531 ) -> SmallVec<[ast::GenericParam; 1]> {
532 noop_flat_map_generic_param(configure!(self, param), self)
533 }
534
535 fn flat_map_stmt(&mut self, stmt: ast::Stmt) -> SmallVec<[ast::Stmt; 1]> {
536 noop_flat_map_stmt(configure!(self, stmt), self)
537 }
538
539 fn flat_map_item(&mut self, item: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
540 noop_flat_map_item(configure!(self, item), self)
541 }
542
543 fn flat_map_impl_item(&mut self, item: P<ast::AssocItem>) -> SmallVec<[P<ast::AssocItem>; 1]> {
544 noop_flat_map_assoc_item(configure!(self, item), self)
545 }
546
547 fn flat_map_trait_item(&mut self, item: P<ast::AssocItem>) -> SmallVec<[P<ast::AssocItem>; 1]> {
548 noop_flat_map_assoc_item(configure!(self, item), self)
549 }
550
551 fn visit_mac(&mut self, _mac: &mut ast::MacCall) {
552 // Don't configure interpolated AST (cf. issue #34171).
553 // Interpolated AST will get configured once the surrounding tokens are parsed.
554 }
555
556 fn visit_pat(&mut self, pat: &mut P<ast::Pat>) {
557 self.configure_pat(pat);
558 noop_visit_pat(pat, self)
559 }
560
561 fn visit_fn_decl(&mut self, mut fn_decl: &mut P<ast::FnDecl>) {
562 self.configure_fn_decl(&mut fn_decl);
563 noop_visit_fn_decl(fn_decl, self);
564 }
565 }
566
567 fn is_cfg(sess: &Session, attr: &Attribute) -> bool {
568 sess.check_name(attr, sym::cfg)
569 }