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