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