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 use rustc_error_codes::*;
17 pub fn is_builtin_attr(attr: &Attribute) -> bool {
18 attr.is_doc_comment() || attr.ident().filter(|ident| is_builtin_attr_name(ident.name)).is_some()
23 UnknownMetaItem(String, &'static [&'static str]),
26 MultipleStabilityLevels,
27 UnsupportedLiteral(&'static str, /* is_bytestr */ bool),
30 fn handle_errors(sess: &ParseSess, span: Span, error: AttrError) {
31 let diag = &sess.span_diagnostic;
33 AttrError::MultipleItem(item) => {
34 struct_span_err!(diag, span, E0538, "multiple '{}' items", item).emit();
36 AttrError::UnknownMetaItem(item, expected) => {
37 let expected = expected.iter().map(|name| format!("`{}`", name)).collect::<Vec<_>>();
38 struct_span_err!(diag, span, E0541, "unknown meta item '{}'", item)
39 .span_label(span, format!("expected one of {}", expected.join(", ")))
42 AttrError::MissingSince => 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 is_soft = false;
378 if let Some(mi) = meta.meta_item() {
379 match mi.name_or_empty() {
381 if !get(mi, &mut feature) {
386 if !get(mi, &mut reason) {
391 if !get(mi, &mut issue) {
397 let msg = "`soft` should not have any arguments";
398 sess.span_diagnostic.span_err(mi.span, msg);
406 AttrError::UnknownMetaItem(
407 pprust::path_to_string(&mi.path),
408 &["feature", "reason", "issue", "soft"],
418 AttrError::UnsupportedLiteral("unsupported literal", false),
424 match (feature, reason, issue) {
425 (Some(feature), reason, Some(issue)) => {
426 let issue = match &*issue.as_str() {
429 if let Ok(num) = issue.parse() {
430 // FIXME(rossmacarthur): disallow 0
431 // Disallowing this requires updates to some submodules
445 let level = Unstable { reason, issue, is_soft };
446 if sym::unstable == meta_name {
447 stab = Some(Stability { level, feature, rustc_depr: None });
449 const_stab = Some(ConstStability {
453 allow_const_fn_ptr: false,
458 handle_errors(sess, attr.span, AttrError::MissingFeature);
462 struct_span_err!(diagnostic, attr.span, E0547, "missing 'issue'")
468 sym::rustc_const_stable | sym::stable => {
469 if meta_name == sym::stable && stab.is_some() {
470 handle_errors(sess, attr.span, AttrError::MultipleStabilityLevels);
472 } else if meta_name == sym::rustc_const_stable && const_stab.is_some() {
473 handle_errors(sess, attr.span, AttrError::MultipleStabilityLevels);
477 let mut feature = None;
478 let mut since = None;
481 NestedMetaItem::MetaItem(mi) => match mi.name_or_empty() {
483 if !get(mi, &mut feature) {
488 if !get(mi, &mut since) {
496 AttrError::UnknownMetaItem(
497 pprust::path_to_string(&mi.path),
504 NestedMetaItem::Literal(lit) => {
508 AttrError::UnsupportedLiteral("unsupported literal", false),
515 match (feature, since) {
516 (Some(feature), Some(since)) => {
517 let level = Stable { since };
518 if sym::stable == meta_name {
519 stab = Some(Stability { level, feature, rustc_depr: None });
521 const_stab = Some(ConstStability {
525 allow_const_fn_ptr: false,
530 handle_errors(sess, attr.span, AttrError::MissingFeature);
534 handle_errors(sess, attr.span, AttrError::MissingSince);
544 // Merge the deprecation info into the stability info
545 if let Some(rustc_depr) = rustc_depr {
546 if let Some(ref mut stab) = stab {
547 stab.rustc_depr = Some(rustc_depr);
553 "rustc_deprecated attribute must be paired with \
554 either stable or unstable attribute"
560 // Merge the const-unstable info into the stability info
561 if promotable || allow_const_fn_ptr {
562 if let Some(ref mut stab) = const_stab {
563 stab.promotable = promotable;
564 stab.allow_const_fn_ptr = allow_const_fn_ptr;
570 "rustc_promotable and rustc_allow_const_fn_ptr attributes \
571 must be paired with either a rustc_const_unstable or a rustc_const_stable \
581 pub fn find_crate_name(attrs: &[Attribute]) -> Option<Symbol> {
582 super::first_attr_value_str_by_name(attrs, sym::crate_name)
585 /// Tests if a cfg-pattern matches the cfg set
586 pub fn cfg_matches(cfg: &ast::MetaItem, sess: &ParseSess, features: Option<&Features>) -> bool {
587 eval_condition(cfg, sess, &mut |cfg| {
588 let gate = find_gated_cfg(|sym| cfg.check_name(sym));
589 if let (Some(feats), Some(gated_cfg)) = (features, gate) {
590 gate_cfg(&gated_cfg, cfg.span, sess, feats);
592 let error = |span, msg| {
593 sess.span_diagnostic.span_err(span, msg);
596 if cfg.path.segments.len() != 1 {
597 return error(cfg.path.span, "`cfg` predicate key must be an identifier");
600 MetaItemKind::List(..) => {
601 error(cfg.span, "unexpected parentheses after `cfg` predicate key")
603 MetaItemKind::NameValue(lit) if !lit.kind.is_str() => {
607 AttrError::UnsupportedLiteral(
608 "literal in `cfg` predicate value must be a string",
609 lit.kind.is_bytestr(),
614 MetaItemKind::NameValue(..) | MetaItemKind::Word => {
615 let ident = cfg.ident().expect("multi-segment cfg predicate");
616 sess.config.contains(&(ident.name, cfg.value_str()))
622 fn gate_cfg(gated_cfg: &GatedCfg, cfg_span: Span, sess: &ParseSess, features: &Features) {
623 let (cfg, feature, has_feature) = gated_cfg;
624 if !has_feature(features) && !cfg_span.allows_unstable(*feature) {
625 let explain = format!("`cfg({})` is experimental and subject to change", cfg);
626 feature_err(sess, *feature, cfg_span, &explain).emit()
630 /// Evaluate a cfg-like condition (with `any` and `all`), using `eval` to
631 /// evaluate individual items.
632 pub fn eval_condition(
635 eval: &mut impl FnMut(&ast::MetaItem) -> bool,
638 ast::MetaItemKind::List(ref mis) => {
639 for mi in mis.iter() {
640 if !mi.is_meta_item() {
644 AttrError::UnsupportedLiteral("unsupported literal", false),
650 // The unwraps below may look dangerous, but we've already asserted
651 // that they won't fail with the loop above.
652 match cfg.name_or_empty() {
654 mis.iter().any(|mi| eval_condition(mi.meta_item().unwrap(), sess, eval))
657 mis.iter().all(|mi| eval_condition(mi.meta_item().unwrap(), sess, eval))
662 sess.span_diagnostic,
665 "expected 1 cfg-pattern"
671 !eval_condition(mis[0].meta_item().unwrap(), sess, eval)
675 sess.span_diagnostic,
678 "invalid predicate `{}`",
679 pprust::path_to_string(&cfg.path)
686 ast::MetaItemKind::Word | ast::MetaItemKind::NameValue(..) => eval(cfg),
690 #[derive(RustcEncodable, RustcDecodable, Clone, HashStable_Generic)]
691 pub struct Deprecation {
692 pub since: Option<Symbol>,
693 pub note: Option<Symbol>,
696 /// Finds the deprecation attribute. `None` if none exists.
697 pub fn find_deprecation(
701 ) -> Option<Deprecation> {
702 find_deprecation_generic(sess, attrs.iter(), item_sp)
705 fn find_deprecation_generic<'a, I>(
709 ) -> Option<Deprecation>
711 I: Iterator<Item = &'a Attribute>,
713 let mut depr: Option<Deprecation> = None;
714 let diagnostic = &sess.span_diagnostic;
716 'outer: for attr in attrs_iter {
717 if !attr.check_name(sym::deprecated) {
722 struct_span_err!(diagnostic, item_sp, E0550, "multiple deprecated attributes").emit();
726 let meta = match attr.meta() {
730 depr = match &meta.kind {
731 MetaItemKind::Word => Some(Deprecation { since: None, note: None }),
732 MetaItemKind::NameValue(..) => {
733 meta.value_str().map(|note| Deprecation { since: None, note: Some(note) })
735 MetaItemKind::List(list) => {
736 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
741 AttrError::MultipleItem(pprust::path_to_string(&meta.path)),
745 if let Some(v) = meta.value_str() {
749 if let Some(lit) = meta.name_value_literal() {
753 AttrError::UnsupportedLiteral(
754 "literal in `deprecated` \
755 value must be a string",
756 lit.kind.is_bytestr(),
760 struct_span_err!(diagnostic, meta.span, E0551, "incorrect meta item")
768 let mut since = None;
772 NestedMetaItem::MetaItem(mi) => match mi.name_or_empty() {
774 if !get(mi, &mut since) {
779 if !get(mi, &mut note) {
787 AttrError::UnknownMetaItem(
788 pprust::path_to_string(&mi.path),
795 NestedMetaItem::Literal(lit) => {
799 AttrError::UnsupportedLiteral(
800 "item in `deprecated` must be a key/value pair",
809 Some(Deprecation { since, note })
817 #[derive(PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
827 #[derive(Eq, PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone, HashStable_Generic)]
829 SignedInt(ast::IntTy),
830 UnsignedInt(ast::UintTy),
835 pub fn is_signed(self) -> bool {
839 SignedInt(..) => true,
840 UnsignedInt(..) => false,
845 /// Parse #[repr(...)] forms.
847 /// Valid repr contents: any of the primitive integral type names (see
848 /// `int_type_of_word`, below) to specify enum discriminant type; `C`, to use
849 /// the same discriminant size that the corresponding C enum would or C
850 /// structure layout, `packed` to remove padding, and `transparent` to elegate representation
851 /// concerns to the only non-ZST field.
852 pub fn find_repr_attrs(sess: &ParseSess, attr: &Attribute) -> Vec<ReprAttr> {
855 let mut acc = Vec::new();
856 let diagnostic = &sess.span_diagnostic;
857 if attr.has_name(sym::repr) {
858 if let Some(items) = attr.meta_item_list() {
861 if !item.is_meta_item() {
865 AttrError::UnsupportedLiteral(
866 "meta item in `repr` must be an identifier",
873 let mut recognised = false;
875 let hint = match item.name_or_empty() {
876 sym::C => Some(ReprC),
877 sym::packed => Some(ReprPacked(1)),
878 sym::simd => Some(ReprSimd),
879 sym::transparent => Some(ReprTransparent),
880 name => int_type_of_word(name).map(ReprInt),
883 if let Some(h) = hint {
887 } else if let Some((name, value)) = item.name_value_literal() {
888 let parse_alignment = |node: &ast::LitKind| -> Result<u32, &'static str> {
889 if let ast::LitKind::Int(literal, ast::LitIntType::Unsuffixed) = node {
890 if literal.is_power_of_two() {
891 // rustc::ty::layout::Align restricts align to <= 2^29
892 if *literal <= 1 << 29 {
895 Err("larger than 2^29")
898 Err("not a power of two")
901 Err("not an unsuffixed integer")
905 let mut literal_error = None;
906 if name == sym::align {
908 match parse_alignment(&value.kind) {
909 Ok(literal) => acc.push(ReprAlign(literal)),
910 Err(message) => literal_error = Some(message),
912 } else if name == sym::packed {
914 match parse_alignment(&value.kind) {
915 Ok(literal) => acc.push(ReprPacked(literal)),
916 Err(message) => literal_error = Some(message),
919 if let Some(literal_error) = literal_error {
924 "invalid `repr(align)` attribute: {}",
930 if let Some(meta_item) = item.meta_item() {
931 if meta_item.check_name(sym::align) {
932 if let MetaItemKind::NameValue(ref value) = meta_item.kind {
934 let mut err = struct_span_err!(
938 "incorrect `repr(align)` attribute format"
941 ast::LitKind::Int(int, ast::LitIntType::Unsuffixed) => {
944 "use parentheses instead",
945 format!("align({})", int),
946 Applicability::MachineApplicable,
949 ast::LitKind::Str(s, _) => {
952 "use parentheses instead",
953 format!("align({})", s),
954 Applicability::MachineApplicable,
965 // Not a word we recognize
970 "unrecognized representation hint"
980 fn int_type_of_word(s: Symbol) -> Option<IntType> {
984 sym::i8 => Some(SignedInt(ast::IntTy::I8)),
985 sym::u8 => Some(UnsignedInt(ast::UintTy::U8)),
986 sym::i16 => Some(SignedInt(ast::IntTy::I16)),
987 sym::u16 => Some(UnsignedInt(ast::UintTy::U16)),
988 sym::i32 => Some(SignedInt(ast::IntTy::I32)),
989 sym::u32 => Some(UnsignedInt(ast::UintTy::U32)),
990 sym::i64 => Some(SignedInt(ast::IntTy::I64)),
991 sym::u64 => Some(UnsignedInt(ast::UintTy::U64)),
992 sym::i128 => Some(SignedInt(ast::IntTy::I128)),
993 sym::u128 => Some(UnsignedInt(ast::UintTy::U128)),
994 sym::isize => Some(SignedInt(ast::IntTy::Isize)),
995 sym::usize => Some(UnsignedInt(ast::UintTy::Usize)),
1000 pub enum TransparencyError {
1001 UnknownTransparency(Symbol, Span),
1002 MultipleTransparencyAttrs(Span, Span),
1005 pub fn find_transparency(
1006 attrs: &[Attribute],
1008 ) -> (Transparency, Option<TransparencyError>) {
1009 let mut transparency = None;
1010 let mut error = None;
1012 if attr.check_name(sym::rustc_macro_transparency) {
1013 if let Some((_, old_span)) = transparency {
1014 error = Some(TransparencyError::MultipleTransparencyAttrs(old_span, attr.span));
1016 } else if let Some(value) = attr.value_str() {
1017 transparency = Some((
1018 match &*value.as_str() {
1019 "transparent" => Transparency::Transparent,
1020 "semitransparent" => Transparency::SemiTransparent,
1021 "opaque" => Transparency::Opaque,
1023 error = Some(TransparencyError::UnknownTransparency(value, attr.span));
1032 let fallback = if is_legacy { Transparency::SemiTransparent } else { Transparency::Opaque };
1033 (transparency.map_or(fallback, |t| t.0), error)