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