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::{emit_feature_err, GateIssue};
6 use crate::print::pprust;
7 use crate::sess::ParseSess;
9 use errors::{Applicability, Handler};
10 use std::num::NonZeroU32;
11 use syntax_pos::hygiene::Transparency;
12 use syntax_pos::{symbol::Symbol, symbol::sym, Span};
13 use rustc_feature::{Features, find_gated_cfg, GatedCfg, is_builtin_attr_name};
14 use rustc_macros::HashStable_Generic;
16 use rustc_error_codes::*;
18 pub fn is_builtin_attr(attr: &Attribute) -> bool {
19 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) => span_err!(diag, span, E0538,
35 "multiple '{}' items", item),
36 AttrError::UnknownMetaItem(item, expected) => {
37 let expected = expected
39 .map(|name| format!("`{}`", name))
41 struct_span_err!(diag, span, E0541, "unknown meta item '{}'", item)
42 .span_label(span, format!("expected one of {}", expected.join(", ")))
45 AttrError::MissingSince => span_err!(diag, span, E0542, "missing 'since'"),
46 AttrError::MissingFeature => span_err!(diag, span, E0546, "missing 'feature'"),
47 AttrError::MultipleStabilityLevels => span_err!(diag, span, E0544,
48 "multiple stability levels"),
49 AttrError::UnsupportedLiteral(
53 let mut err = struct_span_err!(diag, span, E0565, "{}", msg);
55 if let Ok(lint_str) = sess.source_map().span_to_snippet(span) {
58 "consider removing the prefix",
59 format!("{}", &lint_str[1..]),
60 Applicability::MaybeIncorrect,
69 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
77 #[derive(Clone, RustcEncodable, RustcDecodable)]
78 pub enum OptimizeAttr {
84 #[derive(Copy, Clone, PartialEq)]
90 /// Determine what `#[unwind]` attribute is present in `attrs`, if any.
91 pub fn find_unwind_attr(diagnostic: Option<&Handler>, attrs: &[Attribute]) -> Option<UnwindAttr> {
92 attrs.iter().fold(None, |ia, attr| {
93 if attr.check_name(sym::unwind) {
94 if let Some(meta) = attr.meta() {
95 if let MetaItemKind::List(items) = meta.kind {
97 if items[0].check_name(sym::allowed) {
98 return Some(UnwindAttr::Allowed);
99 } else if items[0].check_name(sym::aborts) {
100 return Some(UnwindAttr::Aborts);
105 struct_span_err!(d, attr.span, E0633, "malformed `unwind` attribute input")
106 .span_label(attr.span, "invalid argument")
109 "the allowed arguments are `allowed` and `aborts`",
110 (vec!["allowed", "aborts"]).into_iter()
111 .map(|s| format!("#[unwind({})]", s)),
112 Applicability::MachineApplicable,
123 /// Represents the #[stable], #[unstable], #[rustc_{deprecated,const_unstable}] attributes.
124 #[derive(RustcEncodable, RustcDecodable, Copy, Clone, Debug,
125 PartialEq, Eq, Hash, HashStable_Generic)]
126 pub struct Stability {
127 pub level: StabilityLevel,
129 pub rustc_depr: Option<RustcDeprecation>,
130 /// `None` means the function is stable but needs to be a stable const fn, too
131 /// `Some` contains the feature gate required to be able to use the function
133 pub const_stability: Option<Symbol>,
134 /// whether the function has a `#[rustc_promotable]` attribute
135 pub promotable: bool,
136 /// whether the function has a `#[rustc_allow_const_fn_ptr]` attribute
137 pub allow_const_fn_ptr: bool,
140 /// The available stability levels.
141 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd,
142 Copy, Clone, Debug, Eq, Hash, HashStable_Generic)]
143 pub enum StabilityLevel {
144 // Reason for the current stability level and the relevant rust-lang issue
145 Unstable { reason: Option<Symbol>, issue: Option<NonZeroU32>, is_soft: bool },
146 Stable { since: Symbol },
149 impl StabilityLevel {
150 pub fn is_unstable(&self) -> bool {
151 if let StabilityLevel::Unstable {..} = *self {
157 pub fn is_stable(&self) -> bool {
158 if let StabilityLevel::Stable {..} = *self {
166 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd,
167 Copy, Clone, Debug, Eq, Hash, HashStable_Generic)]
168 pub struct RustcDeprecation {
171 /// A text snippet used to completely replace any use of the deprecated item in an expression.
172 pub suggestion: Option<Symbol>,
175 /// Checks if `attrs` contains an attribute like `#![feature(feature_name)]`.
176 /// This will not perform any "sanity checks" on the form of the attributes.
177 pub fn contains_feature_attr(attrs: &[Attribute], feature_name: Symbol) -> bool {
178 attrs.iter().any(|item| {
179 item.check_name(sym::feature) &&
180 item.meta_item_list().map(|list| {
181 list.iter().any(|mi| mi.is_word() && mi.check_name(feature_name))
186 /// Collects stability info from all stability attributes in `attrs`.
187 /// Returns `None` if no stability attributes are found.
188 pub fn find_stability(sess: &ParseSess, attrs: &[Attribute],
189 item_sp: Span) -> Option<Stability> {
190 find_stability_generic(sess, attrs.iter(), item_sp)
193 fn find_stability_generic<'a, I>(sess: &ParseSess,
197 where I: Iterator<Item = &'a Attribute>
199 use StabilityLevel::*;
201 let mut stab: Option<Stability> = None;
202 let mut rustc_depr: Option<RustcDeprecation> = None;
203 let mut rustc_const_unstable: Option<Symbol> = None;
204 let mut promotable = false;
205 let mut allow_const_fn_ptr = false;
206 let diagnostic = &sess.span_diagnostic;
208 'outer: for attr in attrs_iter {
210 sym::rustc_deprecated,
211 sym::rustc_const_unstable,
214 sym::rustc_promotable,
215 sym::rustc_allow_const_fn_ptr,
216 ].iter().any(|&s| attr.has_name(s)) {
217 continue // not a stability level
222 let meta = attr.meta();
224 if attr.has_name(sym::rustc_promotable) {
227 if attr.has_name(sym::rustc_allow_const_fn_ptr) {
228 allow_const_fn_ptr = true;
230 // attributes with data
231 else if let Some(MetaItem { kind: MetaItemKind::List(ref metas), .. }) = meta {
232 let meta = meta.as_ref().unwrap();
233 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
238 AttrError::MultipleItem(pprust::path_to_string(&meta.path)),
242 if let Some(v) = meta.value_str() {
246 span_err!(diagnostic, meta.span, E0539, "incorrect meta item");
251 macro_rules! get_meta {
252 ($($name:ident),+) => {
254 let mut $name = None;
257 if let Some(mi) = meta.meta_item() {
258 match mi.name_or_empty() {
260 sym::$name => if !get(mi, &mut $name) { continue 'outer },
263 let expected = &[ $( stringify!($name) ),+ ];
267 AttrError::UnknownMetaItem(
268 pprust::path_to_string(&mi.path),
279 AttrError::UnsupportedLiteral(
280 "unsupported literal",
290 match meta.name_or_empty() {
291 sym::rustc_deprecated => {
292 if rustc_depr.is_some() {
293 span_err!(diagnostic, item_sp, E0540,
294 "multiple rustc_deprecated attributes");
298 get_meta!(since, reason, suggestion);
300 match (since, reason) {
301 (Some(since), Some(reason)) => {
302 rustc_depr = Some(RustcDeprecation {
309 handle_errors(sess, attr.span, AttrError::MissingSince);
313 span_err!(diagnostic, attr.span, E0543, "missing 'reason'");
318 sym::rustc_const_unstable => {
319 if rustc_const_unstable.is_some() {
320 span_err!(diagnostic, item_sp, E0553,
321 "multiple rustc_const_unstable attributes");
326 if let Some(feature) = feature {
327 rustc_const_unstable = Some(feature);
329 span_err!(diagnostic, attr.span, E0629, "missing 'feature'");
335 handle_errors(sess, attr.span, AttrError::MultipleStabilityLevels);
339 let mut feature = None;
340 let mut reason = None;
341 let mut issue = None;
342 let mut is_soft = false;
344 if let Some(mi) = meta.meta_item() {
345 match mi.name_or_empty() {
346 sym::feature => if !get(mi, &mut feature) { continue 'outer },
347 sym::reason => if !get(mi, &mut reason) { continue 'outer },
348 sym::issue => if !get(mi, &mut issue) { continue 'outer },
351 let msg = "`soft` should not have any arguments";
352 sess.span_diagnostic.span_err(mi.span, msg);
360 AttrError::UnknownMetaItem(
361 pprust::path_to_string(&mi.path),
362 &["feature", "reason", "issue", "soft"]
372 AttrError::UnsupportedLiteral(
373 "unsupported literal",
381 match (feature, reason, issue) {
382 (Some(feature), reason, Some(issue)) => {
383 let issue = match &*issue.as_str() {
384 // FIXME(rossmacarthur): remove "0" because "none" should be used
386 "none" | "0" => None,
388 if let Ok(num) = issue.parse() {
401 stab = Some(Stability {
409 const_stability: None,
411 allow_const_fn_ptr: false,
415 handle_errors(sess, attr.span, AttrError::MissingFeature);
419 span_err!(diagnostic, attr.span, E0547, "missing 'issue'");
426 handle_errors(sess, attr.span, AttrError::MultipleStabilityLevels);
430 let mut feature = None;
431 let mut since = None;
434 NestedMetaItem::MetaItem(mi) => {
435 match mi.name_or_empty() {
436 sym::feature => if !get(mi, &mut feature) { continue 'outer },
437 sym::since => if !get(mi, &mut since) { continue 'outer },
442 AttrError::UnknownMetaItem(
443 pprust::path_to_string(&mi.path),
451 NestedMetaItem::Literal(lit) => {
455 AttrError::UnsupportedLiteral(
456 "unsupported literal",
465 match (feature, since) {
466 (Some(feature), Some(since)) => {
467 stab = Some(Stability {
473 const_stability: None,
475 allow_const_fn_ptr: false,
479 handle_errors(sess, attr.span, AttrError::MissingFeature);
483 handle_errors(sess, attr.span, AttrError::MissingSince);
493 // Merge the deprecation info into the stability info
494 if let Some(rustc_depr) = rustc_depr {
495 if let Some(ref mut stab) = stab {
496 stab.rustc_depr = Some(rustc_depr);
498 span_err!(diagnostic, item_sp, E0549,
499 "rustc_deprecated attribute must be paired with \
500 either stable or unstable attribute");
504 // Merge the const-unstable info into the stability info
505 if let Some(feature) = rustc_const_unstable {
506 if let Some(ref mut stab) = stab {
507 stab.const_stability = Some(feature);
509 span_err!(diagnostic, item_sp, E0630,
510 "rustc_const_unstable attribute must be paired with \
511 either stable or unstable attribute");
515 // Merge the const-unstable info into the stability info
516 if promotable || allow_const_fn_ptr {
517 if let Some(ref mut stab) = stab {
518 stab.promotable = promotable;
519 stab.allow_const_fn_ptr = allow_const_fn_ptr;
521 span_err!(diagnostic, item_sp, E0717,
522 "rustc_promotable and rustc_allow_const_fn_ptr attributes \
523 must be paired with either stable or unstable attribute");
530 pub fn find_crate_name(attrs: &[Attribute]) -> Option<Symbol> {
531 super::first_attr_value_str_by_name(attrs, sym::crate_name)
534 /// Tests if a cfg-pattern matches the cfg set
535 pub fn cfg_matches(cfg: &ast::MetaItem, sess: &ParseSess, features: Option<&Features>) -> bool {
536 eval_condition(cfg, sess, &mut |cfg| {
537 let gate = find_gated_cfg(|sym| cfg.check_name(sym));
538 if let (Some(feats), Some(gated_cfg)) = (features, gate) {
539 gate_cfg(&gated_cfg, cfg.span, sess, feats);
541 let error = |span, msg| { sess.span_diagnostic.span_err(span, msg); true };
542 if cfg.path.segments.len() != 1 {
543 return error(cfg.path.span, "`cfg` predicate key must be an identifier");
546 MetaItemKind::List(..) => {
547 error(cfg.span, "unexpected parentheses after `cfg` predicate key")
549 MetaItemKind::NameValue(lit) if !lit.kind.is_str() => {
553 AttrError::UnsupportedLiteral(
554 "literal in `cfg` predicate value must be a string",
555 lit.kind.is_bytestr()
560 MetaItemKind::NameValue(..) | MetaItemKind::Word => {
561 let ident = cfg.ident().expect("multi-segment cfg predicate");
562 sess.config.contains(&(ident.name, cfg.value_str()))
568 fn gate_cfg(gated_cfg: &GatedCfg, cfg_span: Span, sess: &ParseSess, features: &Features) {
569 let (cfg, feature, has_feature) = gated_cfg;
570 if !has_feature(features) && !cfg_span.allows_unstable(*feature) {
571 let explain = format!("`cfg({})` is experimental and subject to change", cfg);
572 emit_feature_err(sess, *feature, cfg_span, GateIssue::Language, &explain);
576 /// Evaluate a cfg-like condition (with `any` and `all`), using `eval` to
577 /// evaluate individual items.
578 pub fn eval_condition(
581 eval: &mut impl FnMut(&ast::MetaItem) -> bool,
584 ast::MetaItemKind::List(ref mis) => {
585 for mi in mis.iter() {
586 if !mi.is_meta_item() {
590 AttrError::UnsupportedLiteral(
591 "unsupported literal",
599 // The unwraps below may look dangerous, but we've already asserted
600 // that they won't fail with the loop above.
601 match cfg.name_or_empty() {
602 sym::any => mis.iter().any(|mi| {
603 eval_condition(mi.meta_item().unwrap(), sess, eval)
605 sym::all => mis.iter().all(|mi| {
606 eval_condition(mi.meta_item().unwrap(), sess, eval)
610 span_err!(sess.span_diagnostic, cfg.span, E0536, "expected 1 cfg-pattern");
614 !eval_condition(mis[0].meta_item().unwrap(), sess, eval)
618 sess.span_diagnostic, cfg.span, E0537,
619 "invalid predicate `{}`",
620 pprust::path_to_string(&cfg.path)
626 ast::MetaItemKind::Word | ast::MetaItemKind::NameValue(..) => {
632 #[derive(RustcEncodable, RustcDecodable, Clone, HashStable_Generic)]
633 pub struct Deprecation {
634 pub since: Option<Symbol>,
635 pub note: Option<Symbol>,
638 /// Finds the deprecation attribute. `None` if none exists.
639 pub fn find_deprecation(sess: &ParseSess, attrs: &[Attribute],
640 item_sp: Span) -> Option<Deprecation> {
641 find_deprecation_generic(sess, attrs.iter(), item_sp)
644 fn find_deprecation_generic<'a, I>(sess: &ParseSess,
647 -> Option<Deprecation>
648 where I: Iterator<Item = &'a Attribute>
650 let mut depr: Option<Deprecation> = None;
651 let diagnostic = &sess.span_diagnostic;
653 'outer: for attr in attrs_iter {
654 if !attr.check_name(sym::deprecated) {
659 span_err!(diagnostic, item_sp, E0550, "multiple deprecated attributes");
663 let meta = match attr.meta() {
667 depr = match &meta.kind {
668 MetaItemKind::Word => Some(Deprecation { since: None, note: None }),
669 MetaItemKind::NameValue(..) => {
670 meta.value_str().map(|note| {
671 Deprecation { since: None, note: Some(note) }
674 MetaItemKind::List(list) => {
675 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
680 AttrError::MultipleItem(pprust::path_to_string(&meta.path)),
684 if let Some(v) = meta.value_str() {
688 if let Some(lit) = meta.name_value_literal() {
692 AttrError::UnsupportedLiteral(
693 "literal in `deprecated` \
694 value must be a string",
695 lit.kind.is_bytestr()
699 span_err!(diagnostic, meta.span, E0551, "incorrect meta item");
706 let mut since = None;
710 NestedMetaItem::MetaItem(mi) => {
711 match mi.name_or_empty() {
712 sym::since => if !get(mi, &mut since) { continue 'outer },
713 sym::note => if !get(mi, &mut note) { continue 'outer },
718 AttrError::UnknownMetaItem(
719 pprust::path_to_string(&mi.path),
727 NestedMetaItem::Literal(lit) => {
731 AttrError::UnsupportedLiteral(
732 "item in `deprecated` must be a key/value pair",
741 Some(Deprecation { since, note })
749 #[derive(PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
759 #[derive(Eq, PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone, HashStable_Generic)]
761 SignedInt(ast::IntTy),
762 UnsignedInt(ast::UintTy)
767 pub fn is_signed(self) -> bool {
771 SignedInt(..) => true,
772 UnsignedInt(..) => false
777 /// Parse #[repr(...)] forms.
779 /// Valid repr contents: any of the primitive integral type names (see
780 /// `int_type_of_word`, below) to specify enum discriminant type; `C`, to use
781 /// the same discriminant size that the corresponding C enum would or C
782 /// structure layout, `packed` to remove padding, and `transparent` to elegate representation
783 /// concerns to the only non-ZST field.
784 pub fn find_repr_attrs(sess: &ParseSess, attr: &Attribute) -> Vec<ReprAttr> {
787 let mut acc = Vec::new();
788 let diagnostic = &sess.span_diagnostic;
789 if attr.has_name(sym::repr) {
790 if let Some(items) = attr.meta_item_list() {
793 if !item.is_meta_item() {
797 AttrError::UnsupportedLiteral(
798 "meta item in `repr` must be an identifier",
805 let mut recognised = false;
807 let hint = match item.name_or_empty() {
808 sym::C => Some(ReprC),
809 sym::packed => Some(ReprPacked(1)),
810 sym::simd => Some(ReprSimd),
811 sym::transparent => Some(ReprTransparent),
812 name => int_type_of_word(name).map(ReprInt),
815 if let Some(h) = hint {
819 } else if let Some((name, value)) = item.name_value_literal() {
820 let parse_alignment = |node: &ast::LitKind| -> Result<u32, &'static str> {
821 if let ast::LitKind::Int(literal, ast::LitIntType::Unsuffixed) = node {
822 if literal.is_power_of_two() {
823 // rustc::ty::layout::Align restricts align to <= 2^29
824 if *literal <= 1 << 29 {
827 Err("larger than 2^29")
830 Err("not a power of two")
833 Err("not an unsuffixed integer")
837 let mut literal_error = None;
838 if name == sym::align {
840 match parse_alignment(&value.kind) {
841 Ok(literal) => acc.push(ReprAlign(literal)),
842 Err(message) => literal_error = Some(message)
845 else if name == sym::packed {
847 match parse_alignment(&value.kind) {
848 Ok(literal) => acc.push(ReprPacked(literal)),
849 Err(message) => literal_error = Some(message)
852 if let Some(literal_error) = literal_error {
853 span_err!(diagnostic, item.span(), E0589,
854 "invalid `repr(align)` attribute: {}", literal_error);
857 if let Some(meta_item) = item.meta_item() {
858 if meta_item.check_name(sym::align) {
859 if let MetaItemKind::NameValue(ref value) = meta_item.kind {
861 let mut err = struct_span_err!(diagnostic, item.span(), E0693,
862 "incorrect `repr(align)` attribute format");
864 ast::LitKind::Int(int, ast::LitIntType::Unsuffixed) => {
867 "use parentheses instead",
868 format!("align({})", int),
869 Applicability::MachineApplicable
872 ast::LitKind::Str(s, _) => {
875 "use parentheses instead",
876 format!("align({})", s),
877 Applicability::MachineApplicable
888 // Not a word we recognize
889 span_err!(diagnostic, item.span(), E0552,
890 "unrecognized representation hint");
898 fn int_type_of_word(s: Symbol) -> Option<IntType> {
902 sym::i8 => Some(SignedInt(ast::IntTy::I8)),
903 sym::u8 => Some(UnsignedInt(ast::UintTy::U8)),
904 sym::i16 => Some(SignedInt(ast::IntTy::I16)),
905 sym::u16 => Some(UnsignedInt(ast::UintTy::U16)),
906 sym::i32 => Some(SignedInt(ast::IntTy::I32)),
907 sym::u32 => Some(UnsignedInt(ast::UintTy::U32)),
908 sym::i64 => Some(SignedInt(ast::IntTy::I64)),
909 sym::u64 => Some(UnsignedInt(ast::UintTy::U64)),
910 sym::i128 => Some(SignedInt(ast::IntTy::I128)),
911 sym::u128 => Some(UnsignedInt(ast::UintTy::U128)),
912 sym::isize => Some(SignedInt(ast::IntTy::Isize)),
913 sym::usize => Some(UnsignedInt(ast::UintTy::Usize)),
918 pub enum TransparencyError {
919 UnknownTransparency(Symbol, Span),
920 MultipleTransparencyAttrs(Span, Span),
923 pub fn find_transparency(
924 attrs: &[Attribute], is_legacy: bool
925 ) -> (Transparency, Option<TransparencyError>) {
926 let mut transparency = None;
927 let mut error = None;
929 if attr.check_name(sym::rustc_macro_transparency) {
930 if let Some((_, old_span)) = transparency {
931 error = Some(TransparencyError::MultipleTransparencyAttrs(old_span, attr.span));
933 } else if let Some(value) = attr.value_str() {
934 transparency = Some((match &*value.as_str() {
935 "transparent" => Transparency::Transparent,
936 "semitransparent" => Transparency::SemiTransparent,
937 "opaque" => Transparency::Opaque,
939 error = Some(TransparencyError::UnknownTransparency(value, attr.span));
946 let fallback = if is_legacy { Transparency::SemiTransparent } else { Transparency::Opaque };
947 (transparency.map_or(fallback, |t| t.0), error)