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 let Some(mi) = meta.meta_item() else {
224 AttrError::UnsupportedLiteral("unsupported literal", false),
228 match mi.name_or_empty() {
230 if !get(mi, &mut feature) {
235 if !get(mi, &mut reason) {
240 if !get(mi, &mut issue) {
244 // These unwraps are safe because `get` ensures the meta item
245 // is a name/value pair string literal.
246 issue_num = match issue.unwrap().as_str() {
249 let emit_diag = |msg: &str| {
254 "`issue` must be a non-zero numeric string \
257 .span_label(mi.name_value_literal_span().unwrap(), msg)
260 match issue.parse() {
263 "`issue` must not be \"0\", \
264 use \"none\" instead",
268 Ok(num) => NonZeroU32::new(num),
270 emit_diag(&err.to_string());
279 let msg = "`soft` should not have any arguments";
280 sess.parse_sess.span_diagnostic.span_err(mi.span, msg);
288 AttrError::UnknownMetaItem(
289 pprust::path_to_string(&mi.path),
290 &["feature", "reason", "issue", "soft"],
298 match (feature, reason, issue) {
299 (Some(feature), reason, Some(_)) => {
300 if !rustc_lexer::is_ident(feature.as_str()) {
304 AttrError::NonIdentFeature,
308 let level = Unstable { reason, issue: issue_num, is_soft };
309 if sym::unstable == meta_name {
310 stab = Some((Stability { level, feature }, attr.span));
313 ConstStability { level, feature, promotable: false },
319 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingFeature);
323 struct_span_err!(diagnostic, attr.span, E0547, "missing 'issue'")
329 sym::rustc_const_stable | sym::stable => {
330 if meta_name == sym::stable && stab.is_some() {
334 AttrError::MultipleStabilityLevels,
337 } else if meta_name == sym::rustc_const_stable && const_stab.is_some() {
341 AttrError::MultipleStabilityLevels,
346 let mut feature = None;
347 let mut since = None;
350 NestedMetaItem::MetaItem(mi) => match mi.name_or_empty() {
352 if !get(mi, &mut feature) {
357 if !get(mi, &mut since) {
365 AttrError::UnknownMetaItem(
366 pprust::path_to_string(&mi.path),
373 NestedMetaItem::Literal(lit) => {
377 AttrError::UnsupportedLiteral("unsupported literal", false),
384 match (feature, since) {
385 (Some(feature), Some(since)) => {
386 let level = Stable { since };
387 if sym::stable == meta_name {
388 stab = Some((Stability { level, feature }, attr.span));
391 ConstStability { level, feature, promotable: false },
397 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingFeature);
401 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingSince);
411 // Merge the const-unstable info into the stability info
413 if let Some((ref mut stab, _)) = const_stab {
414 stab.promotable = promotable;
420 "`rustc_promotable` attribute must be paired with either a `rustc_const_unstable` \
421 or a `rustc_const_stable` attribute"
430 pub fn find_crate_name(sess: &Session, attrs: &[Attribute]) -> Option<Symbol> {
431 sess.first_attr_value_str_by_name(attrs, sym::crate_name)
434 /// Tests if a cfg-pattern matches the cfg set
435 pub fn cfg_matches(cfg: &ast::MetaItem, sess: &ParseSess, features: Option<&Features>) -> bool {
436 eval_condition(cfg, sess, features, &mut |cfg| {
437 try_gate_cfg(cfg, sess, features);
438 let error = |span, msg| {
439 sess.span_diagnostic.span_err(span, msg);
442 if cfg.path.segments.len() != 1 {
443 return error(cfg.path.span, "`cfg` predicate key must be an identifier");
446 MetaItemKind::List(..) => {
447 error(cfg.span, "unexpected parentheses after `cfg` predicate key")
449 MetaItemKind::NameValue(lit) if !lit.kind.is_str() => {
453 AttrError::UnsupportedLiteral(
454 "literal in `cfg` predicate value must be a string",
455 lit.kind.is_bytestr(),
460 MetaItemKind::NameValue(..) | MetaItemKind::Word => {
461 let ident = cfg.ident().expect("multi-segment cfg predicate");
462 sess.config.contains(&(ident.name, cfg.value_str()))
468 fn try_gate_cfg(cfg: &ast::MetaItem, sess: &ParseSess, features: Option<&Features>) {
469 let gate = find_gated_cfg(|sym| cfg.has_name(sym));
470 if let (Some(feats), Some(gated_cfg)) = (features, gate) {
471 gate_cfg(&gated_cfg, cfg.span, sess, feats);
475 fn gate_cfg(gated_cfg: &GatedCfg, cfg_span: Span, sess: &ParseSess, features: &Features) {
476 let (cfg, feature, has_feature) = gated_cfg;
477 if !has_feature(features) && !cfg_span.allows_unstable(*feature) {
478 let explain = format!("`cfg({})` is experimental and subject to change", cfg);
479 feature_err(sess, *feature, cfg_span, &explain).emit();
483 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
490 fn parse_version(s: &str, allow_appendix: bool) -> Option<Version> {
491 let mut components = s.split('-');
492 let d = components.next()?;
493 if !allow_appendix && components.next().is_some() {
496 let mut digits = d.splitn(3, '.');
497 let major = digits.next()?.parse().ok()?;
498 let minor = digits.next()?.parse().ok()?;
499 let patch = digits.next().unwrap_or("0").parse().ok()?;
500 Some(Version { major, minor, patch })
503 /// Evaluate a cfg-like condition (with `any` and `all`), using `eval` to
504 /// evaluate individual items.
505 pub fn eval_condition(
508 features: Option<&Features>,
509 eval: &mut impl FnMut(&ast::MetaItem) -> bool,
512 ast::MetaItemKind::List(ref mis) if cfg.name_or_empty() == sym::version => {
513 try_gate_cfg(cfg, sess, features);
514 let (min_version, span) = match &mis[..] {
515 [NestedMetaItem::Literal(Lit { kind: LitKind::Str(sym, ..), span, .. })] => {
519 NestedMetaItem::Literal(Lit { span, .. })
520 | NestedMetaItem::MetaItem(MetaItem { span, .. }),
523 .struct_span_err(*span, "expected a version literal")
529 .struct_span_err(cfg.span, "expected single version literal")
534 let min_version = match parse_version(min_version.as_str(), false) {
540 "unknown version literal format, assuming it refers to a future version",
546 let rustc_version = parse_version(env!("CFG_RELEASE"), true).unwrap();
548 // See https://github.com/rust-lang/rust/issues/64796#issuecomment-640851454 for details
549 if sess.assume_incomplete_release {
550 rustc_version > min_version
552 rustc_version >= min_version
555 ast::MetaItemKind::List(ref mis) => {
556 for mi in mis.iter() {
557 if !mi.is_meta_item() {
561 AttrError::UnsupportedLiteral("unsupported literal", false),
567 // The unwraps below may look dangerous, but we've already asserted
568 // that they won't fail with the loop above.
569 match cfg.name_or_empty() {
572 .any(|mi| eval_condition(mi.meta_item().unwrap(), sess, features, eval)),
575 .all(|mi| eval_condition(mi.meta_item().unwrap(), sess, features, eval)),
579 sess.span_diagnostic,
582 "expected 1 cfg-pattern"
588 !eval_condition(mis[0].meta_item().unwrap(), sess, features, eval)
592 sess.span_diagnostic,
595 "invalid predicate `{}`",
596 pprust::path_to_string(&cfg.path)
603 ast::MetaItemKind::Word | ast::MetaItemKind::NameValue(..) => eval(cfg),
607 #[derive(Debug, Encodable, Decodable, Clone, HashStable_Generic)]
608 pub struct Deprecation {
609 pub since: Option<Symbol>,
610 /// The note to issue a reason.
611 pub note: Option<Symbol>,
612 /// A text snippet used to completely replace any use of the deprecated item in an expression.
614 /// This is currently unstable.
615 pub suggestion: Option<Symbol>,
617 /// Whether to treat the since attribute as being a Rust version identifier
618 /// (rather than an opaque string).
619 pub is_since_rustc_version: bool,
622 /// Finds the deprecation attribute. `None` if none exists.
623 pub fn find_deprecation(sess: &Session, attrs: &[Attribute]) -> Option<(Deprecation, Span)> {
624 find_deprecation_generic(sess, attrs.iter())
627 fn find_deprecation_generic<'a, I>(sess: &Session, attrs_iter: I) -> Option<(Deprecation, Span)>
629 I: Iterator<Item = &'a Attribute>,
631 let mut depr: Option<(Deprecation, Span)> = None;
632 let diagnostic = &sess.parse_sess.span_diagnostic;
634 'outer: for attr in attrs_iter {
635 if !(attr.has_name(sym::deprecated) || attr.has_name(sym::rustc_deprecated)) {
639 if let Some((_, span)) = &depr {
640 struct_span_err!(diagnostic, attr.span, E0550, "multiple deprecated attributes")
641 .span_label(attr.span, "repeated deprecation attribute")
642 .span_label(*span, "first deprecation attribute")
647 let meta = match attr.meta() {
651 let mut since = None;
653 let mut suggestion = None;
655 MetaItemKind::Word => {}
656 MetaItemKind::NameValue(..) => note = meta.value_str(),
657 MetaItemKind::List(list) => {
658 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
663 AttrError::MultipleItem(pprust::path_to_string(&meta.path)),
667 if let Some(v) = meta.value_str() {
671 if let Some(lit) = meta.name_value_literal() {
675 AttrError::UnsupportedLiteral(
676 "literal in `deprecated` \
677 value must be a string",
678 lit.kind.is_bytestr(),
682 struct_span_err!(diagnostic, meta.span, E0551, "incorrect meta item")
692 NestedMetaItem::MetaItem(mi) => match mi.name_or_empty() {
694 if !get(mi, &mut since) {
698 sym::note if attr.has_name(sym::deprecated) => {
699 if !get(mi, &mut note) {
703 sym::reason if attr.has_name(sym::rustc_deprecated) => {
704 if !get(mi, &mut note) {
708 sym::suggestion if attr.has_name(sym::rustc_deprecated) => {
709 if !get(mi, &mut suggestion) {
717 AttrError::UnknownMetaItem(
718 pprust::path_to_string(&mi.path),
719 if attr.has_name(sym::deprecated) {
722 &["since", "reason", "suggestion"]
729 NestedMetaItem::Literal(lit) => {
733 AttrError::UnsupportedLiteral(
734 "item in `deprecated` must be a key/value pair",
745 if suggestion.is_some() && attr.has_name(sym::deprecated) {
746 unreachable!("only allowed on rustc_deprecated")
749 if attr.has_name(sym::rustc_deprecated) {
751 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingSince);
756 struct_span_err!(diagnostic, attr.span, E0543, "missing 'reason'").emit();
761 let is_since_rustc_version = attr.has_name(sym::rustc_deprecated);
762 depr = Some((Deprecation { since, note, suggestion, is_since_rustc_version }, attr.span));
768 #[derive(PartialEq, Debug, Encodable, Decodable, Copy, Clone)]
779 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
780 #[derive(Encodable, Decodable, HashStable_Generic)]
782 SignedInt(ast::IntTy),
783 UnsignedInt(ast::UintTy),
788 pub fn is_signed(self) -> bool {
792 SignedInt(..) => true,
793 UnsignedInt(..) => false,
798 /// Parse #[repr(...)] forms.
800 /// Valid repr contents: any of the primitive integral type names (see
801 /// `int_type_of_word`, below) to specify enum discriminant type; `C`, to use
802 /// the same discriminant size that the corresponding C enum would or C
803 /// structure layout, `packed` to remove padding, and `transparent` to delegate representation
804 /// concerns to the only non-ZST field.
805 pub fn find_repr_attrs(sess: &Session, attr: &Attribute) -> Vec<ReprAttr> {
808 let mut acc = Vec::new();
809 let diagnostic = &sess.parse_sess.span_diagnostic;
810 if attr.has_name(sym::repr) {
811 if let Some(items) = attr.meta_item_list() {
813 let mut recognised = false;
815 let hint = match item.name_or_empty() {
816 sym::C => Some(ReprC),
817 sym::packed => Some(ReprPacked(1)),
818 sym::simd => Some(ReprSimd),
819 sym::transparent => Some(ReprTransparent),
820 sym::no_niche => Some(ReprNoNiche),
822 let mut err = struct_span_err!(
826 "invalid `repr(align)` attribute: `align` needs an argument"
830 "supply an argument here",
831 "align(...)".to_string(),
832 Applicability::HasPlaceholders,
838 name => int_type_of_word(name).map(ReprInt),
841 if let Some(h) = hint {
845 } else if let Some((name, value)) = item.name_value_literal() {
846 let mut literal_error = None;
847 if name == sym::align {
849 match parse_alignment(&value.kind) {
850 Ok(literal) => acc.push(ReprAlign(literal)),
851 Err(message) => literal_error = Some(message),
853 } else if name == sym::packed {
855 match parse_alignment(&value.kind) {
856 Ok(literal) => acc.push(ReprPacked(literal)),
857 Err(message) => literal_error = Some(message),
859 } else if matches!(name, sym::C | sym::simd | sym::transparent | sym::no_niche)
860 || int_type_of_word(name).is_some()
867 "invalid representation hint: `{}` does not take a parenthesized argument list",
868 name.to_ident_string(),
871 if let Some(literal_error) = literal_error {
876 "invalid `repr({})` attribute: {}",
877 name.to_ident_string(),
882 } else if let Some(meta_item) = item.meta_item() {
883 if let MetaItemKind::NameValue(ref value) = meta_item.kind {
884 if meta_item.has_name(sym::align) || meta_item.has_name(sym::packed) {
885 let name = meta_item.name_or_empty().to_ident_string();
887 let mut err = struct_span_err!(
891 "incorrect `repr({})` attribute format",
895 ast::LitKind::Int(int, ast::LitIntType::Unsuffixed) => {
898 "use parentheses instead",
899 format!("{}({})", name, int),
900 Applicability::MachineApplicable,
903 ast::LitKind::Str(s, _) => {
906 "use parentheses instead",
907 format!("{}({})", name, s),
908 Applicability::MachineApplicable,
916 meta_item.name_or_empty(),
917 sym::C | sym::simd | sym::transparent | sym::no_niche
918 ) || int_type_of_word(meta_item.name_or_empty()).is_some()
925 "invalid representation hint: `{}` does not take a value",
926 meta_item.name_or_empty().to_ident_string(),
931 } else if let MetaItemKind::List(_) = meta_item.kind {
932 if meta_item.has_name(sym::align) {
938 "incorrect `repr(align)` attribute format: \
939 `align` takes exactly one argument in parentheses"
942 } else if meta_item.has_name(sym::packed) {
948 "incorrect `repr(packed)` attribute format: \
949 `packed` takes exactly one parenthesized argument, \
950 or no parentheses at all"
954 meta_item.name_or_empty(),
955 sym::C | sym::simd | sym::transparent | sym::no_niche
956 ) || int_type_of_word(meta_item.name_or_empty()).is_some()
963 "invalid representation hint: `{}` does not take a parenthesized argument list",
964 meta_item.name_or_empty().to_ident_string(),
970 // Not a word we recognize. This will be caught and reported by
971 // the `check_mod_attrs` pass, but this pass doesn't always run
972 // (e.g. if we only pretty-print the source), so we have to gate
973 // the `delay_span_bug` call as follows:
974 if sess.opts.pretty.map_or(true, |pp| pp.needs_analysis()) {
975 diagnostic.delay_span_bug(item.span(), "unrecognized representation hint");
984 fn int_type_of_word(s: Symbol) -> Option<IntType> {
988 sym::i8 => Some(SignedInt(ast::IntTy::I8)),
989 sym::u8 => Some(UnsignedInt(ast::UintTy::U8)),
990 sym::i16 => Some(SignedInt(ast::IntTy::I16)),
991 sym::u16 => Some(UnsignedInt(ast::UintTy::U16)),
992 sym::i32 => Some(SignedInt(ast::IntTy::I32)),
993 sym::u32 => Some(UnsignedInt(ast::UintTy::U32)),
994 sym::i64 => Some(SignedInt(ast::IntTy::I64)),
995 sym::u64 => Some(UnsignedInt(ast::UintTy::U64)),
996 sym::i128 => Some(SignedInt(ast::IntTy::I128)),
997 sym::u128 => Some(UnsignedInt(ast::UintTy::U128)),
998 sym::isize => Some(SignedInt(ast::IntTy::Isize)),
999 sym::usize => Some(UnsignedInt(ast::UintTy::Usize)),
1004 pub enum TransparencyError {
1005 UnknownTransparency(Symbol, Span),
1006 MultipleTransparencyAttrs(Span, Span),
1009 pub fn find_transparency(
1010 attrs: &[Attribute],
1012 ) -> (Transparency, Option<TransparencyError>) {
1013 let mut transparency = None;
1014 let mut error = None;
1016 if attr.has_name(sym::rustc_macro_transparency) {
1017 if let Some((_, old_span)) = transparency {
1018 error = Some(TransparencyError::MultipleTransparencyAttrs(old_span, attr.span));
1020 } else if let Some(value) = attr.value_str() {
1021 transparency = Some((
1023 sym::transparent => Transparency::Transparent,
1024 sym::semitransparent => Transparency::SemiTransparent,
1025 sym::opaque => Transparency::Opaque,
1027 error = Some(TransparencyError::UnknownTransparency(value, attr.span));
1036 let fallback = if macro_rules { Transparency::SemiTransparent } else { Transparency::Opaque };
1037 (transparency.map_or(fallback, |t| t.0), error)
1040 pub fn allow_internal_unstable<'a>(
1042 attrs: &'a [Attribute],
1043 ) -> impl Iterator<Item = Symbol> + 'a {
1044 allow_unstable(sess, attrs, sym::allow_internal_unstable)
1047 pub fn rustc_allow_const_fn_unstable<'a>(
1049 attrs: &'a [Attribute],
1050 ) -> impl Iterator<Item = Symbol> + 'a {
1051 allow_unstable(sess, attrs, sym::rustc_allow_const_fn_unstable)
1054 fn allow_unstable<'a>(
1056 attrs: &'a [Attribute],
1058 ) -> impl Iterator<Item = Symbol> + 'a {
1059 let attrs = sess.filter_by_name(attrs, symbol);
1061 .filter_map(move |attr| {
1062 attr.meta_item_list().or_else(|| {
1063 sess.diagnostic().span_err(
1065 &format!("`{}` expects a list of feature names", symbol.to_ident_string()),
1072 list.into_iter().filter_map(move |it| {
1073 let name = it.ident().map(|ident| ident.name);
1075 sess.diagnostic().span_err(
1077 &format!("`{}` expects feature names", symbol.to_ident_string()),
1084 pub fn parse_alignment(node: &ast::LitKind) -> Result<u32, &'static str> {
1085 if let ast::LitKind::Int(literal, ast::LitIntType::Unsuffixed) = node {
1086 if literal.is_power_of_two() {
1087 // rustc_middle::ty::layout::Align restricts align to <= 2^29
1088 if *literal <= 1 << 29 { Ok(*literal as u32) } else { Err("larger than 2^29") }
1090 Err("not a power of two")
1093 Err("not an unsuffixed integer")