]> git.lizzy.rs Git - rust.git/blob - src/librustc_expand/config.rs
Fix missed same-sized member clash in ClashingExternDeclarations.
[rust.git] / src / librustc_expand / config.rs
1 //! Conditional compilation stripping.
2
3 use rustc_ast::ast::{self, AttrItem, Attribute, MetaItem};
4 use rustc_ast::attr::HasAttrs;
5 use rustc_ast::mut_visit::*;
6 use rustc_ast::ptr::P;
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, ParseSess};
17 use rustc_span::edition::{Edition, ALL_EDITIONS};
18 use rustc_span::symbol::{sym, Symbol};
19 use rustc_span::{Span, DUMMY_SP};
20
21 use smallvec::SmallVec;
22
23 /// A folder that strips out items that do not belong in the current configuration.
24 pub struct StripUnconfigured<'a> {
25     pub sess: &'a ParseSess,
26     pub features: Option<&'a Features>,
27 }
28
29 fn get_features(
30     span_handler: &Handler,
31     krate_attrs: &[ast::Attribute],
32     crate_edition: Edition,
33     allow_features: &Option<Vec<String>>,
34 ) -> Features {
35     fn feature_removed(span_handler: &Handler, span: Span, reason: Option<&str>) {
36         let mut err = struct_span_err!(span_handler, span, E0557, "feature has been removed");
37         err.span_label(span, "feature has been removed");
38         if let Some(reason) = reason {
39             err.note(reason);
40         }
41         err.emit();
42     }
43
44     fn active_features_up_to(edition: Edition) -> impl Iterator<Item = &'static Feature> {
45         ACTIVE_FEATURES.iter().filter(move |feature| {
46             if let Some(feature_edition) = feature.edition {
47                 feature_edition <= edition
48             } else {
49                 false
50             }
51         })
52     }
53
54     let mut features = Features::default();
55     let mut edition_enabled_features = FxHashMap::default();
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 !attr.check_name(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 !attr.check_name(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) = 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(
197     mut krate: ast::Crate,
198     sess: &ParseSess,
199     edition: Edition,
200     allow_features: &Option<Vec<String>>,
201 ) -> (ast::Crate, Features) {
202     let mut strip_unconfigured = StripUnconfigured { sess, features: None };
203
204     let unconfigured_attrs = krate.attrs.clone();
205     let diag = &sess.span_diagnostic;
206     let err_count = diag.err_count();
207     let features = match strip_unconfigured.configure(krate.attrs) {
208         None => {
209             // The entire crate is unconfigured.
210             krate.attrs = Vec::new();
211             krate.module.items = Vec::new();
212             Features::default()
213         }
214         Some(attrs) => {
215             krate.attrs = attrs;
216             let features = get_features(diag, &krate.attrs, edition, allow_features);
217             if err_count == diag.err_count() {
218                 // Avoid reconfiguring malformed `cfg_attr`s.
219                 strip_unconfigured.features = Some(&features);
220                 strip_unconfigured.configure(unconfigured_attrs);
221             }
222             features
223         }
224     };
225     (krate, features)
226 }
227
228 #[macro_export]
229 macro_rules! configure {
230     ($this:ident, $node:ident) => {
231         match $this.configure($node) {
232             Some(node) => node,
233             None => return Default::default(),
234         }
235     };
236 }
237
238 const CFG_ATTR_GRAMMAR_HELP: &str = "#[cfg_attr(condition, attribute, other_attribute, ...)]";
239 const CFG_ATTR_NOTE_REF: &str = "for more information, visit \
240     <https://doc.rust-lang.org/reference/conditional-compilation.html\
241     #the-cfg_attr-attribute>";
242
243 impl<'a> StripUnconfigured<'a> {
244     pub fn configure<T: HasAttrs>(&mut self, mut node: T) -> Option<T> {
245         self.process_cfg_attrs(&mut node);
246         self.in_cfg(node.attrs()).then_some(node)
247     }
248
249     /// Parse and expand all `cfg_attr` attributes into a list of attributes
250     /// that are within each `cfg_attr` that has a true configuration predicate.
251     ///
252     /// Gives compiler warnings if any `cfg_attr` does not contain any
253     /// attributes and is in the original source code. Gives compiler errors if
254     /// the syntax of any `cfg_attr` is incorrect.
255     pub fn process_cfg_attrs<T: HasAttrs>(&mut self, node: &mut T) {
256         node.visit_attrs(|attrs| {
257             attrs.flat_map_in_place(|attr| self.process_cfg_attr(attr));
258         });
259     }
260
261     /// Parse and expand a single `cfg_attr` attribute into a list of attributes
262     /// when the configuration predicate is true, or otherwise expand into an
263     /// empty list of attributes.
264     ///
265     /// Gives a compiler warning when the `cfg_attr` contains no attributes and
266     /// is in the original source file. Gives a compiler error if the syntax of
267     /// the attribute is incorrect.
268     fn process_cfg_attr(&mut self, attr: Attribute) -> Vec<Attribute> {
269         if !attr.has_name(sym::cfg_attr) {
270             return vec![attr];
271         }
272
273         let (cfg_predicate, expanded_attrs) = match self.parse_cfg_attr(&attr) {
274             None => return vec![],
275             Some(r) => r,
276         };
277
278         // Lint on zero attributes in source.
279         if expanded_attrs.is_empty() {
280             return vec![attr];
281         }
282
283         // At this point we know the attribute is considered used.
284         attr::mark_used(&attr);
285
286         if !attr::cfg_matches(&cfg_predicate, self.sess, self.features) {
287             return vec![];
288         }
289
290         // We call `process_cfg_attr` recursively in case there's a
291         // `cfg_attr` inside of another `cfg_attr`. E.g.
292         //  `#[cfg_attr(false, cfg_attr(true, some_attr))]`.
293         expanded_attrs
294             .into_iter()
295             .flat_map(|(item, span)| {
296                 let attr = attr::mk_attr_from_item(attr.style, item, span);
297                 self.process_cfg_attr(attr)
298             })
299             .collect()
300     }
301
302     fn parse_cfg_attr(&self, attr: &Attribute) -> Option<(MetaItem, Vec<(AttrItem, Span)>)> {
303         match attr.get_normal_item().args {
304             ast::MacArgs::Delimited(dspan, delim, ref tts) if !tts.is_empty() => {
305                 let msg = "wrong `cfg_attr` delimiters";
306                 validate_attr::check_meta_bad_delim(self.sess, dspan, delim, msg);
307                 match parse_in(self.sess, tts.clone(), "`cfg_attr` input", |p| p.parse_cfg_attr()) {
308                     Ok(r) => return Some(r),
309                     Err(mut e) => {
310                         e.help(&format!("the valid syntax is `{}`", CFG_ATTR_GRAMMAR_HELP))
311                             .note(CFG_ATTR_NOTE_REF)
312                             .emit();
313                     }
314                 }
315             }
316             _ => self.error_malformed_cfg_attr_missing(attr.span),
317         }
318         None
319     }
320
321     fn error_malformed_cfg_attr_missing(&self, span: Span) {
322         self.sess
323             .span_diagnostic
324             .struct_span_err(span, "malformed `cfg_attr` attribute input")
325             .span_suggestion(
326                 span,
327                 "missing condition and attribute",
328                 CFG_ATTR_GRAMMAR_HELP.to_string(),
329                 Applicability::HasPlaceholders,
330             )
331             .note(CFG_ATTR_NOTE_REF)
332             .emit();
333     }
334
335     /// Determines if a node with the given attributes should be included in this configuration.
336     pub fn in_cfg(&self, attrs: &[Attribute]) -> bool {
337         attrs.iter().all(|attr| {
338             if !is_cfg(attr) {
339                 return true;
340             }
341             let meta_item = match validate_attr::parse_meta(self.sess, attr) {
342                 Ok(meta_item) => meta_item,
343                 Err(mut err) => {
344                     err.emit();
345                     return true;
346                 }
347             };
348             let error = |span, msg, suggestion: &str| {
349                 let mut err = self.sess.span_diagnostic.struct_span_err(span, msg);
350                 if !suggestion.is_empty() {
351                     err.span_suggestion(
352                         span,
353                         "expected syntax is",
354                         suggestion.into(),
355                         Applicability::MaybeIncorrect,
356                     );
357                 }
358                 err.emit();
359                 true
360             };
361             let span = meta_item.span;
362             match meta_item.meta_item_list() {
363                 None => error(span, "`cfg` is not followed by parentheses", "cfg(/* predicate */)"),
364                 Some([]) => error(span, "`cfg` predicate is not specified", ""),
365                 Some([_, .., l]) => error(l.span(), "multiple `cfg` predicates are specified", ""),
366                 Some([single]) => match single.meta_item() {
367                     Some(meta_item) => attr::cfg_matches(meta_item, self.sess, self.features),
368                     None => error(single.span(), "`cfg` predicate key cannot be a literal", ""),
369                 },
370             }
371         })
372     }
373
374     /// Visit attributes on expression and statements (but not attributes on items in blocks).
375     fn visit_expr_attrs(&mut self, attrs: &[Attribute]) {
376         // flag the offending attributes
377         for attr in attrs.iter() {
378             self.maybe_emit_expr_attr_err(attr);
379         }
380     }
381
382     /// If attributes are not allowed on expressions, emit an error for `attr`
383     pub fn maybe_emit_expr_attr_err(&self, attr: &Attribute) {
384         if !self.features.map(|features| features.stmt_expr_attributes).unwrap_or(true) {
385             let mut err = feature_err(
386                 self.sess,
387                 sym::stmt_expr_attributes,
388                 attr.span,
389                 "attributes on expressions are experimental",
390             );
391
392             if attr.is_doc_comment() {
393                 err.help("`///` is for documentation comments. For a plain comment, use `//`.");
394             }
395
396             err.emit();
397         }
398     }
399
400     pub fn configure_foreign_mod(&mut self, foreign_mod: &mut ast::ForeignMod) {
401         let ast::ForeignMod { abi: _, items } = foreign_mod;
402         items.flat_map_in_place(|item| self.configure(item));
403     }
404
405     pub fn configure_generic_params(&mut self, params: &mut Vec<ast::GenericParam>) {
406         params.flat_map_in_place(|param| self.configure(param));
407     }
408
409     fn configure_variant_data(&mut self, vdata: &mut ast::VariantData) {
410         match vdata {
411             ast::VariantData::Struct(fields, ..) | ast::VariantData::Tuple(fields, _) => {
412                 fields.flat_map_in_place(|field| self.configure(field))
413             }
414             ast::VariantData::Unit(_) => {}
415         }
416     }
417
418     pub fn configure_item_kind(&mut self, item: &mut ast::ItemKind) {
419         match item {
420             ast::ItemKind::Struct(def, _generics) | ast::ItemKind::Union(def, _generics) => {
421                 self.configure_variant_data(def)
422             }
423             ast::ItemKind::Enum(ast::EnumDef { variants }, _generics) => {
424                 variants.flat_map_in_place(|variant| self.configure(variant));
425                 for variant in variants {
426                     self.configure_variant_data(&mut variant.data);
427                 }
428             }
429             _ => {}
430         }
431     }
432
433     pub fn configure_expr_kind(&mut self, expr_kind: &mut ast::ExprKind) {
434         match expr_kind {
435             ast::ExprKind::Match(_m, arms) => {
436                 arms.flat_map_in_place(|arm| self.configure(arm));
437             }
438             ast::ExprKind::Struct(_path, fields, _base) => {
439                 fields.flat_map_in_place(|field| self.configure(field));
440             }
441             _ => {}
442         }
443     }
444
445     pub fn configure_expr(&mut self, expr: &mut P<ast::Expr>) {
446         self.visit_expr_attrs(expr.attrs());
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(a)) {
456             let msg = "removing an expression is not supported in this position";
457             self.sess.span_diagnostic.span_err(attr.span, msg);
458         }
459
460         self.process_cfg_attrs(expr)
461     }
462
463     pub fn configure_pat(&mut self, pat: &mut P<ast::Pat>) {
464         if let ast::PatKind::Struct(_path, fields, _etc) = &mut pat.kind {
465             fields.flat_map_in_place(|field| self.configure(field));
466         }
467     }
468
469     pub fn configure_fn_decl(&mut self, fn_decl: &mut ast::FnDecl) {
470         fn_decl.inputs.flat_map_in_place(|arg| self.configure(arg));
471     }
472 }
473
474 impl<'a> MutVisitor for StripUnconfigured<'a> {
475     fn visit_foreign_mod(&mut self, foreign_mod: &mut ast::ForeignMod) {
476         self.configure_foreign_mod(foreign_mod);
477         noop_visit_foreign_mod(foreign_mod, self);
478     }
479
480     fn visit_item_kind(&mut self, item: &mut ast::ItemKind) {
481         self.configure_item_kind(item);
482         noop_visit_item_kind(item, self);
483     }
484
485     fn visit_expr(&mut self, expr: &mut P<ast::Expr>) {
486         self.configure_expr(expr);
487         self.configure_expr_kind(&mut expr.kind);
488         noop_visit_expr(expr, self);
489     }
490
491     fn filter_map_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
492         let mut expr = configure!(self, expr);
493         self.configure_expr_kind(&mut expr.kind);
494         noop_visit_expr(&mut expr, self);
495         Some(expr)
496     }
497
498     fn flat_map_stmt(&mut self, stmt: ast::Stmt) -> SmallVec<[ast::Stmt; 1]> {
499         noop_flat_map_stmt(configure!(self, stmt), self)
500     }
501
502     fn flat_map_item(&mut self, item: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
503         noop_flat_map_item(configure!(self, item), self)
504     }
505
506     fn flat_map_impl_item(&mut self, item: P<ast::AssocItem>) -> SmallVec<[P<ast::AssocItem>; 1]> {
507         noop_flat_map_assoc_item(configure!(self, item), self)
508     }
509
510     fn flat_map_trait_item(&mut self, item: P<ast::AssocItem>) -> SmallVec<[P<ast::AssocItem>; 1]> {
511         noop_flat_map_assoc_item(configure!(self, item), self)
512     }
513
514     fn visit_mac(&mut self, _mac: &mut ast::MacCall) {
515         // Don't configure interpolated AST (cf. issue #34171).
516         // Interpolated AST will get configured once the surrounding tokens are parsed.
517     }
518
519     fn visit_pat(&mut self, pat: &mut P<ast::Pat>) {
520         self.configure_pat(pat);
521         noop_visit_pat(pat, self)
522     }
523
524     fn visit_fn_decl(&mut self, mut fn_decl: &mut P<ast::FnDecl>) {
525         self.configure_fn_decl(&mut fn_decl);
526         noop_visit_fn_decl(fn_decl, self);
527     }
528 }
529
530 fn is_cfg(attr: &Attribute) -> bool {
531     attr.check_name(sym::cfg)
532 }