1 //! Parsing and validation of builtin attributes
3 use rustc_ast::{self as ast, Attribute, Lit, LitKind, MetaItem, MetaItemKind, NestedMetaItem};
4 use rustc_ast_pretty::pprust;
5 use rustc_errors::{struct_span_err, Applicability};
6 use rustc_feature::{find_gated_cfg, is_builtin_attr_name, Features, GatedCfg};
7 use rustc_macros::HashStable_Generic;
8 use rustc_session::parse::{feature_err, ParseSess};
9 use rustc_session::Session;
10 use rustc_span::hygiene::Transparency;
11 use rustc_span::{symbol::sym, symbol::Symbol, Span};
12 use std::num::NonZeroU32;
14 pub fn is_builtin_attr(attr: &Attribute) -> bool {
15 attr.is_doc_comment() || attr.ident().filter(|ident| is_builtin_attr_name(ident.name)).is_some()
20 UnknownMetaItem(String, &'static [&'static str]),
24 MultipleStabilityLevels,
25 UnsupportedLiteral(&'static str, /* is_bytestr */ bool),
28 fn handle_errors(sess: &ParseSess, span: Span, error: AttrError) {
29 let diag = &sess.span_diagnostic;
31 AttrError::MultipleItem(item) => {
32 struct_span_err!(diag, span, E0538, "multiple '{}' items", item).emit();
34 AttrError::UnknownMetaItem(item, expected) => {
35 let expected = expected.iter().map(|name| format!("`{}`", name)).collect::<Vec<_>>();
36 struct_span_err!(diag, span, E0541, "unknown meta item '{}'", item)
37 .span_label(span, format!("expected one of {}", expected.join(", ")))
40 AttrError::MissingSince => {
41 struct_span_err!(diag, span, E0542, "missing 'since'").emit();
43 AttrError::NonIdentFeature => {
44 struct_span_err!(diag, span, E0546, "'feature' is not an identifier").emit();
46 AttrError::MissingFeature => {
47 struct_span_err!(diag, span, E0546, "missing 'feature'").emit();
49 AttrError::MultipleStabilityLevels => {
50 struct_span_err!(diag, span, E0544, "multiple stability levels").emit();
52 AttrError::UnsupportedLiteral(msg, is_bytestr) => {
53 let mut err = struct_span_err!(diag, span, E0565, "{}", msg);
55 if let Ok(lint_str) = sess.source_map().span_to_snippet(span) {
58 "consider removing the prefix",
59 lint_str[1..].to_string(),
60 Applicability::MaybeIncorrect,
69 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
77 #[derive(Clone, Encodable, Decodable, Debug, PartialEq, Eq, HashStable_Generic)]
78 pub enum InstructionSetAttr {
83 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
84 pub enum OptimizeAttr {
90 /// Represents the following attributes:
94 #[derive(Encodable, Decodable, Copy, Clone, Debug, PartialEq, Eq, Hash)]
95 #[derive(HashStable_Generic)]
96 pub struct Stability {
97 pub level: StabilityLevel,
101 /// Represents the `#[rustc_const_unstable]` and `#[rustc_const_stable]` attributes.
102 #[derive(Encodable, Decodable, Copy, Clone, Debug, PartialEq, Eq, Hash)]
103 #[derive(HashStable_Generic)]
104 pub struct ConstStability {
105 pub level: StabilityLevel,
107 /// whether the function has a `#[rustc_promotable]` attribute
108 pub promotable: bool,
111 /// The available stability levels.
112 #[derive(Encodable, Decodable, PartialEq, Copy, Clone, Debug, Eq, Hash)]
113 #[derive(HashStable_Generic)]
114 pub enum StabilityLevel {
115 // Reason for the current stability level and the relevant rust-lang issue
116 Unstable { reason: Option<Symbol>, issue: Option<NonZeroU32>, is_soft: bool },
117 Stable { since: Symbol },
120 impl StabilityLevel {
121 pub fn is_unstable(&self) -> bool {
122 matches!(self, StabilityLevel::Unstable { .. })
124 pub fn is_stable(&self) -> bool {
125 matches!(self, StabilityLevel::Stable { .. })
129 /// Collects stability info from all stability attributes in `attrs`.
130 /// Returns `None` if no stability attributes are found.
131 pub fn find_stability(
135 ) -> (Option<(Stability, Span)>, Option<(ConstStability, Span)>) {
136 find_stability_generic(sess, attrs.iter(), item_sp)
139 fn find_stability_generic<'a, I>(
143 ) -> (Option<(Stability, Span)>, Option<(ConstStability, Span)>)
145 I: Iterator<Item = &'a Attribute>,
147 use StabilityLevel::*;
149 let mut stab: Option<(Stability, Span)> = None;
150 let mut const_stab: Option<(ConstStability, Span)> = None;
151 let mut promotable = false;
153 let diagnostic = &sess.parse_sess.span_diagnostic;
155 'outer: for attr in attrs_iter {
157 sym::rustc_const_unstable,
158 sym::rustc_const_stable,
161 sym::rustc_promotable,
164 .any(|&s| attr.has_name(s))
166 continue; // not a stability level
169 let meta = attr.meta();
171 if attr.has_name(sym::rustc_promotable) {
174 // attributes with data
175 else if let Some(MetaItem { kind: MetaItemKind::List(ref metas), .. }) = meta {
176 let meta = meta.as_ref().unwrap();
177 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
182 AttrError::MultipleItem(pprust::path_to_string(&meta.path)),
186 if let Some(v) = meta.value_str() {
190 struct_span_err!(diagnostic, meta.span, E0539, "incorrect meta item").emit();
195 let meta_name = meta.name_or_empty();
197 sym::rustc_const_unstable | sym::unstable => {
198 if meta_name == sym::unstable && stab.is_some() {
202 AttrError::MultipleStabilityLevels,
205 } else if meta_name == sym::rustc_const_unstable && const_stab.is_some() {
209 AttrError::MultipleStabilityLevels,
214 let mut feature = None;
215 let mut reason = None;
216 let mut issue = None;
217 let mut issue_num = None;
218 let mut is_soft = false;
220 if let Some(mi) = meta.meta_item() {
221 match mi.name_or_empty() {
223 if !get(mi, &mut feature) {
228 if !get(mi, &mut reason) {
233 if !get(mi, &mut issue) {
237 // These unwraps are safe because `get` ensures the meta item
238 // is a name/value pair string literal.
239 issue_num = match issue.unwrap().as_str() {
242 let emit_diag = |msg: &str| {
247 "`issue` must be a non-zero numeric string \
251 mi.name_value_literal_span().unwrap(),
256 match issue.parse() {
259 "`issue` must not be \"0\", \
260 use \"none\" instead",
264 Ok(num) => NonZeroU32::new(num),
266 emit_diag(&err.to_string());
275 let msg = "`soft` should not have any arguments";
276 sess.parse_sess.span_diagnostic.span_err(mi.span, msg);
284 AttrError::UnknownMetaItem(
285 pprust::path_to_string(&mi.path),
286 &["feature", "reason", "issue", "soft"],
296 AttrError::UnsupportedLiteral("unsupported literal", false),
302 match (feature, reason, issue) {
303 (Some(feature), reason, Some(_)) => {
304 if !rustc_lexer::is_ident(feature.as_str()) {
308 AttrError::NonIdentFeature,
312 let level = Unstable { reason, issue: issue_num, is_soft };
313 if sym::unstable == meta_name {
314 stab = Some((Stability { level, feature }, attr.span));
317 ConstStability { level, feature, promotable: false },
323 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingFeature);
327 struct_span_err!(diagnostic, attr.span, E0547, "missing 'issue'")
333 sym::rustc_const_stable | sym::stable => {
334 if meta_name == sym::stable && stab.is_some() {
338 AttrError::MultipleStabilityLevels,
341 } else if meta_name == sym::rustc_const_stable && const_stab.is_some() {
345 AttrError::MultipleStabilityLevels,
350 let mut feature = None;
351 let mut since = None;
354 NestedMetaItem::MetaItem(mi) => match mi.name_or_empty() {
356 if !get(mi, &mut feature) {
361 if !get(mi, &mut since) {
369 AttrError::UnknownMetaItem(
370 pprust::path_to_string(&mi.path),
377 NestedMetaItem::Literal(lit) => {
381 AttrError::UnsupportedLiteral("unsupported literal", false),
388 match (feature, since) {
389 (Some(feature), Some(since)) => {
390 let level = Stable { since };
391 if sym::stable == meta_name {
392 stab = Some((Stability { level, feature }, attr.span));
395 ConstStability { level, feature, promotable: false },
401 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingFeature);
405 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingSince);
415 // Merge the const-unstable info into the stability info
417 if let Some((ref mut stab, _)) = const_stab {
418 stab.promotable = promotable;
424 "`rustc_promotable` attribute must be paired with either a `rustc_const_unstable` \
425 or a `rustc_const_stable` attribute"
434 pub fn find_crate_name(sess: &Session, attrs: &[Attribute]) -> Option<Symbol> {
435 sess.first_attr_value_str_by_name(attrs, sym::crate_name)
438 /// Tests if a cfg-pattern matches the cfg set
439 pub fn cfg_matches(cfg: &ast::MetaItem, sess: &ParseSess, features: Option<&Features>) -> bool {
440 eval_condition(cfg, sess, features, &mut |cfg| {
441 try_gate_cfg(cfg, sess, features);
442 let error = |span, msg| {
443 sess.span_diagnostic.span_err(span, msg);
446 if cfg.path.segments.len() != 1 {
447 return error(cfg.path.span, "`cfg` predicate key must be an identifier");
450 MetaItemKind::List(..) => {
451 error(cfg.span, "unexpected parentheses after `cfg` predicate key")
453 MetaItemKind::NameValue(lit) if !lit.kind.is_str() => {
457 AttrError::UnsupportedLiteral(
458 "literal in `cfg` predicate value must be a string",
459 lit.kind.is_bytestr(),
464 MetaItemKind::NameValue(..) | MetaItemKind::Word => {
465 let ident = cfg.ident().expect("multi-segment cfg predicate");
466 sess.config.contains(&(ident.name, cfg.value_str()))
472 fn try_gate_cfg(cfg: &ast::MetaItem, sess: &ParseSess, features: Option<&Features>) {
473 let gate = find_gated_cfg(|sym| cfg.has_name(sym));
474 if let (Some(feats), Some(gated_cfg)) = (features, gate) {
475 gate_cfg(&gated_cfg, cfg.span, sess, feats);
479 fn gate_cfg(gated_cfg: &GatedCfg, cfg_span: Span, sess: &ParseSess, features: &Features) {
480 let (cfg, feature, has_feature) = gated_cfg;
481 if !has_feature(features) && !cfg_span.allows_unstable(*feature) {
482 let explain = format!("`cfg({})` is experimental and subject to change", cfg);
483 feature_err(sess, *feature, cfg_span, &explain).emit();
487 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
494 fn parse_version(s: &str, allow_appendix: bool) -> Option<Version> {
495 let mut components = s.split('-');
496 let d = components.next()?;
497 if !allow_appendix && components.next().is_some() {
500 let mut digits = d.splitn(3, '.');
501 let major = digits.next()?.parse().ok()?;
502 let minor = digits.next()?.parse().ok()?;
503 let patch = digits.next().unwrap_or("0").parse().ok()?;
504 Some(Version { major, minor, patch })
507 /// Evaluate a cfg-like condition (with `any` and `all`), using `eval` to
508 /// evaluate individual items.
509 pub fn eval_condition(
512 features: Option<&Features>,
513 eval: &mut impl FnMut(&ast::MetaItem) -> bool,
516 ast::MetaItemKind::List(ref mis) if cfg.name_or_empty() == sym::version => {
517 try_gate_cfg(cfg, sess, features);
518 let (min_version, span) = match &mis[..] {
519 [NestedMetaItem::Literal(Lit { kind: LitKind::Str(sym, ..), span, .. })] => {
523 NestedMetaItem::Literal(Lit { span, .. })
524 | NestedMetaItem::MetaItem(MetaItem { span, .. }),
527 .struct_span_err(*span, "expected a version literal")
533 .struct_span_err(cfg.span, "expected single version literal")
538 let min_version = match parse_version(min_version.as_str(), false) {
544 "unknown version literal format, assuming it refers to a future version",
550 let rustc_version = parse_version(env!("CFG_RELEASE"), true).unwrap();
552 // See https://github.com/rust-lang/rust/issues/64796#issuecomment-640851454 for details
553 if sess.assume_incomplete_release {
554 rustc_version > min_version
556 rustc_version >= min_version
559 ast::MetaItemKind::List(ref mis) => {
560 for mi in mis.iter() {
561 if !mi.is_meta_item() {
565 AttrError::UnsupportedLiteral("unsupported literal", false),
571 // The unwraps below may look dangerous, but we've already asserted
572 // that they won't fail with the loop above.
573 match cfg.name_or_empty() {
576 .any(|mi| eval_condition(mi.meta_item().unwrap(), sess, features, eval)),
579 .all(|mi| eval_condition(mi.meta_item().unwrap(), sess, features, eval)),
583 sess.span_diagnostic,
586 "expected 1 cfg-pattern"
592 !eval_condition(mis[0].meta_item().unwrap(), sess, features, eval)
596 sess.span_diagnostic,
599 "invalid predicate `{}`",
600 pprust::path_to_string(&cfg.path)
607 ast::MetaItemKind::Word | ast::MetaItemKind::NameValue(..) => eval(cfg),
611 #[derive(Debug, Encodable, Decodable, Clone, HashStable_Generic)]
612 pub struct Deprecation {
613 pub since: Option<Symbol>,
614 /// The note to issue a reason.
615 pub note: Option<Symbol>,
616 /// A text snippet used to completely replace any use of the deprecated item in an expression.
618 /// This is currently unstable.
619 pub suggestion: Option<Symbol>,
621 /// Whether to treat the since attribute as being a Rust version identifier
622 /// (rather than an opaque string).
623 pub is_since_rustc_version: bool,
626 /// Finds the deprecation attribute. `None` if none exists.
627 pub fn find_deprecation(sess: &Session, attrs: &[Attribute]) -> Option<(Deprecation, Span)> {
628 find_deprecation_generic(sess, attrs.iter())
631 fn find_deprecation_generic<'a, I>(sess: &Session, attrs_iter: I) -> Option<(Deprecation, Span)>
633 I: Iterator<Item = &'a Attribute>,
635 let mut depr: Option<(Deprecation, Span)> = None;
636 let diagnostic = &sess.parse_sess.span_diagnostic;
638 'outer: for attr in attrs_iter {
639 if !(attr.has_name(sym::deprecated) || attr.has_name(sym::rustc_deprecated)) {
643 if let Some((_, span)) = &depr {
644 struct_span_err!(diagnostic, attr.span, E0550, "multiple deprecated attributes")
645 .span_label(attr.span, "repeated deprecation attribute")
646 .span_label(*span, "first deprecation attribute")
651 let meta = match attr.meta() {
655 let mut since = None;
657 let mut suggestion = None;
659 MetaItemKind::Word => {}
660 MetaItemKind::NameValue(..) => note = meta.value_str(),
661 MetaItemKind::List(list) => {
662 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
667 AttrError::MultipleItem(pprust::path_to_string(&meta.path)),
671 if let Some(v) = meta.value_str() {
675 if let Some(lit) = meta.name_value_literal() {
679 AttrError::UnsupportedLiteral(
680 "literal in `deprecated` \
681 value must be a string",
682 lit.kind.is_bytestr(),
686 struct_span_err!(diagnostic, meta.span, E0551, "incorrect meta item")
696 NestedMetaItem::MetaItem(mi) => match mi.name_or_empty() {
698 if !get(mi, &mut since) {
702 sym::note if attr.has_name(sym::deprecated) => {
703 if !get(mi, &mut note) {
707 sym::reason if attr.has_name(sym::rustc_deprecated) => {
708 if !get(mi, &mut note) {
712 sym::suggestion if attr.has_name(sym::rustc_deprecated) => {
713 if !get(mi, &mut suggestion) {
721 AttrError::UnknownMetaItem(
722 pprust::path_to_string(&mi.path),
723 if attr.has_name(sym::deprecated) {
726 &["since", "reason", "suggestion"]
733 NestedMetaItem::Literal(lit) => {
737 AttrError::UnsupportedLiteral(
738 "item in `deprecated` must be a key/value pair",
749 if suggestion.is_some() && attr.has_name(sym::deprecated) {
750 unreachable!("only allowed on rustc_deprecated")
753 if attr.has_name(sym::rustc_deprecated) {
755 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingSince);
760 struct_span_err!(diagnostic, attr.span, E0543, "missing 'reason'").emit();
765 let is_since_rustc_version = attr.has_name(sym::rustc_deprecated);
766 depr = Some((Deprecation { since, note, suggestion, is_since_rustc_version }, attr.span));
772 #[derive(PartialEq, Debug, Encodable, Decodable, Copy, Clone)]
783 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
784 #[derive(Encodable, Decodable, HashStable_Generic)]
786 SignedInt(ast::IntTy),
787 UnsignedInt(ast::UintTy),
792 pub fn is_signed(self) -> bool {
796 SignedInt(..) => true,
797 UnsignedInt(..) => false,
802 /// Parse #[repr(...)] forms.
804 /// Valid repr contents: any of the primitive integral type names (see
805 /// `int_type_of_word`, below) to specify enum discriminant type; `C`, to use
806 /// the same discriminant size that the corresponding C enum would or C
807 /// structure layout, `packed` to remove padding, and `transparent` to delegate representation
808 /// concerns to the only non-ZST field.
809 pub fn find_repr_attrs(sess: &Session, attr: &Attribute) -> Vec<ReprAttr> {
812 let mut acc = Vec::new();
813 let diagnostic = &sess.parse_sess.span_diagnostic;
814 if attr.has_name(sym::repr) {
815 if let Some(items) = attr.meta_item_list() {
817 let mut recognised = false;
819 let hint = match item.name_or_empty() {
820 sym::C => Some(ReprC),
821 sym::packed => Some(ReprPacked(1)),
822 sym::simd => Some(ReprSimd),
823 sym::transparent => Some(ReprTransparent),
824 sym::no_niche => Some(ReprNoNiche),
826 let mut err = struct_span_err!(
830 "invalid `repr(align)` attribute: `align` needs an argument"
834 "supply an argument here",
835 "align(...)".to_string(),
836 Applicability::HasPlaceholders,
842 name => int_type_of_word(name).map(ReprInt),
845 if let Some(h) = hint {
849 } else if let Some((name, value)) = item.name_value_literal() {
850 let mut literal_error = None;
851 if name == sym::align {
853 match parse_alignment(&value.kind) {
854 Ok(literal) => acc.push(ReprAlign(literal)),
855 Err(message) => literal_error = Some(message),
857 } else if name == sym::packed {
859 match parse_alignment(&value.kind) {
860 Ok(literal) => acc.push(ReprPacked(literal)),
861 Err(message) => literal_error = Some(message),
863 } else if matches!(name, sym::C | sym::simd | sym::transparent | sym::no_niche)
864 || int_type_of_word(name).is_some()
871 "invalid representation hint: `{}` does not take a parenthesized argument list",
872 name.to_ident_string(),
875 if let Some(literal_error) = literal_error {
880 "invalid `repr({})` attribute: {}",
881 name.to_ident_string(),
886 } else if let Some(meta_item) = item.meta_item() {
887 if let MetaItemKind::NameValue(ref value) = meta_item.kind {
888 if meta_item.has_name(sym::align) || meta_item.has_name(sym::packed) {
889 let name = meta_item.name_or_empty().to_ident_string();
891 let mut err = struct_span_err!(
895 "incorrect `repr({})` attribute format",
899 ast::LitKind::Int(int, ast::LitIntType::Unsuffixed) => {
902 "use parentheses instead",
903 format!("{}({})", name, int),
904 Applicability::MachineApplicable,
907 ast::LitKind::Str(s, _) => {
910 "use parentheses instead",
911 format!("{}({})", name, s),
912 Applicability::MachineApplicable,
920 meta_item.name_or_empty(),
921 sym::C | sym::simd | sym::transparent | sym::no_niche
922 ) || int_type_of_word(meta_item.name_or_empty()).is_some()
929 "invalid representation hint: `{}` does not take a value",
930 meta_item.name_or_empty().to_ident_string(),
935 } else if let MetaItemKind::List(_) = meta_item.kind {
936 if meta_item.has_name(sym::align) {
942 "incorrect `repr(align)` attribute format: \
943 `align` takes exactly one argument in parentheses"
946 } else if meta_item.has_name(sym::packed) {
952 "incorrect `repr(packed)` attribute format: \
953 `packed` takes exactly one parenthesized argument, \
954 or no parentheses at all"
958 meta_item.name_or_empty(),
959 sym::C | sym::simd | sym::transparent | sym::no_niche
960 ) || int_type_of_word(meta_item.name_or_empty()).is_some()
967 "invalid representation hint: `{}` does not take a parenthesized argument list",
968 meta_item.name_or_empty().to_ident_string(),
974 // Not a word we recognize. This will be caught and reported by
975 // the `check_mod_attrs` pass, but this pass doesn't always run
976 // (e.g. if we only pretty-print the source), so we have to gate
977 // the `delay_span_bug` call as follows:
978 if sess.opts.pretty.map_or(true, |pp| pp.needs_analysis()) {
979 diagnostic.delay_span_bug(item.span(), "unrecognized representation hint");
988 fn int_type_of_word(s: Symbol) -> Option<IntType> {
992 sym::i8 => Some(SignedInt(ast::IntTy::I8)),
993 sym::u8 => Some(UnsignedInt(ast::UintTy::U8)),
994 sym::i16 => Some(SignedInt(ast::IntTy::I16)),
995 sym::u16 => Some(UnsignedInt(ast::UintTy::U16)),
996 sym::i32 => Some(SignedInt(ast::IntTy::I32)),
997 sym::u32 => Some(UnsignedInt(ast::UintTy::U32)),
998 sym::i64 => Some(SignedInt(ast::IntTy::I64)),
999 sym::u64 => Some(UnsignedInt(ast::UintTy::U64)),
1000 sym::i128 => Some(SignedInt(ast::IntTy::I128)),
1001 sym::u128 => Some(UnsignedInt(ast::UintTy::U128)),
1002 sym::isize => Some(SignedInt(ast::IntTy::Isize)),
1003 sym::usize => Some(UnsignedInt(ast::UintTy::Usize)),
1008 pub enum TransparencyError {
1009 UnknownTransparency(Symbol, Span),
1010 MultipleTransparencyAttrs(Span, Span),
1013 pub fn find_transparency(
1014 attrs: &[Attribute],
1016 ) -> (Transparency, Option<TransparencyError>) {
1017 let mut transparency = None;
1018 let mut error = None;
1020 if attr.has_name(sym::rustc_macro_transparency) {
1021 if let Some((_, old_span)) = transparency {
1022 error = Some(TransparencyError::MultipleTransparencyAttrs(old_span, attr.span));
1024 } else if let Some(value) = attr.value_str() {
1025 transparency = Some((
1027 sym::transparent => Transparency::Transparent,
1028 sym::semitransparent => Transparency::SemiTransparent,
1029 sym::opaque => Transparency::Opaque,
1031 error = Some(TransparencyError::UnknownTransparency(value, attr.span));
1040 let fallback = if macro_rules { Transparency::SemiTransparent } else { Transparency::Opaque };
1041 (transparency.map_or(fallback, |t| t.0), error)
1044 pub fn allow_internal_unstable<'a>(
1046 attrs: &'a [Attribute],
1047 ) -> impl Iterator<Item = Symbol> + 'a {
1048 allow_unstable(sess, attrs, sym::allow_internal_unstable)
1051 pub fn rustc_allow_const_fn_unstable<'a>(
1053 attrs: &'a [Attribute],
1054 ) -> impl Iterator<Item = Symbol> + 'a {
1055 allow_unstable(sess, attrs, sym::rustc_allow_const_fn_unstable)
1058 fn allow_unstable<'a>(
1060 attrs: &'a [Attribute],
1062 ) -> impl Iterator<Item = Symbol> + 'a {
1063 let attrs = sess.filter_by_name(attrs, symbol);
1065 .filter_map(move |attr| {
1066 attr.meta_item_list().or_else(|| {
1067 sess.diagnostic().span_err(
1069 &format!("`{}` expects a list of feature names", symbol.to_ident_string()),
1076 list.into_iter().filter_map(move |it| {
1077 let name = it.ident().map(|ident| ident.name);
1079 sess.diagnostic().span_err(
1081 &format!("`{}` expects feature names", symbol.to_ident_string()),
1088 pub fn parse_alignment(node: &ast::LitKind) -> Result<u32, &'static str> {
1089 if let ast::LitKind::Int(literal, ast::LitIntType::Unsuffixed) = node {
1090 if literal.is_power_of_two() {
1091 // rustc_middle::ty::layout::Align restricts align to <= 2^29
1092 if *literal <= 1 << 29 { Ok(*literal as u32) } else { Err("larger than 2^29") }
1094 Err("not a power of two")
1097 Err("not an unsuffixed integer")