1 //! Parsing and validation of builtin attributes
3 use crate::ast::{self, Attribute, MetaItem, NestedMetaItem};
4 use crate::feature_gate::{Features, GatedCfg};
5 use crate::print::pprust;
6 use crate::sess::ParseSess;
8 use errors::{Applicability, Handler};
9 use std::num::NonZeroU32;
10 use syntax_pos::hygiene::Transparency;
11 use syntax_pos::{symbol::Symbol, symbol::sym, Span};
13 use super::{mark_used, MetaItemKind};
17 UnknownMetaItem(String, &'static [&'static str]),
20 MultipleStabilityLevels,
21 UnsupportedLiteral(&'static str, /* is_bytestr */ bool),
24 /// A template that the attribute input must match.
25 /// Only top-level shape (`#[attr]` vs `#[attr(...)]` vs `#[attr = ...]`) is considered now.
26 #[derive(Clone, Copy)]
27 pub struct AttributeTemplate {
29 pub list: Option<&'static str>,
30 pub name_value_str: Option<&'static str>,
33 impl AttributeTemplate {
34 pub fn only_word() -> Self {
35 Self { word: true, list: None, name_value_str: None }
38 /// Checks that the given meta-item is compatible with this template.
39 pub fn compatible(&self, meta_item_kind: &ast::MetaItemKind) -> bool {
40 match meta_item_kind {
41 ast::MetaItemKind::Word => self.word,
42 ast::MetaItemKind::List(..) => self.list.is_some(),
43 ast::MetaItemKind::NameValue(lit) if lit.kind.is_str() => self.name_value_str.is_some(),
44 ast::MetaItemKind::NameValue(..) => false,
49 fn handle_errors(sess: &ParseSess, span: Span, error: AttrError) {
50 let diag = &sess.span_diagnostic;
52 AttrError::MultipleItem(item) => span_err!(diag, span, E0538,
53 "multiple '{}' items", item),
54 AttrError::UnknownMetaItem(item, expected) => {
55 let expected = expected
57 .map(|name| format!("`{}`", name))
59 struct_span_err!(diag, span, E0541, "unknown meta item '{}'", item)
60 .span_label(span, format!("expected one of {}", expected.join(", ")))
63 AttrError::MissingSince => span_err!(diag, span, E0542, "missing 'since'"),
64 AttrError::MissingFeature => span_err!(diag, span, E0546, "missing 'feature'"),
65 AttrError::MultipleStabilityLevels => span_err!(diag, span, E0544,
66 "multiple stability levels"),
67 AttrError::UnsupportedLiteral(
71 let mut err = struct_span_err!(diag, span, E0565, "{}", msg);
73 if let Ok(lint_str) = sess.source_map().span_to_snippet(span) {
76 "consider removing the prefix",
77 format!("{}", &lint_str[1..]),
78 Applicability::MaybeIncorrect,
87 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
95 #[derive(Clone, RustcEncodable, RustcDecodable)]
96 pub enum OptimizeAttr {
102 #[derive(Copy, Clone, PartialEq)]
103 pub enum UnwindAttr {
108 /// Determine what `#[unwind]` attribute is present in `attrs`, if any.
109 pub fn find_unwind_attr(diagnostic: Option<&Handler>, attrs: &[Attribute]) -> Option<UnwindAttr> {
110 attrs.iter().fold(None, |ia, attr| {
111 if attr.check_name(sym::unwind) {
112 if let Some(meta) = attr.meta() {
113 if let MetaItemKind::List(items) = meta.kind {
114 if items.len() == 1 {
115 if items[0].check_name(sym::allowed) {
116 return Some(UnwindAttr::Allowed);
117 } else if items[0].check_name(sym::aborts) {
118 return Some(UnwindAttr::Aborts);
123 struct_span_err!(d, attr.span, E0633, "malformed `unwind` attribute input")
124 .span_label(attr.span, "invalid argument")
127 "the allowed arguments are `allowed` and `aborts`",
128 (vec!["allowed", "aborts"]).into_iter()
129 .map(|s| format!("#[unwind({})]", s)),
130 Applicability::MachineApplicable,
141 /// Represents the #[stable], #[unstable], #[rustc_{deprecated,const_unstable}] attributes.
142 #[derive(RustcEncodable, RustcDecodable, Copy, Clone, Debug, PartialEq, Eq, Hash)]
143 pub struct Stability {
144 pub level: StabilityLevel,
146 pub rustc_depr: Option<RustcDeprecation>,
147 /// `None` means the function is stable but needs to be a stable const fn, too
148 /// `Some` contains the feature gate required to be able to use the function
150 pub const_stability: Option<Symbol>,
151 /// whether the function has a `#[rustc_promotable]` attribute
152 pub promotable: bool,
153 /// whether the function has a `#[rustc_allow_const_fn_ptr]` attribute
154 pub allow_const_fn_ptr: bool,
157 /// The available stability levels.
158 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Copy, Clone, Debug, Eq, Hash)]
159 pub enum StabilityLevel {
160 // Reason for the current stability level and the relevant rust-lang issue
161 Unstable { reason: Option<Symbol>, issue: Option<NonZeroU32>, is_soft: bool },
162 Stable { since: Symbol },
165 impl StabilityLevel {
166 pub fn is_unstable(&self) -> bool {
167 if let StabilityLevel::Unstable {..} = *self {
173 pub fn is_stable(&self) -> bool {
174 if let StabilityLevel::Stable {..} = *self {
182 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Copy, Clone, Debug, Eq, Hash)]
183 pub struct RustcDeprecation {
186 /// A text snippet used to completely replace any use of the deprecated item in an expression.
187 pub suggestion: Option<Symbol>,
190 /// Checks if `attrs` contains an attribute like `#![feature(feature_name)]`.
191 /// This will not perform any "sanity checks" on the form of the attributes.
192 pub fn contains_feature_attr(attrs: &[Attribute], feature_name: Symbol) -> bool {
193 attrs.iter().any(|item| {
194 item.check_name(sym::feature) &&
195 item.meta_item_list().map(|list| {
196 list.iter().any(|mi| mi.is_word() && mi.check_name(feature_name))
201 /// Collects stability info from all stability attributes in `attrs`.
202 /// Returns `None` if no stability attributes are found.
203 pub fn find_stability(sess: &ParseSess, attrs: &[Attribute],
204 item_sp: Span) -> Option<Stability> {
205 find_stability_generic(sess, attrs.iter(), item_sp)
208 fn find_stability_generic<'a, I>(sess: &ParseSess,
212 where I: Iterator<Item = &'a Attribute>
214 use StabilityLevel::*;
216 let mut stab: Option<Stability> = None;
217 let mut rustc_depr: Option<RustcDeprecation> = None;
218 let mut rustc_const_unstable: Option<Symbol> = None;
219 let mut promotable = false;
220 let mut allow_const_fn_ptr = false;
221 let diagnostic = &sess.span_diagnostic;
223 'outer: for attr in attrs_iter {
225 sym::rustc_deprecated,
226 sym::rustc_const_unstable,
229 sym::rustc_promotable,
230 sym::rustc_allow_const_fn_ptr,
231 ].iter().any(|&s| attr.has_name(s)) {
232 continue // not a stability level
237 let meta = attr.meta();
239 if attr.has_name(sym::rustc_promotable) {
242 if attr.has_name(sym::rustc_allow_const_fn_ptr) {
243 allow_const_fn_ptr = true;
245 // attributes with data
246 else if let Some(MetaItem { kind: MetaItemKind::List(ref metas), .. }) = meta {
247 let meta = meta.as_ref().unwrap();
248 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
253 AttrError::MultipleItem(pprust::path_to_string(&meta.path)),
257 if let Some(v) = meta.value_str() {
261 span_err!(diagnostic, meta.span, E0539, "incorrect meta item");
266 macro_rules! get_meta {
267 ($($name:ident),+) => {
269 let mut $name = None;
272 if let Some(mi) = meta.meta_item() {
273 match mi.name_or_empty() {
275 sym::$name => if !get(mi, &mut $name) { continue 'outer },
278 let expected = &[ $( stringify!($name) ),+ ];
282 AttrError::UnknownMetaItem(
283 pprust::path_to_string(&mi.path),
294 AttrError::UnsupportedLiteral(
295 "unsupported literal",
305 match meta.name_or_empty() {
306 sym::rustc_deprecated => {
307 if rustc_depr.is_some() {
308 span_err!(diagnostic, item_sp, E0540,
309 "multiple rustc_deprecated attributes");
313 get_meta!(since, reason, suggestion);
315 match (since, reason) {
316 (Some(since), Some(reason)) => {
317 rustc_depr = Some(RustcDeprecation {
324 handle_errors(sess, attr.span, AttrError::MissingSince);
328 span_err!(diagnostic, attr.span, E0543, "missing 'reason'");
333 sym::rustc_const_unstable => {
334 if rustc_const_unstable.is_some() {
335 span_err!(diagnostic, item_sp, E0553,
336 "multiple rustc_const_unstable attributes");
341 if let Some(feature) = feature {
342 rustc_const_unstable = Some(feature);
344 span_err!(diagnostic, attr.span, E0629, "missing 'feature'");
350 handle_errors(sess, attr.span, AttrError::MultipleStabilityLevels);
354 let mut feature = None;
355 let mut reason = None;
356 let mut issue = None;
357 let mut is_soft = false;
359 if let Some(mi) = meta.meta_item() {
360 match mi.name_or_empty() {
361 sym::feature => if !get(mi, &mut feature) { continue 'outer },
362 sym::reason => if !get(mi, &mut reason) { continue 'outer },
363 sym::issue => if !get(mi, &mut issue) { continue 'outer },
366 let msg = "`soft` should not have any arguments";
367 sess.span_diagnostic.span_err(mi.span, msg);
375 AttrError::UnknownMetaItem(
376 pprust::path_to_string(&mi.path),
377 &["feature", "reason", "issue", "soft"]
387 AttrError::UnsupportedLiteral(
388 "unsupported literal",
396 match (feature, reason, issue) {
397 (Some(feature), reason, Some(issue)) => {
398 let issue = match &*issue.as_str() {
399 // FIXME(rossmacarthur): remove "0" because "none" should be used
401 "none" | "0" => None,
403 if let Ok(num) = issue.parse() {
416 stab = Some(Stability {
424 const_stability: None,
426 allow_const_fn_ptr: false,
430 handle_errors(sess, attr.span, AttrError::MissingFeature);
434 span_err!(diagnostic, attr.span, E0547, "missing 'issue'");
441 handle_errors(sess, attr.span, AttrError::MultipleStabilityLevels);
445 let mut feature = None;
446 let mut since = None;
449 NestedMetaItem::MetaItem(mi) => {
450 match mi.name_or_empty() {
451 sym::feature => if !get(mi, &mut feature) { continue 'outer },
452 sym::since => if !get(mi, &mut since) { continue 'outer },
457 AttrError::UnknownMetaItem(
458 pprust::path_to_string(&mi.path),
466 NestedMetaItem::Literal(lit) => {
470 AttrError::UnsupportedLiteral(
471 "unsupported literal",
480 match (feature, since) {
481 (Some(feature), Some(since)) => {
482 stab = Some(Stability {
488 const_stability: None,
490 allow_const_fn_ptr: false,
494 handle_errors(sess, attr.span, AttrError::MissingFeature);
498 handle_errors(sess, attr.span, AttrError::MissingSince);
508 // Merge the deprecation info into the stability info
509 if let Some(rustc_depr) = rustc_depr {
510 if let Some(ref mut stab) = stab {
511 stab.rustc_depr = Some(rustc_depr);
513 span_err!(diagnostic, item_sp, E0549,
514 "rustc_deprecated attribute must be paired with \
515 either stable or unstable attribute");
519 // Merge the const-unstable info into the stability info
520 if let Some(feature) = rustc_const_unstable {
521 if let Some(ref mut stab) = stab {
522 stab.const_stability = Some(feature);
524 span_err!(diagnostic, item_sp, E0630,
525 "rustc_const_unstable attribute must be paired with \
526 either stable or unstable attribute");
530 // Merge the const-unstable info into the stability info
531 if promotable || allow_const_fn_ptr {
532 if let Some(ref mut stab) = stab {
533 stab.promotable = promotable;
534 stab.allow_const_fn_ptr = allow_const_fn_ptr;
536 span_err!(diagnostic, item_sp, E0717,
537 "rustc_promotable and rustc_allow_const_fn_ptr attributes \
538 must be paired with either stable or unstable attribute");
545 pub fn find_crate_name(attrs: &[Attribute]) -> Option<Symbol> {
546 super::first_attr_value_str_by_name(attrs, sym::crate_name)
549 /// Tests if a cfg-pattern matches the cfg set
550 pub fn cfg_matches(cfg: &ast::MetaItem, sess: &ParseSess, features: Option<&Features>) -> bool {
551 eval_condition(cfg, sess, &mut |cfg| {
552 if let (Some(feats), Some(gated_cfg)) = (features, GatedCfg::gate(cfg)) {
553 gated_cfg.check_and_emit(sess, feats);
555 let error = |span, msg| { sess.span_diagnostic.span_err(span, msg); true };
556 if cfg.path.segments.len() != 1 {
557 return error(cfg.path.span, "`cfg` predicate key must be an identifier");
560 MetaItemKind::List(..) => {
561 error(cfg.span, "unexpected parentheses after `cfg` predicate key")
563 MetaItemKind::NameValue(lit) if !lit.kind.is_str() => {
567 AttrError::UnsupportedLiteral(
568 "literal in `cfg` predicate value must be a string",
569 lit.kind.is_bytestr()
574 MetaItemKind::NameValue(..) | MetaItemKind::Word => {
575 let ident = cfg.ident().expect("multi-segment cfg predicate");
576 sess.config.contains(&(ident.name, cfg.value_str()))
582 /// Evaluate a cfg-like condition (with `any` and `all`), using `eval` to
583 /// evaluate individual items.
584 pub fn eval_condition<F>(cfg: &ast::MetaItem, sess: &ParseSess, eval: &mut F)
586 where F: FnMut(&ast::MetaItem) -> bool
589 ast::MetaItemKind::List(ref mis) => {
590 for mi in mis.iter() {
591 if !mi.is_meta_item() {
595 AttrError::UnsupportedLiteral(
596 "unsupported literal",
604 // The unwraps below may look dangerous, but we've already asserted
605 // that they won't fail with the loop above.
606 match cfg.name_or_empty() {
607 sym::any => mis.iter().any(|mi| {
608 eval_condition(mi.meta_item().unwrap(), sess, eval)
610 sym::all => mis.iter().all(|mi| {
611 eval_condition(mi.meta_item().unwrap(), sess, eval)
615 span_err!(sess.span_diagnostic, cfg.span, E0536, "expected 1 cfg-pattern");
619 !eval_condition(mis[0].meta_item().unwrap(), sess, eval)
623 sess.span_diagnostic, cfg.span, E0537,
624 "invalid predicate `{}`",
625 pprust::path_to_string(&cfg.path)
631 ast::MetaItemKind::Word | ast::MetaItemKind::NameValue(..) => {
637 #[derive(RustcEncodable, RustcDecodable, Clone)]
638 pub struct Deprecation {
639 pub since: Option<Symbol>,
640 pub note: Option<Symbol>,
643 /// Finds the deprecation attribute. `None` if none exists.
644 pub fn find_deprecation(sess: &ParseSess, attrs: &[Attribute],
645 item_sp: Span) -> Option<Deprecation> {
646 find_deprecation_generic(sess, attrs.iter(), item_sp)
649 fn find_deprecation_generic<'a, I>(sess: &ParseSess,
652 -> Option<Deprecation>
653 where I: Iterator<Item = &'a Attribute>
655 let mut depr: Option<Deprecation> = None;
656 let diagnostic = &sess.span_diagnostic;
658 'outer: for attr in attrs_iter {
659 if !attr.check_name(sym::deprecated) {
664 span_err!(diagnostic, item_sp, E0550, "multiple deprecated attributes");
668 let meta = match attr.meta() {
672 depr = match &meta.kind {
673 MetaItemKind::Word => Some(Deprecation { since: None, note: None }),
674 MetaItemKind::NameValue(..) => {
675 meta.value_str().map(|note| {
676 Deprecation { since: None, note: Some(note) }
679 MetaItemKind::List(list) => {
680 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
685 AttrError::MultipleItem(pprust::path_to_string(&meta.path)),
689 if let Some(v) = meta.value_str() {
693 if let Some(lit) = meta.name_value_literal() {
697 AttrError::UnsupportedLiteral(
698 "literal in `deprecated` \
699 value must be a string",
700 lit.kind.is_bytestr()
704 span_err!(diagnostic, meta.span, E0551, "incorrect meta item");
711 let mut since = None;
715 NestedMetaItem::MetaItem(mi) => {
716 match mi.name_or_empty() {
717 sym::since => if !get(mi, &mut since) { continue 'outer },
718 sym::note => if !get(mi, &mut note) { continue 'outer },
723 AttrError::UnknownMetaItem(
724 pprust::path_to_string(&mi.path),
732 NestedMetaItem::Literal(lit) => {
736 AttrError::UnsupportedLiteral(
737 "item in `deprecated` must be a key/value pair",
746 Some(Deprecation { since, note })
754 #[derive(PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
764 #[derive(Eq, PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
766 SignedInt(ast::IntTy),
767 UnsignedInt(ast::UintTy)
772 pub fn is_signed(self) -> bool {
776 SignedInt(..) => true,
777 UnsignedInt(..) => false
782 /// Parse #[repr(...)] forms.
784 /// Valid repr contents: any of the primitive integral type names (see
785 /// `int_type_of_word`, below) to specify enum discriminant type; `C`, to use
786 /// the same discriminant size that the corresponding C enum would or C
787 /// structure layout, `packed` to remove padding, and `transparent` to elegate representation
788 /// concerns to the only non-ZST field.
789 pub fn find_repr_attrs(sess: &ParseSess, attr: &Attribute) -> Vec<ReprAttr> {
792 let mut acc = Vec::new();
793 let diagnostic = &sess.span_diagnostic;
794 if attr.has_name(sym::repr) {
795 if let Some(items) = attr.meta_item_list() {
798 if !item.is_meta_item() {
802 AttrError::UnsupportedLiteral(
803 "meta item in `repr` must be an identifier",
810 let mut recognised = false;
812 let hint = match item.name_or_empty() {
813 sym::C => Some(ReprC),
814 sym::packed => Some(ReprPacked(1)),
815 sym::simd => Some(ReprSimd),
816 sym::transparent => Some(ReprTransparent),
817 name => int_type_of_word(name).map(ReprInt),
820 if let Some(h) = hint {
824 } else if let Some((name, value)) = item.name_value_literal() {
825 let parse_alignment = |node: &ast::LitKind| -> Result<u32, &'static str> {
826 if let ast::LitKind::Int(literal, ast::LitIntType::Unsuffixed) = node {
827 if literal.is_power_of_two() {
828 // rustc::ty::layout::Align restricts align to <= 2^29
829 if *literal <= 1 << 29 {
832 Err("larger than 2^29")
835 Err("not a power of two")
838 Err("not an unsuffixed integer")
842 let mut literal_error = None;
843 if name == sym::align {
845 match parse_alignment(&value.kind) {
846 Ok(literal) => acc.push(ReprAlign(literal)),
847 Err(message) => literal_error = Some(message)
850 else if name == sym::packed {
852 match parse_alignment(&value.kind) {
853 Ok(literal) => acc.push(ReprPacked(literal)),
854 Err(message) => literal_error = Some(message)
857 if let Some(literal_error) = literal_error {
858 span_err!(diagnostic, item.span(), E0589,
859 "invalid `repr(align)` attribute: {}", literal_error);
862 if let Some(meta_item) = item.meta_item() {
863 if meta_item.check_name(sym::align) {
864 if let MetaItemKind::NameValue(ref value) = meta_item.kind {
866 let mut err = struct_span_err!(diagnostic, item.span(), E0693,
867 "incorrect `repr(align)` attribute format");
869 ast::LitKind::Int(int, ast::LitIntType::Unsuffixed) => {
872 "use parentheses instead",
873 format!("align({})", int),
874 Applicability::MachineApplicable
877 ast::LitKind::Str(s, _) => {
880 "use parentheses instead",
881 format!("align({})", s),
882 Applicability::MachineApplicable
893 // Not a word we recognize
894 span_err!(diagnostic, item.span(), E0552,
895 "unrecognized representation hint");
903 fn int_type_of_word(s: Symbol) -> Option<IntType> {
907 sym::i8 => Some(SignedInt(ast::IntTy::I8)),
908 sym::u8 => Some(UnsignedInt(ast::UintTy::U8)),
909 sym::i16 => Some(SignedInt(ast::IntTy::I16)),
910 sym::u16 => Some(UnsignedInt(ast::UintTy::U16)),
911 sym::i32 => Some(SignedInt(ast::IntTy::I32)),
912 sym::u32 => Some(UnsignedInt(ast::UintTy::U32)),
913 sym::i64 => Some(SignedInt(ast::IntTy::I64)),
914 sym::u64 => Some(UnsignedInt(ast::UintTy::U64)),
915 sym::i128 => Some(SignedInt(ast::IntTy::I128)),
916 sym::u128 => Some(UnsignedInt(ast::UintTy::U128)),
917 sym::isize => Some(SignedInt(ast::IntTy::Isize)),
918 sym::usize => Some(UnsignedInt(ast::UintTy::Usize)),
923 pub enum TransparencyError {
924 UnknownTransparency(Symbol, Span),
925 MultipleTransparencyAttrs(Span, Span),
928 pub fn find_transparency(
929 attrs: &[Attribute], is_legacy: bool
930 ) -> (Transparency, Option<TransparencyError>) {
931 let mut transparency = None;
932 let mut error = None;
934 if attr.check_name(sym::rustc_macro_transparency) {
935 if let Some((_, old_span)) = transparency {
936 error = Some(TransparencyError::MultipleTransparencyAttrs(old_span, attr.span));
938 } else if let Some(value) = attr.value_str() {
939 transparency = Some((match &*value.as_str() {
940 "transparent" => Transparency::Transparent,
941 "semitransparent" => Transparency::SemiTransparent,
942 "opaque" => Transparency::Opaque,
944 error = Some(TransparencyError::UnknownTransparency(value, attr.span));
951 let fallback = if is_legacy { Transparency::SemiTransparent } else { Transparency::Opaque };
952 (transparency.map_or(fallback, |t| t.0), error)