]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_attr/src/builtin.rs
Rollup merge of #97633 - mkroening:object-osabi, r=petrochenkov
[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     ReprNoNiche,
860 }
861
862 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
863 #[derive(Encodable, Decodable, HashStable_Generic)]
864 pub enum IntType {
865     SignedInt(ast::IntTy),
866     UnsignedInt(ast::UintTy),
867 }
868
869 impl IntType {
870     #[inline]
871     pub fn is_signed(self) -> bool {
872         use IntType::*;
873
874         match self {
875             SignedInt(..) => true,
876             UnsignedInt(..) => false,
877         }
878     }
879 }
880
881 /// Parse #[repr(...)] forms.
882 ///
883 /// Valid repr contents: any of the primitive integral type names (see
884 /// `int_type_of_word`, below) to specify enum discriminant type; `C`, to use
885 /// the same discriminant size that the corresponding C enum would or C
886 /// structure layout, `packed` to remove padding, and `transparent` to delegate representation
887 /// concerns to the only non-ZST field.
888 pub fn find_repr_attrs(sess: &Session, attr: &Attribute) -> Vec<ReprAttr> {
889     if attr.has_name(sym::repr) { parse_repr_attr(sess, attr) } else { Vec::new() }
890 }
891
892 pub fn parse_repr_attr(sess: &Session, attr: &Attribute) -> Vec<ReprAttr> {
893     assert!(attr.has_name(sym::repr), "expected `#[repr(..)]`, found: {:?}", attr);
894     use ReprAttr::*;
895     let mut acc = Vec::new();
896     let diagnostic = &sess.parse_sess.span_diagnostic;
897
898     if let Some(items) = attr.meta_item_list() {
899         for item in items {
900             let mut recognised = false;
901             if item.is_word() {
902                 let hint = match item.name_or_empty() {
903                     sym::C => Some(ReprC),
904                     sym::packed => Some(ReprPacked(1)),
905                     sym::simd => Some(ReprSimd),
906                     sym::transparent => Some(ReprTransparent),
907                     sym::no_niche => Some(ReprNoNiche),
908                     sym::align => {
909                         let mut err = struct_span_err!(
910                             diagnostic,
911                             item.span(),
912                             E0589,
913                             "invalid `repr(align)` attribute: `align` needs an argument"
914                         );
915                         err.span_suggestion(
916                             item.span(),
917                             "supply an argument here",
918                             "align(...)",
919                             Applicability::HasPlaceholders,
920                         );
921                         err.emit();
922                         recognised = true;
923                         None
924                     }
925                     name => int_type_of_word(name).map(ReprInt),
926                 };
927
928                 if let Some(h) = hint {
929                     recognised = true;
930                     acc.push(h);
931                 }
932             } else if let Some((name, value)) = item.name_value_literal() {
933                 let mut literal_error = None;
934                 if name == sym::align {
935                     recognised = true;
936                     match parse_alignment(&value.kind) {
937                         Ok(literal) => acc.push(ReprAlign(literal)),
938                         Err(message) => literal_error = Some(message),
939                     };
940                 } else if name == sym::packed {
941                     recognised = true;
942                     match parse_alignment(&value.kind) {
943                         Ok(literal) => acc.push(ReprPacked(literal)),
944                         Err(message) => literal_error = Some(message),
945                     };
946                 } else if matches!(name, sym::C | sym::simd | sym::transparent | sym::no_niche)
947                     || int_type_of_word(name).is_some()
948                 {
949                     recognised = true;
950                     struct_span_err!(
951                                 diagnostic,
952                                 item.span(),
953                                 E0552,
954                                 "invalid representation hint: `{}` does not take a parenthesized argument list",
955                                 name.to_ident_string(),
956                             ).emit();
957                 }
958                 if let Some(literal_error) = literal_error {
959                     struct_span_err!(
960                         diagnostic,
961                         item.span(),
962                         E0589,
963                         "invalid `repr({})` attribute: {}",
964                         name.to_ident_string(),
965                         literal_error
966                     )
967                     .emit();
968                 }
969             } else if let Some(meta_item) = item.meta_item() {
970                 if let MetaItemKind::NameValue(ref value) = meta_item.kind {
971                     if meta_item.has_name(sym::align) || meta_item.has_name(sym::packed) {
972                         let name = meta_item.name_or_empty().to_ident_string();
973                         recognised = true;
974                         let mut err = struct_span_err!(
975                             diagnostic,
976                             item.span(),
977                             E0693,
978                             "incorrect `repr({})` attribute format",
979                             name,
980                         );
981                         match value.kind {
982                             ast::LitKind::Int(int, ast::LitIntType::Unsuffixed) => {
983                                 err.span_suggestion(
984                                     item.span(),
985                                     "use parentheses instead",
986                                     format!("{}({})", name, int),
987                                     Applicability::MachineApplicable,
988                                 );
989                             }
990                             ast::LitKind::Str(s, _) => {
991                                 err.span_suggestion(
992                                     item.span(),
993                                     "use parentheses instead",
994                                     format!("{}({})", name, s),
995                                     Applicability::MachineApplicable,
996                                 );
997                             }
998                             _ => {}
999                         }
1000                         err.emit();
1001                     } else {
1002                         if matches!(
1003                             meta_item.name_or_empty(),
1004                             sym::C | sym::simd | sym::transparent | sym::no_niche
1005                         ) || int_type_of_word(meta_item.name_or_empty()).is_some()
1006                         {
1007                             recognised = true;
1008                             struct_span_err!(
1009                                 diagnostic,
1010                                 meta_item.span,
1011                                 E0552,
1012                                 "invalid representation hint: `{}` does not take a value",
1013                                 meta_item.name_or_empty().to_ident_string(),
1014                             )
1015                             .emit();
1016                         }
1017                     }
1018                 } else if let MetaItemKind::List(_) = meta_item.kind {
1019                     if meta_item.has_name(sym::align) {
1020                         recognised = true;
1021                         struct_span_err!(
1022                             diagnostic,
1023                             meta_item.span,
1024                             E0693,
1025                             "incorrect `repr(align)` attribute format: \
1026                                  `align` takes exactly one argument in parentheses"
1027                         )
1028                         .emit();
1029                     } else if meta_item.has_name(sym::packed) {
1030                         recognised = true;
1031                         struct_span_err!(
1032                             diagnostic,
1033                             meta_item.span,
1034                             E0552,
1035                             "incorrect `repr(packed)` attribute format: \
1036                                  `packed` takes exactly one parenthesized argument, \
1037                                  or no parentheses at all"
1038                         )
1039                         .emit();
1040                     } else if matches!(
1041                         meta_item.name_or_empty(),
1042                         sym::C | sym::simd | sym::transparent | sym::no_niche
1043                     ) || int_type_of_word(meta_item.name_or_empty()).is_some()
1044                     {
1045                         recognised = true;
1046                         struct_span_err!(
1047                                 diagnostic,
1048                                 meta_item.span,
1049                                 E0552,
1050                                 "invalid representation hint: `{}` does not take a parenthesized argument list",
1051                                 meta_item.name_or_empty().to_ident_string(),
1052                             ).emit();
1053                     }
1054                 }
1055             }
1056             if !recognised {
1057                 // Not a word we recognize. This will be caught and reported by
1058                 // the `check_mod_attrs` pass, but this pass doesn't always run
1059                 // (e.g. if we only pretty-print the source), so we have to gate
1060                 // the `delay_span_bug` call as follows:
1061                 if sess.opts.pretty.map_or(true, |pp| pp.needs_analysis()) {
1062                     diagnostic.delay_span_bug(item.span(), "unrecognized representation hint");
1063                 }
1064             }
1065         }
1066     }
1067     acc
1068 }
1069
1070 fn int_type_of_word(s: Symbol) -> Option<IntType> {
1071     use IntType::*;
1072
1073     match s {
1074         sym::i8 => Some(SignedInt(ast::IntTy::I8)),
1075         sym::u8 => Some(UnsignedInt(ast::UintTy::U8)),
1076         sym::i16 => Some(SignedInt(ast::IntTy::I16)),
1077         sym::u16 => Some(UnsignedInt(ast::UintTy::U16)),
1078         sym::i32 => Some(SignedInt(ast::IntTy::I32)),
1079         sym::u32 => Some(UnsignedInt(ast::UintTy::U32)),
1080         sym::i64 => Some(SignedInt(ast::IntTy::I64)),
1081         sym::u64 => Some(UnsignedInt(ast::UintTy::U64)),
1082         sym::i128 => Some(SignedInt(ast::IntTy::I128)),
1083         sym::u128 => Some(UnsignedInt(ast::UintTy::U128)),
1084         sym::isize => Some(SignedInt(ast::IntTy::Isize)),
1085         sym::usize => Some(UnsignedInt(ast::UintTy::Usize)),
1086         _ => None,
1087     }
1088 }
1089
1090 pub enum TransparencyError {
1091     UnknownTransparency(Symbol, Span),
1092     MultipleTransparencyAttrs(Span, Span),
1093 }
1094
1095 pub fn find_transparency(
1096     attrs: &[Attribute],
1097     macro_rules: bool,
1098 ) -> (Transparency, Option<TransparencyError>) {
1099     let mut transparency = None;
1100     let mut error = None;
1101     for attr in attrs {
1102         if attr.has_name(sym::rustc_macro_transparency) {
1103             if let Some((_, old_span)) = transparency {
1104                 error = Some(TransparencyError::MultipleTransparencyAttrs(old_span, attr.span));
1105                 break;
1106             } else if let Some(value) = attr.value_str() {
1107                 transparency = Some((
1108                     match value {
1109                         sym::transparent => Transparency::Transparent,
1110                         sym::semitransparent => Transparency::SemiTransparent,
1111                         sym::opaque => Transparency::Opaque,
1112                         _ => {
1113                             error = Some(TransparencyError::UnknownTransparency(value, attr.span));
1114                             continue;
1115                         }
1116                     },
1117                     attr.span,
1118                 ));
1119             }
1120         }
1121     }
1122     let fallback = if macro_rules { Transparency::SemiTransparent } else { Transparency::Opaque };
1123     (transparency.map_or(fallback, |t| t.0), error)
1124 }
1125
1126 pub fn allow_internal_unstable<'a>(
1127     sess: &'a Session,
1128     attrs: &'a [Attribute],
1129 ) -> impl Iterator<Item = Symbol> + 'a {
1130     allow_unstable(sess, attrs, sym::allow_internal_unstable)
1131 }
1132
1133 pub fn rustc_allow_const_fn_unstable<'a>(
1134     sess: &'a Session,
1135     attrs: &'a [Attribute],
1136 ) -> impl Iterator<Item = Symbol> + 'a {
1137     allow_unstable(sess, attrs, sym::rustc_allow_const_fn_unstable)
1138 }
1139
1140 fn allow_unstable<'a>(
1141     sess: &'a Session,
1142     attrs: &'a [Attribute],
1143     symbol: Symbol,
1144 ) -> impl Iterator<Item = Symbol> + 'a {
1145     let attrs = sess.filter_by_name(attrs, symbol);
1146     let list = attrs
1147         .filter_map(move |attr| {
1148             attr.meta_item_list().or_else(|| {
1149                 sess.diagnostic().span_err(
1150                     attr.span,
1151                     &format!("`{}` expects a list of feature names", symbol.to_ident_string()),
1152                 );
1153                 None
1154             })
1155         })
1156         .flatten();
1157
1158     list.into_iter().filter_map(move |it| {
1159         let name = it.ident().map(|ident| ident.name);
1160         if name.is_none() {
1161             sess.diagnostic().span_err(
1162                 it.span(),
1163                 &format!("`{}` expects feature names", symbol.to_ident_string()),
1164             );
1165         }
1166         name
1167     })
1168 }
1169
1170 pub fn parse_alignment(node: &ast::LitKind) -> Result<u32, &'static str> {
1171     if let ast::LitKind::Int(literal, ast::LitIntType::Unsuffixed) = node {
1172         if literal.is_power_of_two() {
1173             // rustc_middle::ty::layout::Align restricts align to <= 2^29
1174             if *literal <= 1 << 29 { Ok(*literal as u32) } else { Err("larger than 2^29") }
1175         } else {
1176             Err("not a power of two")
1177         }
1178     } else {
1179         Err("not an unsuffixed integer")
1180     }
1181 }