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