1 //! Parsing and validation of builtin attributes
3 use ast::{self, Attribute, MetaItem, Name, NestedMetaItemKind};
4 use errors::{Applicability, Handler};
5 use feature_gate::{Features, GatedCfg};
7 use syntax_pos::{symbol::Symbol, Span};
9 use super::{list_contains_name, mark_used, MetaItemKind};
13 UnknownMetaItem(Name, &'static [&'static str]),
16 MultipleStabilityLevels,
17 UnsupportedLiteral(&'static str, /* is_bytestr */ bool),
20 fn handle_errors(sess: &ParseSess, span: Span, error: AttrError) {
21 let diag = &sess.span_diagnostic;
23 AttrError::MultipleItem(item) => span_err!(diag, span, E0538,
24 "multiple '{}' items", item),
25 AttrError::UnknownMetaItem(item, expected) => {
26 let expected = expected
28 .map(|name| format!("`{}`", name))
30 struct_span_err!(diag, span, E0541, "unknown meta item '{}'", item)
31 .span_label(span, format!("expected one of {}", expected.join(", ")))
34 AttrError::MissingSince => span_err!(diag, span, E0542, "missing 'since'"),
35 AttrError::MissingFeature => span_err!(diag, span, E0546, "missing 'feature'"),
36 AttrError::MultipleStabilityLevels => span_err!(diag, span, E0544,
37 "multiple stability levels"),
38 AttrError::UnsupportedLiteral(
42 let mut err = struct_span_err!(diag, span, E0565, "{}", msg);
44 if let Ok(lint_str) = sess.source_map().span_to_snippet(span) {
45 err.span_suggestion_with_applicability(
47 "consider removing the prefix",
48 format!("{}", &lint_str[1..]),
49 Applicability::MaybeIncorrect,
58 #[derive(Copy, Clone, Hash, PartialEq, RustcEncodable, RustcDecodable)]
66 #[derive(Copy, Clone, Hash, PartialEq, RustcEncodable, RustcDecodable)]
67 pub enum OptimizeAttr {
73 #[derive(Copy, Clone, PartialEq)]
79 /// Determine what `#[unwind]` attribute is present in `attrs`, if any.
80 pub fn find_unwind_attr(diagnostic: Option<&Handler>, attrs: &[Attribute]) -> Option<UnwindAttr> {
81 let syntax_error = |attr: &Attribute| {
84 span_err!(d, attr.span, E0633, "malformed `#[unwind]` attribute");
89 attrs.iter().fold(None, |ia, attr| {
90 if attr.path != "unwind" {
93 let meta = match attr.meta() {
94 Some(meta) => meta.node,
98 MetaItemKind::Word => {
101 MetaItemKind::List(ref items) => {
103 if items.len() != 1 {
105 } else if list_contains_name(&items[..], "allowed") {
106 Some(UnwindAttr::Allowed)
107 } else if list_contains_name(&items[..], "aborts") {
108 Some(UnwindAttr::Aborts)
118 /// Represents the #[stable], #[unstable], #[rustc_{deprecated,const_unstable}] attributes.
119 #[derive(RustcEncodable, RustcDecodable, Clone, Debug, PartialEq, Eq, Hash)]
120 pub struct Stability {
121 pub level: StabilityLevel,
123 pub rustc_depr: Option<RustcDeprecation>,
124 /// `None` means the function is stable but needs to be a stable const fn, too
125 /// `Some` contains the feature gate required to be able to use the function
127 pub const_stability: Option<Symbol>,
128 /// whether the function has a `#[rustc_promotable]` attribute
129 pub promotable: bool,
132 /// The available stability levels.
133 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Debug, Eq, Hash)]
134 pub enum StabilityLevel {
135 // Reason for the current stability level and the relevant rust-lang issue
136 Unstable { reason: Option<Symbol>, issue: u32 },
137 Stable { since: Symbol },
140 impl StabilityLevel {
141 pub fn is_unstable(&self) -> bool {
142 if let StabilityLevel::Unstable {..} = *self {
148 pub fn is_stable(&self) -> bool {
149 if let StabilityLevel::Stable {..} = *self {
157 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Debug, Eq, Hash)]
158 pub struct RustcDeprecation {
163 /// Check if `attrs` contains an attribute like `#![feature(feature_name)]`.
164 /// This will not perform any "sanity checks" on the form of the attributes.
165 pub fn contains_feature_attr(attrs: &[Attribute], feature_name: &str) -> bool {
166 attrs.iter().any(|item| {
167 item.check_name("feature") &&
168 item.meta_item_list().map(|list| {
169 list.iter().any(|mi| {
170 mi.word().map(|w| w.name() == feature_name)
177 /// Find the first stability attribute. `None` if none exists.
178 pub fn find_stability(sess: &ParseSess, attrs: &[Attribute],
179 item_sp: Span) -> Option<Stability> {
180 find_stability_generic(sess, attrs.iter(), item_sp)
183 fn find_stability_generic<'a, I>(sess: &ParseSess,
187 where I: Iterator<Item = &'a Attribute>
189 use self::StabilityLevel::*;
191 let mut stab: Option<Stability> = None;
192 let mut rustc_depr: Option<RustcDeprecation> = None;
193 let mut rustc_const_unstable: Option<Symbol> = None;
194 let mut promotable = false;
195 let diagnostic = &sess.span_diagnostic;
197 'outer: for attr in attrs_iter {
200 "rustc_const_unstable",
204 ].iter().any(|&s| attr.path == s) {
205 continue // not a stability level
210 let meta = attr.meta();
212 if attr.path == "rustc_promotable" {
215 // attributes with data
216 else if let Some(MetaItem { node: MetaItemKind::List(ref metas), .. }) = meta {
217 let meta = meta.as_ref().unwrap();
218 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
220 handle_errors(sess, meta.span, AttrError::MultipleItem(meta.name()));
223 if let Some(v) = meta.value_str() {
227 span_err!(diagnostic, meta.span, E0539, "incorrect meta item");
232 macro_rules! get_meta {
233 ($($name:ident),+) => {
235 let mut $name = None;
238 if let Some(mi) = meta.meta_item() {
239 match &*mi.name().as_str() {
242 => if !get(mi, &mut $name) { continue 'outer },
245 let expected = &[ $( stringify!($name) ),+ ];
249 AttrError::UnknownMetaItem(mi.name(), expected),
258 AttrError::UnsupportedLiteral(
259 "unsupported literal",
269 match &*meta.name().as_str() {
270 "rustc_deprecated" => {
271 if rustc_depr.is_some() {
272 span_err!(diagnostic, item_sp, E0540,
273 "multiple rustc_deprecated attributes");
277 get_meta!(since, reason);
279 match (since, reason) {
280 (Some(since), Some(reason)) => {
281 rustc_depr = Some(RustcDeprecation {
287 handle_errors(sess, attr.span(), AttrError::MissingSince);
291 span_err!(diagnostic, attr.span(), E0543, "missing 'reason'");
296 "rustc_const_unstable" => {
297 if rustc_const_unstable.is_some() {
298 span_err!(diagnostic, item_sp, E0553,
299 "multiple rustc_const_unstable attributes");
304 if let Some(feature) = feature {
305 rustc_const_unstable = Some(feature);
307 span_err!(diagnostic, attr.span(), E0629, "missing 'feature'");
313 handle_errors(sess, attr.span(), AttrError::MultipleStabilityLevels);
317 let mut feature = None;
318 let mut reason = None;
319 let mut issue = None;
321 if let Some(mi) = meta.meta_item() {
322 match &*mi.name().as_str() {
323 "feature" => if !get(mi, &mut feature) { continue 'outer },
324 "reason" => if !get(mi, &mut reason) { continue 'outer },
325 "issue" => if !get(mi, &mut issue) { continue 'outer },
330 AttrError::UnknownMetaItem(
332 &["feature", "reason", "issue"]
342 AttrError::UnsupportedLiteral(
343 "unsupported literal",
351 match (feature, reason, issue) {
352 (Some(feature), reason, Some(issue)) => {
353 stab = Some(Stability {
357 if let Ok(issue) = issue.as_str().parse() {
360 span_err!(diagnostic, attr.span(), E0545,
361 "incorrect 'issue'");
368 const_stability: None,
373 handle_errors(sess, attr.span(), AttrError::MissingFeature);
377 span_err!(diagnostic, attr.span(), E0547, "missing 'issue'");
384 handle_errors(sess, attr.span(), AttrError::MultipleStabilityLevels);
388 let mut feature = None;
389 let mut since = None;
392 NestedMetaItemKind::MetaItem(mi) => {
393 match &*mi.name().as_str() {
394 "feature" => if !get(mi, &mut feature) { continue 'outer },
395 "since" => if !get(mi, &mut since) { continue 'outer },
400 AttrError::UnknownMetaItem(
401 mi.name(), &["since", "note"],
408 NestedMetaItemKind::Literal(lit) => {
412 AttrError::UnsupportedLiteral(
413 "unsupported literal",
422 match (feature, since) {
423 (Some(feature), Some(since)) => {
424 stab = Some(Stability {
430 const_stability: None,
435 handle_errors(sess, attr.span(), AttrError::MissingFeature);
439 handle_errors(sess, attr.span(), AttrError::MissingSince);
449 // Merge the deprecation info into the stability info
450 if let Some(rustc_depr) = rustc_depr {
451 if let Some(ref mut stab) = stab {
452 stab.rustc_depr = Some(rustc_depr);
454 span_err!(diagnostic, item_sp, E0549,
455 "rustc_deprecated attribute must be paired with \
456 either stable or unstable attribute");
460 // Merge the const-unstable info into the stability info
461 if let Some(feature) = rustc_const_unstable {
462 if let Some(ref mut stab) = stab {
463 stab.const_stability = Some(feature);
465 span_err!(diagnostic, item_sp, E0630,
466 "rustc_const_unstable attribute must be paired with \
467 either stable or unstable attribute");
471 // Merge the const-unstable info into the stability info
473 if let Some(ref mut stab) = stab {
474 stab.promotable = true;
476 span_err!(diagnostic, item_sp, E0717,
477 "rustc_promotable attribute must be paired with \
478 either stable or unstable attribute");
485 pub fn find_crate_name(attrs: &[Attribute]) -> Option<Symbol> {
486 super::first_attr_value_str_by_name(attrs, "crate_name")
489 /// Tests if a cfg-pattern matches the cfg set
490 pub fn cfg_matches(cfg: &ast::MetaItem, sess: &ParseSess, features: Option<&Features>) -> bool {
491 eval_condition(cfg, sess, &mut |cfg| {
492 if let (Some(feats), Some(gated_cfg)) = (features, GatedCfg::gate(cfg)) {
493 gated_cfg.check_and_emit(sess, feats);
495 let error = |span, msg| { sess.span_diagnostic.span_err(span, msg); true };
496 if cfg.ident.segments.len() != 1 {
497 return error(cfg.ident.span, "`cfg` predicate key must be an identifier");
500 MetaItemKind::List(..) => {
501 error(cfg.span, "unexpected parentheses after `cfg` predicate key")
503 MetaItemKind::NameValue(lit) if !lit.node.is_str() => {
507 AttrError::UnsupportedLiteral(
508 "literal in `cfg` predicate value must be a string",
509 lit.node.is_bytestr()
514 MetaItemKind::NameValue(..) | MetaItemKind::Word => {
515 sess.config.contains(&(cfg.name(), cfg.value_str()))
521 /// Evaluate a cfg-like condition (with `any` and `all`), using `eval` to
522 /// evaluate individual items.
523 pub fn eval_condition<F>(cfg: &ast::MetaItem, sess: &ParseSess, eval: &mut F)
525 where F: FnMut(&ast::MetaItem) -> bool
528 ast::MetaItemKind::List(ref mis) => {
529 for mi in mis.iter() {
530 if !mi.is_meta_item() {
534 AttrError::UnsupportedLiteral(
535 "unsupported literal",
543 // The unwraps below may look dangerous, but we've already asserted
544 // that they won't fail with the loop above.
545 match &*cfg.name().as_str() {
546 "any" => mis.iter().any(|mi| {
547 eval_condition(mi.meta_item().unwrap(), sess, eval)
549 "all" => mis.iter().all(|mi| {
550 eval_condition(mi.meta_item().unwrap(), sess, eval)
554 span_err!(sess.span_diagnostic, cfg.span, E0536, "expected 1 cfg-pattern");
558 !eval_condition(mis[0].meta_item().unwrap(), sess, eval)
561 span_err!(sess.span_diagnostic, cfg.span, E0537, "invalid predicate `{}`", p);
566 ast::MetaItemKind::Word | ast::MetaItemKind::NameValue(..) => {
573 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Debug, Eq, Hash)]
574 pub struct Deprecation {
575 pub since: Option<Symbol>,
576 pub note: Option<Symbol>,
579 /// Find the deprecation attribute. `None` if none exists.
580 pub fn find_deprecation(sess: &ParseSess, attrs: &[Attribute],
581 item_sp: Span) -> Option<Deprecation> {
582 find_deprecation_generic(sess, attrs.iter(), item_sp)
585 fn find_deprecation_generic<'a, I>(sess: &ParseSess,
588 -> Option<Deprecation>
589 where I: Iterator<Item = &'a Attribute>
591 let mut depr: Option<Deprecation> = None;
592 let diagnostic = &sess.span_diagnostic;
594 'outer: for attr in attrs_iter {
595 if attr.path != "deprecated" {
602 span_err!(diagnostic, item_sp, E0550, "multiple deprecated attributes");
606 depr = if let Some(metas) = attr.meta_item_list() {
607 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
609 handle_errors(sess, meta.span, AttrError::MultipleItem(meta.name()));
612 if let Some(v) = meta.value_str() {
616 if let Some(lit) = meta.name_value_literal() {
620 AttrError::UnsupportedLiteral(
621 "literal in `deprecated` \
622 value must be a string",
623 lit.node.is_bytestr()
627 span_err!(diagnostic, meta.span, E0551, "incorrect meta item");
634 let mut since = None;
638 NestedMetaItemKind::MetaItem(mi) => {
639 match &*mi.name().as_str() {
640 "since" => if !get(mi, &mut since) { continue 'outer },
641 "note" => if !get(mi, &mut note) { continue 'outer },
646 AttrError::UnknownMetaItem(mi.name(), &["since", "note"]),
652 NestedMetaItemKind::Literal(lit) => {
656 AttrError::UnsupportedLiteral(
657 "item in `deprecated` must be a key/value pair",
666 Some(Deprecation {since: since, note: note})
668 Some(Deprecation{since: None, note: None})
675 #[derive(PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
685 #[derive(Eq, Hash, PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
687 SignedInt(ast::IntTy),
688 UnsignedInt(ast::UintTy)
693 pub fn is_signed(self) -> bool {
694 use self::IntType::*;
697 SignedInt(..) => true,
698 UnsignedInt(..) => false
703 /// Parse #[repr(...)] forms.
705 /// Valid repr contents: any of the primitive integral type names (see
706 /// `int_type_of_word`, below) to specify enum discriminant type; `C`, to use
707 /// the same discriminant size that the corresponding C enum would or C
708 /// structure layout, `packed` to remove padding, and `transparent` to elegate representation
709 /// concerns to the only non-ZST field.
710 pub fn find_repr_attrs(sess: &ParseSess, attr: &Attribute) -> Vec<ReprAttr> {
711 use self::ReprAttr::*;
713 let mut acc = Vec::new();
714 let diagnostic = &sess.span_diagnostic;
715 if attr.path == "repr" {
716 if let Some(items) = attr.meta_item_list() {
719 if !item.is_meta_item() {
723 AttrError::UnsupportedLiteral(
724 "meta item in `repr` must be an identifier",
731 let mut recognised = false;
732 if let Some(mi) = item.word() {
733 let word = &*mi.name().as_str();
734 let hint = match word {
736 "packed" => Some(ReprPacked(1)),
737 "simd" => Some(ReprSimd),
738 "transparent" => Some(ReprTransparent),
739 _ => match int_type_of_word(word) {
740 Some(ity) => Some(ReprInt(ity)),
747 if let Some(h) = hint {
751 } else if let Some((name, value)) = item.name_value_literal() {
752 let parse_alignment = |node: &ast::LitKind| -> Result<u32, &'static str> {
753 if let ast::LitKind::Int(literal, ast::LitIntType::Unsuffixed) = node {
754 if literal.is_power_of_two() {
755 // rustc::ty::layout::Align restricts align to <= 2^29
756 if *literal <= 1 << 29 {
759 Err("larger than 2^29")
762 Err("not a power of two")
765 Err("not an unsuffixed integer")
769 let mut literal_error = None;
772 match parse_alignment(&value.node) {
773 Ok(literal) => acc.push(ReprAlign(literal)),
774 Err(message) => literal_error = Some(message)
777 else if name == "packed" {
779 match parse_alignment(&value.node) {
780 Ok(literal) => acc.push(ReprPacked(literal)),
781 Err(message) => literal_error = Some(message)
784 if let Some(literal_error) = literal_error {
785 span_err!(diagnostic, item.span, E0589,
786 "invalid `repr(align)` attribute: {}", literal_error);
789 if let Some(meta_item) = item.meta_item() {
790 if meta_item.name() == "align" {
791 if let MetaItemKind::NameValue(ref value) = meta_item.node {
793 let mut err = struct_span_err!(diagnostic, item.span, E0693,
794 "incorrect `repr(align)` attribute format");
796 ast::LitKind::Int(int, ast::LitIntType::Unsuffixed) => {
797 err.span_suggestion_with_applicability(
799 "use parentheses instead",
800 format!("align({})", int),
801 Applicability::MachineApplicable
804 ast::LitKind::Str(s, _) => {
805 err.span_suggestion_with_applicability(
807 "use parentheses instead",
808 format!("align({})", s),
809 Applicability::MachineApplicable
820 // Not a word we recognize
821 span_err!(diagnostic, item.span, E0552,
822 "unrecognized representation hint");
830 fn int_type_of_word(s: &str) -> Option<IntType> {
831 use self::IntType::*;
834 "i8" => Some(SignedInt(ast::IntTy::I8)),
835 "u8" => Some(UnsignedInt(ast::UintTy::U8)),
836 "i16" => Some(SignedInt(ast::IntTy::I16)),
837 "u16" => Some(UnsignedInt(ast::UintTy::U16)),
838 "i32" => Some(SignedInt(ast::IntTy::I32)),
839 "u32" => Some(UnsignedInt(ast::UintTy::U32)),
840 "i64" => Some(SignedInt(ast::IntTy::I64)),
841 "u64" => Some(UnsignedInt(ast::UintTy::U64)),
842 "i128" => Some(SignedInt(ast::IntTy::I128)),
843 "u128" => Some(UnsignedInt(ast::UintTy::U128)),
844 "isize" => Some(SignedInt(ast::IntTy::Isize)),
845 "usize" => Some(UnsignedInt(ast::UintTy::Usize)),