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 /// The version placeholder that recently stabilized features contain inside the
19 /// `since` field of the `#[stable]` attribute.
21 /// For more, see [this pull request](https://github.com/rust-lang/rust/pull/100591).
22 pub const VERSION_PLACEHOLDER: &str = "CURRENT_RUSTC_VERSION";
24 pub fn is_builtin_attr(attr: &Attribute) -> bool {
25 attr.is_doc_comment() || attr.ident().filter(|ident| is_builtin_attr_name(ident.name)).is_some()
30 UnknownMetaItem(String, &'static [&'static str]),
34 MultipleStabilityLevels,
35 UnsupportedLiteral(UnsupportedLiteralReason, /* is_bytestr */ bool),
38 pub(crate) enum UnsupportedLiteralReason {
45 fn handle_errors(sess: &ParseSess, span: Span, error: AttrError) {
47 AttrError::MultipleItem(item) => {
48 sess.emit_err(session_diagnostics::MultipleItem { span, item });
50 AttrError::UnknownMetaItem(item, expected) => {
51 sess.emit_err(session_diagnostics::UnknownMetaItem { span, item, expected });
53 AttrError::MissingSince => {
54 sess.emit_err(session_diagnostics::MissingSince { span });
56 AttrError::NonIdentFeature => {
57 sess.emit_err(session_diagnostics::NonIdentFeature { span });
59 AttrError::MissingFeature => {
60 sess.emit_err(session_diagnostics::MissingFeature { span });
62 AttrError::MultipleStabilityLevels => {
63 sess.emit_err(session_diagnostics::MultipleStabilityLevels { span });
65 AttrError::UnsupportedLiteral(reason, is_bytestr) => {
66 sess.emit_err(session_diagnostics::UnsupportedLiteral { span, reason, is_bytestr });
71 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
79 #[derive(Clone, Encodable, Decodable, Debug, PartialEq, Eq, HashStable_Generic)]
80 pub enum InstructionSetAttr {
85 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
86 pub enum OptimizeAttr {
92 /// Represents the following attributes:
96 #[derive(Encodable, Decodable, Copy, Clone, Debug, PartialEq, Eq, Hash)]
97 #[derive(HashStable_Generic)]
98 pub struct Stability {
99 pub level: StabilityLevel,
104 pub fn is_unstable(&self) -> bool {
105 self.level.is_unstable()
108 pub fn is_stable(&self) -> bool {
109 self.level.is_stable()
113 /// Represents the `#[rustc_const_unstable]` and `#[rustc_const_stable]` attributes.
114 #[derive(Encodable, Decodable, Copy, Clone, Debug, PartialEq, Eq, Hash)]
115 #[derive(HashStable_Generic)]
116 pub struct ConstStability {
117 pub level: StabilityLevel,
119 /// whether the function has a `#[rustc_promotable]` attribute
120 pub promotable: bool,
123 impl ConstStability {
124 pub fn is_const_unstable(&self) -> bool {
125 self.level.is_unstable()
128 pub fn is_const_stable(&self) -> bool {
129 self.level.is_stable()
133 /// Represents the `#[rustc_default_body_unstable]` attribute.
134 #[derive(Encodable, Decodable, Copy, Clone, Debug, PartialEq, Eq, Hash)]
135 #[derive(HashStable_Generic)]
136 pub struct DefaultBodyStability {
137 pub level: StabilityLevel,
141 /// The available stability levels.
142 #[derive(Encodable, Decodable, PartialEq, Copy, Clone, Debug, Eq, Hash)]
143 #[derive(HashStable_Generic)]
144 pub enum StabilityLevel {
147 /// Reason for the current stability level.
148 reason: UnstableReason,
149 /// Relevant `rust-lang/rust` issue.
150 issue: Option<NonZeroU32>,
152 /// If part of a feature is stabilized and a new feature is added for the remaining parts,
153 /// then the `implied_by` attribute is used to indicate which now-stable feature previously
154 /// contained a item.
157 /// #[unstable(feature = "foo", issue = "...")]
159 /// #[unstable(feature = "foo", issue = "...")]
166 /// #[stable(feature = "foo", since = "1.XX.X")]
168 /// #[unstable(feature = "foobar", issue = "...", implied_by = "foo")]
171 implied_by: Option<Symbol>,
175 /// Rust release which stabilized this feature.
177 /// Is this item allowed to be referred to on stable, despite being contained in unstable
179 allowed_through_unstable_modules: bool,
183 impl StabilityLevel {
184 pub fn is_unstable(&self) -> bool {
185 matches!(self, StabilityLevel::Unstable { .. })
187 pub fn is_stable(&self) -> bool {
188 matches!(self, StabilityLevel::Stable { .. })
192 #[derive(Encodable, Decodable, PartialEq, Copy, Clone, Debug, Eq, Hash)]
193 #[derive(HashStable_Generic)]
194 pub enum UnstableReason {
200 impl UnstableReason {
201 fn from_opt_reason(reason: Option<Symbol>) -> Self {
202 // UnstableReason::Default constructed manually
204 Some(r) => Self::Some(r),
209 pub fn to_opt_reason(&self) -> Option<Symbol> {
212 Self::Default => Some(sym::unstable_location_reason_default),
213 Self::Some(r) => Some(*r),
218 /// Collects stability info from all stability attributes in `attrs`.
219 /// Returns `None` if no stability attributes are found.
220 pub fn find_stability(
224 ) -> (Option<(Stability, Span)>, Option<(ConstStability, Span)>, Option<(DefaultBodyStability, Span)>)
226 find_stability_generic(sess, attrs.iter(), item_sp)
229 fn find_stability_generic<'a, I>(
233 ) -> (Option<(Stability, Span)>, Option<(ConstStability, Span)>, Option<(DefaultBodyStability, Span)>)
235 I: Iterator<Item = &'a Attribute>,
237 use StabilityLevel::*;
239 let mut stab: Option<(Stability, Span)> = None;
240 let mut const_stab: Option<(ConstStability, Span)> = None;
241 let mut body_stab: Option<(DefaultBodyStability, Span)> = None;
242 let mut promotable = false;
243 let mut allowed_through_unstable_modules = false;
245 'outer: for attr in attrs_iter {
247 sym::rustc_const_unstable,
248 sym::rustc_const_stable,
251 sym::rustc_promotable,
252 sym::rustc_allowed_through_unstable_modules,
253 sym::rustc_default_body_unstable,
256 .any(|&s| attr.has_name(s))
258 continue; // not a stability level
261 let meta = attr.meta();
263 if attr.has_name(sym::rustc_promotable) {
265 } else if attr.has_name(sym::rustc_allowed_through_unstable_modules) {
266 allowed_through_unstable_modules = true;
268 // attributes with data
269 else if let Some(MetaItem { kind: MetaItemKind::List(ref metas), .. }) = meta {
270 let meta = meta.as_ref().unwrap();
271 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
276 AttrError::MultipleItem(pprust::path_to_string(&meta.path)),
280 if let Some(v) = meta.value_str() {
284 sess.emit_err(session_diagnostics::IncorrectMetaItem { span: meta.span });
289 let meta_name = meta.name_or_empty();
291 sym::rustc_const_unstable | sym::rustc_default_body_unstable | sym::unstable => {
292 if meta_name == sym::unstable && stab.is_some() {
296 AttrError::MultipleStabilityLevels,
299 } else if meta_name == sym::rustc_const_unstable && const_stab.is_some() {
303 AttrError::MultipleStabilityLevels,
306 } else if meta_name == sym::rustc_default_body_unstable && body_stab.is_some() {
310 AttrError::MultipleStabilityLevels,
315 let mut feature = None;
316 let mut reason = None;
317 let mut issue = None;
318 let mut issue_num = None;
319 let mut is_soft = false;
320 let mut implied_by = None;
322 let Some(mi) = meta.meta_item() else {
326 AttrError::UnsupportedLiteral(UnsupportedLiteralReason::Generic, false),
330 match mi.name_or_empty() {
332 if !get(mi, &mut feature) {
337 if !get(mi, &mut reason) {
342 if !get(mi, &mut issue) {
346 // These unwraps are safe because `get` ensures the meta item
347 // is a name/value pair string literal.
348 issue_num = match issue.unwrap().as_str() {
350 issue => match issue.parse::<NonZeroU32>() {
351 Ok(num) => Some(num),
354 session_diagnostics::InvalidIssueString {
356 cause: session_diagnostics::InvalidIssueStringCause::from_int_error_kind(
357 mi.name_value_literal_span().unwrap(),
369 sess.emit_err(session_diagnostics::SoftNoArgs {
376 if !get(mi, &mut implied_by) {
384 AttrError::UnknownMetaItem(
385 pprust::path_to_string(&mi.path),
386 &["feature", "reason", "issue", "soft"],
394 match (feature, reason, issue) {
395 (Some(feature), reason, Some(_)) => {
396 if !rustc_lexer::is_ident(feature.as_str()) {
400 AttrError::NonIdentFeature,
404 let level = Unstable {
405 reason: UnstableReason::from_opt_reason(reason),
410 if sym::unstable == meta_name {
411 stab = Some((Stability { level, feature }, attr.span));
412 } else if sym::rustc_const_unstable == meta_name {
414 ConstStability { level, feature, promotable: false },
417 } else if sym::rustc_default_body_unstable == meta_name {
419 Some((DefaultBodyStability { level, feature }, attr.span));
421 unreachable!("Unknown stability attribute {meta_name}");
425 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingFeature);
429 sess.emit_err(session_diagnostics::MissingIssue { span: attr.span });
434 sym::rustc_const_stable | sym::stable => {
435 if meta_name == sym::stable && stab.is_some() {
439 AttrError::MultipleStabilityLevels,
442 } else if meta_name == sym::rustc_const_stable && const_stab.is_some() {
446 AttrError::MultipleStabilityLevels,
451 let mut feature = None;
452 let mut since = None;
455 NestedMetaItem::MetaItem(mi) => match mi.name_or_empty() {
457 if !get(mi, &mut feature) {
462 if !get(mi, &mut since) {
470 AttrError::UnknownMetaItem(
471 pprust::path_to_string(&mi.path),
472 &["feature", "since"],
478 NestedMetaItem::Literal(lit) => {
482 AttrError::UnsupportedLiteral(
483 UnsupportedLiteralReason::Generic,
492 if let Some(s) = since && s.as_str() == VERSION_PLACEHOLDER {
493 let version = option_env!("CFG_VERSION").unwrap_or("<current>");
494 let version = version.split(' ').next().unwrap();
495 since = Some(Symbol::intern(&version));
498 match (feature, since) {
499 (Some(feature), Some(since)) => {
500 let level = Stable { since, allowed_through_unstable_modules: false };
501 if sym::stable == meta_name {
502 stab = Some((Stability { level, feature }, attr.span));
505 ConstStability { level, feature, promotable: false },
511 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingFeature);
515 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingSince);
525 // Merge the const-unstable info into the stability info
527 if let Some((ref mut stab, _)) = const_stab {
528 stab.promotable = promotable;
530 sess.emit_err(session_diagnostics::RustcPromotablePairing { span: item_sp });
534 if allowed_through_unstable_modules {
537 level: StabilityLevel::Stable { ref mut allowed_through_unstable_modules, .. },
543 *allowed_through_unstable_modules = true;
545 sess.emit_err(session_diagnostics::RustcAllowedUnstablePairing { span: item_sp });
549 (stab, const_stab, body_stab)
552 pub fn find_crate_name(sess: &Session, attrs: &[Attribute]) -> Option<Symbol> {
553 sess.first_attr_value_str_by_name(attrs, sym::crate_name)
556 #[derive(Clone, Debug)]
557 pub struct Condition {
560 pub value: Option<Symbol>,
561 pub value_span: Option<Span>,
565 /// Tests if a cfg-pattern matches the cfg set
569 lint_node_id: NodeId,
570 features: Option<&Features>,
572 eval_condition(cfg, sess, features, &mut |cfg| {
573 try_gate_cfg(cfg.name, cfg.span, sess, features);
574 if let Some(names_valid) = &sess.check_config.names_valid {
575 if !names_valid.contains(&cfg.name) {
576 sess.buffer_lint_with_diagnostic(
580 "unexpected `cfg` condition name",
581 BuiltinLintDiagnostics::UnexpectedCfg((cfg.name, cfg.name_span), None),
585 if let Some(value) = cfg.value {
586 if let Some(values) = &sess.check_config.values_valid.get(&cfg.name) {
587 if !values.contains(&value) {
588 sess.buffer_lint_with_diagnostic(
592 "unexpected `cfg` condition value",
593 BuiltinLintDiagnostics::UnexpectedCfg(
594 (cfg.name, cfg.name_span),
595 cfg.value_span.map(|vs| (value, vs)),
601 sess.config.contains(&(cfg.name, cfg.value))
605 fn try_gate_cfg(name: Symbol, span: Span, sess: &ParseSess, features: Option<&Features>) {
606 let gate = find_gated_cfg(|sym| sym == name);
607 if let (Some(feats), Some(gated_cfg)) = (features, gate) {
608 gate_cfg(&gated_cfg, span, sess, feats);
612 fn gate_cfg(gated_cfg: &GatedCfg, cfg_span: Span, sess: &ParseSess, features: &Features) {
613 let (cfg, feature, has_feature) = gated_cfg;
614 if !has_feature(features) && !cfg_span.allows_unstable(*feature) {
615 let explain = format!("`cfg({})` is experimental and subject to change", cfg);
616 feature_err(sess, *feature, cfg_span, &explain).emit();
620 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
627 fn parse_version(s: &str, allow_appendix: bool) -> Option<Version> {
628 let mut components = s.split('-');
629 let d = components.next()?;
630 if !allow_appendix && components.next().is_some() {
633 let mut digits = d.splitn(3, '.');
634 let major = digits.next()?.parse().ok()?;
635 let minor = digits.next()?.parse().ok()?;
636 let patch = digits.next().unwrap_or("0").parse().ok()?;
637 Some(Version { major, minor, patch })
640 /// Evaluate a cfg-like condition (with `any` and `all`), using `eval` to
641 /// evaluate individual items.
642 pub fn eval_condition(
645 features: Option<&Features>,
646 eval: &mut impl FnMut(Condition) -> bool,
649 ast::MetaItemKind::List(ref mis) if cfg.name_or_empty() == sym::version => {
650 try_gate_cfg(sym::version, cfg.span, sess, features);
651 let (min_version, span) = match &mis[..] {
652 [NestedMetaItem::Literal(Lit { kind: LitKind::Str(sym, ..), span, .. })] => {
656 NestedMetaItem::Literal(Lit { span, .. })
657 | NestedMetaItem::MetaItem(MetaItem { span, .. }),
659 sess.emit_err(session_diagnostics::ExpectedVersionLiteral { span: *span });
663 sess.emit_err(session_diagnostics::ExpectedSingleVersionLiteral {
669 let Some(min_version) = parse_version(min_version.as_str(), false) else {
670 sess.emit_warning(session_diagnostics::UnknownVersionLiteral { span: *span });
673 let rustc_version = parse_version(env!("CFG_RELEASE"), true).unwrap();
675 // See https://github.com/rust-lang/rust/issues/64796#issuecomment-640851454 for details
676 if sess.assume_incomplete_release {
677 rustc_version > min_version
679 rustc_version >= min_version
682 ast::MetaItemKind::List(ref mis) => {
683 for mi in mis.iter() {
684 if !mi.is_meta_item() {
688 AttrError::UnsupportedLiteral(UnsupportedLiteralReason::Generic, false),
694 // The unwraps below may look dangerous, but we've already asserted
695 // that they won't fail with the loop above.
696 match cfg.name_or_empty() {
699 // We don't use any() here, because we want to evaluate all cfg condition
700 // as eval_condition can (and does) extra checks
701 .fold(false, |res, mi| {
702 res | eval_condition(mi.meta_item().unwrap(), sess, features, eval)
706 // We don't use all() here, because we want to evaluate all cfg condition
707 // as eval_condition can (and does) extra checks
708 .fold(true, |res, mi| {
709 res & eval_condition(mi.meta_item().unwrap(), sess, features, eval)
713 sess.emit_err(session_diagnostics::ExpectedOneCfgPattern {
719 !eval_condition(mis[0].meta_item().unwrap(), sess, features, eval)
722 if let Some(features) = features && !features.cfg_target_compact {
725 sym::cfg_target_compact,
727 &"compact `cfg(target(..))` is experimental and subject to change"
731 mis.iter().fold(true, |res, mi| {
732 let mut mi = mi.meta_item().unwrap().clone();
733 if let [seg, ..] = &mut mi.path.segments[..] {
734 seg.ident.name = Symbol::intern(&format!("target_{}", seg.ident.name));
737 res & eval_condition(&mi, sess, features, eval)
741 sess.emit_err(session_diagnostics::InvalidPredicate {
743 predicate: pprust::path_to_string(&cfg.path),
749 ast::MetaItemKind::Word | MetaItemKind::NameValue(..) if cfg.path.segments.len() != 1 => {
750 sess.emit_err(session_diagnostics::CfgPredicateIdentifier { span: cfg.path.span });
753 MetaItemKind::NameValue(ref lit) if !lit.kind.is_str() => {
757 AttrError::UnsupportedLiteral(
758 UnsupportedLiteralReason::CfgString,
759 lit.kind.is_bytestr(),
764 ast::MetaItemKind::Word | ast::MetaItemKind::NameValue(..) => {
765 let ident = cfg.ident().expect("multi-segment cfg predicate");
768 name_span: ident.span,
769 value: cfg.value_str(),
770 value_span: cfg.name_value_literal_span(),
777 #[derive(Copy, Debug, Encodable, Decodable, Clone, HashStable_Generic)]
778 pub struct Deprecation {
779 pub since: Option<Symbol>,
780 /// The note to issue a reason.
781 pub note: Option<Symbol>,
782 /// A text snippet used to completely replace any use of the deprecated item in an expression.
784 /// This is currently unstable.
785 pub suggestion: Option<Symbol>,
787 /// Whether to treat the since attribute as being a Rust version identifier
788 /// (rather than an opaque string).
789 pub is_since_rustc_version: bool,
792 /// Finds the deprecation attribute. `None` if none exists.
793 pub fn find_deprecation(sess: &Session, attrs: &[Attribute]) -> Option<(Deprecation, Span)> {
794 find_deprecation_generic(sess, attrs.iter())
797 fn find_deprecation_generic<'a, I>(sess: &Session, attrs_iter: I) -> Option<(Deprecation, Span)>
799 I: Iterator<Item = &'a Attribute>,
801 let mut depr: Option<(Deprecation, Span)> = None;
802 let is_rustc = sess.features_untracked().staged_api;
804 'outer: for attr in attrs_iter {
805 if !attr.has_name(sym::deprecated) {
809 let Some(meta) = attr.meta() else {
812 let mut since = None;
814 let mut suggestion = None;
816 MetaItemKind::Word => {}
817 MetaItemKind::NameValue(..) => note = meta.value_str(),
818 MetaItemKind::List(list) => {
819 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
824 AttrError::MultipleItem(pprust::path_to_string(&meta.path)),
828 if let Some(v) = meta.value_str() {
832 if let Some(lit) = meta.name_value_literal() {
836 AttrError::UnsupportedLiteral(
837 UnsupportedLiteralReason::DeprecatedString,
838 lit.kind.is_bytestr(),
842 sess.emit_err(session_diagnostics::IncorrectMetaItem2 {
853 NestedMetaItem::MetaItem(mi) => match mi.name_or_empty() {
855 if !get(mi, &mut since) {
860 if !get(mi, &mut note) {
865 if !sess.features_untracked().deprecated_suggestion {
866 sess.emit_err(session_diagnostics::DeprecatedItemSuggestion {
868 is_nightly: sess.is_nightly_build().then_some(()),
873 if !get(mi, &mut suggestion) {
881 AttrError::UnknownMetaItem(
882 pprust::path_to_string(&mi.path),
883 if sess.features_untracked().deprecated_suggestion {
884 &["since", "note", "suggestion"]
893 NestedMetaItem::Literal(lit) => {
897 AttrError::UnsupportedLiteral(
898 UnsupportedLiteralReason::DeprecatedKvPair,
911 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingSince);
916 sess.emit_err(session_diagnostics::MissingNote { span: attr.span });
922 Deprecation { since, note, suggestion, is_since_rustc_version: is_rustc },
930 #[derive(PartialEq, Debug, Encodable, Decodable, Copy, Clone)]
940 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
941 #[derive(Encodable, Decodable, HashStable_Generic)]
943 SignedInt(ast::IntTy),
944 UnsignedInt(ast::UintTy),
949 pub fn is_signed(self) -> bool {
953 SignedInt(..) => true,
954 UnsignedInt(..) => false,
959 /// Parse #[repr(...)] forms.
961 /// Valid repr contents: any of the primitive integral type names (see
962 /// `int_type_of_word`, below) to specify enum discriminant type; `C`, to use
963 /// the same discriminant size that the corresponding C enum would or C
964 /// structure layout, `packed` to remove padding, and `transparent` to delegate representation
965 /// concerns to the only non-ZST field.
966 pub fn find_repr_attrs(sess: &Session, attr: &Attribute) -> Vec<ReprAttr> {
967 if attr.has_name(sym::repr) { parse_repr_attr(sess, attr) } else { Vec::new() }
970 pub fn parse_repr_attr(sess: &Session, attr: &Attribute) -> Vec<ReprAttr> {
971 assert!(attr.has_name(sym::repr), "expected `#[repr(..)]`, found: {:?}", attr);
973 let mut acc = Vec::new();
974 let diagnostic = &sess.parse_sess.span_diagnostic;
976 if let Some(items) = attr.meta_item_list() {
978 let mut recognised = false;
980 let hint = match item.name_or_empty() {
981 sym::C => Some(ReprC),
982 sym::packed => Some(ReprPacked(1)),
983 sym::simd => Some(ReprSimd),
984 sym::transparent => Some(ReprTransparent),
986 sess.emit_err(session_diagnostics::InvalidReprAlignNeedArg {
992 name => int_type_of_word(name).map(ReprInt),
995 if let Some(h) = hint {
999 } else if let Some((name, value)) = item.name_value_literal() {
1000 let mut literal_error = None;
1001 if name == sym::align {
1003 match parse_alignment(&value.kind) {
1004 Ok(literal) => acc.push(ReprAlign(literal)),
1005 Err(message) => literal_error = Some(message),
1007 } else if name == sym::packed {
1009 match parse_alignment(&value.kind) {
1010 Ok(literal) => acc.push(ReprPacked(literal)),
1011 Err(message) => literal_error = Some(message),
1013 } else if matches!(name, sym::C | sym::simd | sym::transparent)
1014 || int_type_of_word(name).is_some()
1017 sess.emit_err(session_diagnostics::InvalidReprHintNoParen {
1019 name: name.to_ident_string(),
1022 if let Some(literal_error) = literal_error {
1023 sess.emit_err(session_diagnostics::InvalidReprGeneric {
1025 repr_arg: name.to_ident_string(),
1026 error_part: literal_error,
1029 } else if let Some(meta_item) = item.meta_item() {
1030 if let MetaItemKind::NameValue(ref value) = meta_item.kind {
1031 if meta_item.has_name(sym::align) || meta_item.has_name(sym::packed) {
1032 let name = meta_item.name_or_empty().to_ident_string();
1034 sess.emit_err(session_diagnostics::IncorrectReprFormatGeneric {
1037 cause: IncorrectReprFormatGenericCause::from_lit_kind(
1045 meta_item.name_or_empty(),
1046 sym::C | sym::simd | sym::transparent
1047 ) || int_type_of_word(meta_item.name_or_empty()).is_some()
1050 sess.emit_err(session_diagnostics::InvalidReprHintNoValue {
1051 span: meta_item.span,
1052 name: meta_item.name_or_empty().to_ident_string(),
1056 } else if let MetaItemKind::List(_) = meta_item.kind {
1057 if meta_item.has_name(sym::align) {
1059 sess.emit_err(session_diagnostics::IncorrectReprFormatAlignOneArg {
1060 span: meta_item.span,
1062 } else if meta_item.has_name(sym::packed) {
1064 sess.emit_err(session_diagnostics::IncorrectReprFormatPackedOneOrZeroArg {
1065 span: meta_item.span,
1068 meta_item.name_or_empty(),
1069 sym::C | sym::simd | sym::transparent
1070 ) || int_type_of_word(meta_item.name_or_empty()).is_some()
1073 sess.emit_err(session_diagnostics::InvalidReprHintNoParen {
1074 span: meta_item.span,
1075 name: meta_item.name_or_empty().to_ident_string(),
1081 // Not a word we recognize. This will be caught and reported by
1082 // the `check_mod_attrs` pass, but this pass doesn't always run
1083 // (e.g. if we only pretty-print the source), so we have to gate
1084 // the `delay_span_bug` call as follows:
1085 if sess.opts.pretty.map_or(true, |pp| pp.needs_analysis()) {
1086 diagnostic.delay_span_bug(item.span(), "unrecognized representation hint");
1094 fn int_type_of_word(s: Symbol) -> Option<IntType> {
1098 sym::i8 => Some(SignedInt(ast::IntTy::I8)),
1099 sym::u8 => Some(UnsignedInt(ast::UintTy::U8)),
1100 sym::i16 => Some(SignedInt(ast::IntTy::I16)),
1101 sym::u16 => Some(UnsignedInt(ast::UintTy::U16)),
1102 sym::i32 => Some(SignedInt(ast::IntTy::I32)),
1103 sym::u32 => Some(UnsignedInt(ast::UintTy::U32)),
1104 sym::i64 => Some(SignedInt(ast::IntTy::I64)),
1105 sym::u64 => Some(UnsignedInt(ast::UintTy::U64)),
1106 sym::i128 => Some(SignedInt(ast::IntTy::I128)),
1107 sym::u128 => Some(UnsignedInt(ast::UintTy::U128)),
1108 sym::isize => Some(SignedInt(ast::IntTy::Isize)),
1109 sym::usize => Some(UnsignedInt(ast::UintTy::Usize)),
1114 pub enum TransparencyError {
1115 UnknownTransparency(Symbol, Span),
1116 MultipleTransparencyAttrs(Span, Span),
1119 pub fn find_transparency(
1120 attrs: &[Attribute],
1122 ) -> (Transparency, Option<TransparencyError>) {
1123 let mut transparency = None;
1124 let mut error = None;
1126 if attr.has_name(sym::rustc_macro_transparency) {
1127 if let Some((_, old_span)) = transparency {
1128 error = Some(TransparencyError::MultipleTransparencyAttrs(old_span, attr.span));
1130 } else if let Some(value) = attr.value_str() {
1131 transparency = Some((
1133 sym::transparent => Transparency::Transparent,
1134 sym::semitransparent => Transparency::SemiTransparent,
1135 sym::opaque => Transparency::Opaque,
1137 error = Some(TransparencyError::UnknownTransparency(value, attr.span));
1146 let fallback = if macro_rules { Transparency::SemiTransparent } else { Transparency::Opaque };
1147 (transparency.map_or(fallback, |t| t.0), error)
1150 pub fn allow_internal_unstable<'a>(
1152 attrs: &'a [Attribute],
1153 ) -> impl Iterator<Item = Symbol> + 'a {
1154 allow_unstable(sess, attrs, sym::allow_internal_unstable)
1157 pub fn rustc_allow_const_fn_unstable<'a>(
1159 attrs: &'a [Attribute],
1160 ) -> impl Iterator<Item = Symbol> + 'a {
1161 allow_unstable(sess, attrs, sym::rustc_allow_const_fn_unstable)
1164 fn allow_unstable<'a>(
1166 attrs: &'a [Attribute],
1168 ) -> impl Iterator<Item = Symbol> + 'a {
1169 let attrs = sess.filter_by_name(attrs, symbol);
1171 .filter_map(move |attr| {
1172 attr.meta_item_list().or_else(|| {
1173 sess.emit_err(session_diagnostics::ExpectsFeatureList {
1175 name: symbol.to_ident_string(),
1182 list.into_iter().filter_map(move |it| {
1183 let name = it.ident().map(|ident| ident.name);
1185 sess.emit_err(session_diagnostics::ExpectsFeatures {
1187 name: symbol.to_ident_string(),
1194 pub fn parse_alignment(node: &ast::LitKind) -> Result<u32, &'static str> {
1195 if let ast::LitKind::Int(literal, ast::LitIntType::Unsuffixed) = node {
1196 if literal.is_power_of_two() {
1197 // rustc_middle::ty::layout::Align restricts align to <= 2^29
1198 if *literal <= 1 << 29 { Ok(*literal as u32) } else { Err("larger than 2^29") }
1200 Err("not a power of two")
1203 Err("not an unsuffixed integer")