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