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