1 //! Parsing and validation of builtin attributes
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;
17 use crate::session_diagnostics;
19 pub fn is_builtin_attr(attr: &Attribute) -> bool {
20 attr.is_doc_comment() || attr.ident().filter(|ident| is_builtin_attr_name(ident.name)).is_some()
25 UnknownMetaItem(String, &'static [&'static str]),
29 MultipleStabilityLevels,
30 UnsupportedLiteral(UnsupportedLiteralReason, /* is_bytestr */ bool),
33 pub(crate) enum UnsupportedLiteralReason {
40 fn handle_errors(sess: &ParseSess, span: Span, error: AttrError) {
42 AttrError::MultipleItem(item) => {
43 sess.emit_err(session_diagnostics::MultipleItem { span, item });
45 AttrError::UnknownMetaItem(item, expected) => {
46 sess.emit_err(session_diagnostics::UnknownMetaItem { span, item, expected });
48 AttrError::MissingSince => {
49 sess.emit_err(session_diagnostics::MissingSince { span });
51 AttrError::NonIdentFeature => {
52 sess.emit_err(session_diagnostics::NonIdentFeature { span });
54 AttrError::MissingFeature => {
55 sess.emit_err(session_diagnostics::MissingFeature { span });
57 AttrError::MultipleStabilityLevels => {
58 sess.emit_err(session_diagnostics::MultipleStabilityLevels { span });
60 AttrError::UnsupportedLiteral(reason, is_bytestr) => {
61 sess.emit_err(session_diagnostics::UnsupportedLiteral { span, reason, is_bytestr });
66 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
74 #[derive(Clone, Encodable, Decodable, Debug, PartialEq, Eq, HashStable_Generic)]
75 pub enum InstructionSetAttr {
80 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
81 pub enum OptimizeAttr {
87 /// Represents the following attributes:
91 #[derive(Encodable, Decodable, Copy, Clone, Debug, PartialEq, Eq, Hash)]
92 #[derive(HashStable_Generic)]
93 pub struct Stability {
94 pub level: StabilityLevel,
99 pub fn is_unstable(&self) -> bool {
100 self.level.is_unstable()
103 pub fn is_stable(&self) -> bool {
104 self.level.is_stable()
108 /// Represents the `#[rustc_const_unstable]` and `#[rustc_const_stable]` attributes.
109 #[derive(Encodable, Decodable, Copy, Clone, Debug, PartialEq, Eq, Hash)]
110 #[derive(HashStable_Generic)]
111 pub struct ConstStability {
112 pub level: StabilityLevel,
114 /// whether the function has a `#[rustc_promotable]` attribute
115 pub promotable: bool,
118 impl ConstStability {
119 pub fn is_const_unstable(&self) -> bool {
120 self.level.is_unstable()
123 pub fn is_const_stable(&self) -> bool {
124 self.level.is_stable()
128 /// Represents the `#[rustc_default_body_unstable]` attribute.
129 #[derive(Encodable, Decodable, Copy, Clone, Debug, PartialEq, Eq, Hash)]
130 #[derive(HashStable_Generic)]
131 pub struct DefaultBodyStability {
132 pub level: StabilityLevel,
136 /// The available stability levels.
137 #[derive(Encodable, Decodable, PartialEq, Copy, Clone, Debug, Eq, Hash)]
138 #[derive(HashStable_Generic)]
139 pub enum StabilityLevel {
142 /// Reason for the current stability level.
143 reason: UnstableReason,
144 /// Relevant `rust-lang/rust` issue.
145 issue: Option<NonZeroU32>,
147 /// If part of a feature is stabilized and a new feature is added for the remaining parts,
148 /// then the `implied_by` attribute is used to indicate which now-stable feature previously
149 /// contained a item.
152 /// #[unstable(feature = "foo", issue = "...")]
154 /// #[unstable(feature = "foo", issue = "...")]
161 /// #[stable(feature = "foo", since = "1.XX.X")]
163 /// #[unstable(feature = "foobar", issue = "...", implied_by = "foo")]
166 implied_by: Option<Symbol>,
170 /// Rust release which stabilized this feature.
172 /// Is this item allowed to be referred to on stable, despite being contained in unstable
174 allowed_through_unstable_modules: bool,
178 impl StabilityLevel {
179 pub fn is_unstable(&self) -> bool {
180 matches!(self, StabilityLevel::Unstable { .. })
182 pub fn is_stable(&self) -> bool {
183 matches!(self, StabilityLevel::Stable { .. })
187 #[derive(Encodable, Decodable, PartialEq, Copy, Clone, Debug, Eq, Hash)]
188 #[derive(HashStable_Generic)]
189 pub enum UnstableReason {
195 impl UnstableReason {
196 fn from_opt_reason(reason: Option<Symbol>) -> Self {
197 // UnstableReason::Default constructed manually
199 Some(r) => Self::Some(r),
204 pub fn to_opt_reason(&self) -> Option<Symbol> {
207 Self::Default => Some(sym::unstable_location_reason_default),
208 Self::Some(r) => Some(*r),
213 /// Collects stability info from all stability attributes in `attrs`.
214 /// Returns `None` if no stability attributes are found.
215 pub fn find_stability(
219 ) -> (Option<(Stability, Span)>, Option<(ConstStability, Span)>, Option<(DefaultBodyStability, Span)>)
221 find_stability_generic(sess, attrs.iter(), item_sp)
224 fn find_stability_generic<'a, I>(
228 ) -> (Option<(Stability, Span)>, Option<(ConstStability, Span)>, Option<(DefaultBodyStability, Span)>)
230 I: Iterator<Item = &'a Attribute>,
232 use StabilityLevel::*;
234 let mut stab: Option<(Stability, Span)> = None;
235 let mut const_stab: Option<(ConstStability, Span)> = None;
236 let mut body_stab: Option<(DefaultBodyStability, Span)> = None;
237 let mut promotable = false;
238 let mut allowed_through_unstable_modules = false;
240 let diagnostic = &sess.parse_sess.span_diagnostic;
242 'outer: for attr in attrs_iter {
244 sym::rustc_const_unstable,
245 sym::rustc_const_stable,
248 sym::rustc_promotable,
249 sym::rustc_allowed_through_unstable_modules,
250 sym::rustc_default_body_unstable,
253 .any(|&s| attr.has_name(s))
255 continue; // not a stability level
258 let meta = attr.meta();
260 if attr.has_name(sym::rustc_promotable) {
262 } else if attr.has_name(sym::rustc_allowed_through_unstable_modules) {
263 allowed_through_unstable_modules = true;
265 // attributes with data
266 else if let Some(MetaItem { kind: MetaItemKind::List(ref metas), .. }) = meta {
267 let meta = meta.as_ref().unwrap();
268 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
273 AttrError::MultipleItem(pprust::path_to_string(&meta.path)),
277 if let Some(v) = meta.value_str() {
281 struct_span_err!(diagnostic, meta.span, E0539, "incorrect meta item").emit();
286 let meta_name = meta.name_or_empty();
288 sym::rustc_const_unstable | sym::rustc_default_body_unstable | sym::unstable => {
289 if meta_name == sym::unstable && stab.is_some() {
293 AttrError::MultipleStabilityLevels,
296 } else if meta_name == sym::rustc_const_unstable && const_stab.is_some() {
300 AttrError::MultipleStabilityLevels,
303 } else if meta_name == sym::rustc_default_body_unstable && body_stab.is_some() {
307 AttrError::MultipleStabilityLevels,
312 let mut feature = None;
313 let mut reason = None;
314 let mut issue = None;
315 let mut issue_num = None;
316 let mut is_soft = false;
317 let mut implied_by = None;
319 let Some(mi) = meta.meta_item() else {
323 AttrError::UnsupportedLiteral(UnsupportedLiteralReason::Generic, false),
327 match mi.name_or_empty() {
329 if !get(mi, &mut feature) {
334 if !get(mi, &mut reason) {
339 if !get(mi, &mut issue) {
343 // These unwraps are safe because `get` ensures the meta item
344 // is a name/value pair string literal.
345 issue_num = match issue.unwrap().as_str() {
348 let emit_diag = |msg: &str| {
353 "`issue` must be a non-zero numeric string \
356 .span_label(mi.name_value_literal_span().unwrap(), msg)
359 match issue.parse() {
362 "`issue` must not be \"0\", \
363 use \"none\" instead",
367 Ok(num) => NonZeroU32::new(num),
369 emit_diag(&err.to_string());
378 let msg = "`soft` should not have any arguments";
379 sess.parse_sess.span_diagnostic.span_err(mi.span, msg);
384 if !get(mi, &mut implied_by) {
392 AttrError::UnknownMetaItem(
393 pprust::path_to_string(&mi.path),
394 &["feature", "reason", "issue", "soft"],
402 match (feature, reason, issue) {
403 (Some(feature), reason, Some(_)) => {
404 if !rustc_lexer::is_ident(feature.as_str()) {
408 AttrError::NonIdentFeature,
412 let level = Unstable {
413 reason: UnstableReason::from_opt_reason(reason),
418 if sym::unstable == meta_name {
419 stab = Some((Stability { level, feature }, attr.span));
420 } else if sym::rustc_const_unstable == meta_name {
422 ConstStability { level, feature, promotable: false },
425 } else if sym::rustc_default_body_unstable == meta_name {
427 Some((DefaultBodyStability { level, feature }, attr.span));
429 unreachable!("Unknown stability attribute {meta_name}");
433 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingFeature);
437 struct_span_err!(diagnostic, attr.span, E0547, "missing 'issue'")
443 sym::rustc_const_stable | sym::stable => {
444 if meta_name == sym::stable && stab.is_some() {
448 AttrError::MultipleStabilityLevels,
451 } else if meta_name == sym::rustc_const_stable && const_stab.is_some() {
455 AttrError::MultipleStabilityLevels,
460 let mut feature = None;
461 let mut since = None;
464 NestedMetaItem::MetaItem(mi) => match mi.name_or_empty() {
466 if !get(mi, &mut feature) {
471 if !get(mi, &mut since) {
479 AttrError::UnknownMetaItem(
480 pprust::path_to_string(&mi.path),
481 &["feature", "since"],
487 NestedMetaItem::Literal(lit) => {
491 AttrError::UnsupportedLiteral(
492 UnsupportedLiteralReason::Generic,
501 match (feature, since) {
502 (Some(feature), Some(since)) => {
503 let level = Stable { since, allowed_through_unstable_modules: false };
504 if sym::stable == meta_name {
505 stab = Some((Stability { level, feature }, attr.span));
508 ConstStability { level, feature, promotable: false },
514 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingFeature);
518 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingSince);
528 // Merge the const-unstable info into the stability info
530 if let Some((ref mut stab, _)) = const_stab {
531 stab.promotable = promotable;
537 "`rustc_promotable` attribute must be paired with either a `rustc_const_unstable` \
538 or a `rustc_const_stable` attribute"
544 if allowed_through_unstable_modules {
547 level: StabilityLevel::Stable { ref mut allowed_through_unstable_modules, .. },
553 *allowed_through_unstable_modules = true;
559 "`rustc_allowed_through_unstable_modules` attribute must be paired with a `stable` attribute"
565 (stab, const_stab, body_stab)
568 pub fn find_crate_name(sess: &Session, attrs: &[Attribute]) -> Option<Symbol> {
569 sess.first_attr_value_str_by_name(attrs, sym::crate_name)
572 #[derive(Clone, Debug)]
573 pub struct Condition {
576 pub value: Option<Symbol>,
577 pub value_span: Option<Span>,
581 /// Tests if a cfg-pattern matches the cfg set
585 lint_node_id: NodeId,
586 features: Option<&Features>,
588 eval_condition(cfg, sess, features, &mut |cfg| {
589 try_gate_cfg(cfg.name, cfg.span, sess, features);
590 if let Some(names_valid) = &sess.check_config.names_valid {
591 if !names_valid.contains(&cfg.name) {
592 sess.buffer_lint_with_diagnostic(
596 "unexpected `cfg` condition name",
597 BuiltinLintDiagnostics::UnexpectedCfg((cfg.name, cfg.name_span), None),
601 if let Some(value) = cfg.value {
602 if let Some(values) = &sess.check_config.values_valid.get(&cfg.name) {
603 if !values.contains(&value) {
604 sess.buffer_lint_with_diagnostic(
608 "unexpected `cfg` condition value",
609 BuiltinLintDiagnostics::UnexpectedCfg(
610 (cfg.name, cfg.name_span),
611 cfg.value_span.map(|vs| (value, vs)),
617 sess.config.contains(&(cfg.name, cfg.value))
621 fn try_gate_cfg(name: Symbol, span: Span, sess: &ParseSess, features: Option<&Features>) {
622 let gate = find_gated_cfg(|sym| sym == name);
623 if let (Some(feats), Some(gated_cfg)) = (features, gate) {
624 gate_cfg(&gated_cfg, span, sess, feats);
628 fn gate_cfg(gated_cfg: &GatedCfg, cfg_span: Span, sess: &ParseSess, features: &Features) {
629 let (cfg, feature, has_feature) = gated_cfg;
630 if !has_feature(features) && !cfg_span.allows_unstable(*feature) {
631 let explain = format!("`cfg({})` is experimental and subject to change", cfg);
632 feature_err(sess, *feature, cfg_span, &explain).emit();
636 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
643 fn parse_version(s: &str, allow_appendix: bool) -> Option<Version> {
644 let mut components = s.split('-');
645 let d = components.next()?;
646 if !allow_appendix && components.next().is_some() {
649 let mut digits = d.splitn(3, '.');
650 let major = digits.next()?.parse().ok()?;
651 let minor = digits.next()?.parse().ok()?;
652 let patch = digits.next().unwrap_or("0").parse().ok()?;
653 Some(Version { major, minor, patch })
656 /// Evaluate a cfg-like condition (with `any` and `all`), using `eval` to
657 /// evaluate individual items.
658 pub fn eval_condition(
661 features: Option<&Features>,
662 eval: &mut impl FnMut(Condition) -> bool,
665 ast::MetaItemKind::List(ref mis) if cfg.name_or_empty() == sym::version => {
666 try_gate_cfg(sym::version, cfg.span, sess, features);
667 let (min_version, span) = match &mis[..] {
668 [NestedMetaItem::Literal(Lit { kind: LitKind::Str(sym, ..), span, .. })] => {
672 NestedMetaItem::Literal(Lit { span, .. })
673 | NestedMetaItem::MetaItem(MetaItem { span, .. }),
676 .struct_span_err(*span, "expected a version literal")
682 .struct_span_err(cfg.span, "expected single version literal")
687 let Some(min_version) = parse_version(min_version.as_str(), false) else {
691 "unknown version literal format, assuming it refers to a future version",
696 let rustc_version = parse_version(env!("CFG_RELEASE"), true).unwrap();
698 // See https://github.com/rust-lang/rust/issues/64796#issuecomment-640851454 for details
699 if sess.assume_incomplete_release {
700 rustc_version > min_version
702 rustc_version >= min_version
705 ast::MetaItemKind::List(ref mis) => {
706 for mi in mis.iter() {
707 if !mi.is_meta_item() {
711 AttrError::UnsupportedLiteral(UnsupportedLiteralReason::Generic, false),
717 // The unwraps below may look dangerous, but we've already asserted
718 // that they won't fail with the loop above.
719 match cfg.name_or_empty() {
722 // We don't use any() here, because we want to evaluate all cfg condition
723 // as eval_condition can (and does) extra checks
724 .fold(false, |res, mi| {
725 res | eval_condition(mi.meta_item().unwrap(), sess, features, eval)
729 // We don't use all() here, because we want to evaluate all cfg condition
730 // as eval_condition can (and does) extra checks
731 .fold(true, |res, mi| {
732 res & eval_condition(mi.meta_item().unwrap(), sess, features, eval)
737 sess.span_diagnostic,
740 "expected 1 cfg-pattern"
746 !eval_condition(mis[0].meta_item().unwrap(), sess, features, eval)
749 if let Some(features) = features && !features.cfg_target_compact {
752 sym::cfg_target_compact,
754 &"compact `cfg(target(..))` is experimental and subject to change"
758 mis.iter().fold(true, |res, mi| {
759 let mut mi = mi.meta_item().unwrap().clone();
760 if let [seg, ..] = &mut mi.path.segments[..] {
761 seg.ident.name = Symbol::intern(&format!("target_{}", seg.ident.name));
764 res & eval_condition(&mi, sess, features, eval)
769 sess.span_diagnostic,
772 "invalid predicate `{}`",
773 pprust::path_to_string(&cfg.path)
780 ast::MetaItemKind::Word | MetaItemKind::NameValue(..) if cfg.path.segments.len() != 1 => {
782 .span_err(cfg.path.span, "`cfg` predicate key must be an identifier");
785 MetaItemKind::NameValue(ref lit) if !lit.kind.is_str() => {
789 AttrError::UnsupportedLiteral(
790 UnsupportedLiteralReason::CfgString,
791 lit.kind.is_bytestr(),
796 ast::MetaItemKind::Word | ast::MetaItemKind::NameValue(..) => {
797 let ident = cfg.ident().expect("multi-segment cfg predicate");
800 name_span: ident.span,
801 value: cfg.value_str(),
802 value_span: cfg.name_value_literal_span(),
809 #[derive(Copy, Debug, Encodable, Decodable, Clone, HashStable_Generic)]
810 pub struct Deprecation {
811 pub since: Option<Symbol>,
812 /// The note to issue a reason.
813 pub note: Option<Symbol>,
814 /// A text snippet used to completely replace any use of the deprecated item in an expression.
816 /// This is currently unstable.
817 pub suggestion: Option<Symbol>,
819 /// Whether to treat the since attribute as being a Rust version identifier
820 /// (rather than an opaque string).
821 pub is_since_rustc_version: bool,
824 /// Finds the deprecation attribute. `None` if none exists.
825 pub fn find_deprecation(sess: &Session, attrs: &[Attribute]) -> Option<(Deprecation, Span)> {
826 find_deprecation_generic(sess, attrs.iter())
829 fn find_deprecation_generic<'a, I>(sess: &Session, attrs_iter: I) -> Option<(Deprecation, Span)>
831 I: Iterator<Item = &'a Attribute>,
833 let mut depr: Option<(Deprecation, Span)> = None;
834 let diagnostic = &sess.parse_sess.span_diagnostic;
835 let is_rustc = sess.features_untracked().staged_api;
837 'outer: for attr in attrs_iter {
838 if !attr.has_name(sym::deprecated) {
842 let Some(meta) = attr.meta() else {
845 let mut since = None;
847 let mut suggestion = None;
849 MetaItemKind::Word => {}
850 MetaItemKind::NameValue(..) => note = meta.value_str(),
851 MetaItemKind::List(list) => {
852 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
857 AttrError::MultipleItem(pprust::path_to_string(&meta.path)),
861 if let Some(v) = meta.value_str() {
865 if let Some(lit) = meta.name_value_literal() {
869 AttrError::UnsupportedLiteral(
870 UnsupportedLiteralReason::DeprecatedString,
871 lit.kind.is_bytestr(),
875 struct_span_err!(diagnostic, meta.span, E0551, "incorrect meta item")
885 NestedMetaItem::MetaItem(mi) => match mi.name_or_empty() {
887 if !get(mi, &mut since) {
892 if !get(mi, &mut note) {
897 if !sess.features_untracked().deprecated_suggestion {
898 let mut diag = sess.struct_span_err(
900 "suggestions on deprecated items are unstable",
902 if sess.is_nightly_build() {
903 diag.help("add `#![feature(deprecated_suggestion)]` to the crate root");
905 diag.note("see #94785 for more details").emit();
908 if !get(mi, &mut suggestion) {
916 AttrError::UnknownMetaItem(
917 pprust::path_to_string(&mi.path),
918 if sess.features_untracked().deprecated_suggestion {
919 &["since", "note", "suggestion"]
928 NestedMetaItem::Literal(lit) => {
932 AttrError::UnsupportedLiteral(
933 UnsupportedLiteralReason::DeprecatedKvPair,
946 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingSince);
951 struct_span_err!(diagnostic, attr.span, E0543, "missing 'note'").emit();
957 Deprecation { since, note, suggestion, is_since_rustc_version: is_rustc },
965 #[derive(PartialEq, Debug, Encodable, Decodable, Copy, Clone)]
975 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
976 #[derive(Encodable, Decodable, HashStable_Generic)]
978 SignedInt(ast::IntTy),
979 UnsignedInt(ast::UintTy),
984 pub fn is_signed(self) -> bool {
988 SignedInt(..) => true,
989 UnsignedInt(..) => false,
994 /// Parse #[repr(...)] forms.
996 /// Valid repr contents: any of the primitive integral type names (see
997 /// `int_type_of_word`, below) to specify enum discriminant type; `C`, to use
998 /// the same discriminant size that the corresponding C enum would or C
999 /// structure layout, `packed` to remove padding, and `transparent` to delegate representation
1000 /// concerns to the only non-ZST field.
1001 pub fn find_repr_attrs(sess: &Session, attr: &Attribute) -> Vec<ReprAttr> {
1002 if attr.has_name(sym::repr) { parse_repr_attr(sess, attr) } else { Vec::new() }
1005 pub fn parse_repr_attr(sess: &Session, attr: &Attribute) -> Vec<ReprAttr> {
1006 assert!(attr.has_name(sym::repr), "expected `#[repr(..)]`, found: {:?}", attr);
1008 let mut acc = Vec::new();
1009 let diagnostic = &sess.parse_sess.span_diagnostic;
1011 if let Some(items) = attr.meta_item_list() {
1013 let mut recognised = false;
1015 let hint = match item.name_or_empty() {
1016 sym::C => Some(ReprC),
1017 sym::packed => Some(ReprPacked(1)),
1018 sym::simd => Some(ReprSimd),
1019 sym::transparent => Some(ReprTransparent),
1021 let mut err = struct_span_err!(
1025 "invalid `repr(align)` attribute: `align` needs an argument"
1027 err.span_suggestion(
1029 "supply an argument here",
1031 Applicability::HasPlaceholders,
1037 name => int_type_of_word(name).map(ReprInt),
1040 if let Some(h) = hint {
1044 } else if let Some((name, value)) = item.name_value_literal() {
1045 let mut literal_error = None;
1046 if name == sym::align {
1048 match parse_alignment(&value.kind) {
1049 Ok(literal) => acc.push(ReprAlign(literal)),
1050 Err(message) => literal_error = Some(message),
1052 } else if name == sym::packed {
1054 match parse_alignment(&value.kind) {
1055 Ok(literal) => acc.push(ReprPacked(literal)),
1056 Err(message) => literal_error = Some(message),
1058 } else if matches!(name, sym::C | sym::simd | sym::transparent)
1059 || int_type_of_word(name).is_some()
1066 "invalid representation hint: `{}` does not take a parenthesized argument list",
1067 name.to_ident_string(),
1070 if let Some(literal_error) = literal_error {
1075 "invalid `repr({})` attribute: {}",
1076 name.to_ident_string(),
1081 } else if let Some(meta_item) = item.meta_item() {
1082 if let MetaItemKind::NameValue(ref value) = meta_item.kind {
1083 if meta_item.has_name(sym::align) || meta_item.has_name(sym::packed) {
1084 let name = meta_item.name_or_empty().to_ident_string();
1086 let mut err = struct_span_err!(
1090 "incorrect `repr({})` attribute format",
1094 ast::LitKind::Int(int, ast::LitIntType::Unsuffixed) => {
1095 err.span_suggestion(
1097 "use parentheses instead",
1098 format!("{}({})", name, int),
1099 Applicability::MachineApplicable,
1102 ast::LitKind::Str(s, _) => {
1103 err.span_suggestion(
1105 "use parentheses instead",
1106 format!("{}({})", name, s),
1107 Applicability::MachineApplicable,
1115 meta_item.name_or_empty(),
1116 sym::C | sym::simd | sym::transparent
1117 ) || int_type_of_word(meta_item.name_or_empty()).is_some()
1124 "invalid representation hint: `{}` does not take a value",
1125 meta_item.name_or_empty().to_ident_string(),
1130 } else if let MetaItemKind::List(_) = meta_item.kind {
1131 if meta_item.has_name(sym::align) {
1137 "incorrect `repr(align)` attribute format: \
1138 `align` takes exactly one argument in parentheses"
1141 } else if meta_item.has_name(sym::packed) {
1147 "incorrect `repr(packed)` attribute format: \
1148 `packed` takes exactly one parenthesized argument, \
1149 or no parentheses at all"
1153 meta_item.name_or_empty(),
1154 sym::C | sym::simd | sym::transparent
1155 ) || int_type_of_word(meta_item.name_or_empty()).is_some()
1162 "invalid representation hint: `{}` does not take a parenthesized argument list",
1163 meta_item.name_or_empty().to_ident_string(),
1169 // Not a word we recognize. This will be caught and reported by
1170 // the `check_mod_attrs` pass, but this pass doesn't always run
1171 // (e.g. if we only pretty-print the source), so we have to gate
1172 // the `delay_span_bug` call as follows:
1173 if sess.opts.pretty.map_or(true, |pp| pp.needs_analysis()) {
1174 diagnostic.delay_span_bug(item.span(), "unrecognized representation hint");
1182 fn int_type_of_word(s: Symbol) -> Option<IntType> {
1186 sym::i8 => Some(SignedInt(ast::IntTy::I8)),
1187 sym::u8 => Some(UnsignedInt(ast::UintTy::U8)),
1188 sym::i16 => Some(SignedInt(ast::IntTy::I16)),
1189 sym::u16 => Some(UnsignedInt(ast::UintTy::U16)),
1190 sym::i32 => Some(SignedInt(ast::IntTy::I32)),
1191 sym::u32 => Some(UnsignedInt(ast::UintTy::U32)),
1192 sym::i64 => Some(SignedInt(ast::IntTy::I64)),
1193 sym::u64 => Some(UnsignedInt(ast::UintTy::U64)),
1194 sym::i128 => Some(SignedInt(ast::IntTy::I128)),
1195 sym::u128 => Some(UnsignedInt(ast::UintTy::U128)),
1196 sym::isize => Some(SignedInt(ast::IntTy::Isize)),
1197 sym::usize => Some(UnsignedInt(ast::UintTy::Usize)),
1202 pub enum TransparencyError {
1203 UnknownTransparency(Symbol, Span),
1204 MultipleTransparencyAttrs(Span, Span),
1207 pub fn find_transparency(
1208 attrs: &[Attribute],
1210 ) -> (Transparency, Option<TransparencyError>) {
1211 let mut transparency = None;
1212 let mut error = None;
1214 if attr.has_name(sym::rustc_macro_transparency) {
1215 if let Some((_, old_span)) = transparency {
1216 error = Some(TransparencyError::MultipleTransparencyAttrs(old_span, attr.span));
1218 } else if let Some(value) = attr.value_str() {
1219 transparency = Some((
1221 sym::transparent => Transparency::Transparent,
1222 sym::semitransparent => Transparency::SemiTransparent,
1223 sym::opaque => Transparency::Opaque,
1225 error = Some(TransparencyError::UnknownTransparency(value, attr.span));
1234 let fallback = if macro_rules { Transparency::SemiTransparent } else { Transparency::Opaque };
1235 (transparency.map_or(fallback, |t| t.0), error)
1238 pub fn allow_internal_unstable<'a>(
1240 attrs: &'a [Attribute],
1241 ) -> impl Iterator<Item = Symbol> + 'a {
1242 allow_unstable(sess, attrs, sym::allow_internal_unstable)
1245 pub fn rustc_allow_const_fn_unstable<'a>(
1247 attrs: &'a [Attribute],
1248 ) -> impl Iterator<Item = Symbol> + 'a {
1249 allow_unstable(sess, attrs, sym::rustc_allow_const_fn_unstable)
1252 fn allow_unstable<'a>(
1254 attrs: &'a [Attribute],
1256 ) -> impl Iterator<Item = Symbol> + 'a {
1257 let attrs = sess.filter_by_name(attrs, symbol);
1259 .filter_map(move |attr| {
1260 attr.meta_item_list().or_else(|| {
1261 sess.diagnostic().span_err(
1263 &format!("`{}` expects a list of feature names", symbol.to_ident_string()),
1270 list.into_iter().filter_map(move |it| {
1271 let name = it.ident().map(|ident| ident.name);
1273 sess.diagnostic().span_err(
1275 &format!("`{}` expects feature names", symbol.to_ident_string()),
1282 pub fn parse_alignment(node: &ast::LitKind) -> Result<u32, &'static str> {
1283 if let ast::LitKind::Int(literal, ast::LitIntType::Unsuffixed) = node {
1284 if literal.is_power_of_two() {
1285 // rustc_middle::ty::layout::Align restricts align to <= 2^29
1286 if *literal <= 1 << 29 { Ok(*literal as u32) } else { Err("larger than 2^29") }
1288 Err("not a power of two")
1291 Err("not an unsuffixed integer")