1 //! Parsing and validation of builtin attributes
3 use super::{mark_used, MetaItemKind};
4 use crate::ast::{self, Attribute, MetaItem, NestedMetaItem};
5 use crate::feature_gate::feature_err;
6 use crate::print::pprust;
7 use crate::sess::ParseSess;
9 use errors::{struct_span_err, Applicability, Handler};
10 use rustc_feature::{find_gated_cfg, is_builtin_attr_name, Features, GatedCfg};
11 use rustc_macros::HashStable_Generic;
12 use rustc_span::hygiene::Transparency;
13 use rustc_span::{symbol::sym, symbol::Symbol, Span};
14 use std::num::NonZeroU32;
16 use rustc_error_codes::*;
18 pub fn is_builtin_attr(attr: &Attribute) -> bool {
19 attr.is_doc_comment() || attr.ident().filter(|ident| is_builtin_attr_name(ident.name)).is_some()
24 UnknownMetaItem(String, &'static [&'static str]),
27 MultipleStabilityLevels,
28 UnsupportedLiteral(&'static str, /* is_bytestr */ bool),
31 fn handle_errors(sess: &ParseSess, span: Span, error: AttrError) {
32 let diag = &sess.span_diagnostic;
34 AttrError::MultipleItem(item) => {
35 struct_span_err!(diag, span, E0538, "multiple '{}' items", item).emit();
37 AttrError::UnknownMetaItem(item, expected) => {
38 let expected = expected.iter().map(|name| format!("`{}`", name)).collect::<Vec<_>>();
39 struct_span_err!(diag, span, E0541, "unknown meta item '{}'", item)
40 .span_label(span, format!("expected one of {}", expected.join(", ")))
43 AttrError::MissingSince => struct_span_err!(diag, span, E0542, "missing 'since'").emit(),
44 AttrError::MissingFeature => {
45 struct_span_err!(diag, span, E0546, "missing 'feature'").emit();
47 AttrError::MultipleStabilityLevels => {
48 struct_span_err!(diag, span, E0544, "multiple stability levels").emit();
50 AttrError::UnsupportedLiteral(msg, is_bytestr) => {
51 let mut err = struct_span_err!(diag, span, E0565, "{}", msg);
53 if let Ok(lint_str) = sess.source_map().span_to_snippet(span) {
56 "consider removing the prefix",
57 format!("{}", &lint_str[1..]),
58 Applicability::MaybeIncorrect,
67 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
75 #[derive(Clone, RustcEncodable, RustcDecodable)]
76 pub enum OptimizeAttr {
82 #[derive(Copy, Clone, PartialEq)]
88 /// Determine what `#[unwind]` attribute is present in `attrs`, if any.
89 pub fn find_unwind_attr(diagnostic: Option<&Handler>, attrs: &[Attribute]) -> Option<UnwindAttr> {
90 attrs.iter().fold(None, |ia, attr| {
91 if attr.check_name(sym::unwind) {
92 if let Some(meta) = attr.meta() {
93 if let MetaItemKind::List(items) = meta.kind {
95 if items[0].check_name(sym::allowed) {
96 return Some(UnwindAttr::Allowed);
97 } else if items[0].check_name(sym::aborts) {
98 return Some(UnwindAttr::Aborts);
103 struct_span_err!(d, attr.span, E0633, "malformed `unwind` attribute input")
104 .span_label(attr.span, "invalid argument")
107 "the allowed arguments are `allowed` and `aborts`",
108 (vec!["allowed", "aborts"])
110 .map(|s| format!("#[unwind({})]", s)),
111 Applicability::MachineApplicable,
123 /// Represents the #[stable], #[unstable], #[rustc_deprecated] attributes.
135 pub struct Stability {
136 pub level: StabilityLevel,
138 pub rustc_depr: Option<RustcDeprecation>,
141 /// Represents the #[rustc_const_unstable] and #[rustc_const_stable] attributes.
153 pub struct ConstStability {
154 pub level: StabilityLevel,
156 /// whether the function has a `#[rustc_promotable]` attribute
157 pub promotable: bool,
158 /// whether the function has a `#[rustc_allow_const_fn_ptr]` attribute
159 pub allow_const_fn_ptr: bool,
162 /// The available stability levels.
175 pub enum StabilityLevel {
176 // Reason for the current stability level and the relevant rust-lang issue
177 Unstable { reason: Option<Symbol>, issue: Option<NonZeroU32>, is_soft: bool },
178 Stable { since: Symbol },
181 impl StabilityLevel {
182 pub fn is_unstable(&self) -> bool {
183 if let StabilityLevel::Unstable { .. } = *self { true } else { false }
185 pub fn is_stable(&self) -> bool {
186 if let StabilityLevel::Stable { .. } = *self { true } else { false }
202 pub struct RustcDeprecation {
205 /// A text snippet used to completely replace any use of the deprecated item in an expression.
206 pub suggestion: Option<Symbol>,
209 /// Checks if `attrs` contains an attribute like `#![feature(feature_name)]`.
210 /// This will not perform any "sanity checks" on the form of the attributes.
211 pub fn contains_feature_attr(attrs: &[Attribute], feature_name: Symbol) -> bool {
212 attrs.iter().any(|item| {
213 item.check_name(sym::feature)
216 .map(|list| list.iter().any(|mi| mi.is_word() && mi.check_name(feature_name)))
221 /// Collects stability info from all stability attributes in `attrs`.
222 /// Returns `None` if no stability attributes are found.
223 pub fn find_stability(
227 ) -> (Option<Stability>, Option<ConstStability>) {
228 find_stability_generic(sess, attrs.iter(), item_sp)
231 fn find_stability_generic<'a, I>(
235 ) -> (Option<Stability>, Option<ConstStability>)
237 I: Iterator<Item = &'a Attribute>,
239 use StabilityLevel::*;
241 let mut stab: Option<Stability> = None;
242 let mut rustc_depr: Option<RustcDeprecation> = None;
243 let mut const_stab: Option<ConstStability> = None;
244 let mut promotable = false;
245 let mut allow_const_fn_ptr = false;
246 let diagnostic = &sess.span_diagnostic;
248 'outer: for attr in attrs_iter {
250 sym::rustc_deprecated,
251 sym::rustc_const_unstable,
252 sym::rustc_const_stable,
255 sym::rustc_promotable,
256 sym::rustc_allow_const_fn_ptr,
259 .any(|&s| attr.has_name(s))
261 continue; // not a stability level
266 let meta = attr.meta();
268 if attr.has_name(sym::rustc_promotable) {
271 if attr.has_name(sym::rustc_allow_const_fn_ptr) {
272 allow_const_fn_ptr = true;
274 // attributes with data
275 else if let Some(MetaItem { kind: MetaItemKind::List(ref metas), .. }) = meta {
276 let meta = meta.as_ref().unwrap();
277 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
282 AttrError::MultipleItem(pprust::path_to_string(&meta.path)),
286 if let Some(v) = meta.value_str() {
290 struct_span_err!(diagnostic, meta.span, E0539, "incorrect meta item").emit();
295 macro_rules! get_meta {
296 ($($name:ident),+) => {
298 let mut $name = None;
301 if let Some(mi) = meta.meta_item() {
302 match mi.name_or_empty() {
304 sym::$name => if !get(mi, &mut $name) { continue 'outer },
307 let expected = &[ $( stringify!($name) ),+ ];
311 AttrError::UnknownMetaItem(
312 pprust::path_to_string(&mi.path),
323 AttrError::UnsupportedLiteral(
324 "unsupported literal",
334 let meta_name = meta.name_or_empty();
336 sym::rustc_deprecated => {
337 if rustc_depr.is_some() {
342 "multiple rustc_deprecated attributes"
348 get_meta!(since, reason, suggestion);
350 match (since, reason) {
351 (Some(since), Some(reason)) => {
352 rustc_depr = Some(RustcDeprecation { since, reason, suggestion })
355 handle_errors(sess, attr.span, AttrError::MissingSince);
359 struct_span_err!(diagnostic, attr.span, E0543, "missing 'reason'")
365 sym::rustc_const_unstable | sym::unstable => {
366 if meta_name == sym::unstable && stab.is_some() {
367 handle_errors(sess, attr.span, AttrError::MultipleStabilityLevels);
369 } else if meta_name == sym::rustc_const_unstable && const_stab.is_some() {
370 handle_errors(sess, attr.span, AttrError::MultipleStabilityLevels);
374 let mut feature = None;
375 let mut reason = None;
376 let mut issue = 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) {
398 let msg = "`soft` should not have any arguments";
399 sess.span_diagnostic.span_err(mi.span, msg);
407 AttrError::UnknownMetaItem(
408 pprust::path_to_string(&mi.path),
409 &["feature", "reason", "issue", "soft"],
419 AttrError::UnsupportedLiteral("unsupported literal", false),
425 match (feature, reason, issue) {
426 (Some(feature), reason, Some(issue)) => {
427 let issue = match &*issue.as_str() {
430 if let Ok(num) = issue.parse() {
431 // FIXME(rossmacarthur): disallow 0
432 // Disallowing this requires updates to some submodules
446 let level = Unstable { reason, issue, is_soft };
447 if sym::unstable == meta_name {
448 stab = Some(Stability { level, feature, rustc_depr: None });
450 const_stab = Some(ConstStability {
454 allow_const_fn_ptr: false,
459 handle_errors(sess, attr.span, AttrError::MissingFeature);
463 struct_span_err!(diagnostic, attr.span, E0547, "missing 'issue'")
469 sym::rustc_const_stable | sym::stable => {
470 if meta_name == sym::stable && stab.is_some() {
471 handle_errors(sess, attr.span, AttrError::MultipleStabilityLevels);
473 } else if meta_name == sym::rustc_const_stable && const_stab.is_some() {
474 handle_errors(sess, attr.span, AttrError::MultipleStabilityLevels);
478 let mut feature = None;
479 let mut since = None;
482 NestedMetaItem::MetaItem(mi) => match mi.name_or_empty() {
484 if !get(mi, &mut feature) {
489 if !get(mi, &mut since) {
497 AttrError::UnknownMetaItem(
498 pprust::path_to_string(&mi.path),
505 NestedMetaItem::Literal(lit) => {
509 AttrError::UnsupportedLiteral("unsupported literal", false),
516 match (feature, since) {
517 (Some(feature), Some(since)) => {
518 let level = Stable { since };
519 if sym::stable == meta_name {
520 stab = Some(Stability { level, feature, rustc_depr: None });
522 const_stab = Some(ConstStability {
526 allow_const_fn_ptr: false,
531 handle_errors(sess, attr.span, AttrError::MissingFeature);
535 handle_errors(sess, attr.span, AttrError::MissingSince);
545 // Merge the deprecation info into the stability info
546 if let Some(rustc_depr) = rustc_depr {
547 if let Some(ref mut stab) = stab {
548 stab.rustc_depr = Some(rustc_depr);
554 "rustc_deprecated attribute must be paired with \
555 either stable or unstable attribute"
561 // Merge the const-unstable info into the stability info
562 if promotable || allow_const_fn_ptr {
563 if let Some(ref mut stab) = const_stab {
564 stab.promotable = promotable;
565 stab.allow_const_fn_ptr = allow_const_fn_ptr;
571 "rustc_promotable and rustc_allow_const_fn_ptr attributes \
572 must be paired with either a rustc_const_unstable or a rustc_const_stable \
582 pub fn find_crate_name(attrs: &[Attribute]) -> Option<Symbol> {
583 super::first_attr_value_str_by_name(attrs, sym::crate_name)
586 /// Tests if a cfg-pattern matches the cfg set
587 pub fn cfg_matches(cfg: &ast::MetaItem, sess: &ParseSess, features: Option<&Features>) -> bool {
588 eval_condition(cfg, sess, &mut |cfg| {
589 let gate = find_gated_cfg(|sym| cfg.check_name(sym));
590 if let (Some(feats), Some(gated_cfg)) = (features, gate) {
591 gate_cfg(&gated_cfg, cfg.span, sess, feats);
593 let error = |span, msg| {
594 sess.span_diagnostic.span_err(span, msg);
597 if cfg.path.segments.len() != 1 {
598 return error(cfg.path.span, "`cfg` predicate key must be an identifier");
601 MetaItemKind::List(..) => {
602 error(cfg.span, "unexpected parentheses after `cfg` predicate key")
604 MetaItemKind::NameValue(lit) if !lit.kind.is_str() => {
608 AttrError::UnsupportedLiteral(
609 "literal in `cfg` predicate value must be a string",
610 lit.kind.is_bytestr(),
615 MetaItemKind::NameValue(..) | MetaItemKind::Word => {
616 let ident = cfg.ident().expect("multi-segment cfg predicate");
617 sess.config.contains(&(ident.name, cfg.value_str()))
623 fn gate_cfg(gated_cfg: &GatedCfg, cfg_span: Span, sess: &ParseSess, features: &Features) {
624 let (cfg, feature, has_feature) = gated_cfg;
625 if !has_feature(features) && !cfg_span.allows_unstable(*feature) {
626 let explain = format!("`cfg({})` is experimental and subject to change", cfg);
627 feature_err(sess, *feature, cfg_span, &explain).emit()
631 /// Evaluate a cfg-like condition (with `any` and `all`), using `eval` to
632 /// evaluate individual items.
633 pub fn eval_condition(
636 eval: &mut impl FnMut(&ast::MetaItem) -> bool,
639 ast::MetaItemKind::List(ref mis) => {
640 for mi in mis.iter() {
641 if !mi.is_meta_item() {
645 AttrError::UnsupportedLiteral("unsupported literal", false),
651 // The unwraps below may look dangerous, but we've already asserted
652 // that they won't fail with the loop above.
653 match cfg.name_or_empty() {
655 mis.iter().any(|mi| eval_condition(mi.meta_item().unwrap(), sess, eval))
658 mis.iter().all(|mi| eval_condition(mi.meta_item().unwrap(), sess, eval))
663 sess.span_diagnostic,
666 "expected 1 cfg-pattern"
672 !eval_condition(mis[0].meta_item().unwrap(), sess, eval)
676 sess.span_diagnostic,
679 "invalid predicate `{}`",
680 pprust::path_to_string(&cfg.path)
687 ast::MetaItemKind::Word | ast::MetaItemKind::NameValue(..) => eval(cfg),
691 #[derive(RustcEncodable, RustcDecodable, Clone, HashStable_Generic)]
692 pub struct Deprecation {
693 pub since: Option<Symbol>,
694 pub note: Option<Symbol>,
697 /// Finds the deprecation attribute. `None` if none exists.
698 pub fn find_deprecation(
702 ) -> Option<Deprecation> {
703 find_deprecation_generic(sess, attrs.iter(), item_sp)
706 fn find_deprecation_generic<'a, I>(
710 ) -> Option<Deprecation>
712 I: Iterator<Item = &'a Attribute>,
714 let mut depr: Option<Deprecation> = None;
715 let diagnostic = &sess.span_diagnostic;
717 'outer: for attr in attrs_iter {
718 if !attr.check_name(sym::deprecated) {
723 struct_span_err!(diagnostic, item_sp, E0550, "multiple deprecated attributes").emit();
727 let meta = match attr.meta() {
731 depr = match &meta.kind {
732 MetaItemKind::Word => Some(Deprecation { since: None, note: None }),
733 MetaItemKind::NameValue(..) => {
734 meta.value_str().map(|note| Deprecation { since: None, note: Some(note) })
736 MetaItemKind::List(list) => {
737 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
742 AttrError::MultipleItem(pprust::path_to_string(&meta.path)),
746 if let Some(v) = meta.value_str() {
750 if let Some(lit) = meta.name_value_literal() {
754 AttrError::UnsupportedLiteral(
755 "literal in `deprecated` \
756 value must be a string",
757 lit.kind.is_bytestr(),
761 struct_span_err!(diagnostic, meta.span, E0551, "incorrect meta item")
769 let mut since = None;
773 NestedMetaItem::MetaItem(mi) => match mi.name_or_empty() {
775 if !get(mi, &mut since) {
780 if !get(mi, &mut note) {
788 AttrError::UnknownMetaItem(
789 pprust::path_to_string(&mi.path),
796 NestedMetaItem::Literal(lit) => {
800 AttrError::UnsupportedLiteral(
801 "item in `deprecated` must be a key/value pair",
810 Some(Deprecation { since, note })
818 #[derive(PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
828 #[derive(Eq, PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone, HashStable_Generic)]
830 SignedInt(ast::IntTy),
831 UnsignedInt(ast::UintTy),
836 pub fn is_signed(self) -> bool {
840 SignedInt(..) => true,
841 UnsignedInt(..) => false,
846 /// Parse #[repr(...)] forms.
848 /// Valid repr contents: any of the primitive integral type names (see
849 /// `int_type_of_word`, below) to specify enum discriminant type; `C`, to use
850 /// the same discriminant size that the corresponding C enum would or C
851 /// structure layout, `packed` to remove padding, and `transparent` to elegate representation
852 /// concerns to the only non-ZST field.
853 pub fn find_repr_attrs(sess: &ParseSess, attr: &Attribute) -> Vec<ReprAttr> {
856 let mut acc = Vec::new();
857 let diagnostic = &sess.span_diagnostic;
858 if attr.has_name(sym::repr) {
859 if let Some(items) = attr.meta_item_list() {
862 if !item.is_meta_item() {
866 AttrError::UnsupportedLiteral(
867 "meta item in `repr` must be an identifier",
874 let mut recognised = false;
876 let hint = match item.name_or_empty() {
877 sym::C => Some(ReprC),
878 sym::packed => Some(ReprPacked(1)),
879 sym::simd => Some(ReprSimd),
880 sym::transparent => Some(ReprTransparent),
881 name => int_type_of_word(name).map(ReprInt),
884 if let Some(h) = hint {
888 } else if let Some((name, value)) = item.name_value_literal() {
889 let parse_alignment = |node: &ast::LitKind| -> Result<u32, &'static str> {
890 if let ast::LitKind::Int(literal, ast::LitIntType::Unsuffixed) = node {
891 if literal.is_power_of_two() {
892 // rustc::ty::layout::Align restricts align to <= 2^29
893 if *literal <= 1 << 29 {
896 Err("larger than 2^29")
899 Err("not a power of two")
902 Err("not an unsuffixed integer")
906 let mut literal_error = None;
907 if name == sym::align {
909 match parse_alignment(&value.kind) {
910 Ok(literal) => acc.push(ReprAlign(literal)),
911 Err(message) => literal_error = Some(message),
913 } else if name == sym::packed {
915 match parse_alignment(&value.kind) {
916 Ok(literal) => acc.push(ReprPacked(literal)),
917 Err(message) => literal_error = Some(message),
920 if let Some(literal_error) = literal_error {
925 "invalid `repr(align)` attribute: {}",
931 if let Some(meta_item) = item.meta_item() {
932 if meta_item.check_name(sym::align) {
933 if let MetaItemKind::NameValue(ref value) = meta_item.kind {
935 let mut err = struct_span_err!(
939 "incorrect `repr(align)` attribute format"
942 ast::LitKind::Int(int, ast::LitIntType::Unsuffixed) => {
945 "use parentheses instead",
946 format!("align({})", int),
947 Applicability::MachineApplicable,
950 ast::LitKind::Str(s, _) => {
953 "use parentheses instead",
954 format!("align({})", s),
955 Applicability::MachineApplicable,
966 // Not a word we recognize
971 "unrecognized representation hint"
981 fn int_type_of_word(s: Symbol) -> Option<IntType> {
985 sym::i8 => Some(SignedInt(ast::IntTy::I8)),
986 sym::u8 => Some(UnsignedInt(ast::UintTy::U8)),
987 sym::i16 => Some(SignedInt(ast::IntTy::I16)),
988 sym::u16 => Some(UnsignedInt(ast::UintTy::U16)),
989 sym::i32 => Some(SignedInt(ast::IntTy::I32)),
990 sym::u32 => Some(UnsignedInt(ast::UintTy::U32)),
991 sym::i64 => Some(SignedInt(ast::IntTy::I64)),
992 sym::u64 => Some(UnsignedInt(ast::UintTy::U64)),
993 sym::i128 => Some(SignedInt(ast::IntTy::I128)),
994 sym::u128 => Some(UnsignedInt(ast::UintTy::U128)),
995 sym::isize => Some(SignedInt(ast::IntTy::Isize)),
996 sym::usize => Some(UnsignedInt(ast::UintTy::Usize)),
1001 pub enum TransparencyError {
1002 UnknownTransparency(Symbol, Span),
1003 MultipleTransparencyAttrs(Span, Span),
1006 pub fn find_transparency(
1007 attrs: &[Attribute],
1009 ) -> (Transparency, Option<TransparencyError>) {
1010 let mut transparency = None;
1011 let mut error = None;
1013 if attr.check_name(sym::rustc_macro_transparency) {
1014 if let Some((_, old_span)) = transparency {
1015 error = Some(TransparencyError::MultipleTransparencyAttrs(old_span, attr.span));
1017 } else if let Some(value) = attr.value_str() {
1018 transparency = Some((
1019 match &*value.as_str() {
1020 "transparent" => Transparency::Transparent,
1021 "semitransparent" => Transparency::SemiTransparent,
1022 "opaque" => Transparency::Opaque,
1024 error = Some(TransparencyError::UnknownTransparency(value, attr.span));
1033 let fallback = if is_legacy { Transparency::SemiTransparent } else { Transparency::Opaque };
1034 (transparency.map_or(fallback, |t| t.0), error)