1 //! Parsing and validation of builtin attributes
3 use super::{find_by_name, mark_used};
5 use rustc_ast_pretty::pprust;
6 use rustc_errors::{struct_span_err, Applicability, Handler};
7 use rustc_feature::{find_gated_cfg, is_builtin_attr_name, Features, GatedCfg};
8 use rustc_macros::HashStable_Generic;
9 use rustc_session::parse::{feature_err, ParseSess};
10 use rustc_span::hygiene::Transparency;
11 use rustc_span::{symbol::sym, symbol::Symbol, Span};
12 use std::num::NonZeroU32;
13 use syntax::ast::{self, Attribute, MetaItem, MetaItemKind, NestedMetaItem};
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 => {
41 struct_span_err!(diag, span, E0542, "missing 'since'").emit();
43 AttrError::MissingFeature => {
44 struct_span_err!(diag, span, E0546, "missing 'feature'").emit();
46 AttrError::MultipleStabilityLevels => {
47 struct_span_err!(diag, span, E0544, "multiple stability levels").emit();
49 AttrError::UnsupportedLiteral(msg, is_bytestr) => {
50 let mut err = struct_span_err!(diag, span, E0565, "{}", msg);
52 if let Ok(lint_str) = sess.source_map().span_to_snippet(span) {
55 "consider removing the prefix",
56 format!("{}", &lint_str[1..]),
57 Applicability::MaybeIncorrect,
66 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
74 #[derive(Clone, RustcEncodable, RustcDecodable)]
75 pub enum OptimizeAttr {
81 #[derive(Copy, Clone, PartialEq)]
87 /// Determine what `#[unwind]` attribute is present in `attrs`, if any.
88 pub fn find_unwind_attr(diagnostic: Option<&Handler>, attrs: &[Attribute]) -> Option<UnwindAttr> {
89 attrs.iter().fold(None, |ia, attr| {
90 if attr.check_name(sym::unwind) {
91 if let Some(meta) = attr.meta() {
92 if let MetaItemKind::List(items) = meta.kind {
94 if items[0].check_name(sym::allowed) {
95 return Some(UnwindAttr::Allowed);
96 } else if items[0].check_name(sym::aborts) {
97 return Some(UnwindAttr::Aborts);
102 struct_span_err!(d, attr.span, E0633, "malformed `unwind` attribute input")
103 .span_label(attr.span, "invalid argument")
106 "the allowed arguments are `allowed` and `aborts`",
107 (vec!["allowed", "aborts"])
109 .map(|s| format!("#[unwind({})]", s)),
110 Applicability::MachineApplicable,
122 /// Represents the #[stable], #[unstable], #[rustc_deprecated] attributes.
134 pub struct Stability {
135 pub level: StabilityLevel,
137 pub rustc_depr: Option<RustcDeprecation>,
140 /// Represents the #[rustc_const_unstable] and #[rustc_const_stable] attributes.
152 pub struct ConstStability {
153 pub level: StabilityLevel,
155 /// whether the function has a `#[rustc_promotable]` attribute
156 pub promotable: bool,
157 /// whether the function has a `#[rustc_allow_const_fn_ptr]` attribute
158 pub allow_const_fn_ptr: bool,
161 /// The available stability levels.
174 pub enum StabilityLevel {
175 // Reason for the current stability level and the relevant rust-lang issue
176 Unstable { reason: Option<Symbol>, issue: Option<NonZeroU32>, is_soft: bool },
177 Stable { since: Symbol },
180 impl StabilityLevel {
181 pub fn is_unstable(&self) -> bool {
182 if let StabilityLevel::Unstable { .. } = *self { true } else { false }
184 pub fn is_stable(&self) -> bool {
185 if let StabilityLevel::Stable { .. } = *self { true } else { false }
201 pub struct RustcDeprecation {
204 /// A text snippet used to completely replace any use of the deprecated item in an expression.
205 pub suggestion: Option<Symbol>,
208 /// Checks if `attrs` contains an attribute like `#![feature(feature_name)]`.
209 /// This will not perform any "sanity checks" on the form of the attributes.
210 pub fn contains_feature_attr(attrs: &[Attribute], feature_name: Symbol) -> bool {
211 attrs.iter().any(|item| {
212 item.check_name(sym::feature)
215 .map(|list| list.iter().any(|mi| mi.is_word() && mi.check_name(feature_name)))
220 /// Collects stability info from all stability attributes in `attrs`.
221 /// Returns `None` if no stability attributes are found.
222 pub fn find_stability(
226 ) -> (Option<Stability>, Option<ConstStability>) {
227 find_stability_generic(sess, attrs.iter(), item_sp)
230 fn find_stability_generic<'a, I>(
234 ) -> (Option<Stability>, Option<ConstStability>)
236 I: Iterator<Item = &'a Attribute>,
238 use StabilityLevel::*;
240 let mut stab: Option<Stability> = None;
241 let mut rustc_depr: Option<RustcDeprecation> = None;
242 let mut const_stab: Option<ConstStability> = None;
243 let mut promotable = false;
244 let mut allow_const_fn_ptr = false;
245 let diagnostic = &sess.span_diagnostic;
247 'outer: for attr in attrs_iter {
249 sym::rustc_deprecated,
250 sym::rustc_const_unstable,
251 sym::rustc_const_stable,
254 sym::rustc_promotable,
255 sym::rustc_allow_const_fn_ptr,
258 .any(|&s| attr.has_name(s))
260 continue; // not a stability level
265 let meta = attr.meta();
267 if attr.has_name(sym::rustc_promotable) {
270 if attr.has_name(sym::rustc_allow_const_fn_ptr) {
271 allow_const_fn_ptr = true;
273 // attributes with data
274 else if let Some(MetaItem { kind: MetaItemKind::List(ref metas), .. }) = meta {
275 let meta = meta.as_ref().unwrap();
276 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
281 AttrError::MultipleItem(pprust::path_to_string(&meta.path)),
285 if let Some(v) = meta.value_str() {
289 struct_span_err!(diagnostic, meta.span, E0539, "incorrect meta item").emit();
294 macro_rules! get_meta {
295 ($($name:ident),+) => {
297 let mut $name = None;
300 if let Some(mi) = meta.meta_item() {
301 match mi.name_or_empty() {
303 sym::$name => if !get(mi, &mut $name) { continue 'outer },
306 let expected = &[ $( stringify!($name) ),+ ];
310 AttrError::UnknownMetaItem(
311 pprust::path_to_string(&mi.path),
322 AttrError::UnsupportedLiteral(
323 "unsupported literal",
333 let meta_name = meta.name_or_empty();
335 sym::rustc_deprecated => {
336 if rustc_depr.is_some() {
341 "multiple rustc_deprecated attributes"
347 get_meta!(since, reason, suggestion);
349 match (since, reason) {
350 (Some(since), Some(reason)) => {
351 rustc_depr = Some(RustcDeprecation { since, reason, suggestion })
354 handle_errors(sess, attr.span, AttrError::MissingSince);
358 struct_span_err!(diagnostic, attr.span, E0543, "missing 'reason'")
364 sym::rustc_const_unstable | sym::unstable => {
365 if meta_name == sym::unstable && stab.is_some() {
366 handle_errors(sess, attr.span, AttrError::MultipleStabilityLevels);
368 } else if meta_name == sym::rustc_const_unstable && const_stab.is_some() {
369 handle_errors(sess, attr.span, AttrError::MultipleStabilityLevels);
373 let mut feature = None;
374 let mut reason = None;
375 let mut issue = None;
376 let mut issue_num = None;
377 let mut is_soft = false;
379 if let Some(mi) = meta.meta_item() {
380 match mi.name_or_empty() {
382 if !get(mi, &mut feature) {
387 if !get(mi, &mut reason) {
392 if !get(mi, &mut issue) {
396 // These unwraps are safe because `get` ensures the meta item
397 // is a name/value pair string literal.
398 issue_num = match &*issue.unwrap().as_str() {
401 let emit_diag = |msg: &str| {
406 "`issue` must be a non-zero numeric string \
410 mi.name_value_literal().unwrap().span,
415 match issue.parse() {
416 Ok(num) if num == 0 => {
418 "`issue` must not be \"0\", \
419 use \"none\" instead",
423 Ok(num) => NonZeroU32::new(num),
425 emit_diag(&err.to_string());
434 let msg = "`soft` should not have any arguments";
435 sess.span_diagnostic.span_err(mi.span, msg);
443 AttrError::UnknownMetaItem(
444 pprust::path_to_string(&mi.path),
445 &["feature", "reason", "issue", "soft"],
455 AttrError::UnsupportedLiteral("unsupported literal", false),
461 match (feature, reason, issue) {
462 (Some(feature), reason, Some(_)) => {
463 let level = Unstable { reason, issue: issue_num, is_soft };
464 if sym::unstable == meta_name {
465 stab = Some(Stability { level, feature, rustc_depr: None });
467 const_stab = Some(ConstStability {
471 allow_const_fn_ptr: false,
476 handle_errors(sess, attr.span, AttrError::MissingFeature);
480 struct_span_err!(diagnostic, attr.span, E0547, "missing 'issue'")
486 sym::rustc_const_stable | sym::stable => {
487 if meta_name == sym::stable && stab.is_some() {
488 handle_errors(sess, attr.span, AttrError::MultipleStabilityLevels);
490 } else if meta_name == sym::rustc_const_stable && const_stab.is_some() {
491 handle_errors(sess, attr.span, AttrError::MultipleStabilityLevels);
495 let mut feature = None;
496 let mut since = None;
499 NestedMetaItem::MetaItem(mi) => match mi.name_or_empty() {
501 if !get(mi, &mut feature) {
506 if !get(mi, &mut since) {
514 AttrError::UnknownMetaItem(
515 pprust::path_to_string(&mi.path),
522 NestedMetaItem::Literal(lit) => {
526 AttrError::UnsupportedLiteral("unsupported literal", false),
533 match (feature, since) {
534 (Some(feature), Some(since)) => {
535 let level = Stable { since };
536 if sym::stable == meta_name {
537 stab = Some(Stability { level, feature, rustc_depr: None });
539 const_stab = Some(ConstStability {
543 allow_const_fn_ptr: false,
548 handle_errors(sess, attr.span, AttrError::MissingFeature);
552 handle_errors(sess, attr.span, AttrError::MissingSince);
562 // Merge the deprecation info into the stability info
563 if let Some(rustc_depr) = rustc_depr {
564 if let Some(ref mut stab) = stab {
565 stab.rustc_depr = Some(rustc_depr);
571 "rustc_deprecated attribute must be paired with \
572 either stable or unstable attribute"
578 // Merge the const-unstable info into the stability info
579 if promotable || allow_const_fn_ptr {
580 if let Some(ref mut stab) = const_stab {
581 stab.promotable = promotable;
582 stab.allow_const_fn_ptr = allow_const_fn_ptr;
588 "rustc_promotable and rustc_allow_const_fn_ptr attributes \
589 must be paired with either a rustc_const_unstable or a rustc_const_stable \
599 pub fn find_crate_name(attrs: &[Attribute]) -> Option<Symbol> {
600 super::first_attr_value_str_by_name(attrs, sym::crate_name)
603 /// Tests if a cfg-pattern matches the cfg set
604 pub fn cfg_matches(cfg: &ast::MetaItem, sess: &ParseSess, features: Option<&Features>) -> bool {
605 eval_condition(cfg, sess, &mut |cfg| {
606 let gate = find_gated_cfg(|sym| cfg.check_name(sym));
607 if let (Some(feats), Some(gated_cfg)) = (features, gate) {
608 gate_cfg(&gated_cfg, cfg.span, sess, feats);
610 let error = |span, msg| {
611 sess.span_diagnostic.span_err(span, msg);
614 if cfg.path.segments.len() != 1 {
615 return error(cfg.path.span, "`cfg` predicate key must be an identifier");
618 MetaItemKind::List(..) => {
619 error(cfg.span, "unexpected parentheses after `cfg` predicate key")
621 MetaItemKind::NameValue(lit) if !lit.kind.is_str() => {
625 AttrError::UnsupportedLiteral(
626 "literal in `cfg` predicate value must be a string",
627 lit.kind.is_bytestr(),
632 MetaItemKind::NameValue(..) | MetaItemKind::Word => {
633 let ident = cfg.ident().expect("multi-segment cfg predicate");
634 sess.config.contains(&(ident.name, cfg.value_str()))
640 fn gate_cfg(gated_cfg: &GatedCfg, cfg_span: Span, sess: &ParseSess, features: &Features) {
641 let (cfg, feature, has_feature) = gated_cfg;
642 if !has_feature(features) && !cfg_span.allows_unstable(*feature) {
643 let explain = format!("`cfg({})` is experimental and subject to change", cfg);
644 feature_err(sess, *feature, cfg_span, &explain).emit();
648 /// Evaluate a cfg-like condition (with `any` and `all`), using `eval` to
649 /// evaluate individual items.
650 pub fn eval_condition(
653 eval: &mut impl FnMut(&ast::MetaItem) -> bool,
656 ast::MetaItemKind::List(ref mis) => {
657 for mi in mis.iter() {
658 if !mi.is_meta_item() {
662 AttrError::UnsupportedLiteral("unsupported literal", false),
668 // The unwraps below may look dangerous, but we've already asserted
669 // that they won't fail with the loop above.
670 match cfg.name_or_empty() {
672 mis.iter().any(|mi| eval_condition(mi.meta_item().unwrap(), sess, eval))
675 mis.iter().all(|mi| eval_condition(mi.meta_item().unwrap(), sess, eval))
680 sess.span_diagnostic,
683 "expected 1 cfg-pattern"
689 !eval_condition(mis[0].meta_item().unwrap(), sess, eval)
693 sess.span_diagnostic,
696 "invalid predicate `{}`",
697 pprust::path_to_string(&cfg.path)
704 ast::MetaItemKind::Word | ast::MetaItemKind::NameValue(..) => eval(cfg),
708 #[derive(RustcEncodable, RustcDecodable, Clone, HashStable_Generic)]
709 pub struct Deprecation {
710 pub since: Option<Symbol>,
711 pub note: Option<Symbol>,
714 /// Finds the deprecation attribute. `None` if none exists.
715 pub fn find_deprecation(
719 ) -> Option<Deprecation> {
720 find_deprecation_generic(sess, attrs.iter(), item_sp)
723 fn find_deprecation_generic<'a, I>(
727 ) -> Option<Deprecation>
729 I: Iterator<Item = &'a Attribute>,
731 let mut depr: Option<Deprecation> = None;
732 let diagnostic = &sess.span_diagnostic;
734 'outer: for attr in attrs_iter {
735 if !attr.check_name(sym::deprecated) {
740 struct_span_err!(diagnostic, item_sp, E0550, "multiple deprecated attributes").emit();
744 let meta = match attr.meta() {
748 depr = match &meta.kind {
749 MetaItemKind::Word => Some(Deprecation { since: None, note: None }),
750 MetaItemKind::NameValue(..) => {
751 meta.value_str().map(|note| Deprecation { since: None, note: Some(note) })
753 MetaItemKind::List(list) => {
754 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
759 AttrError::MultipleItem(pprust::path_to_string(&meta.path)),
763 if let Some(v) = meta.value_str() {
767 if let Some(lit) = meta.name_value_literal() {
771 AttrError::UnsupportedLiteral(
772 "literal in `deprecated` \
773 value must be a string",
774 lit.kind.is_bytestr(),
778 struct_span_err!(diagnostic, meta.span, E0551, "incorrect meta item")
786 let mut since = None;
790 NestedMetaItem::MetaItem(mi) => match mi.name_or_empty() {
792 if !get(mi, &mut since) {
797 if !get(mi, &mut note) {
805 AttrError::UnknownMetaItem(
806 pprust::path_to_string(&mi.path),
813 NestedMetaItem::Literal(lit) => {
817 AttrError::UnsupportedLiteral(
818 "item in `deprecated` must be a key/value pair",
827 Some(Deprecation { since, note })
835 #[derive(PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
846 #[derive(Eq, PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone, HashStable_Generic)]
848 SignedInt(ast::IntTy),
849 UnsignedInt(ast::UintTy),
854 pub fn is_signed(self) -> bool {
858 SignedInt(..) => true,
859 UnsignedInt(..) => false,
864 /// Parse #[repr(...)] forms.
866 /// Valid repr contents: any of the primitive integral type names (see
867 /// `int_type_of_word`, below) to specify enum discriminant type; `C`, to use
868 /// the same discriminant size that the corresponding C enum would or C
869 /// structure layout, `packed` to remove padding, and `transparent` to elegate representation
870 /// concerns to the only non-ZST field.
871 pub fn find_repr_attrs(sess: &ParseSess, attr: &Attribute) -> Vec<ReprAttr> {
874 let mut acc = Vec::new();
875 let diagnostic = &sess.span_diagnostic;
876 if attr.has_name(sym::repr) {
877 if let Some(items) = attr.meta_item_list() {
880 if !item.is_meta_item() {
884 AttrError::UnsupportedLiteral(
885 "meta item in `repr` must be an identifier",
892 let mut recognised = false;
894 let hint = match item.name_or_empty() {
895 sym::C => Some(ReprC),
896 sym::packed => Some(ReprPacked(1)),
897 sym::simd => Some(ReprSimd),
898 sym::transparent => Some(ReprTransparent),
899 sym::no_niche => Some(ReprNoNiche),
900 name => int_type_of_word(name).map(ReprInt),
903 if let Some(h) = hint {
907 } else if let Some((name, value)) = item.name_value_literal() {
908 let parse_alignment = |node: &ast::LitKind| -> Result<u32, &'static str> {
909 if let ast::LitKind::Int(literal, ast::LitIntType::Unsuffixed) = node {
910 if literal.is_power_of_two() {
911 // rustc::ty::layout::Align restricts align to <= 2^29
912 if *literal <= 1 << 29 {
915 Err("larger than 2^29")
918 Err("not a power of two")
921 Err("not an unsuffixed integer")
925 let mut literal_error = None;
926 if name == sym::align {
928 match parse_alignment(&value.kind) {
929 Ok(literal) => acc.push(ReprAlign(literal)),
930 Err(message) => literal_error = Some(message),
932 } else if name == sym::packed {
934 match parse_alignment(&value.kind) {
935 Ok(literal) => acc.push(ReprPacked(literal)),
936 Err(message) => literal_error = Some(message),
939 if let Some(literal_error) = literal_error {
944 "invalid `repr(align)` attribute: {}",
950 if let Some(meta_item) = item.meta_item() {
951 if meta_item.check_name(sym::align) {
952 if let MetaItemKind::NameValue(ref value) = meta_item.kind {
954 let mut err = struct_span_err!(
958 "incorrect `repr(align)` attribute format"
961 ast::LitKind::Int(int, ast::LitIntType::Unsuffixed) => {
964 "use parentheses instead",
965 format!("align({})", int),
966 Applicability::MachineApplicable,
969 ast::LitKind::Str(s, _) => {
972 "use parentheses instead",
973 format!("align({})", s),
974 Applicability::MachineApplicable,
985 // Not a word we recognize
990 "unrecognized representation hint"
1000 fn int_type_of_word(s: Symbol) -> Option<IntType> {
1004 sym::i8 => Some(SignedInt(ast::IntTy::I8)),
1005 sym::u8 => Some(UnsignedInt(ast::UintTy::U8)),
1006 sym::i16 => Some(SignedInt(ast::IntTy::I16)),
1007 sym::u16 => Some(UnsignedInt(ast::UintTy::U16)),
1008 sym::i32 => Some(SignedInt(ast::IntTy::I32)),
1009 sym::u32 => Some(UnsignedInt(ast::UintTy::U32)),
1010 sym::i64 => Some(SignedInt(ast::IntTy::I64)),
1011 sym::u64 => Some(UnsignedInt(ast::UintTy::U64)),
1012 sym::i128 => Some(SignedInt(ast::IntTy::I128)),
1013 sym::u128 => Some(UnsignedInt(ast::UintTy::U128)),
1014 sym::isize => Some(SignedInt(ast::IntTy::Isize)),
1015 sym::usize => Some(UnsignedInt(ast::UintTy::Usize)),
1020 pub enum TransparencyError {
1021 UnknownTransparency(Symbol, Span),
1022 MultipleTransparencyAttrs(Span, Span),
1025 pub fn find_transparency(
1026 attrs: &[Attribute],
1028 ) -> (Transparency, Option<TransparencyError>) {
1029 let mut transparency = None;
1030 let mut error = None;
1032 if attr.check_name(sym::rustc_macro_transparency) {
1033 if let Some((_, old_span)) = transparency {
1034 error = Some(TransparencyError::MultipleTransparencyAttrs(old_span, attr.span));
1036 } else if let Some(value) = attr.value_str() {
1037 transparency = Some((
1038 match &*value.as_str() {
1039 "transparent" => Transparency::Transparent,
1040 "semitransparent" => Transparency::SemiTransparent,
1041 "opaque" => Transparency::Opaque,
1043 error = Some(TransparencyError::UnknownTransparency(value, attr.span));
1052 let fallback = if is_legacy { Transparency::SemiTransparent } else { Transparency::Opaque };
1053 (transparency.map_or(fallback, |t| t.0), error)
1056 pub fn allow_internal_unstable<'a>(
1057 attrs: &[Attribute],
1058 diag: &'a rustc_errors::Handler,
1059 ) -> Option<impl Iterator<Item = Symbol> + 'a> {
1060 let attr = find_by_name(attrs, sym::allow_internal_unstable)?;
1061 let list = attr.meta_item_list().or_else(|| {
1062 diag.span_err(attr.span, "allow_internal_unstable expects list of feature names");
1065 Some(list.into_iter().filter_map(move |it| {
1066 let name = it.ident().map(|ident| ident.name);
1068 diag.span_err(it.span(), "`allow_internal_unstable` expects feature names");