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_feature::{find_gated_cfg, is_builtin_attr_name, Features, GatedCfg};
7 use rustc_macros::HashStable_Generic;
8 use rustc_session::lint::builtin::UNEXPECTED_CFGS;
9 use rustc_session::lint::BuiltinLintDiagnostics;
10 use rustc_session::parse::{feature_err, ParseSess};
11 use rustc_session::Session;
12 use rustc_span::hygiene::Transparency;
13 use rustc_span::{symbol::sym, symbol::Symbol, Span};
14 use std::num::NonZeroU32;
16 use crate::session_diagnostics::{self, IncorrectReprFormatGenericCause};
18 pub fn is_builtin_attr(attr: &Attribute) -> bool {
19 attr.is_doc_comment() || attr.ident().filter(|ident| is_builtin_attr_name(ident.name)).is_some()
24 UnknownMetaItem(String, &'static [&'static str]),
28 MultipleStabilityLevels,
29 UnsupportedLiteral(UnsupportedLiteralReason, /* is_bytestr */ bool),
32 pub(crate) enum UnsupportedLiteralReason {
39 fn handle_errors(sess: &ParseSess, span: Span, error: AttrError) {
41 AttrError::MultipleItem(item) => {
42 sess.emit_err(session_diagnostics::MultipleItem { span, item });
44 AttrError::UnknownMetaItem(item, expected) => {
45 sess.emit_err(session_diagnostics::UnknownMetaItem { span, item, expected });
47 AttrError::MissingSince => {
48 sess.emit_err(session_diagnostics::MissingSince { span });
50 AttrError::NonIdentFeature => {
51 sess.emit_err(session_diagnostics::NonIdentFeature { span });
53 AttrError::MissingFeature => {
54 sess.emit_err(session_diagnostics::MissingFeature { span });
56 AttrError::MultipleStabilityLevels => {
57 sess.emit_err(session_diagnostics::MultipleStabilityLevels { span });
59 AttrError::UnsupportedLiteral(reason, is_bytestr) => {
60 sess.emit_err(session_diagnostics::UnsupportedLiteral { span, reason, is_bytestr });
65 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
73 #[derive(Clone, Encodable, Decodable, Debug, PartialEq, Eq, HashStable_Generic)]
74 pub enum InstructionSetAttr {
79 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
80 pub enum OptimizeAttr {
86 /// Represents the following attributes:
90 #[derive(Encodable, Decodable, Copy, Clone, Debug, PartialEq, Eq, Hash)]
91 #[derive(HashStable_Generic)]
92 pub struct Stability {
93 pub level: StabilityLevel,
98 pub fn is_unstable(&self) -> bool {
99 self.level.is_unstable()
102 pub fn is_stable(&self) -> bool {
103 self.level.is_stable()
107 /// Represents the `#[rustc_const_unstable]` and `#[rustc_const_stable]` attributes.
108 #[derive(Encodable, Decodable, Copy, Clone, Debug, PartialEq, Eq, Hash)]
109 #[derive(HashStable_Generic)]
110 pub struct ConstStability {
111 pub level: StabilityLevel,
113 /// whether the function has a `#[rustc_promotable]` attribute
114 pub promotable: bool,
117 impl ConstStability {
118 pub fn is_const_unstable(&self) -> bool {
119 self.level.is_unstable()
122 pub fn is_const_stable(&self) -> bool {
123 self.level.is_stable()
127 /// Represents the `#[rustc_default_body_unstable]` attribute.
128 #[derive(Encodable, Decodable, Copy, Clone, Debug, PartialEq, Eq, Hash)]
129 #[derive(HashStable_Generic)]
130 pub struct DefaultBodyStability {
131 pub level: StabilityLevel,
135 /// The available stability levels.
136 #[derive(Encodable, Decodable, PartialEq, Copy, Clone, Debug, Eq, Hash)]
137 #[derive(HashStable_Generic)]
138 pub enum StabilityLevel {
141 /// Reason for the current stability level.
142 reason: UnstableReason,
143 /// Relevant `rust-lang/rust` issue.
144 issue: Option<NonZeroU32>,
146 /// If part of a feature is stabilized and a new feature is added for the remaining parts,
147 /// then the `implied_by` attribute is used to indicate which now-stable feature previously
148 /// contained a item.
151 /// #[unstable(feature = "foo", issue = "...")]
153 /// #[unstable(feature = "foo", issue = "...")]
160 /// #[stable(feature = "foo", since = "1.XX.X")]
162 /// #[unstable(feature = "foobar", issue = "...", implied_by = "foo")]
165 implied_by: Option<Symbol>,
169 /// Rust release which stabilized this feature.
171 /// Is this item allowed to be referred to on stable, despite being contained in unstable
173 allowed_through_unstable_modules: bool,
177 impl StabilityLevel {
178 pub fn is_unstable(&self) -> bool {
179 matches!(self, StabilityLevel::Unstable { .. })
181 pub fn is_stable(&self) -> bool {
182 matches!(self, StabilityLevel::Stable { .. })
186 #[derive(Encodable, Decodable, PartialEq, Copy, Clone, Debug, Eq, Hash)]
187 #[derive(HashStable_Generic)]
188 pub enum UnstableReason {
194 impl UnstableReason {
195 fn from_opt_reason(reason: Option<Symbol>) -> Self {
196 // UnstableReason::Default constructed manually
198 Some(r) => Self::Some(r),
203 pub fn to_opt_reason(&self) -> Option<Symbol> {
206 Self::Default => Some(sym::unstable_location_reason_default),
207 Self::Some(r) => Some(*r),
212 /// Collects stability info from all stability attributes in `attrs`.
213 /// Returns `None` if no stability attributes are found.
214 pub fn find_stability(
218 ) -> (Option<(Stability, Span)>, Option<(ConstStability, Span)>, Option<(DefaultBodyStability, Span)>)
220 find_stability_generic(sess, attrs.iter(), item_sp)
223 fn find_stability_generic<'a, I>(
227 ) -> (Option<(Stability, Span)>, Option<(ConstStability, Span)>, Option<(DefaultBodyStability, Span)>)
229 I: Iterator<Item = &'a Attribute>,
231 use StabilityLevel::*;
233 let mut stab: Option<(Stability, Span)> = None;
234 let mut const_stab: Option<(ConstStability, Span)> = None;
235 let mut body_stab: Option<(DefaultBodyStability, Span)> = None;
236 let mut promotable = false;
237 let mut allowed_through_unstable_modules = false;
239 'outer: for attr in attrs_iter {
241 sym::rustc_const_unstable,
242 sym::rustc_const_stable,
245 sym::rustc_promotable,
246 sym::rustc_allowed_through_unstable_modules,
247 sym::rustc_default_body_unstable,
250 .any(|&s| attr.has_name(s))
252 continue; // not a stability level
255 let meta = attr.meta();
257 if attr.has_name(sym::rustc_promotable) {
259 } else if attr.has_name(sym::rustc_allowed_through_unstable_modules) {
260 allowed_through_unstable_modules = true;
262 // attributes with data
263 else if let Some(MetaItem { kind: MetaItemKind::List(ref metas), .. }) = meta {
264 let meta = meta.as_ref().unwrap();
265 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
270 AttrError::MultipleItem(pprust::path_to_string(&meta.path)),
274 if let Some(v) = meta.value_str() {
278 sess.emit_err(session_diagnostics::IncorrectMetaItem { span: meta.span });
283 let meta_name = meta.name_or_empty();
285 sym::rustc_const_unstable | sym::rustc_default_body_unstable | sym::unstable => {
286 if meta_name == sym::unstable && stab.is_some() {
290 AttrError::MultipleStabilityLevels,
293 } else if meta_name == sym::rustc_const_unstable && const_stab.is_some() {
297 AttrError::MultipleStabilityLevels,
300 } else if meta_name == sym::rustc_default_body_unstable && body_stab.is_some() {
304 AttrError::MultipleStabilityLevels,
309 let mut feature = None;
310 let mut reason = None;
311 let mut issue = None;
312 let mut issue_num = None;
313 let mut is_soft = false;
314 let mut implied_by = None;
316 let Some(mi) = meta.meta_item() else {
320 AttrError::UnsupportedLiteral(UnsupportedLiteralReason::Generic, false),
324 match mi.name_or_empty() {
326 if !get(mi, &mut feature) {
331 if !get(mi, &mut reason) {
336 if !get(mi, &mut issue) {
340 // These unwraps are safe because `get` ensures the meta item
341 // is a name/value pair string literal.
342 issue_num = match issue.unwrap().as_str() {
344 issue => match issue.parse::<NonZeroU32>() {
345 Ok(num) => Some(num),
348 session_diagnostics::InvalidIssueString {
350 cause: session_diagnostics::InvalidIssueStringCause::from_int_error_kind(
351 mi.name_value_literal_span().unwrap(),
363 sess.emit_err(session_diagnostics::SoftNoArgs {
370 if !get(mi, &mut implied_by) {
378 AttrError::UnknownMetaItem(
379 pprust::path_to_string(&mi.path),
380 &["feature", "reason", "issue", "soft"],
388 match (feature, reason, issue) {
389 (Some(feature), reason, Some(_)) => {
390 if !rustc_lexer::is_ident(feature.as_str()) {
394 AttrError::NonIdentFeature,
398 let level = Unstable {
399 reason: UnstableReason::from_opt_reason(reason),
404 if sym::unstable == meta_name {
405 stab = Some((Stability { level, feature }, attr.span));
406 } else if sym::rustc_const_unstable == meta_name {
408 ConstStability { level, feature, promotable: false },
411 } else if sym::rustc_default_body_unstable == meta_name {
413 Some((DefaultBodyStability { level, feature }, attr.span));
415 unreachable!("Unknown stability attribute {meta_name}");
419 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingFeature);
423 sess.emit_err(session_diagnostics::MissingIssue { span: attr.span });
428 sym::rustc_const_stable | sym::stable => {
429 if meta_name == sym::stable && stab.is_some() {
433 AttrError::MultipleStabilityLevels,
436 } else if meta_name == sym::rustc_const_stable && const_stab.is_some() {
440 AttrError::MultipleStabilityLevels,
445 let mut feature = None;
446 let mut since = None;
449 NestedMetaItem::MetaItem(mi) => match mi.name_or_empty() {
451 if !get(mi, &mut feature) {
456 if !get(mi, &mut since) {
464 AttrError::UnknownMetaItem(
465 pprust::path_to_string(&mi.path),
466 &["feature", "since"],
472 NestedMetaItem::Literal(lit) => {
476 AttrError::UnsupportedLiteral(
477 UnsupportedLiteralReason::Generic,
486 match (feature, since) {
487 (Some(feature), Some(since)) => {
488 let level = Stable { since, allowed_through_unstable_modules: false };
489 if sym::stable == meta_name {
490 stab = Some((Stability { level, feature }, attr.span));
493 ConstStability { level, feature, promotable: false },
499 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingFeature);
503 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingSince);
513 // Merge the const-unstable info into the stability info
515 if let Some((ref mut stab, _)) = const_stab {
516 stab.promotable = promotable;
518 sess.emit_err(session_diagnostics::RustcPromotablePairing { span: item_sp });
522 if allowed_through_unstable_modules {
525 level: StabilityLevel::Stable { ref mut allowed_through_unstable_modules, .. },
531 *allowed_through_unstable_modules = true;
533 sess.emit_err(session_diagnostics::RustcAllowedUnstablePairing { span: item_sp });
537 (stab, const_stab, body_stab)
540 pub fn find_crate_name(sess: &Session, attrs: &[Attribute]) -> Option<Symbol> {
541 sess.first_attr_value_str_by_name(attrs, sym::crate_name)
544 #[derive(Clone, Debug)]
545 pub struct Condition {
548 pub value: Option<Symbol>,
549 pub value_span: Option<Span>,
553 /// Tests if a cfg-pattern matches the cfg set
557 lint_node_id: NodeId,
558 features: Option<&Features>,
560 eval_condition(cfg, sess, features, &mut |cfg| {
561 try_gate_cfg(cfg.name, cfg.span, sess, features);
562 if let Some(names_valid) = &sess.check_config.names_valid {
563 if !names_valid.contains(&cfg.name) {
564 sess.buffer_lint_with_diagnostic(
568 "unexpected `cfg` condition name",
569 BuiltinLintDiagnostics::UnexpectedCfg((cfg.name, cfg.name_span), None),
573 if let Some(value) = cfg.value {
574 if let Some(values) = &sess.check_config.values_valid.get(&cfg.name) {
575 if !values.contains(&value) {
576 sess.buffer_lint_with_diagnostic(
580 "unexpected `cfg` condition value",
581 BuiltinLintDiagnostics::UnexpectedCfg(
582 (cfg.name, cfg.name_span),
583 cfg.value_span.map(|vs| (value, vs)),
589 sess.config.contains(&(cfg.name, cfg.value))
593 fn try_gate_cfg(name: Symbol, span: Span, sess: &ParseSess, features: Option<&Features>) {
594 let gate = find_gated_cfg(|sym| sym == name);
595 if let (Some(feats), Some(gated_cfg)) = (features, gate) {
596 gate_cfg(&gated_cfg, span, sess, feats);
600 fn gate_cfg(gated_cfg: &GatedCfg, cfg_span: Span, sess: &ParseSess, features: &Features) {
601 let (cfg, feature, has_feature) = gated_cfg;
602 if !has_feature(features) && !cfg_span.allows_unstable(*feature) {
603 let explain = format!("`cfg({})` is experimental and subject to change", cfg);
604 feature_err(sess, *feature, cfg_span, &explain).emit();
608 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
615 fn parse_version(s: &str, allow_appendix: bool) -> Option<Version> {
616 let mut components = s.split('-');
617 let d = components.next()?;
618 if !allow_appendix && components.next().is_some() {
621 let mut digits = d.splitn(3, '.');
622 let major = digits.next()?.parse().ok()?;
623 let minor = digits.next()?.parse().ok()?;
624 let patch = digits.next().unwrap_or("0").parse().ok()?;
625 Some(Version { major, minor, patch })
628 /// Evaluate a cfg-like condition (with `any` and `all`), using `eval` to
629 /// evaluate individual items.
630 pub fn eval_condition(
633 features: Option<&Features>,
634 eval: &mut impl FnMut(Condition) -> bool,
637 ast::MetaItemKind::List(ref mis) if cfg.name_or_empty() == sym::version => {
638 try_gate_cfg(sym::version, cfg.span, sess, features);
639 let (min_version, span) = match &mis[..] {
640 [NestedMetaItem::Literal(Lit { kind: LitKind::Str(sym, ..), span, .. })] => {
644 NestedMetaItem::Literal(Lit { span, .. })
645 | NestedMetaItem::MetaItem(MetaItem { span, .. }),
647 sess.emit_err(session_diagnostics::ExpectedVersionLiteral { span: *span });
651 sess.emit_err(session_diagnostics::ExpectedSingleVersionLiteral {
657 let Some(min_version) = parse_version(min_version.as_str(), false) else {
658 sess.emit_warning(session_diagnostics::UnknownVersionLiteral { span: *span });
661 let rustc_version = parse_version(env!("CFG_RELEASE"), true).unwrap();
663 // See https://github.com/rust-lang/rust/issues/64796#issuecomment-640851454 for details
664 if sess.assume_incomplete_release {
665 rustc_version > min_version
667 rustc_version >= min_version
670 ast::MetaItemKind::List(ref mis) => {
671 for mi in mis.iter() {
672 if !mi.is_meta_item() {
676 AttrError::UnsupportedLiteral(UnsupportedLiteralReason::Generic, false),
682 // The unwraps below may look dangerous, but we've already asserted
683 // that they won't fail with the loop above.
684 match cfg.name_or_empty() {
687 // We don't use any() here, because we want to evaluate all cfg condition
688 // as eval_condition can (and does) extra checks
689 .fold(false, |res, mi| {
690 res | eval_condition(mi.meta_item().unwrap(), sess, features, eval)
694 // We don't use all() here, because we want to evaluate all cfg condition
695 // as eval_condition can (and does) extra checks
696 .fold(true, |res, mi| {
697 res & eval_condition(mi.meta_item().unwrap(), sess, features, eval)
701 sess.emit_err(session_diagnostics::ExpectedOneCfgPattern {
707 !eval_condition(mis[0].meta_item().unwrap(), sess, features, eval)
710 if let Some(features) = features && !features.cfg_target_compact {
713 sym::cfg_target_compact,
715 &"compact `cfg(target(..))` is experimental and subject to change"
719 mis.iter().fold(true, |res, mi| {
720 let mut mi = mi.meta_item().unwrap().clone();
721 if let [seg, ..] = &mut mi.path.segments[..] {
722 seg.ident.name = Symbol::intern(&format!("target_{}", seg.ident.name));
725 res & eval_condition(&mi, sess, features, eval)
729 sess.emit_err(session_diagnostics::InvalidPredicate {
731 predicate: pprust::path_to_string(&cfg.path),
737 ast::MetaItemKind::Word | MetaItemKind::NameValue(..) if cfg.path.segments.len() != 1 => {
738 sess.emit_err(session_diagnostics::CfgPredicateIdentifier { span: cfg.path.span });
741 MetaItemKind::NameValue(ref lit) if !lit.kind.is_str() => {
745 AttrError::UnsupportedLiteral(
746 UnsupportedLiteralReason::CfgString,
747 lit.kind.is_bytestr(),
752 ast::MetaItemKind::Word | ast::MetaItemKind::NameValue(..) => {
753 let ident = cfg.ident().expect("multi-segment cfg predicate");
756 name_span: ident.span,
757 value: cfg.value_str(),
758 value_span: cfg.name_value_literal_span(),
765 #[derive(Copy, Debug, Encodable, Decodable, Clone, HashStable_Generic)]
766 pub struct Deprecation {
767 pub since: Option<Symbol>,
768 /// The note to issue a reason.
769 pub note: Option<Symbol>,
770 /// A text snippet used to completely replace any use of the deprecated item in an expression.
772 /// This is currently unstable.
773 pub suggestion: Option<Symbol>,
775 /// Whether to treat the since attribute as being a Rust version identifier
776 /// (rather than an opaque string).
777 pub is_since_rustc_version: bool,
780 /// Finds the deprecation attribute. `None` if none exists.
781 pub fn find_deprecation(sess: &Session, attrs: &[Attribute]) -> Option<(Deprecation, Span)> {
782 find_deprecation_generic(sess, attrs.iter())
785 fn find_deprecation_generic<'a, I>(sess: &Session, attrs_iter: I) -> Option<(Deprecation, Span)>
787 I: Iterator<Item = &'a Attribute>,
789 let mut depr: Option<(Deprecation, Span)> = None;
790 let is_rustc = sess.features_untracked().staged_api;
792 'outer: for attr in attrs_iter {
793 if !attr.has_name(sym::deprecated) {
797 let Some(meta) = attr.meta() else {
800 let mut since = None;
802 let mut suggestion = None;
804 MetaItemKind::Word => {}
805 MetaItemKind::NameValue(..) => note = meta.value_str(),
806 MetaItemKind::List(list) => {
807 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
812 AttrError::MultipleItem(pprust::path_to_string(&meta.path)),
816 if let Some(v) = meta.value_str() {
820 if let Some(lit) = meta.name_value_literal() {
824 AttrError::UnsupportedLiteral(
825 UnsupportedLiteralReason::DeprecatedString,
826 lit.kind.is_bytestr(),
830 sess.emit_err(session_diagnostics::IncorrectMetaItem2 {
841 NestedMetaItem::MetaItem(mi) => match mi.name_or_empty() {
843 if !get(mi, &mut since) {
848 if !get(mi, &mut note) {
853 if !sess.features_untracked().deprecated_suggestion {
854 sess.emit_err(session_diagnostics::DeprecatedItemSuggestion {
856 is_nightly: sess.is_nightly_build().then_some(()),
861 if !get(mi, &mut suggestion) {
869 AttrError::UnknownMetaItem(
870 pprust::path_to_string(&mi.path),
871 if sess.features_untracked().deprecated_suggestion {
872 &["since", "note", "suggestion"]
881 NestedMetaItem::Literal(lit) => {
885 AttrError::UnsupportedLiteral(
886 UnsupportedLiteralReason::DeprecatedKvPair,
899 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingSince);
904 sess.emit_err(session_diagnostics::MissingNote { span: attr.span });
910 Deprecation { since, note, suggestion, is_since_rustc_version: is_rustc },
918 #[derive(PartialEq, Debug, Encodable, Decodable, Copy, Clone)]
928 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
929 #[derive(Encodable, Decodable, HashStable_Generic)]
931 SignedInt(ast::IntTy),
932 UnsignedInt(ast::UintTy),
937 pub fn is_signed(self) -> bool {
941 SignedInt(..) => true,
942 UnsignedInt(..) => false,
947 /// Parse #[repr(...)] forms.
949 /// Valid repr contents: any of the primitive integral type names (see
950 /// `int_type_of_word`, below) to specify enum discriminant type; `C`, to use
951 /// the same discriminant size that the corresponding C enum would or C
952 /// structure layout, `packed` to remove padding, and `transparent` to delegate representation
953 /// concerns to the only non-ZST field.
954 pub fn find_repr_attrs(sess: &Session, attr: &Attribute) -> Vec<ReprAttr> {
955 if attr.has_name(sym::repr) { parse_repr_attr(sess, attr) } else { Vec::new() }
958 pub fn parse_repr_attr(sess: &Session, attr: &Attribute) -> Vec<ReprAttr> {
959 assert!(attr.has_name(sym::repr), "expected `#[repr(..)]`, found: {:?}", attr);
961 let mut acc = Vec::new();
962 let diagnostic = &sess.parse_sess.span_diagnostic;
964 if let Some(items) = attr.meta_item_list() {
966 let mut recognised = false;
968 let hint = match item.name_or_empty() {
969 sym::C => Some(ReprC),
970 sym::packed => Some(ReprPacked(1)),
971 sym::simd => Some(ReprSimd),
972 sym::transparent => Some(ReprTransparent),
974 sess.emit_err(session_diagnostics::InvalidReprAlignNeedArg {
980 name => int_type_of_word(name).map(ReprInt),
983 if let Some(h) = hint {
987 } else if let Some((name, value)) = item.name_value_literal() {
988 let mut literal_error = None;
989 if name == sym::align {
991 match parse_alignment(&value.kind) {
992 Ok(literal) => acc.push(ReprAlign(literal)),
993 Err(message) => literal_error = Some(message),
995 } else if name == sym::packed {
997 match parse_alignment(&value.kind) {
998 Ok(literal) => acc.push(ReprPacked(literal)),
999 Err(message) => literal_error = Some(message),
1001 } else if matches!(name, sym::C | sym::simd | sym::transparent)
1002 || int_type_of_word(name).is_some()
1005 sess.emit_err(session_diagnostics::InvalidReprHintNoParen {
1007 name: name.to_ident_string(),
1010 if let Some(literal_error) = literal_error {
1011 sess.emit_err(session_diagnostics::InvalidReprGeneric {
1013 repr_arg: name.to_ident_string(),
1014 error_part: literal_error,
1017 } else if let Some(meta_item) = item.meta_item() {
1018 if let MetaItemKind::NameValue(ref value) = meta_item.kind {
1019 if meta_item.has_name(sym::align) || meta_item.has_name(sym::packed) {
1020 let name = meta_item.name_or_empty().to_ident_string();
1022 sess.emit_err(session_diagnostics::IncorrectReprFormatGeneric {
1025 cause: IncorrectReprFormatGenericCause::from_lit_kind(
1033 meta_item.name_or_empty(),
1034 sym::C | sym::simd | sym::transparent
1035 ) || int_type_of_word(meta_item.name_or_empty()).is_some()
1038 sess.emit_err(session_diagnostics::InvalidReprHintNoValue {
1039 span: meta_item.span,
1040 name: meta_item.name_or_empty().to_ident_string(),
1044 } else if let MetaItemKind::List(_) = meta_item.kind {
1045 if meta_item.has_name(sym::align) {
1047 sess.emit_err(session_diagnostics::IncorrectReprFormatAlignOneArg {
1048 span: meta_item.span,
1050 } else if meta_item.has_name(sym::packed) {
1052 sess.emit_err(session_diagnostics::IncorrectReprFormatPackedOneOrZeroArg {
1053 span: meta_item.span,
1056 meta_item.name_or_empty(),
1057 sym::C | sym::simd | sym::transparent
1058 ) || int_type_of_word(meta_item.name_or_empty()).is_some()
1061 sess.emit_err(session_diagnostics::InvalidReprHintNoParen {
1062 span: meta_item.span,
1063 name: meta_item.name_or_empty().to_ident_string(),
1069 // Not a word we recognize. This will be caught and reported by
1070 // the `check_mod_attrs` pass, but this pass doesn't always run
1071 // (e.g. if we only pretty-print the source), so we have to gate
1072 // the `delay_span_bug` call as follows:
1073 if sess.opts.pretty.map_or(true, |pp| pp.needs_analysis()) {
1074 diagnostic.delay_span_bug(item.span(), "unrecognized representation hint");
1082 fn int_type_of_word(s: Symbol) -> Option<IntType> {
1086 sym::i8 => Some(SignedInt(ast::IntTy::I8)),
1087 sym::u8 => Some(UnsignedInt(ast::UintTy::U8)),
1088 sym::i16 => Some(SignedInt(ast::IntTy::I16)),
1089 sym::u16 => Some(UnsignedInt(ast::UintTy::U16)),
1090 sym::i32 => Some(SignedInt(ast::IntTy::I32)),
1091 sym::u32 => Some(UnsignedInt(ast::UintTy::U32)),
1092 sym::i64 => Some(SignedInt(ast::IntTy::I64)),
1093 sym::u64 => Some(UnsignedInt(ast::UintTy::U64)),
1094 sym::i128 => Some(SignedInt(ast::IntTy::I128)),
1095 sym::u128 => Some(UnsignedInt(ast::UintTy::U128)),
1096 sym::isize => Some(SignedInt(ast::IntTy::Isize)),
1097 sym::usize => Some(UnsignedInt(ast::UintTy::Usize)),
1102 pub enum TransparencyError {
1103 UnknownTransparency(Symbol, Span),
1104 MultipleTransparencyAttrs(Span, Span),
1107 pub fn find_transparency(
1108 attrs: &[Attribute],
1110 ) -> (Transparency, Option<TransparencyError>) {
1111 let mut transparency = None;
1112 let mut error = None;
1114 if attr.has_name(sym::rustc_macro_transparency) {
1115 if let Some((_, old_span)) = transparency {
1116 error = Some(TransparencyError::MultipleTransparencyAttrs(old_span, attr.span));
1118 } else if let Some(value) = attr.value_str() {
1119 transparency = Some((
1121 sym::transparent => Transparency::Transparent,
1122 sym::semitransparent => Transparency::SemiTransparent,
1123 sym::opaque => Transparency::Opaque,
1125 error = Some(TransparencyError::UnknownTransparency(value, attr.span));
1134 let fallback = if macro_rules { Transparency::SemiTransparent } else { Transparency::Opaque };
1135 (transparency.map_or(fallback, |t| t.0), error)
1138 pub fn allow_internal_unstable<'a>(
1140 attrs: &'a [Attribute],
1141 ) -> impl Iterator<Item = Symbol> + 'a {
1142 allow_unstable(sess, attrs, sym::allow_internal_unstable)
1145 pub fn rustc_allow_const_fn_unstable<'a>(
1147 attrs: &'a [Attribute],
1148 ) -> impl Iterator<Item = Symbol> + 'a {
1149 allow_unstable(sess, attrs, sym::rustc_allow_const_fn_unstable)
1152 fn allow_unstable<'a>(
1154 attrs: &'a [Attribute],
1156 ) -> impl Iterator<Item = Symbol> + 'a {
1157 let attrs = sess.filter_by_name(attrs, symbol);
1159 .filter_map(move |attr| {
1160 attr.meta_item_list().or_else(|| {
1161 sess.emit_err(session_diagnostics::ExpectsFeatureList {
1163 name: symbol.to_ident_string(),
1170 list.into_iter().filter_map(move |it| {
1171 let name = it.ident().map(|ident| ident.name);
1173 sess.emit_err(session_diagnostics::ExpectsFeatures {
1175 name: symbol.to_ident_string(),
1182 pub fn parse_alignment(node: &ast::LitKind) -> Result<u32, &'static str> {
1183 if let ast::LitKind::Int(literal, ast::LitIntType::Unsuffixed) = node {
1184 if literal.is_power_of_two() {
1185 // rustc_middle::ty::layout::Align restricts align to <= 2^29
1186 if *literal <= 1 << 29 { Ok(*literal as u32) } else { Err("larger than 2^29") }
1188 Err("not a power of two")
1191 Err("not an unsuffixed integer")