1 //! Parsing and validation of builtin attributes
3 use super::{mark_used, MetaItemKind};
4 use crate::ast::{self, Attribute, MetaItem, NestedMetaItem};
5 use crate::print::pprust;
6 use crate::sess::{feature_err, ParseSess};
8 use rustc_errors::{struct_span_err, Applicability, Handler};
9 use rustc_feature::{find_gated_cfg, is_builtin_attr_name, Features, GatedCfg};
10 use rustc_macros::HashStable_Generic;
11 use rustc_span::hygiene::Transparency;
12 use rustc_span::{symbol::sym, symbol::Symbol, Span};
13 use std::num::NonZeroU32;
15 pub fn is_builtin_attr(attr: &Attribute) -> bool {
16 attr.is_doc_comment() || attr.ident().filter(|ident| is_builtin_attr_name(ident.name)).is_some()
21 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 => struct_span_err!(diag, span, E0542, "missing 'since'").emit(),
41 AttrError::MissingFeature => {
42 struct_span_err!(diag, span, E0546, "missing 'feature'").emit();
44 AttrError::MultipleStabilityLevels => {
45 struct_span_err!(diag, span, E0544, "multiple stability levels").emit();
47 AttrError::UnsupportedLiteral(msg, is_bytestr) => {
48 let mut err = struct_span_err!(diag, span, E0565, "{}", msg);
50 if let Ok(lint_str) = sess.source_map().span_to_snippet(span) {
53 "consider removing the prefix",
54 format!("{}", &lint_str[1..]),
55 Applicability::MaybeIncorrect,
64 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
72 #[derive(Clone, RustcEncodable, RustcDecodable)]
73 pub enum OptimizeAttr {
79 #[derive(Copy, Clone, PartialEq)]
85 /// Determine what `#[unwind]` attribute is present in `attrs`, if any.
86 pub fn find_unwind_attr(diagnostic: Option<&Handler>, attrs: &[Attribute]) -> Option<UnwindAttr> {
87 attrs.iter().fold(None, |ia, attr| {
88 if attr.check_name(sym::unwind) {
89 if let Some(meta) = attr.meta() {
90 if let MetaItemKind::List(items) = meta.kind {
92 if items[0].check_name(sym::allowed) {
93 return Some(UnwindAttr::Allowed);
94 } else if items[0].check_name(sym::aborts) {
95 return Some(UnwindAttr::Aborts);
100 struct_span_err!(d, attr.span, E0633, "malformed `unwind` attribute input")
101 .span_label(attr.span, "invalid argument")
104 "the allowed arguments are `allowed` and `aborts`",
105 (vec!["allowed", "aborts"])
107 .map(|s| format!("#[unwind({})]", s)),
108 Applicability::MachineApplicable,
120 /// Represents the #[stable], #[unstable], #[rustc_deprecated] attributes.
132 pub struct Stability {
133 pub level: StabilityLevel,
135 pub rustc_depr: Option<RustcDeprecation>,
138 /// Represents the #[rustc_const_unstable] and #[rustc_const_stable] attributes.
150 pub struct ConstStability {
151 pub level: StabilityLevel,
153 /// whether the function has a `#[rustc_promotable]` attribute
154 pub promotable: bool,
155 /// whether the function has a `#[rustc_allow_const_fn_ptr]` attribute
156 pub allow_const_fn_ptr: bool,
159 /// The available stability levels.
172 pub enum StabilityLevel {
173 // Reason for the current stability level and the relevant rust-lang issue
174 Unstable { reason: Option<Symbol>, issue: Option<NonZeroU32>, is_soft: bool },
175 Stable { since: Symbol },
178 impl StabilityLevel {
179 pub fn is_unstable(&self) -> bool {
180 if let StabilityLevel::Unstable { .. } = *self { true } else { false }
182 pub fn is_stable(&self) -> bool {
183 if let StabilityLevel::Stable { .. } = *self { true } else { false }
199 pub struct RustcDeprecation {
202 /// A text snippet used to completely replace any use of the deprecated item in an expression.
203 pub suggestion: Option<Symbol>,
206 /// Checks if `attrs` contains an attribute like `#![feature(feature_name)]`.
207 /// This will not perform any "sanity checks" on the form of the attributes.
208 pub fn contains_feature_attr(attrs: &[Attribute], feature_name: Symbol) -> bool {
209 attrs.iter().any(|item| {
210 item.check_name(sym::feature)
213 .map(|list| list.iter().any(|mi| mi.is_word() && mi.check_name(feature_name)))
218 /// Collects stability info from all stability attributes in `attrs`.
219 /// Returns `None` if no stability attributes are found.
220 pub fn find_stability(
224 ) -> (Option<Stability>, Option<ConstStability>) {
225 find_stability_generic(sess, attrs.iter(), item_sp)
228 fn find_stability_generic<'a, I>(
232 ) -> (Option<Stability>, Option<ConstStability>)
234 I: Iterator<Item = &'a Attribute>,
236 use StabilityLevel::*;
238 let mut stab: Option<Stability> = None;
239 let mut rustc_depr: Option<RustcDeprecation> = None;
240 let mut const_stab: Option<ConstStability> = None;
241 let mut promotable = false;
242 let mut allow_const_fn_ptr = false;
243 let diagnostic = &sess.span_diagnostic;
245 'outer: for attr in attrs_iter {
247 sym::rustc_deprecated,
248 sym::rustc_const_unstable,
249 sym::rustc_const_stable,
252 sym::rustc_promotable,
253 sym::rustc_allow_const_fn_ptr,
256 .any(|&s| attr.has_name(s))
258 continue; // not a stability level
263 let meta = attr.meta();
265 if attr.has_name(sym::rustc_promotable) {
268 if attr.has_name(sym::rustc_allow_const_fn_ptr) {
269 allow_const_fn_ptr = true;
271 // attributes with data
272 else if let Some(MetaItem { kind: MetaItemKind::List(ref metas), .. }) = meta {
273 let meta = meta.as_ref().unwrap();
274 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
279 AttrError::MultipleItem(pprust::path_to_string(&meta.path)),
283 if let Some(v) = meta.value_str() {
287 struct_span_err!(diagnostic, meta.span, E0539, "incorrect meta item").emit();
292 macro_rules! get_meta {
293 ($($name:ident),+) => {
295 let mut $name = None;
298 if let Some(mi) = meta.meta_item() {
299 match mi.name_or_empty() {
301 sym::$name => if !get(mi, &mut $name) { continue 'outer },
304 let expected = &[ $( stringify!($name) ),+ ];
308 AttrError::UnknownMetaItem(
309 pprust::path_to_string(&mi.path),
320 AttrError::UnsupportedLiteral(
321 "unsupported literal",
331 let meta_name = meta.name_or_empty();
333 sym::rustc_deprecated => {
334 if rustc_depr.is_some() {
339 "multiple rustc_deprecated attributes"
345 get_meta!(since, reason, suggestion);
347 match (since, reason) {
348 (Some(since), Some(reason)) => {
349 rustc_depr = Some(RustcDeprecation { since, reason, suggestion })
352 handle_errors(sess, attr.span, AttrError::MissingSince);
356 struct_span_err!(diagnostic, attr.span, E0543, "missing 'reason'")
362 sym::rustc_const_unstable | sym::unstable => {
363 if meta_name == sym::unstable && stab.is_some() {
364 handle_errors(sess, attr.span, AttrError::MultipleStabilityLevels);
366 } else if meta_name == sym::rustc_const_unstable && const_stab.is_some() {
367 handle_errors(sess, attr.span, AttrError::MultipleStabilityLevels);
371 let mut feature = None;
372 let mut reason = None;
373 let mut issue = None;
374 let mut is_soft = false;
376 if let Some(mi) = meta.meta_item() {
377 match mi.name_or_empty() {
379 if !get(mi, &mut feature) {
384 if !get(mi, &mut reason) {
389 if !get(mi, &mut issue) {
395 let msg = "`soft` should not have any arguments";
396 sess.span_diagnostic.span_err(mi.span, msg);
404 AttrError::UnknownMetaItem(
405 pprust::path_to_string(&mi.path),
406 &["feature", "reason", "issue", "soft"],
416 AttrError::UnsupportedLiteral("unsupported literal", false),
422 match (feature, reason, issue) {
423 (Some(feature), reason, Some(issue)) => {
424 let issue = match &*issue.as_str() {
427 if let Ok(num) = issue.parse() {
428 // FIXME(rossmacarthur): disallow 0
429 // Disallowing this requires updates to some submodules
443 let level = Unstable { reason, issue, is_soft };
444 if sym::unstable == meta_name {
445 stab = Some(Stability { level, feature, rustc_depr: None });
447 const_stab = Some(ConstStability {
451 allow_const_fn_ptr: false,
456 handle_errors(sess, attr.span, AttrError::MissingFeature);
460 struct_span_err!(diagnostic, attr.span, E0547, "missing 'issue'")
466 sym::rustc_const_stable | sym::stable => {
467 if meta_name == sym::stable && stab.is_some() {
468 handle_errors(sess, attr.span, AttrError::MultipleStabilityLevels);
470 } else if meta_name == sym::rustc_const_stable && const_stab.is_some() {
471 handle_errors(sess, attr.span, AttrError::MultipleStabilityLevels);
475 let mut feature = None;
476 let mut since = None;
479 NestedMetaItem::MetaItem(mi) => match mi.name_or_empty() {
481 if !get(mi, &mut feature) {
486 if !get(mi, &mut since) {
494 AttrError::UnknownMetaItem(
495 pprust::path_to_string(&mi.path),
502 NestedMetaItem::Literal(lit) => {
506 AttrError::UnsupportedLiteral("unsupported literal", false),
513 match (feature, since) {
514 (Some(feature), Some(since)) => {
515 let level = Stable { since };
516 if sym::stable == meta_name {
517 stab = Some(Stability { level, feature, rustc_depr: None });
519 const_stab = Some(ConstStability {
523 allow_const_fn_ptr: false,
528 handle_errors(sess, attr.span, AttrError::MissingFeature);
532 handle_errors(sess, attr.span, AttrError::MissingSince);
542 // Merge the deprecation info into the stability info
543 if let Some(rustc_depr) = rustc_depr {
544 if let Some(ref mut stab) = stab {
545 stab.rustc_depr = Some(rustc_depr);
551 "rustc_deprecated attribute must be paired with \
552 either stable or unstable attribute"
558 // Merge the const-unstable info into the stability info
559 if promotable || allow_const_fn_ptr {
560 if let Some(ref mut stab) = const_stab {
561 stab.promotable = promotable;
562 stab.allow_const_fn_ptr = allow_const_fn_ptr;
568 "rustc_promotable and rustc_allow_const_fn_ptr attributes \
569 must be paired with either a rustc_const_unstable or a rustc_const_stable \
579 pub fn find_crate_name(attrs: &[Attribute]) -> Option<Symbol> {
580 super::first_attr_value_str_by_name(attrs, sym::crate_name)
583 /// Tests if a cfg-pattern matches the cfg set
584 pub fn cfg_matches(cfg: &ast::MetaItem, sess: &ParseSess, features: Option<&Features>) -> bool {
585 eval_condition(cfg, sess, &mut |cfg| {
586 let gate = find_gated_cfg(|sym| cfg.check_name(sym));
587 if let (Some(feats), Some(gated_cfg)) = (features, gate) {
588 gate_cfg(&gated_cfg, cfg.span, sess, feats);
590 let error = |span, msg| {
591 sess.span_diagnostic.span_err(span, msg);
594 if cfg.path.segments.len() != 1 {
595 return error(cfg.path.span, "`cfg` predicate key must be an identifier");
598 MetaItemKind::List(..) => {
599 error(cfg.span, "unexpected parentheses after `cfg` predicate key")
601 MetaItemKind::NameValue(lit) if !lit.kind.is_str() => {
605 AttrError::UnsupportedLiteral(
606 "literal in `cfg` predicate value must be a string",
607 lit.kind.is_bytestr(),
612 MetaItemKind::NameValue(..) | MetaItemKind::Word => {
613 let ident = cfg.ident().expect("multi-segment cfg predicate");
614 sess.config.contains(&(ident.name, cfg.value_str()))
620 fn gate_cfg(gated_cfg: &GatedCfg, cfg_span: Span, sess: &ParseSess, features: &Features) {
621 let (cfg, feature, has_feature) = gated_cfg;
622 if !has_feature(features) && !cfg_span.allows_unstable(*feature) {
623 let explain = format!("`cfg({})` is experimental and subject to change", cfg);
624 feature_err(sess, *feature, cfg_span, &explain).emit()
628 /// Evaluate a cfg-like condition (with `any` and `all`), using `eval` to
629 /// evaluate individual items.
630 pub fn eval_condition(
633 eval: &mut impl FnMut(&ast::MetaItem) -> bool,
636 ast::MetaItemKind::List(ref mis) => {
637 for mi in mis.iter() {
638 if !mi.is_meta_item() {
642 AttrError::UnsupportedLiteral("unsupported literal", false),
648 // The unwraps below may look dangerous, but we've already asserted
649 // that they won't fail with the loop above.
650 match cfg.name_or_empty() {
652 mis.iter().any(|mi| eval_condition(mi.meta_item().unwrap(), sess, eval))
655 mis.iter().all(|mi| eval_condition(mi.meta_item().unwrap(), sess, eval))
660 sess.span_diagnostic,
663 "expected 1 cfg-pattern"
669 !eval_condition(mis[0].meta_item().unwrap(), sess, eval)
673 sess.span_diagnostic,
676 "invalid predicate `{}`",
677 pprust::path_to_string(&cfg.path)
684 ast::MetaItemKind::Word | ast::MetaItemKind::NameValue(..) => eval(cfg),
688 #[derive(RustcEncodable, RustcDecodable, Clone, HashStable_Generic)]
689 pub struct Deprecation {
690 pub since: Option<Symbol>,
691 pub note: Option<Symbol>,
694 /// Finds the deprecation attribute. `None` if none exists.
695 pub fn find_deprecation(
699 ) -> Option<Deprecation> {
700 find_deprecation_generic(sess, attrs.iter(), item_sp)
703 fn find_deprecation_generic<'a, I>(
707 ) -> Option<Deprecation>
709 I: Iterator<Item = &'a Attribute>,
711 let mut depr: Option<Deprecation> = None;
712 let diagnostic = &sess.span_diagnostic;
714 'outer: for attr in attrs_iter {
715 if !attr.check_name(sym::deprecated) {
720 struct_span_err!(diagnostic, item_sp, E0550, "multiple deprecated attributes").emit();
724 let meta = match attr.meta() {
728 depr = match &meta.kind {
729 MetaItemKind::Word => Some(Deprecation { since: None, note: None }),
730 MetaItemKind::NameValue(..) => {
731 meta.value_str().map(|note| Deprecation { since: None, note: Some(note) })
733 MetaItemKind::List(list) => {
734 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
739 AttrError::MultipleItem(pprust::path_to_string(&meta.path)),
743 if let Some(v) = meta.value_str() {
747 if let Some(lit) = meta.name_value_literal() {
751 AttrError::UnsupportedLiteral(
752 "literal in `deprecated` \
753 value must be a string",
754 lit.kind.is_bytestr(),
758 struct_span_err!(diagnostic, meta.span, E0551, "incorrect meta item")
766 let mut since = None;
770 NestedMetaItem::MetaItem(mi) => match mi.name_or_empty() {
772 if !get(mi, &mut since) {
777 if !get(mi, &mut note) {
785 AttrError::UnknownMetaItem(
786 pprust::path_to_string(&mi.path),
793 NestedMetaItem::Literal(lit) => {
797 AttrError::UnsupportedLiteral(
798 "item in `deprecated` must be a key/value pair",
807 Some(Deprecation { since, note })
815 #[derive(PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
825 #[derive(Eq, PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone, HashStable_Generic)]
827 SignedInt(ast::IntTy),
828 UnsignedInt(ast::UintTy),
833 pub fn is_signed(self) -> bool {
837 SignedInt(..) => true,
838 UnsignedInt(..) => false,
843 /// Parse #[repr(...)] forms.
845 /// Valid repr contents: any of the primitive integral type names (see
846 /// `int_type_of_word`, below) to specify enum discriminant type; `C`, to use
847 /// the same discriminant size that the corresponding C enum would or C
848 /// structure layout, `packed` to remove padding, and `transparent` to elegate representation
849 /// concerns to the only non-ZST field.
850 pub fn find_repr_attrs(sess: &ParseSess, attr: &Attribute) -> Vec<ReprAttr> {
853 let mut acc = Vec::new();
854 let diagnostic = &sess.span_diagnostic;
855 if attr.has_name(sym::repr) {
856 if let Some(items) = attr.meta_item_list() {
859 if !item.is_meta_item() {
863 AttrError::UnsupportedLiteral(
864 "meta item in `repr` must be an identifier",
871 let mut recognised = false;
873 let hint = match item.name_or_empty() {
874 sym::C => Some(ReprC),
875 sym::packed => Some(ReprPacked(1)),
876 sym::simd => Some(ReprSimd),
877 sym::transparent => Some(ReprTransparent),
878 name => int_type_of_word(name).map(ReprInt),
881 if let Some(h) = hint {
885 } else if let Some((name, value)) = item.name_value_literal() {
886 let parse_alignment = |node: &ast::LitKind| -> Result<u32, &'static str> {
887 if let ast::LitKind::Int(literal, ast::LitIntType::Unsuffixed) = node {
888 if literal.is_power_of_two() {
889 // rustc::ty::layout::Align restricts align to <= 2^29
890 if *literal <= 1 << 29 {
893 Err("larger than 2^29")
896 Err("not a power of two")
899 Err("not an unsuffixed integer")
903 let mut literal_error = None;
904 if name == sym::align {
906 match parse_alignment(&value.kind) {
907 Ok(literal) => acc.push(ReprAlign(literal)),
908 Err(message) => literal_error = Some(message),
910 } else if name == sym::packed {
912 match parse_alignment(&value.kind) {
913 Ok(literal) => acc.push(ReprPacked(literal)),
914 Err(message) => literal_error = Some(message),
917 if let Some(literal_error) = literal_error {
922 "invalid `repr(align)` attribute: {}",
928 if let Some(meta_item) = item.meta_item() {
929 if meta_item.check_name(sym::align) {
930 if let MetaItemKind::NameValue(ref value) = meta_item.kind {
932 let mut err = struct_span_err!(
936 "incorrect `repr(align)` attribute format"
939 ast::LitKind::Int(int, ast::LitIntType::Unsuffixed) => {
942 "use parentheses instead",
943 format!("align({})", int),
944 Applicability::MachineApplicable,
947 ast::LitKind::Str(s, _) => {
950 "use parentheses instead",
951 format!("align({})", s),
952 Applicability::MachineApplicable,
963 // Not a word we recognize
968 "unrecognized representation hint"
978 fn int_type_of_word(s: Symbol) -> Option<IntType> {
982 sym::i8 => Some(SignedInt(ast::IntTy::I8)),
983 sym::u8 => Some(UnsignedInt(ast::UintTy::U8)),
984 sym::i16 => Some(SignedInt(ast::IntTy::I16)),
985 sym::u16 => Some(UnsignedInt(ast::UintTy::U16)),
986 sym::i32 => Some(SignedInt(ast::IntTy::I32)),
987 sym::u32 => Some(UnsignedInt(ast::UintTy::U32)),
988 sym::i64 => Some(SignedInt(ast::IntTy::I64)),
989 sym::u64 => Some(UnsignedInt(ast::UintTy::U64)),
990 sym::i128 => Some(SignedInt(ast::IntTy::I128)),
991 sym::u128 => Some(UnsignedInt(ast::UintTy::U128)),
992 sym::isize => Some(SignedInt(ast::IntTy::Isize)),
993 sym::usize => Some(UnsignedInt(ast::UintTy::Usize)),
998 pub enum TransparencyError {
999 UnknownTransparency(Symbol, Span),
1000 MultipleTransparencyAttrs(Span, Span),
1003 pub fn find_transparency(
1004 attrs: &[Attribute],
1006 ) -> (Transparency, Option<TransparencyError>) {
1007 let mut transparency = None;
1008 let mut error = None;
1010 if attr.check_name(sym::rustc_macro_transparency) {
1011 if let Some((_, old_span)) = transparency {
1012 error = Some(TransparencyError::MultipleTransparencyAttrs(old_span, attr.span));
1014 } else if let Some(value) = attr.value_str() {
1015 transparency = Some((
1016 match &*value.as_str() {
1017 "transparent" => Transparency::Transparent,
1018 "semitransparent" => Transparency::SemiTransparent,
1019 "opaque" => Transparency::Opaque,
1021 error = Some(TransparencyError::UnknownTransparency(value, attr.span));
1030 let fallback = if is_legacy { Transparency::SemiTransparent } else { Transparency::Opaque };
1031 (transparency.map_or(fallback, |t| t.0), error)