1 //! Parsing and validation of builtin attributes
3 use crate::ast::{self, Attribute, MetaItem, Name, NestedMetaItemKind};
4 use crate::errors::{Applicability, Handler};
5 use crate::feature_gate::{Features, GatedCfg};
6 use crate::parse::ParseSess;
8 use syntax_pos::{symbol::Symbol, Span};
10 use super::{list_contains_name, mark_used, MetaItemKind};
14 UnknownMetaItem(Name, &'static [&'static str]),
17 MultipleStabilityLevels,
18 UnsupportedLiteral(&'static str, /* is_bytestr */ bool),
21 fn handle_errors(sess: &ParseSess, span: Span, error: AttrError) {
22 let diag = &sess.span_diagnostic;
24 AttrError::MultipleItem(item) => span_err!(diag, span, E0538,
25 "multiple '{}' items", item),
26 AttrError::UnknownMetaItem(item, expected) => {
27 let expected = expected
29 .map(|name| format!("`{}`", name))
31 struct_span_err!(diag, span, E0541, "unknown meta item '{}'", item)
32 .span_label(span, format!("expected one of {}", expected.join(", ")))
35 AttrError::MissingSince => span_err!(diag, span, E0542, "missing 'since'"),
36 AttrError::MissingFeature => span_err!(diag, span, E0546, "missing 'feature'"),
37 AttrError::MultipleStabilityLevels => span_err!(diag, span, E0544,
38 "multiple stability levels"),
39 AttrError::UnsupportedLiteral(
43 let mut err = struct_span_err!(diag, span, E0565, "{}", msg);
45 if let Ok(lint_str) = sess.source_map().span_to_snippet(span) {
48 "consider removing the prefix",
49 format!("{}", &lint_str[1..]),
50 Applicability::MaybeIncorrect,
59 #[derive(Copy, Clone, Hash, PartialEq, RustcEncodable, RustcDecodable)]
67 #[derive(Copy, Clone, Hash, PartialEq, RustcEncodable, RustcDecodable)]
68 pub enum OptimizeAttr {
74 #[derive(Copy, Clone, PartialEq)]
80 /// Determine what `#[unwind]` attribute is present in `attrs`, if any.
81 pub fn find_unwind_attr(diagnostic: Option<&Handler>, attrs: &[Attribute]) -> Option<UnwindAttr> {
82 let syntax_error = |attr: &Attribute| {
85 span_err!(d, attr.span, E0633, "malformed `#[unwind]` attribute");
90 attrs.iter().fold(None, |ia, attr| {
91 if attr.path != "unwind" {
94 let meta = match attr.meta() {
95 Some(meta) => meta.node,
99 MetaItemKind::Word => {
102 MetaItemKind::List(ref items) => {
104 if items.len() != 1 {
106 } else if list_contains_name(&items[..], "allowed") {
107 Some(UnwindAttr::Allowed)
108 } else if list_contains_name(&items[..], "aborts") {
109 Some(UnwindAttr::Aborts)
119 /// Represents the #[stable], #[unstable], #[rustc_{deprecated,const_unstable}] attributes.
120 #[derive(RustcEncodable, RustcDecodable, Clone, Debug, PartialEq, Eq, Hash)]
121 pub struct Stability {
122 pub level: StabilityLevel,
124 pub rustc_depr: Option<RustcDeprecation>,
125 /// `None` means the function is stable but needs to be a stable const fn, too
126 /// `Some` contains the feature gate required to be able to use the function
128 pub const_stability: Option<Symbol>,
129 /// whether the function has a `#[rustc_promotable]` attribute
130 pub promotable: bool,
133 /// The available stability levels.
134 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Debug, Eq, Hash)]
135 pub enum StabilityLevel {
136 // Reason for the current stability level and the relevant rust-lang issue
137 Unstable { reason: Option<Symbol>, issue: u32 },
138 Stable { since: Symbol },
141 impl StabilityLevel {
142 pub fn is_unstable(&self) -> bool {
143 if let StabilityLevel::Unstable {..} = *self {
149 pub fn is_stable(&self) -> bool {
150 if let StabilityLevel::Stable {..} = *self {
158 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Debug, Eq, Hash)]
159 pub struct RustcDeprecation {
162 /// A text snippet used to completely replace any use of the deprecated item in an expression.
163 pub suggestion: Option<Symbol>,
166 /// Checks if `attrs` contains an attribute like `#![feature(feature_name)]`.
167 /// This will not perform any "sanity checks" on the form of the attributes.
168 pub fn contains_feature_attr(attrs: &[Attribute], feature_name: &str) -> bool {
169 attrs.iter().any(|item| {
170 item.check_name("feature") &&
171 item.meta_item_list().map(|list| {
172 list.iter().any(|mi| {
173 mi.word().map(|w| w.name() == feature_name)
180 /// Finds the first stability attribute. `None` if none exists.
181 pub fn find_stability(sess: &ParseSess, attrs: &[Attribute],
182 item_sp: Span) -> Option<Stability> {
183 find_stability_generic(sess, attrs.iter(), item_sp)
186 fn find_stability_generic<'a, I>(sess: &ParseSess,
190 where I: Iterator<Item = &'a Attribute>
192 use StabilityLevel::*;
194 let mut stab: Option<Stability> = None;
195 let mut rustc_depr: Option<RustcDeprecation> = None;
196 let mut rustc_const_unstable: Option<Symbol> = None;
197 let mut promotable = false;
198 let diagnostic = &sess.span_diagnostic;
200 'outer: for attr in attrs_iter {
203 "rustc_const_unstable",
207 ].iter().any(|&s| attr.path == s) {
208 continue // not a stability level
213 let meta = attr.meta();
215 if attr.path == "rustc_promotable" {
218 // attributes with data
219 else if let Some(MetaItem { node: MetaItemKind::List(ref metas), .. }) = meta {
220 let meta = meta.as_ref().unwrap();
221 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
223 handle_errors(sess, meta.span, AttrError::MultipleItem(meta.name()));
226 if let Some(v) = meta.value_str() {
230 span_err!(diagnostic, meta.span, E0539, "incorrect meta item");
235 macro_rules! get_meta {
236 ($($name:ident),+) => {
238 let mut $name = None;
241 if let Some(mi) = meta.meta_item() {
242 match &*mi.name().as_str() {
245 => if !get(mi, &mut $name) { continue 'outer },
248 let expected = &[ $( stringify!($name) ),+ ];
252 AttrError::UnknownMetaItem(mi.name(), expected),
261 AttrError::UnsupportedLiteral(
262 "unsupported literal",
272 match &*meta.name().as_str() {
273 "rustc_deprecated" => {
274 if rustc_depr.is_some() {
275 span_err!(diagnostic, item_sp, E0540,
276 "multiple rustc_deprecated attributes");
280 get_meta!(since, reason, suggestion);
282 match (since, reason) {
283 (Some(since), Some(reason)) => {
284 rustc_depr = Some(RustcDeprecation {
291 handle_errors(sess, attr.span(), AttrError::MissingSince);
295 span_err!(diagnostic, attr.span(), E0543, "missing 'reason'");
300 "rustc_const_unstable" => {
301 if rustc_const_unstable.is_some() {
302 span_err!(diagnostic, item_sp, E0553,
303 "multiple rustc_const_unstable attributes");
308 if let Some(feature) = feature {
309 rustc_const_unstable = Some(feature);
311 span_err!(diagnostic, attr.span(), E0629, "missing 'feature'");
317 handle_errors(sess, attr.span(), AttrError::MultipleStabilityLevels);
321 let mut feature = None;
322 let mut reason = None;
323 let mut issue = None;
325 if let Some(mi) = meta.meta_item() {
326 match &*mi.name().as_str() {
327 "feature" => if !get(mi, &mut feature) { continue 'outer },
328 "reason" => if !get(mi, &mut reason) { continue 'outer },
329 "issue" => if !get(mi, &mut issue) { continue 'outer },
334 AttrError::UnknownMetaItem(
336 &["feature", "reason", "issue"]
346 AttrError::UnsupportedLiteral(
347 "unsupported literal",
355 match (feature, reason, issue) {
356 (Some(feature), reason, Some(issue)) => {
357 stab = Some(Stability {
361 if let Ok(issue) = issue.as_str().parse() {
364 span_err!(diagnostic, attr.span(), E0545,
365 "incorrect 'issue'");
372 const_stability: None,
377 handle_errors(sess, attr.span(), AttrError::MissingFeature);
381 span_err!(diagnostic, attr.span(), E0547, "missing 'issue'");
388 handle_errors(sess, attr.span(), AttrError::MultipleStabilityLevels);
392 let mut feature = None;
393 let mut since = None;
396 NestedMetaItemKind::MetaItem(mi) => {
397 match &*mi.name().as_str() {
398 "feature" => if !get(mi, &mut feature) { continue 'outer },
399 "since" => if !get(mi, &mut since) { continue 'outer },
404 AttrError::UnknownMetaItem(
405 mi.name(), &["since", "note"],
412 NestedMetaItemKind::Literal(lit) => {
416 AttrError::UnsupportedLiteral(
417 "unsupported literal",
426 match (feature, since) {
427 (Some(feature), Some(since)) => {
428 stab = Some(Stability {
434 const_stability: None,
439 handle_errors(sess, attr.span(), AttrError::MissingFeature);
443 handle_errors(sess, attr.span(), AttrError::MissingSince);
453 // Merge the deprecation info into the stability info
454 if let Some(rustc_depr) = rustc_depr {
455 if let Some(ref mut stab) = stab {
456 stab.rustc_depr = Some(rustc_depr);
458 span_err!(diagnostic, item_sp, E0549,
459 "rustc_deprecated attribute must be paired with \
460 either stable or unstable attribute");
464 // Merge the const-unstable info into the stability info
465 if let Some(feature) = rustc_const_unstable {
466 if let Some(ref mut stab) = stab {
467 stab.const_stability = Some(feature);
469 span_err!(diagnostic, item_sp, E0630,
470 "rustc_const_unstable attribute must be paired with \
471 either stable or unstable attribute");
475 // Merge the const-unstable info into the stability info
477 if let Some(ref mut stab) = stab {
478 stab.promotable = true;
480 span_err!(diagnostic, item_sp, E0717,
481 "rustc_promotable attribute must be paired with \
482 either stable or unstable attribute");
489 pub fn find_crate_name(attrs: &[Attribute]) -> Option<Symbol> {
490 super::first_attr_value_str_by_name(attrs, "crate_name")
493 /// Tests if a cfg-pattern matches the cfg set
494 pub fn cfg_matches(cfg: &ast::MetaItem, sess: &ParseSess, features: Option<&Features>) -> bool {
495 eval_condition(cfg, sess, &mut |cfg| {
496 if let (Some(feats), Some(gated_cfg)) = (features, GatedCfg::gate(cfg)) {
497 gated_cfg.check_and_emit(sess, feats);
499 let error = |span, msg| { sess.span_diagnostic.span_err(span, msg); true };
500 if cfg.ident.segments.len() != 1 {
501 return error(cfg.ident.span, "`cfg` predicate key must be an identifier");
504 MetaItemKind::List(..) => {
505 error(cfg.span, "unexpected parentheses after `cfg` predicate key")
507 MetaItemKind::NameValue(lit) if !lit.node.is_str() => {
511 AttrError::UnsupportedLiteral(
512 "literal in `cfg` predicate value must be a string",
513 lit.node.is_bytestr()
518 MetaItemKind::NameValue(..) | MetaItemKind::Word => {
519 sess.config.contains(&(cfg.name(), cfg.value_str()))
525 /// Evaluate a cfg-like condition (with `any` and `all`), using `eval` to
526 /// evaluate individual items.
527 pub fn eval_condition<F>(cfg: &ast::MetaItem, sess: &ParseSess, eval: &mut F)
529 where F: FnMut(&ast::MetaItem) -> bool
532 ast::MetaItemKind::List(ref mis) => {
533 for mi in mis.iter() {
534 if !mi.is_meta_item() {
538 AttrError::UnsupportedLiteral(
539 "unsupported literal",
547 // The unwraps below may look dangerous, but we've already asserted
548 // that they won't fail with the loop above.
549 match &*cfg.name().as_str() {
550 "any" => mis.iter().any(|mi| {
551 eval_condition(mi.meta_item().unwrap(), sess, eval)
553 "all" => mis.iter().all(|mi| {
554 eval_condition(mi.meta_item().unwrap(), sess, eval)
558 span_err!(sess.span_diagnostic, cfg.span, E0536, "expected 1 cfg-pattern");
562 !eval_condition(mis[0].meta_item().unwrap(), sess, eval)
565 span_err!(sess.span_diagnostic, cfg.span, E0537, "invalid predicate `{}`", p);
570 ast::MetaItemKind::Word | ast::MetaItemKind::NameValue(..) => {
577 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Debug, Eq, Hash)]
578 pub struct Deprecation {
579 pub since: Option<Symbol>,
580 pub note: Option<Symbol>,
583 /// Finds the deprecation attribute. `None` if none exists.
584 pub fn find_deprecation(sess: &ParseSess, attrs: &[Attribute],
585 item_sp: Span) -> Option<Deprecation> {
586 find_deprecation_generic(sess, attrs.iter(), item_sp)
589 fn find_deprecation_generic<'a, I>(sess: &ParseSess,
592 -> Option<Deprecation>
593 where I: Iterator<Item = &'a Attribute>
595 let mut depr: Option<Deprecation> = None;
596 let diagnostic = &sess.span_diagnostic;
598 'outer: for attr in attrs_iter {
599 if !attr.check_name("deprecated") {
604 span_err!(diagnostic, item_sp, E0550, "multiple deprecated attributes");
608 let meta = attr.meta().unwrap();
609 depr = match &meta.node {
610 MetaItemKind::Word => Some(Deprecation { since: None, note: None }),
611 MetaItemKind::NameValue(..) => {
612 meta.value_str().map(|note| {
613 Deprecation { since: None, note: Some(note) }
616 MetaItemKind::List(list) => {
617 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
619 handle_errors(sess, meta.span, AttrError::MultipleItem(meta.name()));
622 if let Some(v) = meta.value_str() {
626 if let Some(lit) = meta.name_value_literal() {
630 AttrError::UnsupportedLiteral(
631 "literal in `deprecated` \
632 value must be a string",
633 lit.node.is_bytestr()
637 span_err!(diagnostic, meta.span, E0551, "incorrect meta item");
644 let mut since = None;
648 NestedMetaItemKind::MetaItem(mi) => {
649 match &*mi.name().as_str() {
650 "since" => if !get(mi, &mut since) { continue 'outer },
651 "note" => if !get(mi, &mut note) { continue 'outer },
656 AttrError::UnknownMetaItem(mi.name(), &["since", "note"]),
662 NestedMetaItemKind::Literal(lit) => {
666 AttrError::UnsupportedLiteral(
667 "item in `deprecated` must be a key/value pair",
676 Some(Deprecation { since, note })
684 #[derive(PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
694 #[derive(Eq, Hash, PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
696 SignedInt(ast::IntTy),
697 UnsignedInt(ast::UintTy)
702 pub fn is_signed(self) -> bool {
706 SignedInt(..) => true,
707 UnsignedInt(..) => false
712 /// Parse #[repr(...)] forms.
714 /// Valid repr contents: any of the primitive integral type names (see
715 /// `int_type_of_word`, below) to specify enum discriminant type; `C`, to use
716 /// the same discriminant size that the corresponding C enum would or C
717 /// structure layout, `packed` to remove padding, and `transparent` to elegate representation
718 /// concerns to the only non-ZST field.
719 pub fn find_repr_attrs(sess: &ParseSess, attr: &Attribute) -> Vec<ReprAttr> {
722 let mut acc = Vec::new();
723 let diagnostic = &sess.span_diagnostic;
724 if attr.path == "repr" {
725 if let Some(items) = attr.meta_item_list() {
728 if !item.is_meta_item() {
732 AttrError::UnsupportedLiteral(
733 "meta item in `repr` must be an identifier",
740 let mut recognised = false;
741 if let Some(mi) = item.word() {
742 let word = &*mi.name().as_str();
743 let hint = match word {
745 "packed" => Some(ReprPacked(1)),
746 "simd" => Some(ReprSimd),
747 "transparent" => Some(ReprTransparent),
748 _ => match int_type_of_word(word) {
749 Some(ity) => Some(ReprInt(ity)),
756 if let Some(h) = hint {
760 } else if let Some((name, value)) = item.name_value_literal() {
761 let parse_alignment = |node: &ast::LitKind| -> Result<u32, &'static str> {
762 if let ast::LitKind::Int(literal, ast::LitIntType::Unsuffixed) = node {
763 if literal.is_power_of_two() {
764 // rustc::ty::layout::Align restricts align to <= 2^29
765 if *literal <= 1 << 29 {
768 Err("larger than 2^29")
771 Err("not a power of two")
774 Err("not an unsuffixed integer")
778 let mut literal_error = None;
781 match parse_alignment(&value.node) {
782 Ok(literal) => acc.push(ReprAlign(literal)),
783 Err(message) => literal_error = Some(message)
786 else if name == "packed" {
788 match parse_alignment(&value.node) {
789 Ok(literal) => acc.push(ReprPacked(literal)),
790 Err(message) => literal_error = Some(message)
793 if let Some(literal_error) = literal_error {
794 span_err!(diagnostic, item.span, E0589,
795 "invalid `repr(align)` attribute: {}", literal_error);
798 if let Some(meta_item) = item.meta_item() {
799 if meta_item.name() == "align" {
800 if let MetaItemKind::NameValue(ref value) = meta_item.node {
802 let mut err = struct_span_err!(diagnostic, item.span, E0693,
803 "incorrect `repr(align)` attribute format");
805 ast::LitKind::Int(int, ast::LitIntType::Unsuffixed) => {
808 "use parentheses instead",
809 format!("align({})", int),
810 Applicability::MachineApplicable
813 ast::LitKind::Str(s, _) => {
816 "use parentheses instead",
817 format!("align({})", s),
818 Applicability::MachineApplicable
829 // Not a word we recognize
830 span_err!(diagnostic, item.span, E0552,
831 "unrecognized representation hint");
839 fn int_type_of_word(s: &str) -> Option<IntType> {
843 "i8" => Some(SignedInt(ast::IntTy::I8)),
844 "u8" => Some(UnsignedInt(ast::UintTy::U8)),
845 "i16" => Some(SignedInt(ast::IntTy::I16)),
846 "u16" => Some(UnsignedInt(ast::UintTy::U16)),
847 "i32" => Some(SignedInt(ast::IntTy::I32)),
848 "u32" => Some(UnsignedInt(ast::UintTy::U32)),
849 "i64" => Some(SignedInt(ast::IntTy::I64)),
850 "u64" => Some(UnsignedInt(ast::UintTy::U64)),
851 "i128" => Some(SignedInt(ast::IntTy::I128)),
852 "u128" => Some(UnsignedInt(ast::UintTy::U128)),
853 "isize" => Some(SignedInt(ast::IntTy::Isize)),
854 "usize" => Some(UnsignedInt(ast::UintTy::Usize)),