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 => 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 issue_num = None;
375 let mut is_soft = false;
377 if let Some(mi) = meta.meta_item() {
378 match mi.name_or_empty() {
380 if !get(mi, &mut feature) {
385 if !get(mi, &mut reason) {
390 if !get(mi, &mut issue) {
394 // These unwraps are safe because `get` ensures the meta item
395 // is a name/value pair string literal.
396 issue_num = match &*issue.unwrap().as_str() {
399 let emit_diag = |msg: &str| {
404 "`issue` must be a non-zero numeric string \
408 mi.name_value_literal().unwrap().span,
413 match issue.parse() {
414 Ok(num) if num == 0 => {
416 "`issue` must not be \"0\", \
417 use \"none\" instead",
421 Ok(num) => NonZeroU32::new(num),
423 emit_diag(&err.to_string());
432 let msg = "`soft` should not have any arguments";
433 sess.span_diagnostic.span_err(mi.span, msg);
441 AttrError::UnknownMetaItem(
442 pprust::path_to_string(&mi.path),
443 &["feature", "reason", "issue", "soft"],
453 AttrError::UnsupportedLiteral("unsupported literal", false),
459 match (feature, reason, issue) {
460 (Some(feature), reason, Some(_)) => {
461 let level = Unstable { reason, issue: issue_num, is_soft };
462 if sym::unstable == meta_name {
463 stab = Some(Stability { level, feature, rustc_depr: None });
465 const_stab = Some(ConstStability {
469 allow_const_fn_ptr: false,
474 handle_errors(sess, attr.span, AttrError::MissingFeature);
478 struct_span_err!(diagnostic, attr.span, E0547, "missing 'issue'")
484 sym::rustc_const_stable | sym::stable => {
485 if meta_name == sym::stable && stab.is_some() {
486 handle_errors(sess, attr.span, AttrError::MultipleStabilityLevels);
488 } else if meta_name == sym::rustc_const_stable && const_stab.is_some() {
489 handle_errors(sess, attr.span, AttrError::MultipleStabilityLevels);
493 let mut feature = None;
494 let mut since = None;
497 NestedMetaItem::MetaItem(mi) => match mi.name_or_empty() {
499 if !get(mi, &mut feature) {
504 if !get(mi, &mut since) {
512 AttrError::UnknownMetaItem(
513 pprust::path_to_string(&mi.path),
520 NestedMetaItem::Literal(lit) => {
524 AttrError::UnsupportedLiteral("unsupported literal", false),
531 match (feature, since) {
532 (Some(feature), Some(since)) => {
533 let level = Stable { since };
534 if sym::stable == meta_name {
535 stab = Some(Stability { level, feature, rustc_depr: None });
537 const_stab = Some(ConstStability {
541 allow_const_fn_ptr: false,
546 handle_errors(sess, attr.span, AttrError::MissingFeature);
550 handle_errors(sess, attr.span, AttrError::MissingSince);
560 // Merge the deprecation info into the stability info
561 if let Some(rustc_depr) = rustc_depr {
562 if let Some(ref mut stab) = stab {
563 stab.rustc_depr = Some(rustc_depr);
569 "rustc_deprecated attribute must be paired with \
570 either stable or unstable attribute"
576 // Merge the const-unstable info into the stability info
577 if promotable || allow_const_fn_ptr {
578 if let Some(ref mut stab) = const_stab {
579 stab.promotable = promotable;
580 stab.allow_const_fn_ptr = allow_const_fn_ptr;
586 "rustc_promotable and rustc_allow_const_fn_ptr attributes \
587 must be paired with either a rustc_const_unstable or a rustc_const_stable \
597 pub fn find_crate_name(attrs: &[Attribute]) -> Option<Symbol> {
598 super::first_attr_value_str_by_name(attrs, sym::crate_name)
601 /// Tests if a cfg-pattern matches the cfg set
602 pub fn cfg_matches(cfg: &ast::MetaItem, sess: &ParseSess, features: Option<&Features>) -> bool {
603 eval_condition(cfg, sess, &mut |cfg| {
604 let gate = find_gated_cfg(|sym| cfg.check_name(sym));
605 if let (Some(feats), Some(gated_cfg)) = (features, gate) {
606 gate_cfg(&gated_cfg, cfg.span, sess, feats);
608 let error = |span, msg| {
609 sess.span_diagnostic.span_err(span, msg);
612 if cfg.path.segments.len() != 1 {
613 return error(cfg.path.span, "`cfg` predicate key must be an identifier");
616 MetaItemKind::List(..) => {
617 error(cfg.span, "unexpected parentheses after `cfg` predicate key")
619 MetaItemKind::NameValue(lit) if !lit.kind.is_str() => {
623 AttrError::UnsupportedLiteral(
624 "literal in `cfg` predicate value must be a string",
625 lit.kind.is_bytestr(),
630 MetaItemKind::NameValue(..) | MetaItemKind::Word => {
631 let ident = cfg.ident().expect("multi-segment cfg predicate");
632 sess.config.contains(&(ident.name, cfg.value_str()))
638 fn gate_cfg(gated_cfg: &GatedCfg, cfg_span: Span, sess: &ParseSess, features: &Features) {
639 let (cfg, feature, has_feature) = gated_cfg;
640 if !has_feature(features) && !cfg_span.allows_unstable(*feature) {
641 let explain = format!("`cfg({})` is experimental and subject to change", cfg);
642 feature_err(sess, *feature, cfg_span, &explain).emit()
646 /// Evaluate a cfg-like condition (with `any` and `all`), using `eval` to
647 /// evaluate individual items.
648 pub fn eval_condition(
651 eval: &mut impl FnMut(&ast::MetaItem) -> bool,
654 ast::MetaItemKind::List(ref mis) => {
655 for mi in mis.iter() {
656 if !mi.is_meta_item() {
660 AttrError::UnsupportedLiteral("unsupported literal", false),
666 // The unwraps below may look dangerous, but we've already asserted
667 // that they won't fail with the loop above.
668 match cfg.name_or_empty() {
670 mis.iter().any(|mi| eval_condition(mi.meta_item().unwrap(), sess, eval))
673 mis.iter().all(|mi| eval_condition(mi.meta_item().unwrap(), sess, eval))
678 sess.span_diagnostic,
681 "expected 1 cfg-pattern"
687 !eval_condition(mis[0].meta_item().unwrap(), sess, eval)
691 sess.span_diagnostic,
694 "invalid predicate `{}`",
695 pprust::path_to_string(&cfg.path)
702 ast::MetaItemKind::Word | ast::MetaItemKind::NameValue(..) => eval(cfg),
706 #[derive(RustcEncodable, RustcDecodable, Clone, HashStable_Generic)]
707 pub struct Deprecation {
708 pub since: Option<Symbol>,
709 pub note: Option<Symbol>,
712 /// Finds the deprecation attribute. `None` if none exists.
713 pub fn find_deprecation(
717 ) -> Option<Deprecation> {
718 find_deprecation_generic(sess, attrs.iter(), item_sp)
721 fn find_deprecation_generic<'a, I>(
725 ) -> Option<Deprecation>
727 I: Iterator<Item = &'a Attribute>,
729 let mut depr: Option<Deprecation> = None;
730 let diagnostic = &sess.span_diagnostic;
732 'outer: for attr in attrs_iter {
733 if !attr.check_name(sym::deprecated) {
738 struct_span_err!(diagnostic, item_sp, E0550, "multiple deprecated attributes").emit();
742 let meta = match attr.meta() {
746 depr = match &meta.kind {
747 MetaItemKind::Word => Some(Deprecation { since: None, note: None }),
748 MetaItemKind::NameValue(..) => {
749 meta.value_str().map(|note| Deprecation { since: None, note: Some(note) })
751 MetaItemKind::List(list) => {
752 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
757 AttrError::MultipleItem(pprust::path_to_string(&meta.path)),
761 if let Some(v) = meta.value_str() {
765 if let Some(lit) = meta.name_value_literal() {
769 AttrError::UnsupportedLiteral(
770 "literal in `deprecated` \
771 value must be a string",
772 lit.kind.is_bytestr(),
776 struct_span_err!(diagnostic, meta.span, E0551, "incorrect meta item")
784 let mut since = None;
788 NestedMetaItem::MetaItem(mi) => match mi.name_or_empty() {
790 if !get(mi, &mut since) {
795 if !get(mi, &mut note) {
803 AttrError::UnknownMetaItem(
804 pprust::path_to_string(&mi.path),
811 NestedMetaItem::Literal(lit) => {
815 AttrError::UnsupportedLiteral(
816 "item in `deprecated` must be a key/value pair",
825 Some(Deprecation { since, note })
833 #[derive(PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
843 #[derive(Eq, PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone, HashStable_Generic)]
845 SignedInt(ast::IntTy),
846 UnsignedInt(ast::UintTy),
851 pub fn is_signed(self) -> bool {
855 SignedInt(..) => true,
856 UnsignedInt(..) => false,
861 /// Parse #[repr(...)] forms.
863 /// Valid repr contents: any of the primitive integral type names (see
864 /// `int_type_of_word`, below) to specify enum discriminant type; `C`, to use
865 /// the same discriminant size that the corresponding C enum would or C
866 /// structure layout, `packed` to remove padding, and `transparent` to elegate representation
867 /// concerns to the only non-ZST field.
868 pub fn find_repr_attrs(sess: &ParseSess, attr: &Attribute) -> Vec<ReprAttr> {
871 let mut acc = Vec::new();
872 let diagnostic = &sess.span_diagnostic;
873 if attr.has_name(sym::repr) {
874 if let Some(items) = attr.meta_item_list() {
877 if !item.is_meta_item() {
881 AttrError::UnsupportedLiteral(
882 "meta item in `repr` must be an identifier",
889 let mut recognised = false;
891 let hint = match item.name_or_empty() {
892 sym::C => Some(ReprC),
893 sym::packed => Some(ReprPacked(1)),
894 sym::simd => Some(ReprSimd),
895 sym::transparent => Some(ReprTransparent),
896 name => int_type_of_word(name).map(ReprInt),
899 if let Some(h) = hint {
903 } else if let Some((name, value)) = item.name_value_literal() {
904 let parse_alignment = |node: &ast::LitKind| -> Result<u32, &'static str> {
905 if let ast::LitKind::Int(literal, ast::LitIntType::Unsuffixed) = node {
906 if literal.is_power_of_two() {
907 // rustc::ty::layout::Align restricts align to <= 2^29
908 if *literal <= 1 << 29 {
911 Err("larger than 2^29")
914 Err("not a power of two")
917 Err("not an unsuffixed integer")
921 let mut literal_error = None;
922 if name == sym::align {
924 match parse_alignment(&value.kind) {
925 Ok(literal) => acc.push(ReprAlign(literal)),
926 Err(message) => literal_error = Some(message),
928 } else if name == sym::packed {
930 match parse_alignment(&value.kind) {
931 Ok(literal) => acc.push(ReprPacked(literal)),
932 Err(message) => literal_error = Some(message),
935 if let Some(literal_error) = literal_error {
940 "invalid `repr(align)` attribute: {}",
946 if let Some(meta_item) = item.meta_item() {
947 if meta_item.check_name(sym::align) {
948 if let MetaItemKind::NameValue(ref value) = meta_item.kind {
950 let mut err = struct_span_err!(
954 "incorrect `repr(align)` attribute format"
957 ast::LitKind::Int(int, ast::LitIntType::Unsuffixed) => {
960 "use parentheses instead",
961 format!("align({})", int),
962 Applicability::MachineApplicable,
965 ast::LitKind::Str(s, _) => {
968 "use parentheses instead",
969 format!("align({})", s),
970 Applicability::MachineApplicable,
981 // Not a word we recognize
986 "unrecognized representation hint"
996 fn int_type_of_word(s: Symbol) -> Option<IntType> {
1000 sym::i8 => Some(SignedInt(ast::IntTy::I8)),
1001 sym::u8 => Some(UnsignedInt(ast::UintTy::U8)),
1002 sym::i16 => Some(SignedInt(ast::IntTy::I16)),
1003 sym::u16 => Some(UnsignedInt(ast::UintTy::U16)),
1004 sym::i32 => Some(SignedInt(ast::IntTy::I32)),
1005 sym::u32 => Some(UnsignedInt(ast::UintTy::U32)),
1006 sym::i64 => Some(SignedInt(ast::IntTy::I64)),
1007 sym::u64 => Some(UnsignedInt(ast::UintTy::U64)),
1008 sym::i128 => Some(SignedInt(ast::IntTy::I128)),
1009 sym::u128 => Some(UnsignedInt(ast::UintTy::U128)),
1010 sym::isize => Some(SignedInt(ast::IntTy::Isize)),
1011 sym::usize => Some(UnsignedInt(ast::UintTy::Usize)),
1016 pub enum TransparencyError {
1017 UnknownTransparency(Symbol, Span),
1018 MultipleTransparencyAttrs(Span, Span),
1021 pub fn find_transparency(
1022 attrs: &[Attribute],
1024 ) -> (Transparency, Option<TransparencyError>) {
1025 let mut transparency = None;
1026 let mut error = None;
1028 if attr.check_name(sym::rustc_macro_transparency) {
1029 if let Some((_, old_span)) = transparency {
1030 error = Some(TransparencyError::MultipleTransparencyAttrs(old_span, attr.span));
1032 } else if let Some(value) = attr.value_str() {
1033 transparency = Some((
1034 match &*value.as_str() {
1035 "transparent" => Transparency::Transparent,
1036 "semitransparent" => Transparency::SemiTransparent,
1037 "opaque" => Transparency::Opaque,
1039 error = Some(TransparencyError::UnknownTransparency(value, attr.span));
1048 let fallback = if is_legacy { Transparency::SemiTransparent } else { Transparency::Opaque };
1049 (transparency.map_or(fallback, |t| t.0), error)
1052 pub fn allow_internal_unstable<'a>(
1053 attrs: &[Attribute],
1054 diag: &'a rustc_errors::Handler,
1055 ) -> Option<impl Iterator<Item = Symbol> + 'a> {
1056 let attr = find_by_name(attrs, sym::allow_internal_unstable)?;
1057 let list = attr.meta_item_list().or_else(|| {
1058 diag.span_err(attr.span, "allow_internal_unstable expects list of feature names");
1061 Some(list.into_iter().filter_map(move |it| {
1062 let name = it.ident().map(|ident| ident.name);
1064 diag.span_err(it.span(), "`allow_internal_unstable` expects feature names");