]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_attr/src/builtin.rs
Auto merge of #101312 - nikic:update-llvm-7, r=cuviper
[rust.git] / compiler / rustc_attr / src / builtin.rs
1 //! Parsing and validation of builtin attributes
2
3 use rustc_ast as ast;
4 use rustc_ast::{Attribute, Lit, LitKind, MetaItem, MetaItemKind, NestedMetaItem, NodeId};
5 use rustc_ast_pretty::pprust;
6 use rustc_feature::{find_gated_cfg, is_builtin_attr_name, Features, GatedCfg};
7 use rustc_macros::HashStable_Generic;
8 use rustc_session::lint::builtin::UNEXPECTED_CFGS;
9 use rustc_session::lint::BuiltinLintDiagnostics;
10 use rustc_session::parse::{feature_err, ParseSess};
11 use rustc_session::Session;
12 use rustc_span::hygiene::Transparency;
13 use rustc_span::{symbol::sym, symbol::Symbol, Span};
14 use std::num::NonZeroU32;
15
16 use crate::session_diagnostics::{self, IncorrectReprFormatGenericCause};
17
18 /// The version placeholder that recently stabilized features contain inside the
19 /// `since` field of the `#[stable]` attribute.
20 ///
21 /// For more, see [this pull request](https://github.com/rust-lang/rust/pull/100591).
22 pub const VERSION_PLACEHOLDER: &str = "CURRENT_RUSTC_VERSION";
23
24 pub fn is_builtin_attr(attr: &Attribute) -> bool {
25     attr.is_doc_comment() || attr.ident().filter(|ident| is_builtin_attr_name(ident.name)).is_some()
26 }
27
28 enum AttrError {
29     MultipleItem(String),
30     UnknownMetaItem(String, &'static [&'static str]),
31     MissingSince,
32     NonIdentFeature,
33     MissingFeature,
34     MultipleStabilityLevels,
35     UnsupportedLiteral(UnsupportedLiteralReason, /* is_bytestr */ bool),
36 }
37
38 pub(crate) enum UnsupportedLiteralReason {
39     Generic,
40     CfgString,
41     DeprecatedString,
42     DeprecatedKvPair,
43 }
44
45 fn handle_errors(sess: &ParseSess, span: Span, error: AttrError) {
46     match error {
47         AttrError::MultipleItem(item) => {
48             sess.emit_err(session_diagnostics::MultipleItem { span, item });
49         }
50         AttrError::UnknownMetaItem(item, expected) => {
51             sess.emit_err(session_diagnostics::UnknownMetaItem { span, item, expected });
52         }
53         AttrError::MissingSince => {
54             sess.emit_err(session_diagnostics::MissingSince { span });
55         }
56         AttrError::NonIdentFeature => {
57             sess.emit_err(session_diagnostics::NonIdentFeature { span });
58         }
59         AttrError::MissingFeature => {
60             sess.emit_err(session_diagnostics::MissingFeature { span });
61         }
62         AttrError::MultipleStabilityLevels => {
63             sess.emit_err(session_diagnostics::MultipleStabilityLevels { span });
64         }
65         AttrError::UnsupportedLiteral(reason, is_bytestr) => {
66             sess.emit_err(session_diagnostics::UnsupportedLiteral { span, reason, is_bytestr });
67         }
68     }
69 }
70
71 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
72 pub enum InlineAttr {
73     None,
74     Hint,
75     Always,
76     Never,
77 }
78
79 #[derive(Clone, Encodable, Decodable, Debug, PartialEq, Eq, HashStable_Generic)]
80 pub enum InstructionSetAttr {
81     ArmA32,
82     ArmT32,
83 }
84
85 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
86 pub enum OptimizeAttr {
87     None,
88     Speed,
89     Size,
90 }
91
92 /// Represents the following attributes:
93 ///
94 /// - `#[stable]`
95 /// - `#[unstable]`
96 #[derive(Encodable, Decodable, Copy, Clone, Debug, PartialEq, Eq, Hash)]
97 #[derive(HashStable_Generic)]
98 pub struct Stability {
99     pub level: StabilityLevel,
100     pub feature: Symbol,
101 }
102
103 impl Stability {
104     pub fn is_unstable(&self) -> bool {
105         self.level.is_unstable()
106     }
107
108     pub fn is_stable(&self) -> bool {
109         self.level.is_stable()
110     }
111 }
112
113 /// Represents the `#[rustc_const_unstable]` and `#[rustc_const_stable]` attributes.
114 #[derive(Encodable, Decodable, Copy, Clone, Debug, PartialEq, Eq, Hash)]
115 #[derive(HashStable_Generic)]
116 pub struct ConstStability {
117     pub level: StabilityLevel,
118     pub feature: Symbol,
119     /// whether the function has a `#[rustc_promotable]` attribute
120     pub promotable: bool,
121 }
122
123 impl ConstStability {
124     pub fn is_const_unstable(&self) -> bool {
125         self.level.is_unstable()
126     }
127
128     pub fn is_const_stable(&self) -> bool {
129         self.level.is_stable()
130     }
131 }
132
133 /// Represents the `#[rustc_default_body_unstable]` attribute.
134 #[derive(Encodable, Decodable, Copy, Clone, Debug, PartialEq, Eq, Hash)]
135 #[derive(HashStable_Generic)]
136 pub struct DefaultBodyStability {
137     pub level: StabilityLevel,
138     pub feature: Symbol,
139 }
140
141 /// The available stability levels.
142 #[derive(Encodable, Decodable, PartialEq, Copy, Clone, Debug, Eq, Hash)]
143 #[derive(HashStable_Generic)]
144 pub enum StabilityLevel {
145     /// `#[unstable]`
146     Unstable {
147         /// Reason for the current stability level.
148         reason: UnstableReason,
149         /// Relevant `rust-lang/rust` issue.
150         issue: Option<NonZeroU32>,
151         is_soft: bool,
152         /// If part of a feature is stabilized and a new feature is added for the remaining parts,
153         /// then the `implied_by` attribute is used to indicate which now-stable feature previously
154         /// contained a item.
155         ///
156         /// ```pseudo-Rust
157         /// #[unstable(feature = "foo", issue = "...")]
158         /// fn foo() {}
159         /// #[unstable(feature = "foo", issue = "...")]
160         /// fn foobar() {}
161         /// ```
162         ///
163         /// ...becomes...
164         ///
165         /// ```pseudo-Rust
166         /// #[stable(feature = "foo", since = "1.XX.X")]
167         /// fn foo() {}
168         /// #[unstable(feature = "foobar", issue = "...", implied_by = "foo")]
169         /// fn foobar() {}
170         /// ```
171         implied_by: Option<Symbol>,
172     },
173     /// `#[stable]`
174     Stable {
175         /// Rust release which stabilized this feature.
176         since: Symbol,
177         /// Is this item allowed to be referred to on stable, despite being contained in unstable
178         /// modules?
179         allowed_through_unstable_modules: bool,
180     },
181 }
182
183 impl StabilityLevel {
184     pub fn is_unstable(&self) -> bool {
185         matches!(self, StabilityLevel::Unstable { .. })
186     }
187     pub fn is_stable(&self) -> bool {
188         matches!(self, StabilityLevel::Stable { .. })
189     }
190 }
191
192 #[derive(Encodable, Decodable, PartialEq, Copy, Clone, Debug, Eq, Hash)]
193 #[derive(HashStable_Generic)]
194 pub enum UnstableReason {
195     None,
196     Default,
197     Some(Symbol),
198 }
199
200 impl UnstableReason {
201     fn from_opt_reason(reason: Option<Symbol>) -> Self {
202         // UnstableReason::Default constructed manually
203         match reason {
204             Some(r) => Self::Some(r),
205             None => Self::None,
206         }
207     }
208
209     pub fn to_opt_reason(&self) -> Option<Symbol> {
210         match self {
211             Self::None => None,
212             Self::Default => Some(sym::unstable_location_reason_default),
213             Self::Some(r) => Some(*r),
214         }
215     }
216 }
217
218 /// Collects stability info from all stability attributes in `attrs`.
219 /// Returns `None` if no stability attributes are found.
220 pub fn find_stability(
221     sess: &Session,
222     attrs: &[Attribute],
223     item_sp: Span,
224 ) -> (Option<(Stability, Span)>, Option<(ConstStability, Span)>, Option<(DefaultBodyStability, Span)>)
225 {
226     find_stability_generic(sess, attrs.iter(), item_sp)
227 }
228
229 fn find_stability_generic<'a, I>(
230     sess: &Session,
231     attrs_iter: I,
232     item_sp: Span,
233 ) -> (Option<(Stability, Span)>, Option<(ConstStability, Span)>, Option<(DefaultBodyStability, Span)>)
234 where
235     I: Iterator<Item = &'a Attribute>,
236 {
237     use StabilityLevel::*;
238
239     let mut stab: Option<(Stability, Span)> = None;
240     let mut const_stab: Option<(ConstStability, Span)> = None;
241     let mut body_stab: Option<(DefaultBodyStability, Span)> = None;
242     let mut promotable = false;
243     let mut allowed_through_unstable_modules = false;
244
245     'outer: for attr in attrs_iter {
246         if ![
247             sym::rustc_const_unstable,
248             sym::rustc_const_stable,
249             sym::unstable,
250             sym::stable,
251             sym::rustc_promotable,
252             sym::rustc_allowed_through_unstable_modules,
253             sym::rustc_default_body_unstable,
254         ]
255         .iter()
256         .any(|&s| attr.has_name(s))
257         {
258             continue; // not a stability level
259         }
260
261         let meta = attr.meta();
262
263         if attr.has_name(sym::rustc_promotable) {
264             promotable = true;
265         } else if attr.has_name(sym::rustc_allowed_through_unstable_modules) {
266             allowed_through_unstable_modules = true;
267         }
268         // attributes with data
269         else if let Some(MetaItem { kind: MetaItemKind::List(ref metas), .. }) = meta {
270             let meta = meta.as_ref().unwrap();
271             let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
272                 if item.is_some() {
273                     handle_errors(
274                         &sess.parse_sess,
275                         meta.span,
276                         AttrError::MultipleItem(pprust::path_to_string(&meta.path)),
277                     );
278                     return false;
279                 }
280                 if let Some(v) = meta.value_str() {
281                     *item = Some(v);
282                     true
283                 } else {
284                     sess.emit_err(session_diagnostics::IncorrectMetaItem { span: meta.span });
285                     false
286                 }
287             };
288
289             let meta_name = meta.name_or_empty();
290             match meta_name {
291                 sym::rustc_const_unstable | sym::rustc_default_body_unstable | sym::unstable => {
292                     if meta_name == sym::unstable && stab.is_some() {
293                         handle_errors(
294                             &sess.parse_sess,
295                             attr.span,
296                             AttrError::MultipleStabilityLevels,
297                         );
298                         break;
299                     } else if meta_name == sym::rustc_const_unstable && const_stab.is_some() {
300                         handle_errors(
301                             &sess.parse_sess,
302                             attr.span,
303                             AttrError::MultipleStabilityLevels,
304                         );
305                         break;
306                     } else if meta_name == sym::rustc_default_body_unstable && body_stab.is_some() {
307                         handle_errors(
308                             &sess.parse_sess,
309                             attr.span,
310                             AttrError::MultipleStabilityLevels,
311                         );
312                         break;
313                     }
314
315                     let mut feature = None;
316                     let mut reason = None;
317                     let mut issue = None;
318                     let mut issue_num = None;
319                     let mut is_soft = false;
320                     let mut implied_by = None;
321                     for meta in metas {
322                         let Some(mi) = meta.meta_item() else {
323                             handle_errors(
324                                 &sess.parse_sess,
325                                 meta.span(),
326                                 AttrError::UnsupportedLiteral(UnsupportedLiteralReason::Generic, false),
327                             );
328                             continue 'outer;
329                         };
330                         match mi.name_or_empty() {
331                             sym::feature => {
332                                 if !get(mi, &mut feature) {
333                                     continue 'outer;
334                                 }
335                             }
336                             sym::reason => {
337                                 if !get(mi, &mut reason) {
338                                     continue 'outer;
339                                 }
340                             }
341                             sym::issue => {
342                                 if !get(mi, &mut issue) {
343                                     continue 'outer;
344                                 }
345
346                                 // These unwraps are safe because `get` ensures the meta item
347                                 // is a name/value pair string literal.
348                                 issue_num = match issue.unwrap().as_str() {
349                                     "none" => None,
350                                     issue => match issue.parse::<NonZeroU32>() {
351                                         Ok(num) => Some(num),
352                                         Err(err) => {
353                                             sess.emit_err(
354                                                 session_diagnostics::InvalidIssueString {
355                                                     span: mi.span,
356                                                     cause: session_diagnostics::InvalidIssueStringCause::from_int_error_kind(
357                                                         mi.name_value_literal_span().unwrap(),
358                                                         err.kind(),
359                                                     ),
360                                                 },
361                                             );
362                                             continue 'outer;
363                                         }
364                                     },
365                                 };
366                             }
367                             sym::soft => {
368                                 if !mi.is_word() {
369                                     sess.emit_err(session_diagnostics::SoftNoArgs {
370                                         span: mi.span,
371                                     });
372                                 }
373                                 is_soft = true;
374                             }
375                             sym::implied_by => {
376                                 if !get(mi, &mut implied_by) {
377                                     continue 'outer;
378                                 }
379                             }
380                             _ => {
381                                 handle_errors(
382                                     &sess.parse_sess,
383                                     meta.span(),
384                                     AttrError::UnknownMetaItem(
385                                         pprust::path_to_string(&mi.path),
386                                         &["feature", "reason", "issue", "soft"],
387                                     ),
388                                 );
389                                 continue 'outer;
390                             }
391                         }
392                     }
393
394                     match (feature, reason, issue) {
395                         (Some(feature), reason, Some(_)) => {
396                             if !rustc_lexer::is_ident(feature.as_str()) {
397                                 handle_errors(
398                                     &sess.parse_sess,
399                                     attr.span,
400                                     AttrError::NonIdentFeature,
401                                 );
402                                 continue;
403                             }
404                             let level = Unstable {
405                                 reason: UnstableReason::from_opt_reason(reason),
406                                 issue: issue_num,
407                                 is_soft,
408                                 implied_by,
409                             };
410                             if sym::unstable == meta_name {
411                                 stab = Some((Stability { level, feature }, attr.span));
412                             } else if sym::rustc_const_unstable == meta_name {
413                                 const_stab = Some((
414                                     ConstStability { level, feature, promotable: false },
415                                     attr.span,
416                                 ));
417                             } else if sym::rustc_default_body_unstable == meta_name {
418                                 body_stab =
419                                     Some((DefaultBodyStability { level, feature }, attr.span));
420                             } else {
421                                 unreachable!("Unknown stability attribute {meta_name}");
422                             }
423                         }
424                         (None, _, _) => {
425                             handle_errors(&sess.parse_sess, attr.span, AttrError::MissingFeature);
426                             continue;
427                         }
428                         _ => {
429                             sess.emit_err(session_diagnostics::MissingIssue { span: attr.span });
430                             continue;
431                         }
432                     }
433                 }
434                 sym::rustc_const_stable | sym::stable => {
435                     if meta_name == sym::stable && stab.is_some() {
436                         handle_errors(
437                             &sess.parse_sess,
438                             attr.span,
439                             AttrError::MultipleStabilityLevels,
440                         );
441                         break;
442                     } else if meta_name == sym::rustc_const_stable && const_stab.is_some() {
443                         handle_errors(
444                             &sess.parse_sess,
445                             attr.span,
446                             AttrError::MultipleStabilityLevels,
447                         );
448                         break;
449                     }
450
451                     let mut feature = None;
452                     let mut since = None;
453                     for meta in metas {
454                         match meta {
455                             NestedMetaItem::MetaItem(mi) => match mi.name_or_empty() {
456                                 sym::feature => {
457                                     if !get(mi, &mut feature) {
458                                         continue 'outer;
459                                     }
460                                 }
461                                 sym::since => {
462                                     if !get(mi, &mut since) {
463                                         continue 'outer;
464                                     }
465                                 }
466                                 _ => {
467                                     handle_errors(
468                                         &sess.parse_sess,
469                                         meta.span(),
470                                         AttrError::UnknownMetaItem(
471                                             pprust::path_to_string(&mi.path),
472                                             &["feature", "since"],
473                                         ),
474                                     );
475                                     continue 'outer;
476                                 }
477                             },
478                             NestedMetaItem::Literal(lit) => {
479                                 handle_errors(
480                                     &sess.parse_sess,
481                                     lit.span,
482                                     AttrError::UnsupportedLiteral(
483                                         UnsupportedLiteralReason::Generic,
484                                         false,
485                                     ),
486                                 );
487                                 continue 'outer;
488                             }
489                         }
490                     }
491
492                     if let Some(s) = since && s.as_str() == VERSION_PLACEHOLDER {
493                         let version = option_env!("CFG_VERSION").unwrap_or("<current>");
494                         let version = version.split(' ').next().unwrap();
495                         since = Some(Symbol::intern(&version));
496                     }
497
498                     match (feature, since) {
499                         (Some(feature), Some(since)) => {
500                             let level = Stable { since, allowed_through_unstable_modules: false };
501                             if sym::stable == meta_name {
502                                 stab = Some((Stability { level, feature }, attr.span));
503                             } else {
504                                 const_stab = Some((
505                                     ConstStability { level, feature, promotable: false },
506                                     attr.span,
507                                 ));
508                             }
509                         }
510                         (None, _) => {
511                             handle_errors(&sess.parse_sess, attr.span, AttrError::MissingFeature);
512                             continue;
513                         }
514                         _ => {
515                             handle_errors(&sess.parse_sess, attr.span, AttrError::MissingSince);
516                             continue;
517                         }
518                     }
519                 }
520                 _ => unreachable!(),
521             }
522         }
523     }
524
525     // Merge the const-unstable info into the stability info
526     if promotable {
527         if let Some((ref mut stab, _)) = const_stab {
528             stab.promotable = promotable;
529         } else {
530             sess.emit_err(session_diagnostics::RustcPromotablePairing { span: item_sp });
531         }
532     }
533
534     if allowed_through_unstable_modules {
535         if let Some((
536             Stability {
537                 level: StabilityLevel::Stable { ref mut allowed_through_unstable_modules, .. },
538                 ..
539             },
540             _,
541         )) = stab
542         {
543             *allowed_through_unstable_modules = true;
544         } else {
545             sess.emit_err(session_diagnostics::RustcAllowedUnstablePairing { span: item_sp });
546         }
547     }
548
549     (stab, const_stab, body_stab)
550 }
551
552 pub fn find_crate_name(sess: &Session, attrs: &[Attribute]) -> Option<Symbol> {
553     sess.first_attr_value_str_by_name(attrs, sym::crate_name)
554 }
555
556 #[derive(Clone, Debug)]
557 pub struct Condition {
558     pub name: Symbol,
559     pub name_span: Span,
560     pub value: Option<Symbol>,
561     pub value_span: Option<Span>,
562     pub span: Span,
563 }
564
565 /// Tests if a cfg-pattern matches the cfg set
566 pub fn cfg_matches(
567     cfg: &ast::MetaItem,
568     sess: &ParseSess,
569     lint_node_id: NodeId,
570     features: Option<&Features>,
571 ) -> bool {
572     eval_condition(cfg, sess, features, &mut |cfg| {
573         try_gate_cfg(cfg.name, cfg.span, sess, features);
574         if let Some(names_valid) = &sess.check_config.names_valid {
575             if !names_valid.contains(&cfg.name) {
576                 sess.buffer_lint_with_diagnostic(
577                     UNEXPECTED_CFGS,
578                     cfg.span,
579                     lint_node_id,
580                     "unexpected `cfg` condition name",
581                     BuiltinLintDiagnostics::UnexpectedCfg((cfg.name, cfg.name_span), None),
582                 );
583             }
584         }
585         if let Some(value) = cfg.value {
586             if let Some(values) = &sess.check_config.values_valid.get(&cfg.name) {
587                 if !values.contains(&value) {
588                     sess.buffer_lint_with_diagnostic(
589                         UNEXPECTED_CFGS,
590                         cfg.span,
591                         lint_node_id,
592                         "unexpected `cfg` condition value",
593                         BuiltinLintDiagnostics::UnexpectedCfg(
594                             (cfg.name, cfg.name_span),
595                             cfg.value_span.map(|vs| (value, vs)),
596                         ),
597                     );
598                 }
599             }
600         }
601         sess.config.contains(&(cfg.name, cfg.value))
602     })
603 }
604
605 fn try_gate_cfg(name: Symbol, span: Span, sess: &ParseSess, features: Option<&Features>) {
606     let gate = find_gated_cfg(|sym| sym == name);
607     if let (Some(feats), Some(gated_cfg)) = (features, gate) {
608         gate_cfg(&gated_cfg, span, sess, feats);
609     }
610 }
611
612 fn gate_cfg(gated_cfg: &GatedCfg, cfg_span: Span, sess: &ParseSess, features: &Features) {
613     let (cfg, feature, has_feature) = gated_cfg;
614     if !has_feature(features) && !cfg_span.allows_unstable(*feature) {
615         let explain = format!("`cfg({})` is experimental and subject to change", cfg);
616         feature_err(sess, *feature, cfg_span, &explain).emit();
617     }
618 }
619
620 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
621 struct Version {
622     major: u16,
623     minor: u16,
624     patch: u16,
625 }
626
627 fn parse_version(s: &str, allow_appendix: bool) -> Option<Version> {
628     let mut components = s.split('-');
629     let d = components.next()?;
630     if !allow_appendix && components.next().is_some() {
631         return None;
632     }
633     let mut digits = d.splitn(3, '.');
634     let major = digits.next()?.parse().ok()?;
635     let minor = digits.next()?.parse().ok()?;
636     let patch = digits.next().unwrap_or("0").parse().ok()?;
637     Some(Version { major, minor, patch })
638 }
639
640 /// Evaluate a cfg-like condition (with `any` and `all`), using `eval` to
641 /// evaluate individual items.
642 pub fn eval_condition(
643     cfg: &ast::MetaItem,
644     sess: &ParseSess,
645     features: Option<&Features>,
646     eval: &mut impl FnMut(Condition) -> bool,
647 ) -> bool {
648     match cfg.kind {
649         ast::MetaItemKind::List(ref mis) if cfg.name_or_empty() == sym::version => {
650             try_gate_cfg(sym::version, cfg.span, sess, features);
651             let (min_version, span) = match &mis[..] {
652                 [NestedMetaItem::Literal(Lit { kind: LitKind::Str(sym, ..), span, .. })] => {
653                     (sym, span)
654                 }
655                 [
656                     NestedMetaItem::Literal(Lit { span, .. })
657                     | NestedMetaItem::MetaItem(MetaItem { span, .. }),
658                 ] => {
659                     sess.emit_err(session_diagnostics::ExpectedVersionLiteral { span: *span });
660                     return false;
661                 }
662                 [..] => {
663                     sess.emit_err(session_diagnostics::ExpectedSingleVersionLiteral {
664                         span: cfg.span,
665                     });
666                     return false;
667                 }
668             };
669             let Some(min_version) = parse_version(min_version.as_str(), false) else {
670                 sess.emit_warning(session_diagnostics::UnknownVersionLiteral { span: *span });
671                 return false;
672             };
673             let rustc_version = parse_version(env!("CFG_RELEASE"), true).unwrap();
674
675             // See https://github.com/rust-lang/rust/issues/64796#issuecomment-640851454 for details
676             if sess.assume_incomplete_release {
677                 rustc_version > min_version
678             } else {
679                 rustc_version >= min_version
680             }
681         }
682         ast::MetaItemKind::List(ref mis) => {
683             for mi in mis.iter() {
684                 if !mi.is_meta_item() {
685                     handle_errors(
686                         sess,
687                         mi.span(),
688                         AttrError::UnsupportedLiteral(UnsupportedLiteralReason::Generic, false),
689                     );
690                     return false;
691                 }
692             }
693
694             // The unwraps below may look dangerous, but we've already asserted
695             // that they won't fail with the loop above.
696             match cfg.name_or_empty() {
697                 sym::any => mis
698                     .iter()
699                     // We don't use any() here, because we want to evaluate all cfg condition
700                     // as eval_condition can (and does) extra checks
701                     .fold(false, |res, mi| {
702                         res | eval_condition(mi.meta_item().unwrap(), sess, features, eval)
703                     }),
704                 sym::all => mis
705                     .iter()
706                     // We don't use all() here, because we want to evaluate all cfg condition
707                     // as eval_condition can (and does) extra checks
708                     .fold(true, |res, mi| {
709                         res & eval_condition(mi.meta_item().unwrap(), sess, features, eval)
710                     }),
711                 sym::not => {
712                     if mis.len() != 1 {
713                         sess.emit_err(session_diagnostics::ExpectedOneCfgPattern {
714                             span: cfg.span,
715                         });
716                         return false;
717                     }
718
719                     !eval_condition(mis[0].meta_item().unwrap(), sess, features, eval)
720                 }
721                 sym::target => {
722                     if let Some(features) = features && !features.cfg_target_compact {
723                         feature_err(
724                             sess,
725                             sym::cfg_target_compact,
726                             cfg.span,
727                             &"compact `cfg(target(..))` is experimental and subject to change"
728                         ).emit();
729                     }
730
731                     mis.iter().fold(true, |res, mi| {
732                         let mut mi = mi.meta_item().unwrap().clone();
733                         if let [seg, ..] = &mut mi.path.segments[..] {
734                             seg.ident.name = Symbol::intern(&format!("target_{}", seg.ident.name));
735                         }
736
737                         res & eval_condition(&mi, sess, features, eval)
738                     })
739                 }
740                 _ => {
741                     sess.emit_err(session_diagnostics::InvalidPredicate {
742                         span: cfg.span,
743                         predicate: pprust::path_to_string(&cfg.path),
744                     });
745                     false
746                 }
747             }
748         }
749         ast::MetaItemKind::Word | MetaItemKind::NameValue(..) if cfg.path.segments.len() != 1 => {
750             sess.emit_err(session_diagnostics::CfgPredicateIdentifier { span: cfg.path.span });
751             true
752         }
753         MetaItemKind::NameValue(ref lit) if !lit.kind.is_str() => {
754             handle_errors(
755                 sess,
756                 lit.span,
757                 AttrError::UnsupportedLiteral(
758                     UnsupportedLiteralReason::CfgString,
759                     lit.kind.is_bytestr(),
760                 ),
761             );
762             true
763         }
764         ast::MetaItemKind::Word | ast::MetaItemKind::NameValue(..) => {
765             let ident = cfg.ident().expect("multi-segment cfg predicate");
766             eval(Condition {
767                 name: ident.name,
768                 name_span: ident.span,
769                 value: cfg.value_str(),
770                 value_span: cfg.name_value_literal_span(),
771                 span: cfg.span,
772             })
773         }
774     }
775 }
776
777 #[derive(Copy, Debug, Encodable, Decodable, Clone, HashStable_Generic)]
778 pub struct Deprecation {
779     pub since: Option<Symbol>,
780     /// The note to issue a reason.
781     pub note: Option<Symbol>,
782     /// A text snippet used to completely replace any use of the deprecated item in an expression.
783     ///
784     /// This is currently unstable.
785     pub suggestion: Option<Symbol>,
786
787     /// Whether to treat the since attribute as being a Rust version identifier
788     /// (rather than an opaque string).
789     pub is_since_rustc_version: bool,
790 }
791
792 /// Finds the deprecation attribute. `None` if none exists.
793 pub fn find_deprecation(sess: &Session, attrs: &[Attribute]) -> Option<(Deprecation, Span)> {
794     find_deprecation_generic(sess, attrs.iter())
795 }
796
797 fn find_deprecation_generic<'a, I>(sess: &Session, attrs_iter: I) -> Option<(Deprecation, Span)>
798 where
799     I: Iterator<Item = &'a Attribute>,
800 {
801     let mut depr: Option<(Deprecation, Span)> = None;
802     let is_rustc = sess.features_untracked().staged_api;
803
804     'outer: for attr in attrs_iter {
805         if !attr.has_name(sym::deprecated) {
806             continue;
807         }
808
809         let Some(meta) = attr.meta() else {
810             continue;
811         };
812         let mut since = None;
813         let mut note = None;
814         let mut suggestion = None;
815         match &meta.kind {
816             MetaItemKind::Word => {}
817             MetaItemKind::NameValue(..) => note = meta.value_str(),
818             MetaItemKind::List(list) => {
819                 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
820                     if item.is_some() {
821                         handle_errors(
822                             &sess.parse_sess,
823                             meta.span,
824                             AttrError::MultipleItem(pprust::path_to_string(&meta.path)),
825                         );
826                         return false;
827                     }
828                     if let Some(v) = meta.value_str() {
829                         *item = Some(v);
830                         true
831                     } else {
832                         if let Some(lit) = meta.name_value_literal() {
833                             handle_errors(
834                                 &sess.parse_sess,
835                                 lit.span,
836                                 AttrError::UnsupportedLiteral(
837                                     UnsupportedLiteralReason::DeprecatedString,
838                                     lit.kind.is_bytestr(),
839                                 ),
840                             );
841                         } else {
842                             sess.emit_err(session_diagnostics::IncorrectMetaItem2 {
843                                 span: meta.span,
844                             });
845                         }
846
847                         false
848                     }
849                 };
850
851                 for meta in list {
852                     match meta {
853                         NestedMetaItem::MetaItem(mi) => match mi.name_or_empty() {
854                             sym::since => {
855                                 if !get(mi, &mut since) {
856                                     continue 'outer;
857                                 }
858                             }
859                             sym::note => {
860                                 if !get(mi, &mut note) {
861                                     continue 'outer;
862                                 }
863                             }
864                             sym::suggestion => {
865                                 if !sess.features_untracked().deprecated_suggestion {
866                                     sess.emit_err(session_diagnostics::DeprecatedItemSuggestion {
867                                         span: mi.span,
868                                         is_nightly: sess.is_nightly_build().then_some(()),
869                                         details: (),
870                                     });
871                                 }
872
873                                 if !get(mi, &mut suggestion) {
874                                     continue 'outer;
875                                 }
876                             }
877                             _ => {
878                                 handle_errors(
879                                     &sess.parse_sess,
880                                     meta.span(),
881                                     AttrError::UnknownMetaItem(
882                                         pprust::path_to_string(&mi.path),
883                                         if sess.features_untracked().deprecated_suggestion {
884                                             &["since", "note", "suggestion"]
885                                         } else {
886                                             &["since", "note"]
887                                         },
888                                     ),
889                                 );
890                                 continue 'outer;
891                             }
892                         },
893                         NestedMetaItem::Literal(lit) => {
894                             handle_errors(
895                                 &sess.parse_sess,
896                                 lit.span,
897                                 AttrError::UnsupportedLiteral(
898                                     UnsupportedLiteralReason::DeprecatedKvPair,
899                                     false,
900                                 ),
901                             );
902                             continue 'outer;
903                         }
904                     }
905                 }
906             }
907         }
908
909         if is_rustc {
910             if since.is_none() {
911                 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingSince);
912                 continue;
913             }
914
915             if note.is_none() {
916                 sess.emit_err(session_diagnostics::MissingNote { span: attr.span });
917                 continue;
918             }
919         }
920
921         depr = Some((
922             Deprecation { since, note, suggestion, is_since_rustc_version: is_rustc },
923             attr.span,
924         ));
925     }
926
927     depr
928 }
929
930 #[derive(PartialEq, Debug, Encodable, Decodable, Copy, Clone)]
931 pub enum ReprAttr {
932     ReprInt(IntType),
933     ReprC,
934     ReprPacked(u32),
935     ReprSimd,
936     ReprTransparent,
937     ReprAlign(u32),
938 }
939
940 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
941 #[derive(Encodable, Decodable, HashStable_Generic)]
942 pub enum IntType {
943     SignedInt(ast::IntTy),
944     UnsignedInt(ast::UintTy),
945 }
946
947 impl IntType {
948     #[inline]
949     pub fn is_signed(self) -> bool {
950         use IntType::*;
951
952         match self {
953             SignedInt(..) => true,
954             UnsignedInt(..) => false,
955         }
956     }
957 }
958
959 /// Parse #[repr(...)] forms.
960 ///
961 /// Valid repr contents: any of the primitive integral type names (see
962 /// `int_type_of_word`, below) to specify enum discriminant type; `C`, to use
963 /// the same discriminant size that the corresponding C enum would or C
964 /// structure layout, `packed` to remove padding, and `transparent` to delegate representation
965 /// concerns to the only non-ZST field.
966 pub fn find_repr_attrs(sess: &Session, attr: &Attribute) -> Vec<ReprAttr> {
967     if attr.has_name(sym::repr) { parse_repr_attr(sess, attr) } else { Vec::new() }
968 }
969
970 pub fn parse_repr_attr(sess: &Session, attr: &Attribute) -> Vec<ReprAttr> {
971     assert!(attr.has_name(sym::repr), "expected `#[repr(..)]`, found: {:?}", attr);
972     use ReprAttr::*;
973     let mut acc = Vec::new();
974     let diagnostic = &sess.parse_sess.span_diagnostic;
975
976     if let Some(items) = attr.meta_item_list() {
977         for item in items {
978             let mut recognised = false;
979             if item.is_word() {
980                 let hint = match item.name_or_empty() {
981                     sym::C => Some(ReprC),
982                     sym::packed => Some(ReprPacked(1)),
983                     sym::simd => Some(ReprSimd),
984                     sym::transparent => Some(ReprTransparent),
985                     sym::align => {
986                         sess.emit_err(session_diagnostics::InvalidReprAlignNeedArg {
987                             span: item.span(),
988                         });
989                         recognised = true;
990                         None
991                     }
992                     name => int_type_of_word(name).map(ReprInt),
993                 };
994
995                 if let Some(h) = hint {
996                     recognised = true;
997                     acc.push(h);
998                 }
999             } else if let Some((name, value)) = item.name_value_literal() {
1000                 let mut literal_error = None;
1001                 if name == sym::align {
1002                     recognised = true;
1003                     match parse_alignment(&value.kind) {
1004                         Ok(literal) => acc.push(ReprAlign(literal)),
1005                         Err(message) => literal_error = Some(message),
1006                     };
1007                 } else if name == sym::packed {
1008                     recognised = true;
1009                     match parse_alignment(&value.kind) {
1010                         Ok(literal) => acc.push(ReprPacked(literal)),
1011                         Err(message) => literal_error = Some(message),
1012                     };
1013                 } else if matches!(name, sym::C | sym::simd | sym::transparent)
1014                     || int_type_of_word(name).is_some()
1015                 {
1016                     recognised = true;
1017                     sess.emit_err(session_diagnostics::InvalidReprHintNoParen {
1018                         span: item.span(),
1019                         name: name.to_ident_string(),
1020                     });
1021                 }
1022                 if let Some(literal_error) = literal_error {
1023                     sess.emit_err(session_diagnostics::InvalidReprGeneric {
1024                         span: item.span(),
1025                         repr_arg: name.to_ident_string(),
1026                         error_part: literal_error,
1027                     });
1028                 }
1029             } else if let Some(meta_item) = item.meta_item() {
1030                 if let MetaItemKind::NameValue(ref value) = meta_item.kind {
1031                     if meta_item.has_name(sym::align) || meta_item.has_name(sym::packed) {
1032                         let name = meta_item.name_or_empty().to_ident_string();
1033                         recognised = true;
1034                         sess.emit_err(session_diagnostics::IncorrectReprFormatGeneric {
1035                             span: item.span(),
1036                             repr_arg: &name,
1037                             cause: IncorrectReprFormatGenericCause::from_lit_kind(
1038                                 item.span(),
1039                                 &value.kind,
1040                                 &name,
1041                             ),
1042                         });
1043                     } else {
1044                         if matches!(
1045                             meta_item.name_or_empty(),
1046                             sym::C | sym::simd | sym::transparent
1047                         ) || int_type_of_word(meta_item.name_or_empty()).is_some()
1048                         {
1049                             recognised = true;
1050                             sess.emit_err(session_diagnostics::InvalidReprHintNoValue {
1051                                 span: meta_item.span,
1052                                 name: meta_item.name_or_empty().to_ident_string(),
1053                             });
1054                         }
1055                     }
1056                 } else if let MetaItemKind::List(_) = meta_item.kind {
1057                     if meta_item.has_name(sym::align) {
1058                         recognised = true;
1059                         sess.emit_err(session_diagnostics::IncorrectReprFormatAlignOneArg {
1060                             span: meta_item.span,
1061                         });
1062                     } else if meta_item.has_name(sym::packed) {
1063                         recognised = true;
1064                         sess.emit_err(session_diagnostics::IncorrectReprFormatPackedOneOrZeroArg {
1065                             span: meta_item.span,
1066                         });
1067                     } else if matches!(
1068                         meta_item.name_or_empty(),
1069                         sym::C | sym::simd | sym::transparent
1070                     ) || int_type_of_word(meta_item.name_or_empty()).is_some()
1071                     {
1072                         recognised = true;
1073                         sess.emit_err(session_diagnostics::InvalidReprHintNoParen {
1074                             span: meta_item.span,
1075                             name: meta_item.name_or_empty().to_ident_string(),
1076                         });
1077                     }
1078                 }
1079             }
1080             if !recognised {
1081                 // Not a word we recognize. This will be caught and reported by
1082                 // the `check_mod_attrs` pass, but this pass doesn't always run
1083                 // (e.g. if we only pretty-print the source), so we have to gate
1084                 // the `delay_span_bug` call as follows:
1085                 if sess.opts.pretty.map_or(true, |pp| pp.needs_analysis()) {
1086                     diagnostic.delay_span_bug(item.span(), "unrecognized representation hint");
1087                 }
1088             }
1089         }
1090     }
1091     acc
1092 }
1093
1094 fn int_type_of_word(s: Symbol) -> Option<IntType> {
1095     use IntType::*;
1096
1097     match s {
1098         sym::i8 => Some(SignedInt(ast::IntTy::I8)),
1099         sym::u8 => Some(UnsignedInt(ast::UintTy::U8)),
1100         sym::i16 => Some(SignedInt(ast::IntTy::I16)),
1101         sym::u16 => Some(UnsignedInt(ast::UintTy::U16)),
1102         sym::i32 => Some(SignedInt(ast::IntTy::I32)),
1103         sym::u32 => Some(UnsignedInt(ast::UintTy::U32)),
1104         sym::i64 => Some(SignedInt(ast::IntTy::I64)),
1105         sym::u64 => Some(UnsignedInt(ast::UintTy::U64)),
1106         sym::i128 => Some(SignedInt(ast::IntTy::I128)),
1107         sym::u128 => Some(UnsignedInt(ast::UintTy::U128)),
1108         sym::isize => Some(SignedInt(ast::IntTy::Isize)),
1109         sym::usize => Some(UnsignedInt(ast::UintTy::Usize)),
1110         _ => None,
1111     }
1112 }
1113
1114 pub enum TransparencyError {
1115     UnknownTransparency(Symbol, Span),
1116     MultipleTransparencyAttrs(Span, Span),
1117 }
1118
1119 pub fn find_transparency(
1120     attrs: &[Attribute],
1121     macro_rules: bool,
1122 ) -> (Transparency, Option<TransparencyError>) {
1123     let mut transparency = None;
1124     let mut error = None;
1125     for attr in attrs {
1126         if attr.has_name(sym::rustc_macro_transparency) {
1127             if let Some((_, old_span)) = transparency {
1128                 error = Some(TransparencyError::MultipleTransparencyAttrs(old_span, attr.span));
1129                 break;
1130             } else if let Some(value) = attr.value_str() {
1131                 transparency = Some((
1132                     match value {
1133                         sym::transparent => Transparency::Transparent,
1134                         sym::semitransparent => Transparency::SemiTransparent,
1135                         sym::opaque => Transparency::Opaque,
1136                         _ => {
1137                             error = Some(TransparencyError::UnknownTransparency(value, attr.span));
1138                             continue;
1139                         }
1140                     },
1141                     attr.span,
1142                 ));
1143             }
1144         }
1145     }
1146     let fallback = if macro_rules { Transparency::SemiTransparent } else { Transparency::Opaque };
1147     (transparency.map_or(fallback, |t| t.0), error)
1148 }
1149
1150 pub fn allow_internal_unstable<'a>(
1151     sess: &'a Session,
1152     attrs: &'a [Attribute],
1153 ) -> impl Iterator<Item = Symbol> + 'a {
1154     allow_unstable(sess, attrs, sym::allow_internal_unstable)
1155 }
1156
1157 pub fn rustc_allow_const_fn_unstable<'a>(
1158     sess: &'a Session,
1159     attrs: &'a [Attribute],
1160 ) -> impl Iterator<Item = Symbol> + 'a {
1161     allow_unstable(sess, attrs, sym::rustc_allow_const_fn_unstable)
1162 }
1163
1164 fn allow_unstable<'a>(
1165     sess: &'a Session,
1166     attrs: &'a [Attribute],
1167     symbol: Symbol,
1168 ) -> impl Iterator<Item = Symbol> + 'a {
1169     let attrs = sess.filter_by_name(attrs, symbol);
1170     let list = attrs
1171         .filter_map(move |attr| {
1172             attr.meta_item_list().or_else(|| {
1173                 sess.emit_err(session_diagnostics::ExpectsFeatureList {
1174                     span: attr.span,
1175                     name: symbol.to_ident_string(),
1176                 });
1177                 None
1178             })
1179         })
1180         .flatten();
1181
1182     list.into_iter().filter_map(move |it| {
1183         let name = it.ident().map(|ident| ident.name);
1184         if name.is_none() {
1185             sess.emit_err(session_diagnostics::ExpectsFeatures {
1186                 span: it.span(),
1187                 name: symbol.to_ident_string(),
1188             });
1189         }
1190         name
1191     })
1192 }
1193
1194 pub fn parse_alignment(node: &ast::LitKind) -> Result<u32, &'static str> {
1195     if let ast::LitKind::Int(literal, ast::LitIntType::Unsuffixed) = node {
1196         if literal.is_power_of_two() {
1197             // rustc_middle::ty::layout::Align restricts align to <= 2^29
1198             if *literal <= 1 << 29 { Ok(*literal as u32) } else { Err("larger than 2^29") }
1199         } else {
1200             Err("not a power of two")
1201         }
1202     } else {
1203         Err("not an unsuffixed integer")
1204     }
1205 }