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)]
77 #[derive(Clone, Encodable, Decodable, Debug, PartialEq, Eq)]
78 pub enum InstructionSetAttr {
83 #[derive(Clone, Encodable, Decodable, Debug)]
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 sess.mark_attr_used(attr);
171 let meta = attr.meta();
173 if attr.has_name(sym::rustc_promotable) {
176 // attributes with data
177 else if let Some(MetaItem { kind: MetaItemKind::List(ref metas), .. }) = meta {
178 let meta = meta.as_ref().unwrap();
179 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
184 AttrError::MultipleItem(pprust::path_to_string(&meta.path)),
188 if let Some(v) = meta.value_str() {
192 struct_span_err!(diagnostic, meta.span, E0539, "incorrect meta item").emit();
197 let meta_name = meta.name_or_empty();
199 sym::rustc_const_unstable | sym::unstable => {
200 if meta_name == sym::unstable && stab.is_some() {
204 AttrError::MultipleStabilityLevels,
207 } else if meta_name == sym::rustc_const_unstable && const_stab.is_some() {
211 AttrError::MultipleStabilityLevels,
216 let mut feature = None;
217 let mut reason = None;
218 let mut issue = None;
219 let mut issue_num = None;
220 let mut is_soft = false;
222 if let Some(mi) = meta.meta_item() {
223 match mi.name_or_empty() {
225 if !get(mi, &mut feature) {
230 if !get(mi, &mut reason) {
235 if !get(mi, &mut issue) {
239 // These unwraps are safe because `get` ensures the meta item
240 // is a name/value pair string literal.
241 issue_num = match &*issue.unwrap().as_str() {
244 let emit_diag = |msg: &str| {
249 "`issue` must be a non-zero numeric string \
253 mi.name_value_literal_span().unwrap(),
258 match issue.parse() {
261 "`issue` must not be \"0\", \
262 use \"none\" instead",
266 Ok(num) => NonZeroU32::new(num),
268 emit_diag(&err.to_string());
277 let msg = "`soft` should not have any arguments";
278 sess.parse_sess.span_diagnostic.span_err(mi.span, msg);
286 AttrError::UnknownMetaItem(
287 pprust::path_to_string(&mi.path),
288 &["feature", "reason", "issue", "soft"],
298 AttrError::UnsupportedLiteral("unsupported literal", false),
304 match (feature, reason, issue) {
305 (Some(feature), reason, Some(_)) => {
306 if !rustc_lexer::is_ident(&feature.as_str()) {
310 AttrError::NonIdentFeature,
314 let level = Unstable { reason, issue: issue_num, is_soft };
315 if sym::unstable == meta_name {
316 stab = Some((Stability { level, feature }, attr.span));
319 ConstStability { level, feature, promotable: false },
325 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingFeature);
329 struct_span_err!(diagnostic, attr.span, E0547, "missing 'issue'")
335 sym::rustc_const_stable | sym::stable => {
336 if meta_name == sym::stable && stab.is_some() {
340 AttrError::MultipleStabilityLevels,
343 } else if meta_name == sym::rustc_const_stable && const_stab.is_some() {
347 AttrError::MultipleStabilityLevels,
352 let mut feature = None;
353 let mut since = None;
356 NestedMetaItem::MetaItem(mi) => match mi.name_or_empty() {
358 if !get(mi, &mut feature) {
363 if !get(mi, &mut since) {
371 AttrError::UnknownMetaItem(
372 pprust::path_to_string(&mi.path),
379 NestedMetaItem::Literal(lit) => {
383 AttrError::UnsupportedLiteral("unsupported literal", false),
390 match (feature, since) {
391 (Some(feature), Some(since)) => {
392 let level = Stable { since };
393 if sym::stable == meta_name {
394 stab = Some((Stability { level, feature }, attr.span));
397 ConstStability { level, feature, promotable: false },
403 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingFeature);
407 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingSince);
417 // Merge the const-unstable info into the stability info
419 if let Some((ref mut stab, _)) = const_stab {
420 stab.promotable = promotable;
426 "`rustc_promotable` attribute must be paired with either a `rustc_const_unstable` \
427 or a `rustc_const_stable` attribute"
436 pub fn find_crate_name(sess: &Session, attrs: &[Attribute]) -> Option<Symbol> {
437 sess.first_attr_value_str_by_name(attrs, sym::crate_name)
440 /// Tests if a cfg-pattern matches the cfg set
441 pub fn cfg_matches(cfg: &ast::MetaItem, sess: &ParseSess, features: Option<&Features>) -> bool {
442 eval_condition(cfg, sess, features, &mut |cfg| {
443 try_gate_cfg(cfg, sess, features);
444 let error = |span, msg| {
445 sess.span_diagnostic.span_err(span, msg);
448 if cfg.path.segments.len() != 1 {
449 return error(cfg.path.span, "`cfg` predicate key must be an identifier");
452 MetaItemKind::List(..) => {
453 error(cfg.span, "unexpected parentheses after `cfg` predicate key")
455 MetaItemKind::NameValue(lit) if !lit.kind.is_str() => {
459 AttrError::UnsupportedLiteral(
460 "literal in `cfg` predicate value must be a string",
461 lit.kind.is_bytestr(),
466 MetaItemKind::NameValue(..) | MetaItemKind::Word => {
467 let ident = cfg.ident().expect("multi-segment cfg predicate");
468 sess.config.contains(&(ident.name, cfg.value_str()))
474 fn try_gate_cfg(cfg: &ast::MetaItem, sess: &ParseSess, features: Option<&Features>) {
475 let gate = find_gated_cfg(|sym| cfg.has_name(sym));
476 if let (Some(feats), Some(gated_cfg)) = (features, gate) {
477 gate_cfg(&gated_cfg, cfg.span, sess, feats);
481 fn gate_cfg(gated_cfg: &GatedCfg, cfg_span: Span, sess: &ParseSess, features: &Features) {
482 let (cfg, feature, has_feature) = gated_cfg;
483 if !has_feature(features) && !cfg_span.allows_unstable(*feature) {
484 let explain = format!("`cfg({})` is experimental and subject to change", cfg);
485 feature_err(sess, *feature, cfg_span, &explain).emit();
489 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
496 fn parse_version(s: &str, allow_appendix: bool) -> Option<Version> {
497 let mut components = s.split('-');
498 let d = components.next()?;
499 if !allow_appendix && components.next().is_some() {
502 let mut digits = d.splitn(3, '.');
503 let major = digits.next()?.parse().ok()?;
504 let minor = digits.next()?.parse().ok()?;
505 let patch = digits.next().unwrap_or("0").parse().ok()?;
506 Some(Version { major, minor, patch })
509 /// Evaluate a cfg-like condition (with `any` and `all`), using `eval` to
510 /// evaluate individual items.
511 pub fn eval_condition(
514 features: Option<&Features>,
515 eval: &mut impl FnMut(&ast::MetaItem) -> bool,
518 ast::MetaItemKind::List(ref mis) if cfg.name_or_empty() == sym::version => {
519 try_gate_cfg(cfg, sess, features);
520 let (min_version, span) = match &mis[..] {
521 [NestedMetaItem::Literal(Lit { kind: LitKind::Str(sym, ..), span, .. })] => {
524 [NestedMetaItem::Literal(Lit { span, .. })
525 | 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 !(sess.check_name(attr, sym::deprecated) || sess.check_name(attr, sym::rustc_deprecated))
644 if let Some((_, span)) = &depr {
645 struct_span_err!(diagnostic, attr.span, E0550, "multiple deprecated attributes")
646 .span_label(attr.span, "repeated deprecation attribute")
647 .span_label(*span, "first deprecation attribute")
652 let meta = match attr.meta() {
656 let mut since = None;
658 let mut suggestion = None;
660 MetaItemKind::Word => {}
661 MetaItemKind::NameValue(..) => note = meta.value_str(),
662 MetaItemKind::List(list) => {
663 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
668 AttrError::MultipleItem(pprust::path_to_string(&meta.path)),
672 if let Some(v) = meta.value_str() {
676 if let Some(lit) = meta.name_value_literal() {
680 AttrError::UnsupportedLiteral(
681 "literal in `deprecated` \
682 value must be a string",
683 lit.kind.is_bytestr(),
687 struct_span_err!(diagnostic, meta.span, E0551, "incorrect meta item")
697 NestedMetaItem::MetaItem(mi) => match mi.name_or_empty() {
699 if !get(mi, &mut since) {
703 sym::note if sess.check_name(attr, sym::deprecated) => {
704 if !get(mi, &mut note) {
708 sym::reason if sess.check_name(attr, sym::rustc_deprecated) => {
709 if !get(mi, &mut note) {
713 sym::suggestion if sess.check_name(attr, sym::rustc_deprecated) => {
714 if !get(mi, &mut suggestion) {
722 AttrError::UnknownMetaItem(
723 pprust::path_to_string(&mi.path),
724 if sess.check_name(attr, sym::deprecated) {
727 &["since", "reason", "suggestion"]
734 NestedMetaItem::Literal(lit) => {
738 AttrError::UnsupportedLiteral(
739 "item in `deprecated` must be a key/value pair",
750 if suggestion.is_some() && sess.check_name(attr, sym::deprecated) {
751 unreachable!("only allowed on rustc_deprecated")
754 if sess.check_name(attr, sym::rustc_deprecated) {
756 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingSince);
761 struct_span_err!(diagnostic, attr.span, E0543, "missing 'reason'").emit();
766 sess.mark_attr_used(&attr);
768 let is_since_rustc_version = sess.check_name(attr, sym::rustc_deprecated);
769 depr = Some((Deprecation { since, note, suggestion, is_since_rustc_version }, attr.span));
775 #[derive(PartialEq, Debug, Encodable, Decodable, Copy, Clone)]
786 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
787 #[derive(Encodable, Decodable, HashStable_Generic)]
789 SignedInt(ast::IntTy),
790 UnsignedInt(ast::UintTy),
795 pub fn is_signed(self) -> bool {
799 SignedInt(..) => true,
800 UnsignedInt(..) => false,
805 /// Parse #[repr(...)] forms.
807 /// Valid repr contents: any of the primitive integral type names (see
808 /// `int_type_of_word`, below) to specify enum discriminant type; `C`, to use
809 /// the same discriminant size that the corresponding C enum would or C
810 /// structure layout, `packed` to remove padding, and `transparent` to elegate representation
811 /// concerns to the only non-ZST field.
812 pub fn find_repr_attrs(sess: &Session, attr: &Attribute) -> Vec<ReprAttr> {
815 let mut acc = Vec::new();
816 let diagnostic = &sess.parse_sess.span_diagnostic;
817 if attr.has_name(sym::repr) {
818 if let Some(items) = attr.meta_item_list() {
819 sess.mark_attr_used(attr);
821 let mut recognised = false;
823 let hint = match item.name_or_empty() {
824 sym::C => Some(ReprC),
825 sym::packed => Some(ReprPacked(1)),
826 sym::simd => Some(ReprSimd),
827 sym::transparent => Some(ReprTransparent),
828 sym::no_niche => Some(ReprNoNiche),
830 let mut err = struct_span_err!(
834 "invalid `repr(align)` attribute: `align` needs an argument"
838 "supply an argument here",
839 "align(...)".to_string(),
840 Applicability::HasPlaceholders,
846 name => int_type_of_word(name).map(ReprInt),
849 if let Some(h) = hint {
853 } else if let Some((name, value)) = item.name_value_literal() {
854 let mut literal_error = None;
855 if name == sym::align {
857 match parse_alignment(&value.kind) {
858 Ok(literal) => acc.push(ReprAlign(literal)),
859 Err(message) => literal_error = Some(message),
861 } else if name == sym::packed {
863 match parse_alignment(&value.kind) {
864 Ok(literal) => acc.push(ReprPacked(literal)),
865 Err(message) => literal_error = Some(message),
867 } else if matches!(name, sym::C | sym::simd | sym::transparent | sym::no_niche)
868 || int_type_of_word(name).is_some()
875 "invalid representation hint: `{}` does not take a parenthesized argument list",
876 name.to_ident_string(),
879 if let Some(literal_error) = literal_error {
884 "invalid `repr({})` attribute: {}",
885 name.to_ident_string(),
890 } else if let Some(meta_item) = item.meta_item() {
891 if let MetaItemKind::NameValue(ref value) = meta_item.kind {
892 if meta_item.has_name(sym::align) || meta_item.has_name(sym::packed) {
893 let name = meta_item.name_or_empty().to_ident_string();
895 let mut err = struct_span_err!(
899 "incorrect `repr({})` attribute format",
903 ast::LitKind::Int(int, ast::LitIntType::Unsuffixed) => {
906 "use parentheses instead",
907 format!("{}({})", name, int),
908 Applicability::MachineApplicable,
911 ast::LitKind::Str(s, _) => {
914 "use parentheses instead",
915 format!("{}({})", name, s),
916 Applicability::MachineApplicable,
924 meta_item.name_or_empty(),
925 sym::C | sym::simd | sym::transparent | sym::no_niche
926 ) || int_type_of_word(meta_item.name_or_empty()).is_some()
933 "invalid representation hint: `{}` does not take a value",
934 meta_item.name_or_empty().to_ident_string(),
939 } else if let MetaItemKind::List(_) = meta_item.kind {
940 if meta_item.has_name(sym::align) {
946 "incorrect `repr(align)` attribute format: \
947 `align` takes exactly one argument in parentheses"
950 } else if meta_item.has_name(sym::packed) {
956 "incorrect `repr(packed)` attribute format: \
957 `packed` takes exactly one parenthesized argument, \
958 or no parentheses at all"
962 meta_item.name_or_empty(),
963 sym::C | sym::simd | sym::transparent | sym::no_niche
964 ) || int_type_of_word(meta_item.name_or_empty()).is_some()
971 "invalid representation hint: `{}` does not take a parenthesized argument list",
972 meta_item.name_or_empty().to_ident_string(),
978 // Not a word we recognize. This will be caught and reported by
979 // the `check_mod_attrs` pass, but this pass doesn't always run
980 // (e.g. if we only pretty-print the source), so we have to gate
981 // the `delay_span_bug` call as follows:
982 if sess.opts.pretty.map_or(true, |pp| pp.needs_analysis()) {
983 diagnostic.delay_span_bug(item.span(), "unrecognized representation hint");
992 fn int_type_of_word(s: Symbol) -> Option<IntType> {
996 sym::i8 => Some(SignedInt(ast::IntTy::I8)),
997 sym::u8 => Some(UnsignedInt(ast::UintTy::U8)),
998 sym::i16 => Some(SignedInt(ast::IntTy::I16)),
999 sym::u16 => Some(UnsignedInt(ast::UintTy::U16)),
1000 sym::i32 => Some(SignedInt(ast::IntTy::I32)),
1001 sym::u32 => Some(UnsignedInt(ast::UintTy::U32)),
1002 sym::i64 => Some(SignedInt(ast::IntTy::I64)),
1003 sym::u64 => Some(UnsignedInt(ast::UintTy::U64)),
1004 sym::i128 => Some(SignedInt(ast::IntTy::I128)),
1005 sym::u128 => Some(UnsignedInt(ast::UintTy::U128)),
1006 sym::isize => Some(SignedInt(ast::IntTy::Isize)),
1007 sym::usize => Some(UnsignedInt(ast::UintTy::Usize)),
1012 pub enum TransparencyError {
1013 UnknownTransparency(Symbol, Span),
1014 MultipleTransparencyAttrs(Span, Span),
1017 pub fn find_transparency(
1019 attrs: &[Attribute],
1021 ) -> (Transparency, Option<TransparencyError>) {
1022 let mut transparency = None;
1023 let mut error = None;
1025 if sess.check_name(attr, sym::rustc_macro_transparency) {
1026 if let Some((_, old_span)) = transparency {
1027 error = Some(TransparencyError::MultipleTransparencyAttrs(old_span, attr.span));
1029 } else if let Some(value) = attr.value_str() {
1030 transparency = Some((
1032 sym::transparent => Transparency::Transparent,
1033 sym::semitransparent => Transparency::SemiTransparent,
1034 sym::opaque => Transparency::Opaque,
1036 error = Some(TransparencyError::UnknownTransparency(value, attr.span));
1045 let fallback = if macro_rules { Transparency::SemiTransparent } else { Transparency::Opaque };
1046 (transparency.map_or(fallback, |t| t.0), error)
1049 pub fn allow_internal_unstable<'a>(
1051 attrs: &'a [Attribute],
1052 ) -> impl Iterator<Item = Symbol> + 'a {
1053 allow_unstable(sess, attrs, sym::allow_internal_unstable)
1056 pub fn rustc_allow_const_fn_unstable<'a>(
1058 attrs: &'a [Attribute],
1059 ) -> impl Iterator<Item = Symbol> + 'a {
1060 allow_unstable(sess, attrs, sym::rustc_allow_const_fn_unstable)
1063 fn allow_unstable<'a>(
1065 attrs: &'a [Attribute],
1067 ) -> impl Iterator<Item = Symbol> + 'a {
1068 let attrs = sess.filter_by_name(attrs, symbol);
1070 .filter_map(move |attr| {
1071 attr.meta_item_list().or_else(|| {
1072 sess.diagnostic().span_err(
1074 &format!("`{}` expects a list of feature names", symbol.to_ident_string()),
1081 list.into_iter().filter_map(move |it| {
1082 let name = it.ident().map(|ident| ident.name);
1084 sess.diagnostic().span_err(
1086 &format!("`{}` expects feature names", symbol.to_ident_string()),
1093 pub fn parse_alignment(node: &ast::LitKind) -> Result<u32, &'static str> {
1094 if let ast::LitKind::Int(literal, ast::LitIntType::Unsuffixed) = node {
1095 if literal.is_power_of_two() {
1096 // rustc_middle::ty::layout::Align restricts align to <= 2^29
1097 if *literal <= 1 << 29 { Ok(*literal as u32) } else { Err("larger than 2^29") }
1099 Err("not a power of two")
1102 Err("not an unsuffixed integer")