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 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()
23 UnknownMetaItem(String, &'static [&'static str]),
27 MultipleStabilityLevels,
28 UnsupportedLiteral(&'static str, /* is_bytestr */ bool),
31 fn handle_errors(sess: &ParseSess, span: Span, error: AttrError) {
32 let diag = &sess.span_diagnostic;
34 AttrError::MultipleItem(item) => {
35 struct_span_err!(diag, span, E0538, "multiple '{}' items", item).emit();
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(", ")))
43 AttrError::MissingSince => {
44 struct_span_err!(diag, span, E0542, "missing 'since'").emit();
46 AttrError::NonIdentFeature => {
47 struct_span_err!(diag, span, E0546, "'feature' is not an identifier").emit();
49 AttrError::MissingFeature => {
50 struct_span_err!(diag, span, E0546, "missing 'feature'").emit();
52 AttrError::MultipleStabilityLevels => {
53 struct_span_err!(diag, span, E0544, "multiple stability levels").emit();
55 AttrError::UnsupportedLiteral(msg, is_bytestr) => {
56 let mut err = struct_span_err!(diag, span, E0565, "{}", msg);
58 if let Ok(lint_str) = sess.source_map().span_to_snippet(span) {
61 "consider removing the prefix",
63 Applicability::MaybeIncorrect,
72 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
80 #[derive(Clone, Encodable, Decodable, Debug, PartialEq, Eq, HashStable_Generic)]
81 pub enum InstructionSetAttr {
86 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
87 pub enum OptimizeAttr {
93 /// Represents the following attributes:
97 #[derive(Encodable, Decodable, Copy, Clone, Debug, PartialEq, Eq, Hash)]
98 #[derive(HashStable_Generic)]
99 pub struct Stability {
100 pub level: StabilityLevel,
105 pub fn is_unstable(&self) -> bool {
106 self.level.is_unstable()
109 pub fn is_stable(&self) -> bool {
110 self.level.is_stable()
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,
120 /// whether the function has a `#[rustc_promotable]` attribute
121 pub promotable: bool,
124 impl ConstStability {
125 pub fn is_const_unstable(&self) -> bool {
126 self.level.is_unstable()
129 pub fn is_const_stable(&self) -> bool {
130 self.level.is_stable()
134 /// The available stability levels.
135 #[derive(Encodable, Decodable, PartialEq, Copy, Clone, Debug, Eq, Hash)]
136 #[derive(HashStable_Generic)]
137 pub enum StabilityLevel {
140 /// Reason for the current stability level.
141 reason: UnstableReason,
142 /// Relevant `rust-lang/rust` issue.
143 issue: Option<NonZeroU32>,
145 /// If part of a feature is stabilized and a new feature is added for the remaining parts,
146 /// then the `implied_by` attribute is used to indicate which now-stable feature previously
147 /// contained a item.
150 /// #[unstable(feature = "foo", issue = "...")]
152 /// #[unstable(feature = "foo", issue = "...")]
159 /// #[stable(feature = "foo", since = "1.XX.X")]
161 /// #[unstable(feature = "foobar", issue = "...", implied_by = "foo")]
164 implied_by: Option<Symbol>,
168 /// Rust release which stabilized this feature.
170 /// Is this item allowed to be referred to on stable, despite being contained in unstable
172 allowed_through_unstable_modules: bool,
176 impl StabilityLevel {
177 pub fn is_unstable(&self) -> bool {
178 matches!(self, StabilityLevel::Unstable { .. })
180 pub fn is_stable(&self) -> bool {
181 matches!(self, StabilityLevel::Stable { .. })
185 #[derive(Encodable, Decodable, PartialEq, Copy, Clone, Debug, Eq, Hash)]
186 #[derive(HashStable_Generic)]
187 pub enum UnstableReason {
193 impl UnstableReason {
194 fn from_opt_reason(reason: Option<Symbol>) -> Self {
195 // UnstableReason::Default constructed manually
197 Some(r) => Self::Some(r),
202 pub fn to_opt_reason(&self) -> Option<Symbol> {
205 Self::Default => Some(sym::unstable_location_reason_default),
206 Self::Some(r) => Some(*r),
211 /// Collects stability info from all stability attributes in `attrs`.
212 /// Returns `None` if no stability attributes are found.
213 pub fn find_stability(
217 ) -> (Option<(Stability, Span)>, Option<(ConstStability, Span)>) {
218 find_stability_generic(sess, attrs.iter(), item_sp)
221 fn find_stability_generic<'a, I>(
225 ) -> (Option<(Stability, Span)>, Option<(ConstStability, Span)>)
227 I: Iterator<Item = &'a Attribute>,
229 use StabilityLevel::*;
231 let mut stab: Option<(Stability, Span)> = None;
232 let mut const_stab: Option<(ConstStability, Span)> = None;
233 let mut promotable = false;
234 let mut allowed_through_unstable_modules = false;
236 let diagnostic = &sess.parse_sess.span_diagnostic;
238 'outer: for attr in attrs_iter {
240 sym::rustc_const_unstable,
241 sym::rustc_const_stable,
244 sym::rustc_promotable,
245 sym::rustc_allowed_through_unstable_modules,
248 .any(|&s| attr.has_name(s))
250 continue; // not a stability level
253 let meta = attr.meta();
255 if attr.has_name(sym::rustc_promotable) {
257 } else if attr.has_name(sym::rustc_allowed_through_unstable_modules) {
258 allowed_through_unstable_modules = true;
260 // attributes with data
261 else if let Some(MetaItem { kind: MetaItemKind::List(ref metas), .. }) = meta {
262 let meta = meta.as_ref().unwrap();
263 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
268 AttrError::MultipleItem(pprust::path_to_string(&meta.path)),
272 if let Some(v) = meta.value_str() {
276 struct_span_err!(diagnostic, meta.span, E0539, "incorrect meta item").emit();
281 let meta_name = meta.name_or_empty();
283 sym::rustc_const_unstable | sym::unstable => {
284 if meta_name == sym::unstable && stab.is_some() {
288 AttrError::MultipleStabilityLevels,
291 } else if meta_name == sym::rustc_const_unstable && const_stab.is_some() {
295 AttrError::MultipleStabilityLevels,
300 let mut feature = None;
301 let mut reason = None;
302 let mut issue = None;
303 let mut issue_num = None;
304 let mut is_soft = false;
305 let mut implied_by = None;
307 let Some(mi) = meta.meta_item() else {
311 AttrError::UnsupportedLiteral("unsupported literal", false),
315 match mi.name_or_empty() {
317 if !get(mi, &mut feature) {
322 if !get(mi, &mut reason) {
327 if !get(mi, &mut issue) {
331 // These unwraps are safe because `get` ensures the meta item
332 // is a name/value pair string literal.
333 issue_num = match issue.unwrap().as_str() {
336 let emit_diag = |msg: &str| {
341 "`issue` must be a non-zero numeric string \
344 .span_label(mi.name_value_literal_span().unwrap(), msg)
347 match issue.parse() {
350 "`issue` must not be \"0\", \
351 use \"none\" instead",
355 Ok(num) => NonZeroU32::new(num),
357 emit_diag(&err.to_string());
366 let msg = "`soft` should not have any arguments";
367 sess.parse_sess.span_diagnostic.span_err(mi.span, msg);
372 if !get(mi, &mut implied_by) {
380 AttrError::UnknownMetaItem(
381 pprust::path_to_string(&mi.path),
382 &["feature", "reason", "issue", "soft"],
390 match (feature, reason, issue) {
391 (Some(feature), reason, Some(_)) => {
392 if !rustc_lexer::is_ident(feature.as_str()) {
396 AttrError::NonIdentFeature,
400 let level = Unstable {
401 reason: UnstableReason::from_opt_reason(reason),
406 if sym::unstable == meta_name {
407 stab = Some((Stability { level, feature }, attr.span));
410 ConstStability { level, feature, promotable: false },
416 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingFeature);
420 struct_span_err!(diagnostic, attr.span, E0547, "missing 'issue'")
426 sym::rustc_const_stable | sym::stable => {
427 if meta_name == sym::stable && stab.is_some() {
431 AttrError::MultipleStabilityLevels,
434 } else if meta_name == sym::rustc_const_stable && const_stab.is_some() {
438 AttrError::MultipleStabilityLevels,
443 let mut feature = None;
444 let mut since = None;
447 NestedMetaItem::MetaItem(mi) => match mi.name_or_empty() {
449 if !get(mi, &mut feature) {
454 if !get(mi, &mut since) {
462 AttrError::UnknownMetaItem(
463 pprust::path_to_string(&mi.path),
464 &["feature", "since"],
470 NestedMetaItem::Literal(lit) => {
474 AttrError::UnsupportedLiteral("unsupported literal", false),
481 match (feature, since) {
482 (Some(feature), Some(since)) => {
483 let level = Stable { since, allowed_through_unstable_modules: false };
484 if sym::stable == meta_name {
485 stab = Some((Stability { level, feature }, attr.span));
488 ConstStability { level, feature, promotable: false },
494 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingFeature);
498 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingSince);
508 // Merge the const-unstable info into the stability info
510 if let Some((ref mut stab, _)) = const_stab {
511 stab.promotable = promotable;
517 "`rustc_promotable` attribute must be paired with either a `rustc_const_unstable` \
518 or a `rustc_const_stable` attribute"
524 if allowed_through_unstable_modules {
527 level: StabilityLevel::Stable { ref mut allowed_through_unstable_modules, .. },
533 *allowed_through_unstable_modules = true;
539 "`rustc_allowed_through_unstable_modules` attribute must be paired with a `stable` attribute"
548 pub fn find_crate_name(sess: &Session, attrs: &[Attribute]) -> Option<Symbol> {
549 sess.first_attr_value_str_by_name(attrs, sym::crate_name)
552 #[derive(Clone, Debug)]
553 pub struct Condition {
556 pub value: Option<Symbol>,
557 pub value_span: Option<Span>,
561 /// Tests if a cfg-pattern matches the cfg set
565 lint_node_id: NodeId,
566 features: Option<&Features>,
568 eval_condition(cfg, sess, features, &mut |cfg| {
569 try_gate_cfg(cfg.name, cfg.span, sess, features);
570 if let Some(names_valid) = &sess.check_config.names_valid {
571 if !names_valid.contains(&cfg.name) {
572 sess.buffer_lint_with_diagnostic(
576 "unexpected `cfg` condition name",
577 BuiltinLintDiagnostics::UnexpectedCfg((cfg.name, cfg.name_span), None),
581 if let Some(value) = cfg.value {
582 if let Some(values) = &sess.check_config.values_valid.get(&cfg.name) {
583 if !values.contains(&value) {
584 sess.buffer_lint_with_diagnostic(
588 "unexpected `cfg` condition value",
589 BuiltinLintDiagnostics::UnexpectedCfg(
590 (cfg.name, cfg.name_span),
591 cfg.value_span.map(|vs| (value, vs)),
597 sess.config.contains(&(cfg.name, cfg.value))
601 fn try_gate_cfg(name: Symbol, span: Span, sess: &ParseSess, features: Option<&Features>) {
602 let gate = find_gated_cfg(|sym| sym == name);
603 if let (Some(feats), Some(gated_cfg)) = (features, gate) {
604 gate_cfg(&gated_cfg, span, sess, feats);
608 fn gate_cfg(gated_cfg: &GatedCfg, cfg_span: Span, sess: &ParseSess, features: &Features) {
609 let (cfg, feature, has_feature) = gated_cfg;
610 if !has_feature(features) && !cfg_span.allows_unstable(*feature) {
611 let explain = format!("`cfg({})` is experimental and subject to change", cfg);
612 feature_err(sess, *feature, cfg_span, &explain).emit();
616 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
623 fn parse_version(s: &str, allow_appendix: bool) -> Option<Version> {
624 let mut components = s.split('-');
625 let d = components.next()?;
626 if !allow_appendix && components.next().is_some() {
629 let mut digits = d.splitn(3, '.');
630 let major = digits.next()?.parse().ok()?;
631 let minor = digits.next()?.parse().ok()?;
632 let patch = digits.next().unwrap_or("0").parse().ok()?;
633 Some(Version { major, minor, patch })
636 /// Evaluate a cfg-like condition (with `any` and `all`), using `eval` to
637 /// evaluate individual items.
638 pub fn eval_condition(
641 features: Option<&Features>,
642 eval: &mut impl FnMut(Condition) -> bool,
645 ast::MetaItemKind::List(ref mis) if cfg.name_or_empty() == sym::version => {
646 try_gate_cfg(sym::version, cfg.span, sess, features);
647 let (min_version, span) = match &mis[..] {
648 [NestedMetaItem::Literal(Lit { kind: LitKind::Str(sym, ..), span, .. })] => {
652 NestedMetaItem::Literal(Lit { span, .. })
653 | NestedMetaItem::MetaItem(MetaItem { span, .. }),
656 .struct_span_err(*span, "expected a version literal")
662 .struct_span_err(cfg.span, "expected single version literal")
667 let Some(min_version) = parse_version(min_version.as_str(), false) else {
671 "unknown version literal format, assuming it refers to a future version",
676 let rustc_version = parse_version(env!("CFG_RELEASE"), true).unwrap();
678 // See https://github.com/rust-lang/rust/issues/64796#issuecomment-640851454 for details
679 if sess.assume_incomplete_release {
680 rustc_version > min_version
682 rustc_version >= min_version
685 ast::MetaItemKind::List(ref mis) => {
686 for mi in mis.iter() {
687 if !mi.is_meta_item() {
691 AttrError::UnsupportedLiteral("unsupported literal", false),
697 // The unwraps below may look dangerous, but we've already asserted
698 // that they won't fail with the loop above.
699 match cfg.name_or_empty() {
702 // We don't use any() here, because we want to evaluate all cfg condition
703 // as eval_condition can (and does) extra checks
704 .fold(false, |res, mi| {
705 res | eval_condition(mi.meta_item().unwrap(), sess, features, eval)
709 // We don't use all() here, because we want to evaluate all cfg condition
710 // as eval_condition can (and does) extra checks
711 .fold(true, |res, mi| {
712 res & eval_condition(mi.meta_item().unwrap(), sess, features, eval)
717 sess.span_diagnostic,
720 "expected 1 cfg-pattern"
726 !eval_condition(mis[0].meta_item().unwrap(), sess, features, eval)
729 if let Some(features) = features && !features.cfg_target_compact {
732 sym::cfg_target_compact,
734 &"compact `cfg(target(..))` is experimental and subject to change"
738 mis.iter().fold(true, |res, mi| {
739 let mut mi = mi.meta_item().unwrap().clone();
740 if let [seg, ..] = &mut mi.path.segments[..] {
741 seg.ident.name = Symbol::intern(&format!("target_{}", seg.ident.name));
744 res & eval_condition(&mi, sess, features, eval)
749 sess.span_diagnostic,
752 "invalid predicate `{}`",
753 pprust::path_to_string(&cfg.path)
760 ast::MetaItemKind::Word | MetaItemKind::NameValue(..) if cfg.path.segments.len() != 1 => {
762 .span_err(cfg.path.span, "`cfg` predicate key must be an identifier");
765 MetaItemKind::NameValue(ref lit) if !lit.kind.is_str() => {
769 AttrError::UnsupportedLiteral(
770 "literal in `cfg` predicate value must be a string",
771 lit.kind.is_bytestr(),
776 ast::MetaItemKind::Word | ast::MetaItemKind::NameValue(..) => {
777 let ident = cfg.ident().expect("multi-segment cfg predicate");
780 name_span: ident.span,
781 value: cfg.value_str(),
782 value_span: cfg.name_value_literal_span(),
789 #[derive(Copy, Debug, Encodable, Decodable, Clone, HashStable_Generic)]
790 pub struct Deprecation {
791 pub since: Option<Symbol>,
792 /// The note to issue a reason.
793 pub note: Option<Symbol>,
794 /// A text snippet used to completely replace any use of the deprecated item in an expression.
796 /// This is currently unstable.
797 pub suggestion: Option<Symbol>,
799 /// Whether to treat the since attribute as being a Rust version identifier
800 /// (rather than an opaque string).
801 pub is_since_rustc_version: bool,
804 /// Finds the deprecation attribute. `None` if none exists.
805 pub fn find_deprecation(sess: &Session, attrs: &[Attribute]) -> Option<(Deprecation, Span)> {
806 find_deprecation_generic(sess, attrs.iter())
809 fn find_deprecation_generic<'a, I>(sess: &Session, attrs_iter: I) -> Option<(Deprecation, Span)>
811 I: Iterator<Item = &'a Attribute>,
813 let mut depr: Option<(Deprecation, Span)> = None;
814 let diagnostic = &sess.parse_sess.span_diagnostic;
815 let is_rustc = sess.features_untracked().staged_api;
817 'outer: for attr in attrs_iter {
818 if !attr.has_name(sym::deprecated) {
822 let Some(meta) = attr.meta() else {
825 let mut since = None;
827 let mut suggestion = None;
829 MetaItemKind::Word => {}
830 MetaItemKind::NameValue(..) => note = meta.value_str(),
831 MetaItemKind::List(list) => {
832 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
837 AttrError::MultipleItem(pprust::path_to_string(&meta.path)),
841 if let Some(v) = meta.value_str() {
845 if let Some(lit) = meta.name_value_literal() {
849 AttrError::UnsupportedLiteral(
850 "literal in `deprecated` \
851 value must be a string",
852 lit.kind.is_bytestr(),
856 struct_span_err!(diagnostic, meta.span, E0551, "incorrect meta item")
866 NestedMetaItem::MetaItem(mi) => match mi.name_or_empty() {
868 if !get(mi, &mut since) {
873 if !get(mi, &mut note) {
878 if !sess.features_untracked().deprecated_suggestion {
879 let mut diag = sess.struct_span_err(
881 "suggestions on deprecated items are unstable",
883 if sess.is_nightly_build() {
884 diag.help("add `#![feature(deprecated_suggestion)]` to the crate root");
886 diag.note("see #94785 for more details").emit();
889 if !get(mi, &mut suggestion) {
897 AttrError::UnknownMetaItem(
898 pprust::path_to_string(&mi.path),
899 if sess.features_untracked().deprecated_suggestion {
900 &["since", "note", "suggestion"]
909 NestedMetaItem::Literal(lit) => {
913 AttrError::UnsupportedLiteral(
914 "item in `deprecated` must be a key/value pair",
927 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingSince);
932 struct_span_err!(diagnostic, attr.span, E0543, "missing 'note'").emit();
938 Deprecation { since, note, suggestion, is_since_rustc_version: is_rustc },
946 #[derive(PartialEq, Debug, Encodable, Decodable, Copy, Clone)]
956 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
957 #[derive(Encodable, Decodable, HashStable_Generic)]
959 SignedInt(ast::IntTy),
960 UnsignedInt(ast::UintTy),
965 pub fn is_signed(self) -> bool {
969 SignedInt(..) => true,
970 UnsignedInt(..) => false,
975 /// Parse #[repr(...)] forms.
977 /// Valid repr contents: any of the primitive integral type names (see
978 /// `int_type_of_word`, below) to specify enum discriminant type; `C`, to use
979 /// the same discriminant size that the corresponding C enum would or C
980 /// structure layout, `packed` to remove padding, and `transparent` to delegate representation
981 /// concerns to the only non-ZST field.
982 pub fn find_repr_attrs(sess: &Session, attr: &Attribute) -> Vec<ReprAttr> {
983 if attr.has_name(sym::repr) { parse_repr_attr(sess, attr) } else { Vec::new() }
986 pub fn parse_repr_attr(sess: &Session, attr: &Attribute) -> Vec<ReprAttr> {
987 assert!(attr.has_name(sym::repr), "expected `#[repr(..)]`, found: {:?}", attr);
989 let mut acc = Vec::new();
990 let diagnostic = &sess.parse_sess.span_diagnostic;
992 if let Some(items) = attr.meta_item_list() {
994 let mut recognised = false;
996 let hint = match item.name_or_empty() {
997 sym::C => Some(ReprC),
998 sym::packed => Some(ReprPacked(1)),
999 sym::simd => Some(ReprSimd),
1000 sym::transparent => Some(ReprTransparent),
1002 let mut err = struct_span_err!(
1006 "invalid `repr(align)` attribute: `align` needs an argument"
1008 err.span_suggestion(
1010 "supply an argument here",
1012 Applicability::HasPlaceholders,
1018 name => int_type_of_word(name).map(ReprInt),
1021 if let Some(h) = hint {
1025 } else if let Some((name, value)) = item.name_value_literal() {
1026 let mut literal_error = None;
1027 if name == sym::align {
1029 match parse_alignment(&value.kind) {
1030 Ok(literal) => acc.push(ReprAlign(literal)),
1031 Err(message) => literal_error = Some(message),
1033 } else if name == sym::packed {
1035 match parse_alignment(&value.kind) {
1036 Ok(literal) => acc.push(ReprPacked(literal)),
1037 Err(message) => literal_error = Some(message),
1039 } else if matches!(name, sym::C | sym::simd | sym::transparent)
1040 || int_type_of_word(name).is_some()
1047 "invalid representation hint: `{}` does not take a parenthesized argument list",
1048 name.to_ident_string(),
1051 if let Some(literal_error) = literal_error {
1056 "invalid `repr({})` attribute: {}",
1057 name.to_ident_string(),
1062 } else if let Some(meta_item) = item.meta_item() {
1063 if let MetaItemKind::NameValue(ref value) = meta_item.kind {
1064 if meta_item.has_name(sym::align) || meta_item.has_name(sym::packed) {
1065 let name = meta_item.name_or_empty().to_ident_string();
1067 let mut err = struct_span_err!(
1071 "incorrect `repr({})` attribute format",
1075 ast::LitKind::Int(int, ast::LitIntType::Unsuffixed) => {
1076 err.span_suggestion(
1078 "use parentheses instead",
1079 format!("{}({})", name, int),
1080 Applicability::MachineApplicable,
1083 ast::LitKind::Str(s, _) => {
1084 err.span_suggestion(
1086 "use parentheses instead",
1087 format!("{}({})", name, s),
1088 Applicability::MachineApplicable,
1096 meta_item.name_or_empty(),
1097 sym::C | sym::simd | sym::transparent
1098 ) || int_type_of_word(meta_item.name_or_empty()).is_some()
1105 "invalid representation hint: `{}` does not take a value",
1106 meta_item.name_or_empty().to_ident_string(),
1111 } else if let MetaItemKind::List(_) = meta_item.kind {
1112 if meta_item.has_name(sym::align) {
1118 "incorrect `repr(align)` attribute format: \
1119 `align` takes exactly one argument in parentheses"
1122 } else if meta_item.has_name(sym::packed) {
1128 "incorrect `repr(packed)` attribute format: \
1129 `packed` takes exactly one parenthesized argument, \
1130 or no parentheses at all"
1134 meta_item.name_or_empty(),
1135 sym::C | sym::simd | sym::transparent
1136 ) || int_type_of_word(meta_item.name_or_empty()).is_some()
1143 "invalid representation hint: `{}` does not take a parenthesized argument list",
1144 meta_item.name_or_empty().to_ident_string(),
1150 // Not a word we recognize. This will be caught and reported by
1151 // the `check_mod_attrs` pass, but this pass doesn't always run
1152 // (e.g. if we only pretty-print the source), so we have to gate
1153 // the `delay_span_bug` call as follows:
1154 if sess.opts.pretty.map_or(true, |pp| pp.needs_analysis()) {
1155 diagnostic.delay_span_bug(item.span(), "unrecognized representation hint");
1163 fn int_type_of_word(s: Symbol) -> Option<IntType> {
1167 sym::i8 => Some(SignedInt(ast::IntTy::I8)),
1168 sym::u8 => Some(UnsignedInt(ast::UintTy::U8)),
1169 sym::i16 => Some(SignedInt(ast::IntTy::I16)),
1170 sym::u16 => Some(UnsignedInt(ast::UintTy::U16)),
1171 sym::i32 => Some(SignedInt(ast::IntTy::I32)),
1172 sym::u32 => Some(UnsignedInt(ast::UintTy::U32)),
1173 sym::i64 => Some(SignedInt(ast::IntTy::I64)),
1174 sym::u64 => Some(UnsignedInt(ast::UintTy::U64)),
1175 sym::i128 => Some(SignedInt(ast::IntTy::I128)),
1176 sym::u128 => Some(UnsignedInt(ast::UintTy::U128)),
1177 sym::isize => Some(SignedInt(ast::IntTy::Isize)),
1178 sym::usize => Some(UnsignedInt(ast::UintTy::Usize)),
1183 pub enum TransparencyError {
1184 UnknownTransparency(Symbol, Span),
1185 MultipleTransparencyAttrs(Span, Span),
1188 pub fn find_transparency(
1189 attrs: &[Attribute],
1191 ) -> (Transparency, Option<TransparencyError>) {
1192 let mut transparency = None;
1193 let mut error = None;
1195 if attr.has_name(sym::rustc_macro_transparency) {
1196 if let Some((_, old_span)) = transparency {
1197 error = Some(TransparencyError::MultipleTransparencyAttrs(old_span, attr.span));
1199 } else if let Some(value) = attr.value_str() {
1200 transparency = Some((
1202 sym::transparent => Transparency::Transparent,
1203 sym::semitransparent => Transparency::SemiTransparent,
1204 sym::opaque => Transparency::Opaque,
1206 error = Some(TransparencyError::UnknownTransparency(value, attr.span));
1215 let fallback = if macro_rules { Transparency::SemiTransparent } else { Transparency::Opaque };
1216 (transparency.map_or(fallback, |t| t.0), error)
1219 pub fn allow_internal_unstable<'a>(
1221 attrs: &'a [Attribute],
1222 ) -> impl Iterator<Item = Symbol> + 'a {
1223 allow_unstable(sess, attrs, sym::allow_internal_unstable)
1226 pub fn rustc_allow_const_fn_unstable<'a>(
1228 attrs: &'a [Attribute],
1229 ) -> impl Iterator<Item = Symbol> + 'a {
1230 allow_unstable(sess, attrs, sym::rustc_allow_const_fn_unstable)
1233 fn allow_unstable<'a>(
1235 attrs: &'a [Attribute],
1237 ) -> impl Iterator<Item = Symbol> + 'a {
1238 let attrs = sess.filter_by_name(attrs, symbol);
1240 .filter_map(move |attr| {
1241 attr.meta_item_list().or_else(|| {
1242 sess.diagnostic().span_err(
1244 &format!("`{}` expects a list of feature names", symbol.to_ident_string()),
1251 list.into_iter().filter_map(move |it| {
1252 let name = it.ident().map(|ident| ident.name);
1254 sess.diagnostic().span_err(
1256 &format!("`{}` expects feature names", symbol.to_ident_string()),
1263 pub fn parse_alignment(node: &ast::LitKind) -> Result<u32, &'static str> {
1264 if let ast::LitKind::Int(literal, ast::LitIntType::Unsuffixed) = node {
1265 if literal.is_power_of_two() {
1266 // rustc_middle::ty::layout::Align restricts align to <= 2^29
1267 if *literal <= 1 << 29 { Ok(*literal as u32) } else { Err("larger than 2^29") }
1269 Err("not a power of two")
1272 Err("not an unsuffixed integer")