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