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 },
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;
176 let diagnostic = &sess.parse_sess.span_diagnostic;
178 'outer: for attr in attrs_iter {
180 sym::rustc_const_unstable,
181 sym::rustc_const_stable,
184 sym::rustc_promotable,
187 .any(|&s| attr.has_name(s))
189 continue; // not a stability level
192 let meta = attr.meta();
194 if attr.has_name(sym::rustc_promotable) {
197 // attributes with data
198 else if let Some(MetaItem { kind: MetaItemKind::List(ref metas), .. }) = meta {
199 let meta = meta.as_ref().unwrap();
200 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
205 AttrError::MultipleItem(pprust::path_to_string(&meta.path)),
209 if let Some(v) = meta.value_str() {
213 struct_span_err!(diagnostic, meta.span, E0539, "incorrect meta item").emit();
218 let meta_name = meta.name_or_empty();
220 sym::rustc_const_unstable | sym::unstable => {
221 if meta_name == sym::unstable && stab.is_some() {
225 AttrError::MultipleStabilityLevels,
228 } else if meta_name == sym::rustc_const_unstable && const_stab.is_some() {
232 AttrError::MultipleStabilityLevels,
237 let mut feature = None;
238 let mut reason = None;
239 let mut issue = None;
240 let mut issue_num = None;
241 let mut is_soft = false;
243 let Some(mi) = meta.meta_item() else {
247 AttrError::UnsupportedLiteral("unsupported literal", false),
251 match mi.name_or_empty() {
253 if !get(mi, &mut feature) {
258 if !get(mi, &mut reason) {
263 if !get(mi, &mut issue) {
267 // These unwraps are safe because `get` ensures the meta item
268 // is a name/value pair string literal.
269 issue_num = match issue.unwrap().as_str() {
272 let emit_diag = |msg: &str| {
277 "`issue` must be a non-zero numeric string \
280 .span_label(mi.name_value_literal_span().unwrap(), msg)
283 match issue.parse() {
286 "`issue` must not be \"0\", \
287 use \"none\" instead",
291 Ok(num) => NonZeroU32::new(num),
293 emit_diag(&err.to_string());
302 let msg = "`soft` should not have any arguments";
303 sess.parse_sess.span_diagnostic.span_err(mi.span, msg);
311 AttrError::UnknownMetaItem(
312 pprust::path_to_string(&mi.path),
313 &["feature", "reason", "issue", "soft"],
321 match (feature, reason, issue) {
322 (Some(feature), reason, Some(_)) => {
323 if !rustc_lexer::is_ident(feature.as_str()) {
327 AttrError::NonIdentFeature,
331 let level = Unstable { reason, issue: issue_num, is_soft };
332 if sym::unstable == meta_name {
333 stab = Some((Stability { level, feature }, attr.span));
336 ConstStability { level, feature, promotable: false },
342 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingFeature);
346 struct_span_err!(diagnostic, attr.span, E0547, "missing 'issue'")
352 sym::rustc_const_stable | sym::stable => {
353 if meta_name == sym::stable && stab.is_some() {
357 AttrError::MultipleStabilityLevels,
360 } else if meta_name == sym::rustc_const_stable && const_stab.is_some() {
364 AttrError::MultipleStabilityLevels,
369 let mut feature = None;
370 let mut since = None;
373 NestedMetaItem::MetaItem(mi) => match mi.name_or_empty() {
375 if !get(mi, &mut feature) {
380 if !get(mi, &mut since) {
388 AttrError::UnknownMetaItem(
389 pprust::path_to_string(&mi.path),
396 NestedMetaItem::Literal(lit) => {
400 AttrError::UnsupportedLiteral("unsupported literal", false),
407 match (feature, since) {
408 (Some(feature), Some(since)) => {
409 let level = Stable { since };
410 if sym::stable == meta_name {
411 stab = Some((Stability { level, feature }, attr.span));
414 ConstStability { level, feature, promotable: false },
420 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingFeature);
424 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingSince);
434 // Merge the const-unstable info into the stability info
436 if let Some((ref mut stab, _)) = const_stab {
437 stab.promotable = promotable;
443 "`rustc_promotable` attribute must be paired with either a `rustc_const_unstable` \
444 or a `rustc_const_stable` attribute"
453 pub fn find_crate_name(sess: &Session, attrs: &[Attribute]) -> Option<Symbol> {
454 sess.first_attr_value_str_by_name(attrs, sym::crate_name)
457 #[derive(Clone, Debug)]
458 pub struct Condition {
461 pub value: Option<Symbol>,
462 pub value_span: Option<Span>,
466 /// Tests if a cfg-pattern matches the cfg set
470 lint_node_id: NodeId,
471 features: Option<&Features>,
473 eval_condition(cfg, sess, features, &mut |cfg| {
474 try_gate_cfg(cfg.name, cfg.span, sess, features);
475 if let Some(names_valid) = &sess.check_config.names_valid {
476 if !names_valid.contains(&cfg.name) {
477 sess.buffer_lint_with_diagnostic(
481 "unexpected `cfg` condition name",
482 BuiltinLintDiagnostics::UnexpectedCfg((cfg.name, cfg.name_span), None),
486 if let Some(value) = cfg.value {
487 if let Some(values) = &sess.check_config.values_valid.get(&cfg.name) {
488 if !values.contains(&value) {
489 sess.buffer_lint_with_diagnostic(
493 "unexpected `cfg` condition value",
494 BuiltinLintDiagnostics::UnexpectedCfg(
495 (cfg.name, cfg.name_span),
496 cfg.value_span.map(|vs| (value, vs)),
502 sess.config.contains(&(cfg.name, cfg.value))
506 fn try_gate_cfg(name: Symbol, span: Span, sess: &ParseSess, features: Option<&Features>) {
507 let gate = find_gated_cfg(|sym| sym == name);
508 if let (Some(feats), Some(gated_cfg)) = (features, gate) {
509 gate_cfg(&gated_cfg, span, sess, feats);
513 fn gate_cfg(gated_cfg: &GatedCfg, cfg_span: Span, sess: &ParseSess, features: &Features) {
514 let (cfg, feature, has_feature) = gated_cfg;
515 if !has_feature(features) && !cfg_span.allows_unstable(*feature) {
516 let explain = format!("`cfg({})` is experimental and subject to change", cfg);
517 feature_err(sess, *feature, cfg_span, &explain).emit();
521 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
528 fn parse_version(s: &str, allow_appendix: bool) -> Option<Version> {
529 let mut components = s.split('-');
530 let d = components.next()?;
531 if !allow_appendix && components.next().is_some() {
534 let mut digits = d.splitn(3, '.');
535 let major = digits.next()?.parse().ok()?;
536 let minor = digits.next()?.parse().ok()?;
537 let patch = digits.next().unwrap_or("0").parse().ok()?;
538 Some(Version { major, minor, patch })
541 /// Evaluate a cfg-like condition (with `any` and `all`), using `eval` to
542 /// evaluate individual items.
543 pub fn eval_condition(
546 features: Option<&Features>,
547 eval: &mut impl FnMut(Condition) -> bool,
550 ast::MetaItemKind::List(ref mis) if cfg.name_or_empty() == sym::version => {
551 try_gate_cfg(sym::version, cfg.span, sess, features);
552 let (min_version, span) = match &mis[..] {
553 [NestedMetaItem::Literal(Lit { kind: LitKind::Str(sym, ..), span, .. })] => {
557 NestedMetaItem::Literal(Lit { span, .. })
558 | NestedMetaItem::MetaItem(MetaItem { span, .. }),
561 .struct_span_err(*span, "expected a version literal")
567 .struct_span_err(cfg.span, "expected single version literal")
572 let Some(min_version) = parse_version(min_version.as_str(), false) else {
576 "unknown version literal format, assuming it refers to a future version",
581 let rustc_version = parse_version(env!("CFG_RELEASE"), true).unwrap();
583 // See https://github.com/rust-lang/rust/issues/64796#issuecomment-640851454 for details
584 if sess.assume_incomplete_release {
585 rustc_version > min_version
587 rustc_version >= min_version
590 ast::MetaItemKind::List(ref mis) => {
591 for mi in mis.iter() {
592 if !mi.is_meta_item() {
596 AttrError::UnsupportedLiteral("unsupported literal", false),
602 // The unwraps below may look dangerous, but we've already asserted
603 // that they won't fail with the loop above.
604 match cfg.name_or_empty() {
607 // We don't use any() here, because we want to evaluate all cfg condition
608 // as eval_condition can (and does) extra checks
609 .fold(false, |res, mi| {
610 res | eval_condition(mi.meta_item().unwrap(), sess, features, eval)
614 // We don't use all() here, because we want to evaluate all cfg condition
615 // as eval_condition can (and does) extra checks
616 .fold(true, |res, mi| {
617 res & eval_condition(mi.meta_item().unwrap(), sess, features, eval)
622 sess.span_diagnostic,
625 "expected 1 cfg-pattern"
631 !eval_condition(mis[0].meta_item().unwrap(), sess, features, eval)
634 if let Some(features) = features && !features.cfg_target_compact {
637 sym::cfg_target_compact,
639 &"compact `cfg(target(..))` is experimental and subject to change"
643 mis.iter().fold(true, |res, mi| {
644 let mut mi = mi.meta_item().unwrap().clone();
645 if let [seg, ..] = &mut mi.path.segments[..] {
646 seg.ident.name = Symbol::intern(&format!("target_{}", seg.ident.name));
649 res & eval_condition(&mi, sess, features, eval)
654 sess.span_diagnostic,
657 "invalid predicate `{}`",
658 pprust::path_to_string(&cfg.path)
665 ast::MetaItemKind::Word | MetaItemKind::NameValue(..) if cfg.path.segments.len() != 1 => {
667 .span_err(cfg.path.span, "`cfg` predicate key must be an identifier");
670 MetaItemKind::NameValue(ref lit) if !lit.kind.is_str() => {
674 AttrError::UnsupportedLiteral(
675 "literal in `cfg` predicate value must be a string",
676 lit.kind.is_bytestr(),
681 ast::MetaItemKind::Word | ast::MetaItemKind::NameValue(..) => {
682 let ident = cfg.ident().expect("multi-segment cfg predicate");
685 name_span: ident.span,
686 value: cfg.value_str(),
687 value_span: cfg.name_value_literal_span(),
694 #[derive(Copy, Debug, Encodable, Decodable, Clone, HashStable_Generic)]
695 pub struct Deprecation {
696 pub since: Option<Symbol>,
697 /// The note to issue a reason.
698 pub note: Option<Symbol>,
699 /// A text snippet used to completely replace any use of the deprecated item in an expression.
701 /// This is currently unstable.
702 pub suggestion: Option<Symbol>,
704 /// Whether to treat the since attribute as being a Rust version identifier
705 /// (rather than an opaque string).
706 pub is_since_rustc_version: bool,
709 /// Finds the deprecation attribute. `None` if none exists.
710 pub fn find_deprecation(sess: &Session, attrs: &[Attribute]) -> Option<(Deprecation, Span)> {
711 find_deprecation_generic(sess, attrs.iter())
714 fn find_deprecation_generic<'a, I>(sess: &Session, attrs_iter: I) -> Option<(Deprecation, Span)>
716 I: Iterator<Item = &'a Attribute>,
718 let mut depr: Option<(Deprecation, Span)> = None;
719 let diagnostic = &sess.parse_sess.span_diagnostic;
720 let is_rustc = sess.features_untracked().staged_api;
722 'outer: for attr in attrs_iter {
723 if !attr.has_name(sym::deprecated) {
727 let Some(meta) = attr.meta() else {
730 let mut since = None;
732 let mut suggestion = None;
734 MetaItemKind::Word => {}
735 MetaItemKind::NameValue(..) => note = meta.value_str(),
736 MetaItemKind::List(list) => {
737 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
742 AttrError::MultipleItem(pprust::path_to_string(&meta.path)),
746 if let Some(v) = meta.value_str() {
750 if let Some(lit) = meta.name_value_literal() {
754 AttrError::UnsupportedLiteral(
755 "literal in `deprecated` \
756 value must be a string",
757 lit.kind.is_bytestr(),
761 struct_span_err!(diagnostic, meta.span, E0551, "incorrect meta item")
771 NestedMetaItem::MetaItem(mi) => match mi.name_or_empty() {
773 if !get(mi, &mut since) {
778 if !get(mi, &mut note) {
783 if !sess.features_untracked().deprecated_suggestion {
784 let mut diag = sess.struct_span_err(
786 "suggestions on deprecated items are unstable",
788 if sess.is_nightly_build() {
789 diag.help("add `#![feature(deprecated_suggestion)]` to the crate root");
791 diag.note("see #94785 for more details").emit();
794 if !get(mi, &mut suggestion) {
802 AttrError::UnknownMetaItem(
803 pprust::path_to_string(&mi.path),
804 if sess.features_untracked().deprecated_suggestion {
805 &["since", "note", "suggestion"]
814 NestedMetaItem::Literal(lit) => {
818 AttrError::UnsupportedLiteral(
819 "item in `deprecated` must be a key/value pair",
832 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingSince);
837 struct_span_err!(diagnostic, attr.span, E0543, "missing 'note'").emit();
843 Deprecation { since, note, suggestion, is_since_rustc_version: is_rustc },
851 #[derive(PartialEq, Debug, Encodable, Decodable, Copy, Clone)]
862 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
863 #[derive(Encodable, Decodable, HashStable_Generic)]
865 SignedInt(ast::IntTy),
866 UnsignedInt(ast::UintTy),
871 pub fn is_signed(self) -> bool {
875 SignedInt(..) => true,
876 UnsignedInt(..) => false,
881 /// Parse #[repr(...)] forms.
883 /// Valid repr contents: any of the primitive integral type names (see
884 /// `int_type_of_word`, below) to specify enum discriminant type; `C`, to use
885 /// the same discriminant size that the corresponding C enum would or C
886 /// structure layout, `packed` to remove padding, and `transparent` to delegate representation
887 /// concerns to the only non-ZST field.
888 pub fn find_repr_attrs(sess: &Session, attr: &Attribute) -> Vec<ReprAttr> {
889 if attr.has_name(sym::repr) { parse_repr_attr(sess, attr) } else { Vec::new() }
892 pub fn parse_repr_attr(sess: &Session, attr: &Attribute) -> Vec<ReprAttr> {
893 assert!(attr.has_name(sym::repr), "expected `#[repr(..)]`, found: {:?}", attr);
895 let mut acc = Vec::new();
896 let diagnostic = &sess.parse_sess.span_diagnostic;
898 if let Some(items) = attr.meta_item_list() {
900 let mut recognised = false;
902 let hint = match item.name_or_empty() {
903 sym::C => Some(ReprC),
904 sym::packed => Some(ReprPacked(1)),
905 sym::simd => Some(ReprSimd),
906 sym::transparent => Some(ReprTransparent),
907 sym::no_niche => Some(ReprNoNiche),
909 let mut err = struct_span_err!(
913 "invalid `repr(align)` attribute: `align` needs an argument"
917 "supply an argument here",
919 Applicability::HasPlaceholders,
925 name => int_type_of_word(name).map(ReprInt),
928 if let Some(h) = hint {
932 } else if let Some((name, value)) = item.name_value_literal() {
933 let mut literal_error = None;
934 if name == sym::align {
936 match parse_alignment(&value.kind) {
937 Ok(literal) => acc.push(ReprAlign(literal)),
938 Err(message) => literal_error = Some(message),
940 } else if name == sym::packed {
942 match parse_alignment(&value.kind) {
943 Ok(literal) => acc.push(ReprPacked(literal)),
944 Err(message) => literal_error = Some(message),
946 } else if matches!(name, sym::C | sym::simd | sym::transparent | sym::no_niche)
947 || int_type_of_word(name).is_some()
954 "invalid representation hint: `{}` does not take a parenthesized argument list",
955 name.to_ident_string(),
958 if let Some(literal_error) = literal_error {
963 "invalid `repr({})` attribute: {}",
964 name.to_ident_string(),
969 } else if let Some(meta_item) = item.meta_item() {
970 if let MetaItemKind::NameValue(ref value) = meta_item.kind {
971 if meta_item.has_name(sym::align) || meta_item.has_name(sym::packed) {
972 let name = meta_item.name_or_empty().to_ident_string();
974 let mut err = struct_span_err!(
978 "incorrect `repr({})` attribute format",
982 ast::LitKind::Int(int, ast::LitIntType::Unsuffixed) => {
985 "use parentheses instead",
986 format!("{}({})", name, int),
987 Applicability::MachineApplicable,
990 ast::LitKind::Str(s, _) => {
993 "use parentheses instead",
994 format!("{}({})", name, s),
995 Applicability::MachineApplicable,
1003 meta_item.name_or_empty(),
1004 sym::C | sym::simd | sym::transparent | sym::no_niche
1005 ) || int_type_of_word(meta_item.name_or_empty()).is_some()
1012 "invalid representation hint: `{}` does not take a value",
1013 meta_item.name_or_empty().to_ident_string(),
1018 } else if let MetaItemKind::List(_) = meta_item.kind {
1019 if meta_item.has_name(sym::align) {
1025 "incorrect `repr(align)` attribute format: \
1026 `align` takes exactly one argument in parentheses"
1029 } else if meta_item.has_name(sym::packed) {
1035 "incorrect `repr(packed)` attribute format: \
1036 `packed` takes exactly one parenthesized argument, \
1037 or no parentheses at all"
1041 meta_item.name_or_empty(),
1042 sym::C | sym::simd | sym::transparent | sym::no_niche
1043 ) || int_type_of_word(meta_item.name_or_empty()).is_some()
1050 "invalid representation hint: `{}` does not take a parenthesized argument list",
1051 meta_item.name_or_empty().to_ident_string(),
1057 // Not a word we recognize. This will be caught and reported by
1058 // the `check_mod_attrs` pass, but this pass doesn't always run
1059 // (e.g. if we only pretty-print the source), so we have to gate
1060 // the `delay_span_bug` call as follows:
1061 if sess.opts.pretty.map_or(true, |pp| pp.needs_analysis()) {
1062 diagnostic.delay_span_bug(item.span(), "unrecognized representation hint");
1070 fn int_type_of_word(s: Symbol) -> Option<IntType> {
1074 sym::i8 => Some(SignedInt(ast::IntTy::I8)),
1075 sym::u8 => Some(UnsignedInt(ast::UintTy::U8)),
1076 sym::i16 => Some(SignedInt(ast::IntTy::I16)),
1077 sym::u16 => Some(UnsignedInt(ast::UintTy::U16)),
1078 sym::i32 => Some(SignedInt(ast::IntTy::I32)),
1079 sym::u32 => Some(UnsignedInt(ast::UintTy::U32)),
1080 sym::i64 => Some(SignedInt(ast::IntTy::I64)),
1081 sym::u64 => Some(UnsignedInt(ast::UintTy::U64)),
1082 sym::i128 => Some(SignedInt(ast::IntTy::I128)),
1083 sym::u128 => Some(UnsignedInt(ast::UintTy::U128)),
1084 sym::isize => Some(SignedInt(ast::IntTy::Isize)),
1085 sym::usize => Some(UnsignedInt(ast::UintTy::Usize)),
1090 pub enum TransparencyError {
1091 UnknownTransparency(Symbol, Span),
1092 MultipleTransparencyAttrs(Span, Span),
1095 pub fn find_transparency(
1096 attrs: &[Attribute],
1098 ) -> (Transparency, Option<TransparencyError>) {
1099 let mut transparency = None;
1100 let mut error = None;
1102 if attr.has_name(sym::rustc_macro_transparency) {
1103 if let Some((_, old_span)) = transparency {
1104 error = Some(TransparencyError::MultipleTransparencyAttrs(old_span, attr.span));
1106 } else if let Some(value) = attr.value_str() {
1107 transparency = Some((
1109 sym::transparent => Transparency::Transparent,
1110 sym::semitransparent => Transparency::SemiTransparent,
1111 sym::opaque => Transparency::Opaque,
1113 error = Some(TransparencyError::UnknownTransparency(value, attr.span));
1122 let fallback = if macro_rules { Transparency::SemiTransparent } else { Transparency::Opaque };
1123 (transparency.map_or(fallback, |t| t.0), error)
1126 pub fn allow_internal_unstable<'a>(
1128 attrs: &'a [Attribute],
1129 ) -> impl Iterator<Item = Symbol> + 'a {
1130 allow_unstable(sess, attrs, sym::allow_internal_unstable)
1133 pub fn rustc_allow_const_fn_unstable<'a>(
1135 attrs: &'a [Attribute],
1136 ) -> impl Iterator<Item = Symbol> + 'a {
1137 allow_unstable(sess, attrs, sym::rustc_allow_const_fn_unstable)
1140 fn allow_unstable<'a>(
1142 attrs: &'a [Attribute],
1144 ) -> impl Iterator<Item = Symbol> + 'a {
1145 let attrs = sess.filter_by_name(attrs, symbol);
1147 .filter_map(move |attr| {
1148 attr.meta_item_list().or_else(|| {
1149 sess.diagnostic().span_err(
1151 &format!("`{}` expects a list of feature names", symbol.to_ident_string()),
1158 list.into_iter().filter_map(move |it| {
1159 let name = it.ident().map(|ident| ident.name);
1161 sess.diagnostic().span_err(
1163 &format!("`{}` expects feature names", symbol.to_ident_string()),
1170 pub fn parse_alignment(node: &ast::LitKind) -> Result<u32, &'static str> {
1171 if let ast::LitKind::Int(literal, ast::LitIntType::Unsuffixed) = node {
1172 if literal.is_power_of_two() {
1173 // rustc_middle::ty::layout::Align restricts align to <= 2^29
1174 if *literal <= 1 << 29 { Ok(*literal as u32) } else { Err("larger than 2^29") }
1176 Err("not a power of two")
1179 Err("not an unsuffixed integer")