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 {
138 // Reason for the current stability level and the relevant rust-lang issue
139 Unstable { reason: Option<Symbol>, issue: Option<NonZeroU32>, is_soft: bool },
140 Stable { since: Symbol, allowed_through_unstable_modules: bool },
143 impl StabilityLevel {
144 pub fn is_unstable(&self) -> bool {
145 matches!(self, StabilityLevel::Unstable { .. })
147 pub fn is_stable(&self) -> bool {
148 matches!(self, StabilityLevel::Stable { .. })
152 /// Collects stability info from all stability attributes in `attrs`.
153 /// Returns `None` if no stability attributes are found.
154 pub fn find_stability(
158 ) -> (Option<(Stability, Span)>, Option<(ConstStability, Span)>) {
159 find_stability_generic(sess, attrs.iter(), item_sp)
162 fn find_stability_generic<'a, I>(
166 ) -> (Option<(Stability, Span)>, Option<(ConstStability, Span)>)
168 I: Iterator<Item = &'a Attribute>,
170 use StabilityLevel::*;
172 let mut stab: Option<(Stability, Span)> = None;
173 let mut const_stab: Option<(ConstStability, Span)> = None;
174 let mut promotable = false;
175 let mut allowed_through_unstable_modules = false;
177 let diagnostic = &sess.parse_sess.span_diagnostic;
179 'outer: for attr in attrs_iter {
181 sym::rustc_const_unstable,
182 sym::rustc_const_stable,
185 sym::rustc_promotable,
186 sym::rustc_allowed_through_unstable_modules,
189 .any(|&s| attr.has_name(s))
191 continue; // not a stability level
194 let meta = attr.meta();
196 if attr.has_name(sym::rustc_promotable) {
198 } else if attr.has_name(sym::rustc_allowed_through_unstable_modules) {
199 allowed_through_unstable_modules = true;
201 // attributes with data
202 else if let Some(MetaItem { kind: MetaItemKind::List(ref metas), .. }) = meta {
203 let meta = meta.as_ref().unwrap();
204 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
209 AttrError::MultipleItem(pprust::path_to_string(&meta.path)),
213 if let Some(v) = meta.value_str() {
217 struct_span_err!(diagnostic, meta.span, E0539, "incorrect meta item").emit();
222 let meta_name = meta.name_or_empty();
224 sym::rustc_const_unstable | sym::unstable => {
225 if meta_name == sym::unstable && stab.is_some() {
229 AttrError::MultipleStabilityLevels,
232 } else if meta_name == sym::rustc_const_unstable && const_stab.is_some() {
236 AttrError::MultipleStabilityLevels,
241 let mut feature = None;
242 let mut reason = None;
243 let mut issue = None;
244 let mut issue_num = None;
245 let mut is_soft = false;
247 let Some(mi) = meta.meta_item() else {
251 AttrError::UnsupportedLiteral("unsupported literal", false),
255 match mi.name_or_empty() {
257 if !get(mi, &mut feature) {
262 if !get(mi, &mut reason) {
267 if !get(mi, &mut issue) {
271 // These unwraps are safe because `get` ensures the meta item
272 // is a name/value pair string literal.
273 issue_num = match issue.unwrap().as_str() {
276 let emit_diag = |msg: &str| {
281 "`issue` must be a non-zero numeric string \
284 .span_label(mi.name_value_literal_span().unwrap(), msg)
287 match issue.parse() {
290 "`issue` must not be \"0\", \
291 use \"none\" instead",
295 Ok(num) => NonZeroU32::new(num),
297 emit_diag(&err.to_string());
306 let msg = "`soft` should not have any arguments";
307 sess.parse_sess.span_diagnostic.span_err(mi.span, msg);
315 AttrError::UnknownMetaItem(
316 pprust::path_to_string(&mi.path),
317 &["feature", "reason", "issue", "soft"],
325 match (feature, reason, issue) {
326 (Some(feature), reason, Some(_)) => {
327 if !rustc_lexer::is_ident(feature.as_str()) {
331 AttrError::NonIdentFeature,
335 let level = Unstable { reason, issue: issue_num, is_soft };
336 if sym::unstable == meta_name {
337 stab = Some((Stability { level, feature }, attr.span));
340 ConstStability { level, feature, promotable: false },
346 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingFeature);
350 struct_span_err!(diagnostic, attr.span, E0547, "missing 'issue'")
356 sym::rustc_const_stable | sym::stable => {
357 if meta_name == sym::stable && stab.is_some() {
361 AttrError::MultipleStabilityLevels,
364 } else if meta_name == sym::rustc_const_stable && const_stab.is_some() {
368 AttrError::MultipleStabilityLevels,
373 let mut feature = None;
374 let mut since = None;
377 NestedMetaItem::MetaItem(mi) => match mi.name_or_empty() {
379 if !get(mi, &mut feature) {
384 if !get(mi, &mut since) {
392 AttrError::UnknownMetaItem(
393 pprust::path_to_string(&mi.path),
400 NestedMetaItem::Literal(lit) => {
404 AttrError::UnsupportedLiteral("unsupported literal", false),
411 match (feature, since) {
412 (Some(feature), Some(since)) => {
413 let level = Stable { since, allowed_through_unstable_modules: false };
414 if sym::stable == meta_name {
415 stab = Some((Stability { level, feature }, attr.span));
418 ConstStability { level, feature, promotable: false },
424 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingFeature);
428 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingSince);
438 // Merge the const-unstable info into the stability info
440 if let Some((ref mut stab, _)) = const_stab {
441 stab.promotable = promotable;
447 "`rustc_promotable` attribute must be paired with either a `rustc_const_unstable` \
448 or a `rustc_const_stable` attribute"
454 if allowed_through_unstable_modules {
457 level: StabilityLevel::Stable { ref mut allowed_through_unstable_modules, .. },
463 *allowed_through_unstable_modules = true;
469 "`rustc_allowed_through_unstable_modules` attribute must be paired with a `stable` attribute"
478 pub fn find_crate_name(sess: &Session, attrs: &[Attribute]) -> Option<Symbol> {
479 sess.first_attr_value_str_by_name(attrs, sym::crate_name)
482 #[derive(Clone, Debug)]
483 pub struct Condition {
486 pub value: Option<Symbol>,
487 pub value_span: Option<Span>,
491 /// Tests if a cfg-pattern matches the cfg set
495 lint_node_id: NodeId,
496 features: Option<&Features>,
498 eval_condition(cfg, sess, features, &mut |cfg| {
499 try_gate_cfg(cfg.name, cfg.span, sess, features);
500 if let Some(names_valid) = &sess.check_config.names_valid {
501 if !names_valid.contains(&cfg.name) {
502 sess.buffer_lint_with_diagnostic(
506 "unexpected `cfg` condition name",
507 BuiltinLintDiagnostics::UnexpectedCfg((cfg.name, cfg.name_span), None),
511 if let Some(value) = cfg.value {
512 if let Some(values) = &sess.check_config.values_valid.get(&cfg.name) {
513 if !values.contains(&value) {
514 sess.buffer_lint_with_diagnostic(
518 "unexpected `cfg` condition value",
519 BuiltinLintDiagnostics::UnexpectedCfg(
520 (cfg.name, cfg.name_span),
521 cfg.value_span.map(|vs| (value, vs)),
527 sess.config.contains(&(cfg.name, cfg.value))
531 fn try_gate_cfg(name: Symbol, span: Span, sess: &ParseSess, features: Option<&Features>) {
532 let gate = find_gated_cfg(|sym| sym == name);
533 if let (Some(feats), Some(gated_cfg)) = (features, gate) {
534 gate_cfg(&gated_cfg, span, sess, feats);
538 fn gate_cfg(gated_cfg: &GatedCfg, cfg_span: Span, sess: &ParseSess, features: &Features) {
539 let (cfg, feature, has_feature) = gated_cfg;
540 if !has_feature(features) && !cfg_span.allows_unstable(*feature) {
541 let explain = format!("`cfg({})` is experimental and subject to change", cfg);
542 feature_err(sess, *feature, cfg_span, &explain).emit();
546 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
553 fn parse_version(s: &str, allow_appendix: bool) -> Option<Version> {
554 let mut components = s.split('-');
555 let d = components.next()?;
556 if !allow_appendix && components.next().is_some() {
559 let mut digits = d.splitn(3, '.');
560 let major = digits.next()?.parse().ok()?;
561 let minor = digits.next()?.parse().ok()?;
562 let patch = digits.next().unwrap_or("0").parse().ok()?;
563 Some(Version { major, minor, patch })
566 /// Evaluate a cfg-like condition (with `any` and `all`), using `eval` to
567 /// evaluate individual items.
568 pub fn eval_condition(
571 features: Option<&Features>,
572 eval: &mut impl FnMut(Condition) -> bool,
575 ast::MetaItemKind::List(ref mis) if cfg.name_or_empty() == sym::version => {
576 try_gate_cfg(sym::version, cfg.span, sess, features);
577 let (min_version, span) = match &mis[..] {
578 [NestedMetaItem::Literal(Lit { kind: LitKind::Str(sym, ..), span, .. })] => {
582 NestedMetaItem::Literal(Lit { span, .. })
583 | NestedMetaItem::MetaItem(MetaItem { span, .. }),
586 .struct_span_err(*span, "expected a version literal")
592 .struct_span_err(cfg.span, "expected single version literal")
597 let Some(min_version) = parse_version(min_version.as_str(), false) else {
601 "unknown version literal format, assuming it refers to a future version",
606 let rustc_version = parse_version(env!("CFG_RELEASE"), true).unwrap();
608 // See https://github.com/rust-lang/rust/issues/64796#issuecomment-640851454 for details
609 if sess.assume_incomplete_release {
610 rustc_version > min_version
612 rustc_version >= min_version
615 ast::MetaItemKind::List(ref mis) => {
616 for mi in mis.iter() {
617 if !mi.is_meta_item() {
621 AttrError::UnsupportedLiteral("unsupported literal", false),
627 // The unwraps below may look dangerous, but we've already asserted
628 // that they won't fail with the loop above.
629 match cfg.name_or_empty() {
632 // We don't use any() here, because we want to evaluate all cfg condition
633 // as eval_condition can (and does) extra checks
634 .fold(false, |res, mi| {
635 res | eval_condition(mi.meta_item().unwrap(), sess, features, eval)
639 // We don't use all() here, because we want to evaluate all cfg condition
640 // as eval_condition can (and does) extra checks
641 .fold(true, |res, mi| {
642 res & eval_condition(mi.meta_item().unwrap(), sess, features, eval)
647 sess.span_diagnostic,
650 "expected 1 cfg-pattern"
656 !eval_condition(mis[0].meta_item().unwrap(), sess, features, eval)
659 if let Some(features) = features && !features.cfg_target_compact {
662 sym::cfg_target_compact,
664 &"compact `cfg(target(..))` is experimental and subject to change"
668 mis.iter().fold(true, |res, mi| {
669 let mut mi = mi.meta_item().unwrap().clone();
670 if let [seg, ..] = &mut mi.path.segments[..] {
671 seg.ident.name = Symbol::intern(&format!("target_{}", seg.ident.name));
674 res & eval_condition(&mi, sess, features, eval)
679 sess.span_diagnostic,
682 "invalid predicate `{}`",
683 pprust::path_to_string(&cfg.path)
690 ast::MetaItemKind::Word | MetaItemKind::NameValue(..) if cfg.path.segments.len() != 1 => {
692 .span_err(cfg.path.span, "`cfg` predicate key must be an identifier");
695 MetaItemKind::NameValue(ref lit) if !lit.kind.is_str() => {
699 AttrError::UnsupportedLiteral(
700 "literal in `cfg` predicate value must be a string",
701 lit.kind.is_bytestr(),
706 ast::MetaItemKind::Word | ast::MetaItemKind::NameValue(..) => {
707 let ident = cfg.ident().expect("multi-segment cfg predicate");
710 name_span: ident.span,
711 value: cfg.value_str(),
712 value_span: cfg.name_value_literal_span(),
719 #[derive(Copy, Debug, Encodable, Decodable, Clone, HashStable_Generic)]
720 pub struct Deprecation {
721 pub since: Option<Symbol>,
722 /// The note to issue a reason.
723 pub note: Option<Symbol>,
724 /// A text snippet used to completely replace any use of the deprecated item in an expression.
726 /// This is currently unstable.
727 pub suggestion: Option<Symbol>,
729 /// Whether to treat the since attribute as being a Rust version identifier
730 /// (rather than an opaque string).
731 pub is_since_rustc_version: bool,
734 /// Finds the deprecation attribute. `None` if none exists.
735 pub fn find_deprecation(sess: &Session, attrs: &[Attribute]) -> Option<(Deprecation, Span)> {
736 find_deprecation_generic(sess, attrs.iter())
739 fn find_deprecation_generic<'a, I>(sess: &Session, attrs_iter: I) -> Option<(Deprecation, Span)>
741 I: Iterator<Item = &'a Attribute>,
743 let mut depr: Option<(Deprecation, Span)> = None;
744 let diagnostic = &sess.parse_sess.span_diagnostic;
745 let is_rustc = sess.features_untracked().staged_api;
747 'outer: for attr in attrs_iter {
748 if !attr.has_name(sym::deprecated) {
752 let Some(meta) = attr.meta() else {
755 let mut since = None;
757 let mut suggestion = None;
759 MetaItemKind::Word => {}
760 MetaItemKind::NameValue(..) => note = meta.value_str(),
761 MetaItemKind::List(list) => {
762 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
767 AttrError::MultipleItem(pprust::path_to_string(&meta.path)),
771 if let Some(v) = meta.value_str() {
775 if let Some(lit) = meta.name_value_literal() {
779 AttrError::UnsupportedLiteral(
780 "literal in `deprecated` \
781 value must be a string",
782 lit.kind.is_bytestr(),
786 struct_span_err!(diagnostic, meta.span, E0551, "incorrect meta item")
796 NestedMetaItem::MetaItem(mi) => match mi.name_or_empty() {
798 if !get(mi, &mut since) {
803 if !get(mi, &mut note) {
808 if !sess.features_untracked().deprecated_suggestion {
809 let mut diag = sess.struct_span_err(
811 "suggestions on deprecated items are unstable",
813 if sess.is_nightly_build() {
814 diag.help("add `#![feature(deprecated_suggestion)]` to the crate root");
816 diag.note("see #94785 for more details").emit();
819 if !get(mi, &mut suggestion) {
827 AttrError::UnknownMetaItem(
828 pprust::path_to_string(&mi.path),
829 if sess.features_untracked().deprecated_suggestion {
830 &["since", "note", "suggestion"]
839 NestedMetaItem::Literal(lit) => {
843 AttrError::UnsupportedLiteral(
844 "item in `deprecated` must be a key/value pair",
857 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingSince);
862 struct_span_err!(diagnostic, attr.span, E0543, "missing 'note'").emit();
868 Deprecation { since, note, suggestion, is_since_rustc_version: is_rustc },
876 #[derive(PartialEq, Debug, Encodable, Decodable, Copy, Clone)]
886 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
887 #[derive(Encodable, Decodable, HashStable_Generic)]
889 SignedInt(ast::IntTy),
890 UnsignedInt(ast::UintTy),
895 pub fn is_signed(self) -> bool {
899 SignedInt(..) => true,
900 UnsignedInt(..) => false,
905 /// Parse #[repr(...)] forms.
907 /// Valid repr contents: any of the primitive integral type names (see
908 /// `int_type_of_word`, below) to specify enum discriminant type; `C`, to use
909 /// the same discriminant size that the corresponding C enum would or C
910 /// structure layout, `packed` to remove padding, and `transparent` to delegate representation
911 /// concerns to the only non-ZST field.
912 pub fn find_repr_attrs(sess: &Session, attr: &Attribute) -> Vec<ReprAttr> {
913 if attr.has_name(sym::repr) { parse_repr_attr(sess, attr) } else { Vec::new() }
916 pub fn parse_repr_attr(sess: &Session, attr: &Attribute) -> Vec<ReprAttr> {
917 assert!(attr.has_name(sym::repr), "expected `#[repr(..)]`, found: {:?}", attr);
919 let mut acc = Vec::new();
920 let diagnostic = &sess.parse_sess.span_diagnostic;
922 if let Some(items) = attr.meta_item_list() {
924 let mut recognised = false;
926 let hint = match item.name_or_empty() {
927 sym::C => Some(ReprC),
928 sym::packed => Some(ReprPacked(1)),
929 sym::simd => Some(ReprSimd),
930 sym::transparent => Some(ReprTransparent),
932 let mut err = struct_span_err!(
936 "invalid `repr(align)` attribute: `align` needs an argument"
940 "supply an argument here",
942 Applicability::HasPlaceholders,
948 name => int_type_of_word(name).map(ReprInt),
951 if let Some(h) = hint {
955 } else if let Some((name, value)) = item.name_value_literal() {
956 let mut literal_error = None;
957 if name == sym::align {
959 match parse_alignment(&value.kind) {
960 Ok(literal) => acc.push(ReprAlign(literal)),
961 Err(message) => literal_error = Some(message),
963 } else if name == sym::packed {
965 match parse_alignment(&value.kind) {
966 Ok(literal) => acc.push(ReprPacked(literal)),
967 Err(message) => literal_error = Some(message),
969 } else if matches!(name, sym::C | sym::simd | sym::transparent)
970 || int_type_of_word(name).is_some()
977 "invalid representation hint: `{}` does not take a parenthesized argument list",
978 name.to_ident_string(),
981 if let Some(literal_error) = literal_error {
986 "invalid `repr({})` attribute: {}",
987 name.to_ident_string(),
992 } else if let Some(meta_item) = item.meta_item() {
993 if let MetaItemKind::NameValue(ref value) = meta_item.kind {
994 if meta_item.has_name(sym::align) || meta_item.has_name(sym::packed) {
995 let name = meta_item.name_or_empty().to_ident_string();
997 let mut err = struct_span_err!(
1001 "incorrect `repr({})` attribute format",
1005 ast::LitKind::Int(int, ast::LitIntType::Unsuffixed) => {
1006 err.span_suggestion(
1008 "use parentheses instead",
1009 format!("{}({})", name, int),
1010 Applicability::MachineApplicable,
1013 ast::LitKind::Str(s, _) => {
1014 err.span_suggestion(
1016 "use parentheses instead",
1017 format!("{}({})", name, s),
1018 Applicability::MachineApplicable,
1026 meta_item.name_or_empty(),
1027 sym::C | sym::simd | sym::transparent
1028 ) || int_type_of_word(meta_item.name_or_empty()).is_some()
1035 "invalid representation hint: `{}` does not take a value",
1036 meta_item.name_or_empty().to_ident_string(),
1041 } else if let MetaItemKind::List(_) = meta_item.kind {
1042 if meta_item.has_name(sym::align) {
1048 "incorrect `repr(align)` attribute format: \
1049 `align` takes exactly one argument in parentheses"
1052 } else if meta_item.has_name(sym::packed) {
1058 "incorrect `repr(packed)` attribute format: \
1059 `packed` takes exactly one parenthesized argument, \
1060 or no parentheses at all"
1064 meta_item.name_or_empty(),
1065 sym::C | sym::simd | sym::transparent
1066 ) || int_type_of_word(meta_item.name_or_empty()).is_some()
1073 "invalid representation hint: `{}` does not take a parenthesized argument list",
1074 meta_item.name_or_empty().to_ident_string(),
1080 // Not a word we recognize. This will be caught and reported by
1081 // the `check_mod_attrs` pass, but this pass doesn't always run
1082 // (e.g. if we only pretty-print the source), so we have to gate
1083 // the `delay_span_bug` call as follows:
1084 if sess.opts.pretty.map_or(true, |pp| pp.needs_analysis()) {
1085 diagnostic.delay_span_bug(item.span(), "unrecognized representation hint");
1093 fn int_type_of_word(s: Symbol) -> Option<IntType> {
1097 sym::i8 => Some(SignedInt(ast::IntTy::I8)),
1098 sym::u8 => Some(UnsignedInt(ast::UintTy::U8)),
1099 sym::i16 => Some(SignedInt(ast::IntTy::I16)),
1100 sym::u16 => Some(UnsignedInt(ast::UintTy::U16)),
1101 sym::i32 => Some(SignedInt(ast::IntTy::I32)),
1102 sym::u32 => Some(UnsignedInt(ast::UintTy::U32)),
1103 sym::i64 => Some(SignedInt(ast::IntTy::I64)),
1104 sym::u64 => Some(UnsignedInt(ast::UintTy::U64)),
1105 sym::i128 => Some(SignedInt(ast::IntTy::I128)),
1106 sym::u128 => Some(UnsignedInt(ast::UintTy::U128)),
1107 sym::isize => Some(SignedInt(ast::IntTy::Isize)),
1108 sym::usize => Some(UnsignedInt(ast::UintTy::Usize)),
1113 pub enum TransparencyError {
1114 UnknownTransparency(Symbol, Span),
1115 MultipleTransparencyAttrs(Span, Span),
1118 pub fn find_transparency(
1119 attrs: &[Attribute],
1121 ) -> (Transparency, Option<TransparencyError>) {
1122 let mut transparency = None;
1123 let mut error = None;
1125 if attr.has_name(sym::rustc_macro_transparency) {
1126 if let Some((_, old_span)) = transparency {
1127 error = Some(TransparencyError::MultipleTransparencyAttrs(old_span, attr.span));
1129 } else if let Some(value) = attr.value_str() {
1130 transparency = Some((
1132 sym::transparent => Transparency::Transparent,
1133 sym::semitransparent => Transparency::SemiTransparent,
1134 sym::opaque => Transparency::Opaque,
1136 error = Some(TransparencyError::UnknownTransparency(value, attr.span));
1145 let fallback = if macro_rules { Transparency::SemiTransparent } else { Transparency::Opaque };
1146 (transparency.map_or(fallback, |t| t.0), error)
1149 pub fn allow_internal_unstable<'a>(
1151 attrs: &'a [Attribute],
1152 ) -> impl Iterator<Item = Symbol> + 'a {
1153 allow_unstable(sess, attrs, sym::allow_internal_unstable)
1156 pub fn rustc_allow_const_fn_unstable<'a>(
1158 attrs: &'a [Attribute],
1159 ) -> impl Iterator<Item = Symbol> + 'a {
1160 allow_unstable(sess, attrs, sym::rustc_allow_const_fn_unstable)
1163 fn allow_unstable<'a>(
1165 attrs: &'a [Attribute],
1167 ) -> impl Iterator<Item = Symbol> + 'a {
1168 let attrs = sess.filter_by_name(attrs, symbol);
1170 .filter_map(move |attr| {
1171 attr.meta_item_list().or_else(|| {
1172 sess.diagnostic().span_err(
1174 &format!("`{}` expects a list of feature names", symbol.to_ident_string()),
1181 list.into_iter().filter_map(move |it| {
1182 let name = it.ident().map(|ident| ident.name);
1184 sess.diagnostic().span_err(
1186 &format!("`{}` expects feature names", symbol.to_ident_string()),
1193 pub fn parse_alignment(node: &ast::LitKind) -> Result<u32, &'static str> {
1194 if let ast::LitKind::Int(literal, ast::LitIntType::Unsuffixed) = node {
1195 if literal.is_power_of_two() {
1196 // rustc_middle::ty::layout::Align restricts align to <= 2^29
1197 if *literal <= 1 << 29 { Ok(*literal as u32) } else { Err("larger than 2^29") }
1199 Err("not a power of two")
1202 Err("not an unsuffixed integer")