1 //! Parsing and validation of builtin attributes
4 use rustc_ast::node_id::CRATE_NODE_ID;
5 use rustc_ast::{Attribute, Lit, LitKind, MetaItem, MetaItemKind, NestedMetaItem};
6 use rustc_ast_pretty::pprust;
7 use rustc_errors::{struct_span_err, Applicability};
8 use rustc_feature::{find_gated_cfg, is_builtin_attr_name, Features, GatedCfg};
9 use rustc_macros::HashStable_Generic;
10 use rustc_session::lint::builtin::UNEXPECTED_CFGS;
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",
62 lint_str[1..].to_string(),
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,
104 /// Represents the `#[rustc_const_unstable]` and `#[rustc_const_stable]` attributes.
105 #[derive(Encodable, Decodable, Copy, Clone, Debug, PartialEq, Eq, Hash)]
106 #[derive(HashStable_Generic)]
107 pub struct ConstStability {
108 pub level: StabilityLevel,
110 /// whether the function has a `#[rustc_promotable]` attribute
111 pub promotable: bool,
114 /// The available stability levels.
115 #[derive(Encodable, Decodable, PartialEq, Copy, Clone, Debug, Eq, Hash)]
116 #[derive(HashStable_Generic)]
117 pub enum StabilityLevel {
118 // Reason for the current stability level and the relevant rust-lang issue
119 Unstable { reason: Option<Symbol>, issue: Option<NonZeroU32>, is_soft: bool },
120 Stable { since: Symbol },
123 impl StabilityLevel {
124 pub fn is_unstable(&self) -> bool {
125 matches!(self, StabilityLevel::Unstable { .. })
127 pub fn is_stable(&self) -> bool {
128 matches!(self, StabilityLevel::Stable { .. })
132 /// Collects stability info from all stability attributes in `attrs`.
133 /// Returns `None` if no stability attributes are found.
134 pub fn find_stability(
138 ) -> (Option<(Stability, Span)>, Option<(ConstStability, Span)>) {
139 find_stability_generic(sess, attrs.iter(), item_sp)
142 fn find_stability_generic<'a, I>(
146 ) -> (Option<(Stability, Span)>, Option<(ConstStability, Span)>)
148 I: Iterator<Item = &'a Attribute>,
150 use StabilityLevel::*;
152 let mut stab: Option<(Stability, Span)> = None;
153 let mut const_stab: Option<(ConstStability, Span)> = None;
154 let mut promotable = false;
156 let diagnostic = &sess.parse_sess.span_diagnostic;
158 'outer: for attr in attrs_iter {
160 sym::rustc_const_unstable,
161 sym::rustc_const_stable,
164 sym::rustc_promotable,
167 .any(|&s| attr.has_name(s))
169 continue; // not a stability level
172 let meta = attr.meta();
174 if attr.has_name(sym::rustc_promotable) {
177 // attributes with data
178 else if let Some(MetaItem { kind: MetaItemKind::List(ref metas), .. }) = meta {
179 let meta = meta.as_ref().unwrap();
180 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
185 AttrError::MultipleItem(pprust::path_to_string(&meta.path)),
189 if let Some(v) = meta.value_str() {
193 struct_span_err!(diagnostic, meta.span, E0539, "incorrect meta item").emit();
198 let meta_name = meta.name_or_empty();
200 sym::rustc_const_unstable | sym::unstable => {
201 if meta_name == sym::unstable && stab.is_some() {
205 AttrError::MultipleStabilityLevels,
208 } else if meta_name == sym::rustc_const_unstable && const_stab.is_some() {
212 AttrError::MultipleStabilityLevels,
217 let mut feature = None;
218 let mut reason = None;
219 let mut issue = None;
220 let mut issue_num = None;
221 let mut is_soft = false;
223 let Some(mi) = meta.meta_item() else {
227 AttrError::UnsupportedLiteral("unsupported literal", false),
231 match mi.name_or_empty() {
233 if !get(mi, &mut feature) {
238 if !get(mi, &mut reason) {
243 if !get(mi, &mut issue) {
247 // These unwraps are safe because `get` ensures the meta item
248 // is a name/value pair string literal.
249 issue_num = match issue.unwrap().as_str() {
252 let emit_diag = |msg: &str| {
257 "`issue` must be a non-zero numeric string \
260 .span_label(mi.name_value_literal_span().unwrap(), msg)
263 match issue.parse() {
266 "`issue` must not be \"0\", \
267 use \"none\" instead",
271 Ok(num) => NonZeroU32::new(num),
273 emit_diag(&err.to_string());
282 let msg = "`soft` should not have any arguments";
283 sess.parse_sess.span_diagnostic.span_err(mi.span, msg);
291 AttrError::UnknownMetaItem(
292 pprust::path_to_string(&mi.path),
293 &["feature", "reason", "issue", "soft"],
301 match (feature, reason, issue) {
302 (Some(feature), reason, Some(_)) => {
303 if !rustc_lexer::is_ident(feature.as_str()) {
307 AttrError::NonIdentFeature,
311 let level = Unstable { reason, issue: issue_num, is_soft };
312 if sym::unstable == meta_name {
313 stab = Some((Stability { level, feature }, attr.span));
316 ConstStability { level, feature, promotable: false },
322 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingFeature);
326 struct_span_err!(diagnostic, attr.span, E0547, "missing 'issue'")
332 sym::rustc_const_stable | sym::stable => {
333 if meta_name == sym::stable && stab.is_some() {
337 AttrError::MultipleStabilityLevels,
340 } else if meta_name == sym::rustc_const_stable && const_stab.is_some() {
344 AttrError::MultipleStabilityLevels,
349 let mut feature = None;
350 let mut since = None;
353 NestedMetaItem::MetaItem(mi) => match mi.name_or_empty() {
355 if !get(mi, &mut feature) {
360 if !get(mi, &mut since) {
368 AttrError::UnknownMetaItem(
369 pprust::path_to_string(&mi.path),
376 NestedMetaItem::Literal(lit) => {
380 AttrError::UnsupportedLiteral("unsupported literal", false),
387 match (feature, since) {
388 (Some(feature), Some(since)) => {
389 let level = Stable { since };
390 if sym::stable == meta_name {
391 stab = Some((Stability { level, feature }, attr.span));
394 ConstStability { level, feature, promotable: false },
400 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingFeature);
404 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingSince);
414 // Merge the const-unstable info into the stability info
416 if let Some((ref mut stab, _)) = const_stab {
417 stab.promotable = promotable;
423 "`rustc_promotable` attribute must be paired with either a `rustc_const_unstable` \
424 or a `rustc_const_stable` attribute"
433 pub fn find_crate_name(sess: &Session, attrs: &[Attribute]) -> Option<Symbol> {
434 sess.first_attr_value_str_by_name(attrs, sym::crate_name)
437 /// Tests if a cfg-pattern matches the cfg set
438 pub fn cfg_matches(cfg: &ast::MetaItem, sess: &ParseSess, features: Option<&Features>) -> bool {
439 eval_condition(cfg, sess, features, &mut |cfg| {
440 try_gate_cfg(cfg, sess, features);
441 let error = |span, msg| {
442 sess.span_diagnostic.span_err(span, msg);
445 if cfg.path.segments.len() != 1 {
446 return error(cfg.path.span, "`cfg` predicate key must be an identifier");
449 MetaItemKind::List(..) => {
450 error(cfg.span, "unexpected parentheses after `cfg` predicate key")
452 MetaItemKind::NameValue(lit) if !lit.kind.is_str() => {
456 AttrError::UnsupportedLiteral(
457 "literal in `cfg` predicate value must be a string",
458 lit.kind.is_bytestr(),
463 MetaItemKind::NameValue(..) | MetaItemKind::Word => {
464 let name = cfg.ident().expect("multi-segment cfg predicate").name;
465 let value = cfg.value_str();
466 if sess.check_config.names_checked && !sess.check_config.names_valid.contains(&name)
472 "unexpected `cfg` condition name",
475 if let Some(val) = value {
476 if sess.check_config.values_checked.contains(&name)
477 && !sess.check_config.values_valid.contains(&(name, val))
483 "unexpected `cfg` condition value",
487 sess.config.contains(&(name, value))
493 fn try_gate_cfg(cfg: &ast::MetaItem, sess: &ParseSess, features: Option<&Features>) {
494 let gate = find_gated_cfg(|sym| cfg.has_name(sym));
495 if let (Some(feats), Some(gated_cfg)) = (features, gate) {
496 gate_cfg(&gated_cfg, cfg.span, sess, feats);
500 fn gate_cfg(gated_cfg: &GatedCfg, cfg_span: Span, sess: &ParseSess, features: &Features) {
501 let (cfg, feature, has_feature) = gated_cfg;
502 if !has_feature(features) && !cfg_span.allows_unstable(*feature) {
503 let explain = format!("`cfg({})` is experimental and subject to change", cfg);
504 feature_err(sess, *feature, cfg_span, &explain).emit();
508 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
515 fn parse_version(s: &str, allow_appendix: bool) -> Option<Version> {
516 let mut components = s.split('-');
517 let d = components.next()?;
518 if !allow_appendix && components.next().is_some() {
521 let mut digits = d.splitn(3, '.');
522 let major = digits.next()?.parse().ok()?;
523 let minor = digits.next()?.parse().ok()?;
524 let patch = digits.next().unwrap_or("0").parse().ok()?;
525 Some(Version { major, minor, patch })
528 /// Evaluate a cfg-like condition (with `any` and `all`), using `eval` to
529 /// evaluate individual items.
530 pub fn eval_condition(
533 features: Option<&Features>,
534 eval: &mut impl FnMut(&ast::MetaItem) -> bool,
537 ast::MetaItemKind::List(ref mis) if cfg.name_or_empty() == sym::version => {
538 try_gate_cfg(cfg, sess, features);
539 let (min_version, span) = match &mis[..] {
540 [NestedMetaItem::Literal(Lit { kind: LitKind::Str(sym, ..), span, .. })] => {
544 NestedMetaItem::Literal(Lit { span, .. })
545 | NestedMetaItem::MetaItem(MetaItem { span, .. }),
548 .struct_span_err(*span, "expected a version literal")
554 .struct_span_err(cfg.span, "expected single version literal")
559 let min_version = match parse_version(min_version.as_str(), false) {
565 "unknown version literal format, assuming it refers to a future version",
571 let rustc_version = parse_version(env!("CFG_RELEASE"), true).unwrap();
573 // See https://github.com/rust-lang/rust/issues/64796#issuecomment-640851454 for details
574 if sess.assume_incomplete_release {
575 rustc_version > min_version
577 rustc_version >= min_version
580 ast::MetaItemKind::List(ref mis) => {
581 for mi in mis.iter() {
582 if !mi.is_meta_item() {
586 AttrError::UnsupportedLiteral("unsupported literal", false),
592 // The unwraps below may look dangerous, but we've already asserted
593 // that they won't fail with the loop above.
594 match cfg.name_or_empty() {
597 .any(|mi| eval_condition(mi.meta_item().unwrap(), sess, features, eval)),
600 .all(|mi| eval_condition(mi.meta_item().unwrap(), sess, features, eval)),
604 sess.span_diagnostic,
607 "expected 1 cfg-pattern"
613 !eval_condition(mis[0].meta_item().unwrap(), sess, features, eval)
617 sess.span_diagnostic,
620 "invalid predicate `{}`",
621 pprust::path_to_string(&cfg.path)
628 ast::MetaItemKind::Word | ast::MetaItemKind::NameValue(..) => eval(cfg),
632 #[derive(Copy, Debug, Encodable, Decodable, Clone, HashStable_Generic)]
633 pub struct Deprecation {
634 pub since: Option<Symbol>,
635 /// The note to issue a reason.
636 pub note: Option<Symbol>,
637 /// A text snippet used to completely replace any use of the deprecated item in an expression.
639 /// This is currently unstable.
640 pub suggestion: Option<Symbol>,
642 /// Whether to treat the since attribute as being a Rust version identifier
643 /// (rather than an opaque string).
644 pub is_since_rustc_version: bool,
647 /// Finds the deprecation attribute. `None` if none exists.
648 pub fn find_deprecation(sess: &Session, attrs: &[Attribute]) -> Option<(Deprecation, Span)> {
649 find_deprecation_generic(sess, attrs.iter())
652 fn find_deprecation_generic<'a, I>(sess: &Session, attrs_iter: I) -> Option<(Deprecation, Span)>
654 I: Iterator<Item = &'a Attribute>,
656 let mut depr: Option<(Deprecation, Span)> = None;
657 let diagnostic = &sess.parse_sess.span_diagnostic;
659 'outer: for attr in attrs_iter {
660 if !(attr.has_name(sym::deprecated) || attr.has_name(sym::rustc_deprecated)) {
664 if let Some((_, span)) = &depr {
665 struct_span_err!(diagnostic, attr.span, E0550, "multiple deprecated attributes")
666 .span_label(attr.span, "repeated deprecation attribute")
667 .span_label(*span, "first deprecation attribute")
672 let meta = match attr.meta() {
676 let mut since = None;
678 let mut suggestion = None;
680 MetaItemKind::Word => {}
681 MetaItemKind::NameValue(..) => note = meta.value_str(),
682 MetaItemKind::List(list) => {
683 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
688 AttrError::MultipleItem(pprust::path_to_string(&meta.path)),
692 if let Some(v) = meta.value_str() {
696 if let Some(lit) = meta.name_value_literal() {
700 AttrError::UnsupportedLiteral(
701 "literal in `deprecated` \
702 value must be a string",
703 lit.kind.is_bytestr(),
707 struct_span_err!(diagnostic, meta.span, E0551, "incorrect meta item")
717 NestedMetaItem::MetaItem(mi) => match mi.name_or_empty() {
719 if !get(mi, &mut since) {
723 sym::note if attr.has_name(sym::deprecated) => {
724 if !get(mi, &mut note) {
728 sym::reason if attr.has_name(sym::rustc_deprecated) => {
729 if !get(mi, &mut note) {
733 sym::suggestion if attr.has_name(sym::rustc_deprecated) => {
734 if !get(mi, &mut suggestion) {
742 AttrError::UnknownMetaItem(
743 pprust::path_to_string(&mi.path),
744 if attr.has_name(sym::deprecated) {
747 &["since", "reason", "suggestion"]
754 NestedMetaItem::Literal(lit) => {
758 AttrError::UnsupportedLiteral(
759 "item in `deprecated` must be a key/value pair",
770 if suggestion.is_some() && attr.has_name(sym::deprecated) {
771 unreachable!("only allowed on rustc_deprecated")
774 if attr.has_name(sym::rustc_deprecated) {
776 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingSince);
781 struct_span_err!(diagnostic, attr.span, E0543, "missing 'reason'").emit();
786 let is_since_rustc_version = attr.has_name(sym::rustc_deprecated);
787 depr = Some((Deprecation { since, note, suggestion, is_since_rustc_version }, attr.span));
793 #[derive(PartialEq, Debug, Encodable, Decodable, Copy, Clone)]
804 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
805 #[derive(Encodable, Decodable, HashStable_Generic)]
807 SignedInt(ast::IntTy),
808 UnsignedInt(ast::UintTy),
813 pub fn is_signed(self) -> bool {
817 SignedInt(..) => true,
818 UnsignedInt(..) => false,
823 /// Parse #[repr(...)] forms.
825 /// Valid repr contents: any of the primitive integral type names (see
826 /// `int_type_of_word`, below) to specify enum discriminant type; `C`, to use
827 /// the same discriminant size that the corresponding C enum would or C
828 /// structure layout, `packed` to remove padding, and `transparent` to delegate representation
829 /// concerns to the only non-ZST field.
830 pub fn find_repr_attrs(sess: &Session, attr: &Attribute) -> Vec<ReprAttr> {
833 let mut acc = Vec::new();
834 let diagnostic = &sess.parse_sess.span_diagnostic;
835 if attr.has_name(sym::repr) {
836 if let Some(items) = attr.meta_item_list() {
838 let mut recognised = false;
840 let hint = match item.name_or_empty() {
841 sym::C => Some(ReprC),
842 sym::packed => Some(ReprPacked(1)),
843 sym::simd => Some(ReprSimd),
844 sym::transparent => Some(ReprTransparent),
845 sym::no_niche => Some(ReprNoNiche),
847 let mut err = struct_span_err!(
851 "invalid `repr(align)` attribute: `align` needs an argument"
855 "supply an argument here",
856 "align(...)".to_string(),
857 Applicability::HasPlaceholders,
863 name => int_type_of_word(name).map(ReprInt),
866 if let Some(h) = hint {
870 } else if let Some((name, value)) = item.name_value_literal() {
871 let mut literal_error = None;
872 if name == sym::align {
874 match parse_alignment(&value.kind) {
875 Ok(literal) => acc.push(ReprAlign(literal)),
876 Err(message) => literal_error = Some(message),
878 } else if name == sym::packed {
880 match parse_alignment(&value.kind) {
881 Ok(literal) => acc.push(ReprPacked(literal)),
882 Err(message) => literal_error = Some(message),
884 } else if matches!(name, sym::C | sym::simd | sym::transparent | sym::no_niche)
885 || int_type_of_word(name).is_some()
892 "invalid representation hint: `{}` does not take a parenthesized argument list",
893 name.to_ident_string(),
896 if let Some(literal_error) = literal_error {
901 "invalid `repr({})` attribute: {}",
902 name.to_ident_string(),
907 } else if let Some(meta_item) = item.meta_item() {
908 if let MetaItemKind::NameValue(ref value) = meta_item.kind {
909 if meta_item.has_name(sym::align) || meta_item.has_name(sym::packed) {
910 let name = meta_item.name_or_empty().to_ident_string();
912 let mut err = struct_span_err!(
916 "incorrect `repr({})` attribute format",
920 ast::LitKind::Int(int, ast::LitIntType::Unsuffixed) => {
923 "use parentheses instead",
924 format!("{}({})", name, int),
925 Applicability::MachineApplicable,
928 ast::LitKind::Str(s, _) => {
931 "use parentheses instead",
932 format!("{}({})", name, s),
933 Applicability::MachineApplicable,
941 meta_item.name_or_empty(),
942 sym::C | sym::simd | sym::transparent | sym::no_niche
943 ) || int_type_of_word(meta_item.name_or_empty()).is_some()
950 "invalid representation hint: `{}` does not take a value",
951 meta_item.name_or_empty().to_ident_string(),
956 } else if let MetaItemKind::List(_) = meta_item.kind {
957 if meta_item.has_name(sym::align) {
963 "incorrect `repr(align)` attribute format: \
964 `align` takes exactly one argument in parentheses"
967 } else if meta_item.has_name(sym::packed) {
973 "incorrect `repr(packed)` attribute format: \
974 `packed` takes exactly one parenthesized argument, \
975 or no parentheses at all"
979 meta_item.name_or_empty(),
980 sym::C | sym::simd | sym::transparent | sym::no_niche
981 ) || int_type_of_word(meta_item.name_or_empty()).is_some()
988 "invalid representation hint: `{}` does not take a parenthesized argument list",
989 meta_item.name_or_empty().to_ident_string(),
995 // Not a word we recognize. This will be caught and reported by
996 // the `check_mod_attrs` pass, but this pass doesn't always run
997 // (e.g. if we only pretty-print the source), so we have to gate
998 // the `delay_span_bug` call as follows:
999 if sess.opts.pretty.map_or(true, |pp| pp.needs_analysis()) {
1000 diagnostic.delay_span_bug(item.span(), "unrecognized representation hint");
1009 fn int_type_of_word(s: Symbol) -> Option<IntType> {
1013 sym::i8 => Some(SignedInt(ast::IntTy::I8)),
1014 sym::u8 => Some(UnsignedInt(ast::UintTy::U8)),
1015 sym::i16 => Some(SignedInt(ast::IntTy::I16)),
1016 sym::u16 => Some(UnsignedInt(ast::UintTy::U16)),
1017 sym::i32 => Some(SignedInt(ast::IntTy::I32)),
1018 sym::u32 => Some(UnsignedInt(ast::UintTy::U32)),
1019 sym::i64 => Some(SignedInt(ast::IntTy::I64)),
1020 sym::u64 => Some(UnsignedInt(ast::UintTy::U64)),
1021 sym::i128 => Some(SignedInt(ast::IntTy::I128)),
1022 sym::u128 => Some(UnsignedInt(ast::UintTy::U128)),
1023 sym::isize => Some(SignedInt(ast::IntTy::Isize)),
1024 sym::usize => Some(UnsignedInt(ast::UintTy::Usize)),
1029 pub enum TransparencyError {
1030 UnknownTransparency(Symbol, Span),
1031 MultipleTransparencyAttrs(Span, Span),
1034 pub fn find_transparency(
1035 attrs: &[Attribute],
1037 ) -> (Transparency, Option<TransparencyError>) {
1038 let mut transparency = None;
1039 let mut error = None;
1041 if attr.has_name(sym::rustc_macro_transparency) {
1042 if let Some((_, old_span)) = transparency {
1043 error = Some(TransparencyError::MultipleTransparencyAttrs(old_span, attr.span));
1045 } else if let Some(value) = attr.value_str() {
1046 transparency = Some((
1048 sym::transparent => Transparency::Transparent,
1049 sym::semitransparent => Transparency::SemiTransparent,
1050 sym::opaque => Transparency::Opaque,
1052 error = Some(TransparencyError::UnknownTransparency(value, attr.span));
1061 let fallback = if macro_rules { Transparency::SemiTransparent } else { Transparency::Opaque };
1062 (transparency.map_or(fallback, |t| t.0), error)
1065 pub fn allow_internal_unstable<'a>(
1067 attrs: &'a [Attribute],
1068 ) -> impl Iterator<Item = Symbol> + 'a {
1069 allow_unstable(sess, attrs, sym::allow_internal_unstable)
1072 pub fn rustc_allow_const_fn_unstable<'a>(
1074 attrs: &'a [Attribute],
1075 ) -> impl Iterator<Item = Symbol> + 'a {
1076 allow_unstable(sess, attrs, sym::rustc_allow_const_fn_unstable)
1079 fn allow_unstable<'a>(
1081 attrs: &'a [Attribute],
1083 ) -> impl Iterator<Item = Symbol> + 'a {
1084 let attrs = sess.filter_by_name(attrs, symbol);
1086 .filter_map(move |attr| {
1087 attr.meta_item_list().or_else(|| {
1088 sess.diagnostic().span_err(
1090 &format!("`{}` expects a list of feature names", symbol.to_ident_string()),
1097 list.into_iter().filter_map(move |it| {
1098 let name = it.ident().map(|ident| ident.name);
1100 sess.diagnostic().span_err(
1102 &format!("`{}` expects feature names", symbol.to_ident_string()),
1109 pub fn parse_alignment(node: &ast::LitKind) -> Result<u32, &'static str> {
1110 if let ast::LitKind::Int(literal, ast::LitIntType::Unsuffixed) = node {
1111 if literal.is_power_of_two() {
1112 // rustc_middle::ty::layout::Align restricts align to <= 2^29
1113 if *literal <= 1 << 29 { Ok(*literal as u32) } else { Err("larger than 2^29") }
1115 Err("not a power of two")
1118 Err("not an unsuffixed integer")