]>
Commit | Line | Data |
---|---|---|
ba9703b0 XL |
1 | //! Conditional compilation stripping. |
2 | ||
74b04a01 | 3 | use rustc_ast::ptr::P; |
29967ef6 XL |
4 | use rustc_ast::token::{DelimToken, Token, TokenKind}; |
5 | use rustc_ast::tokenstream::{DelimSpan, LazyTokenStream, Spacing, TokenStream, TokenTree}; | |
6a06907d | 6 | use rustc_ast::{self as ast, AstLike, AttrItem, Attribute, MetaItem}; |
74b04a01 | 7 | use rustc_attr as attr; |
dfeec247 | 8 | use rustc_data_structures::fx::FxHashMap; |
ba9703b0 | 9 | use rustc_data_structures::map_in_place::MapInPlace; |
dfeec247 XL |
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 | }; | |
ba9703b0 | 15 | use rustc_parse::{parse_in, validate_attr}; |
3dfed10e XL |
16 | use rustc_session::parse::feature_err; |
17 | use rustc_session::Session; | |
dfeec247 XL |
18 | use rustc_span::edition::{Edition, ALL_EDITIONS}; |
19 | use rustc_span::symbol::{sym, Symbol}; | |
20 | use rustc_span::{Span, DUMMY_SP}; | |
60c5eb7d | 21 | |
3157f602 XL |
22 | /// A folder that strips out items that do not belong in the current configuration. |
23 | pub struct StripUnconfigured<'a> { | |
3dfed10e | 24 | pub sess: &'a Session, |
3157f602 | 25 | pub features: Option<&'a Features>, |
5869c6ff | 26 | pub modified: bool, |
1a4d82fc JJ |
27 | } |
28 | ||
dfeec247 | 29 | fn get_features( |
3dfed10e | 30 | sess: &Session, |
dfeec247 XL |
31 | span_handler: &Handler, |
32 | krate_attrs: &[ast::Attribute], | |
dfeec247 XL |
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(); | |
3dfed10e | 55 | let crate_edition = sess.edition(); |
dfeec247 XL |
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 { | |
3dfed10e | 73 | if !sess.check_name(attr, sym::feature) { |
dfeec247 XL |
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 { | |
3dfed10e | 106 | if !sess.check_name(attr, sym::feature) { |
dfeec247 XL |
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 | ||
3dfed10e | 168 | if let Some(allowed) = sess.opts.debugging_opts.allow_features.as_ref() { |
dfeec247 XL |
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 | ||
9e0c209e | 195 | // `cfg_attr`-process the crate's attributes and compute the crate's features. |
3dfed10e | 196 | pub fn features(sess: &Session, mut krate: ast::Crate) -> (ast::Crate, Features) { |
5869c6ff | 197 | let mut strip_unconfigured = StripUnconfigured { sess, features: None, modified: false }; |
9e0c209e | 198 | |
74b04a01 | 199 | let unconfigured_attrs = krate.attrs.clone(); |
3dfed10e | 200 | let diag = &sess.parse_sess.span_diagnostic; |
74b04a01 | 201 | let err_count = diag.err_count(); |
6a06907d | 202 | let features = match strip_unconfigured.configure_krate_attrs(krate.attrs) { |
74b04a01 XL |
203 | None => { |
204 | // The entire crate is unconfigured. | |
9e0c209e | 205 | krate.attrs = Vec::new(); |
6a06907d | 206 | krate.items = Vec::new(); |
74b04a01 | 207 | Features::default() |
9e0c209e | 208 | } |
74b04a01 XL |
209 | Some(attrs) => { |
210 | krate.attrs = attrs; | |
3dfed10e | 211 | let features = get_features(sess, diag, &krate.attrs); |
74b04a01 XL |
212 | if err_count == diag.err_count() { |
213 | // Avoid reconfiguring malformed `cfg_attr`s. | |
214 | strip_unconfigured.features = Some(&features); | |
6a06907d XL |
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); | |
74b04a01 XL |
218 | } |
219 | features | |
9e0c209e | 220 | } |
74b04a01 | 221 | }; |
9e0c209e SL |
222 | (krate, features) |
223 | } | |
224 | ||
e74abb32 | 225 | #[macro_export] |
9e0c209e SL |
226 | macro_rules! configure { |
227 | ($this:ident, $node:ident) => { | |
228 | match $this.configure($node) { | |
229 | Some(node) => node, | |
230 | None => return Default::default(), | |
231 | } | |
dfeec247 | 232 | }; |
9e0c209e SL |
233 | } |
234 | ||
60c5eb7d XL |
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 | ||
3157f602 | 240 | impl<'a> StripUnconfigured<'a> { |
6a06907d | 241 | pub fn configure<T: AstLike>(&mut self, mut node: T) -> Option<T> { |
9fa01778 | 242 | self.process_cfg_attrs(&mut node); |
5869c6ff XL |
243 | if self.in_cfg(node.attrs()) { |
244 | Some(node) | |
245 | } else { | |
246 | self.modified = true; | |
247 | None | |
248 | } | |
1a4d82fc | 249 | } |
1a4d82fc | 250 | |
6a06907d XL |
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 | ||
0bf4aa26 XL |
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 | /// | |
74b04a01 | 267 | /// Gives compiler warnings if any `cfg_attr` does not contain any |
0bf4aa26 XL |
268 | /// attributes and is in the original source code. Gives compiler errors if |
269 | /// the syntax of any `cfg_attr` is incorrect. | |
6a06907d | 270 | fn process_cfg_attrs<T: AstLike>(&mut self, node: &mut T) { |
9fa01778 XL |
271 | node.visit_attrs(|attrs| { |
272 | attrs.flat_map_in_place(|attr| self.process_cfg_attr(attr)); | |
273 | }); | |
1a4d82fc | 274 | } |
85aaf69f | 275 | |
0bf4aa26 XL |
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 | |
9fa01778 | 282 | /// the attribute is incorrect. |
60c5eb7d XL |
283 | fn process_cfg_attr(&mut self, attr: Attribute) -> Vec<Attribute> { |
284 | if !attr.has_name(sym::cfg_attr) { | |
0bf4aa26 | 285 | return vec![attr]; |
85aaf69f SL |
286 | } |
287 | ||
5869c6ff XL |
288 | // A `#[cfg_attr]` either gets removed, or replaced with a new attribute |
289 | self.modified = true; | |
290 | ||
60c5eb7d XL |
291 | let (cfg_predicate, expanded_attrs) = match self.parse_cfg_attr(&attr) { |
292 | None => return vec![], | |
293 | Some(r) => r, | |
d9579d0f | 294 | }; |
9e0c209e | 295 | |
dc9dc135 XL |
296 | // Lint on zero attributes in source. |
297 | if expanded_attrs.is_empty() { | |
298 | return vec![attr]; | |
0bf4aa26 XL |
299 | } |
300 | ||
dc9dc135 | 301 | // At this point we know the attribute is considered used. |
3dfed10e | 302 | self.sess.mark_attr_used(&attr); |
dc9dc135 | 303 | |
3dfed10e | 304 | if !attr::cfg_matches(&cfg_predicate, &self.sess.parse_sess, self.features) { |
60c5eb7d XL |
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)| { | |
29967ef6 XL |
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)) | |
60c5eb7d | 344 | }) |
0bf4aa26 | 345 | .collect() |
60c5eb7d XL |
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"; | |
3dfed10e XL |
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 | }) { | |
60c5eb7d | 356 | Ok(r) => return Some(r), |
74b04a01 XL |
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 | } | |
60c5eb7d XL |
362 | } |
363 | } | |
364 | _ => self.error_malformed_cfg_attr_missing(attr.span), | |
85aaf69f | 365 | } |
60c5eb7d XL |
366 | None |
367 | } | |
368 | ||
369 | fn error_malformed_cfg_attr_missing(&self, span: Span) { | |
370 | self.sess | |
3dfed10e | 371 | .parse_sess |
60c5eb7d XL |
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(); | |
85aaf69f SL |
382 | } |
383 | ||
9fa01778 | 384 | /// Determines if a node with the given attributes should be included in this configuration. |
6a06907d | 385 | fn in_cfg(&self, attrs: &[Attribute]) -> bool { |
3157f602 | 386 | attrs.iter().all(|attr| { |
3dfed10e | 387 | if !is_cfg(self.sess, attr) { |
cc61c64b | 388 | return true; |
8faf50e0 | 389 | } |
3dfed10e | 390 | let meta_item = match validate_attr::parse_meta(&self.sess.parse_sess, attr) { |
74b04a01 XL |
391 | Ok(meta_item) => meta_item, |
392 | Err(mut err) => { | |
393 | err.emit(); | |
394 | return true; | |
395 | } | |
396 | }; | |
8faf50e0 | 397 | let error = |span, msg, suggestion: &str| { |
3dfed10e | 398 | let mut err = self.sess.parse_sess.span_diagnostic.struct_span_err(span, msg); |
8faf50e0 | 399 | if !suggestion.is_empty() { |
9fa01778 | 400 | err.span_suggestion( |
0bf4aa26 XL |
401 | span, |
402 | "expected syntax is", | |
403 | suggestion.into(), | |
404 | Applicability::MaybeIncorrect, | |
405 | ); | |
8faf50e0 XL |
406 | } |
407 | err.emit(); | |
408 | true | |
409 | }; | |
74b04a01 XL |
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() { | |
3dfed10e XL |
416 | Some(meta_item) => { |
417 | attr::cfg_matches(meta_item, &self.sess.parse_sess, self.features) | |
418 | } | |
74b04a01 XL |
419 | None => error(single.span(), "`cfg` predicate key cannot be a literal", ""), |
420 | }, | |
9e0c209e | 421 | } |
3157f602 XL |
422 | }) |
423 | } | |
92a42be0 | 424 | |
0531ce1d | 425 | /// If attributes are not allowed on expressions, emit an error for `attr` |
6a06907d | 426 | crate fn maybe_emit_expr_attr_err(&self, attr: &Attribute) { |
5869c6ff | 427 | if !self.features.map_or(true, |features| features.stmt_expr_attributes) { |
dfeec247 | 428 | let mut err = feature_err( |
3dfed10e | 429 | &self.sess.parse_sess, |
dfeec247 XL |
430 | sym::stmt_expr_attributes, |
431 | attr.span, | |
432 | "attributes on expressions are experimental", | |
433 | ); | |
0531ce1d | 434 | |
60c5eb7d | 435 | if attr.is_doc_comment() { |
0531ce1d | 436 | err.help("`///` is for documentation comments. For a plain comment, use `//`."); |
92a42be0 | 437 | } |
0531ce1d XL |
438 | |
439 | err.emit(); | |
92a42be0 SL |
440 | } |
441 | } | |
92a42be0 | 442 | |
9fa01778 | 443 | pub fn configure_expr(&mut self, expr: &mut P<ast::Expr>) { |
6a06907d XL |
444 | for attr in expr.attrs.iter() { |
445 | self.maybe_emit_expr_attr_err(attr); | |
446 | } | |
3157f602 XL |
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 | // | |
9fa01778 XL |
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 | |
3dfed10e | 455 | if let Some(attr) = expr.attrs().iter().find(|a| is_cfg(self.sess, a)) { |
3157f602 | 456 | let msg = "removing an expression is not supported in this position"; |
3dfed10e | 457 | self.sess.parse_sess.span_diagnostic.span_err(attr.span, msg); |
92a42be0 | 458 | } |
3157f602 | 459 | |
9e0c209e | 460 | self.process_cfg_attrs(expr) |
92a42be0 | 461 | } |
92a42be0 SL |
462 | } |
463 | ||
3dfed10e XL |
464 | fn is_cfg(sess: &Session, attr: &Attribute) -> bool { |
465 | sess.check_name(attr, sym::cfg) | |
92a42be0 | 466 | } |