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) {
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 {
161 /// A text snippet used to completely replace any use of the deprecated item in an expression.
162 pub suggestion: Option<Symbol>,
165 /// Check if `attrs` contains an attribute like `#![feature(feature_name)]`.
166 /// This will not perform any "sanity checks" on the form of the attributes.
167 pub fn contains_feature_attr(attrs: &[Attribute], feature_name: &str) -> bool {
168 attrs.iter().any(|item| {
169 item.check_name("feature") &&
170 item.meta_item_list().map(|list| {
171 list.iter().any(|mi| {
172 mi.word().map(|w| w.name() == feature_name)
179 /// Find the first stability attribute. `None` if none exists.
180 pub fn find_stability(sess: &ParseSess, attrs: &[Attribute],
181 item_sp: Span) -> Option<Stability> {
182 find_stability_generic(sess, attrs.iter(), item_sp)
185 fn find_stability_generic<'a, I>(sess: &ParseSess,
189 where I: Iterator<Item = &'a Attribute>
191 use self::StabilityLevel::*;
193 let mut stab: Option<Stability> = None;
194 let mut rustc_depr: Option<RustcDeprecation> = None;
195 let mut rustc_const_unstable: Option<Symbol> = None;
196 let mut promotable = false;
197 let diagnostic = &sess.span_diagnostic;
199 'outer: for attr in attrs_iter {
202 "rustc_const_unstable",
206 ].iter().any(|&s| attr.path == s) {
207 continue // not a stability level
212 let meta = attr.meta();
214 if attr.path == "rustc_promotable" {
217 // attributes with data
218 else if let Some(MetaItem { node: MetaItemKind::List(ref metas), .. }) = meta {
219 let meta = meta.as_ref().unwrap();
220 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
222 handle_errors(sess, meta.span, AttrError::MultipleItem(meta.name()));
225 if let Some(v) = meta.value_str() {
229 span_err!(diagnostic, meta.span, E0539, "incorrect meta item");
234 macro_rules! get_meta {
235 ($($name:ident),+) => {
237 let mut $name = None;
240 if let Some(mi) = meta.meta_item() {
241 match &*mi.name().as_str() {
244 => if !get(mi, &mut $name) { continue 'outer },
247 let expected = &[ $( stringify!($name) ),+ ];
251 AttrError::UnknownMetaItem(mi.name(), expected),
260 AttrError::UnsupportedLiteral(
261 "unsupported literal",
271 match &*meta.name().as_str() {
272 "rustc_deprecated" => {
273 if rustc_depr.is_some() {
274 span_err!(diagnostic, item_sp, E0540,
275 "multiple rustc_deprecated attributes");
279 get_meta!(since, reason, suggestion);
281 match (since, reason) {
282 (Some(since), Some(reason)) => {
283 rustc_depr = Some(RustcDeprecation {
290 handle_errors(sess, attr.span(), AttrError::MissingSince);
294 span_err!(diagnostic, attr.span(), E0543, "missing 'reason'");
299 "rustc_const_unstable" => {
300 if rustc_const_unstable.is_some() {
301 span_err!(diagnostic, item_sp, E0553,
302 "multiple rustc_const_unstable attributes");
307 if let Some(feature) = feature {
308 rustc_const_unstable = Some(feature);
310 span_err!(diagnostic, attr.span(), E0629, "missing 'feature'");
316 handle_errors(sess, attr.span(), AttrError::MultipleStabilityLevels);
320 let mut feature = None;
321 let mut reason = None;
322 let mut issue = None;
324 if let Some(mi) = meta.meta_item() {
325 match &*mi.name().as_str() {
326 "feature" => if !get(mi, &mut feature) { continue 'outer },
327 "reason" => if !get(mi, &mut reason) { continue 'outer },
328 "issue" => if !get(mi, &mut issue) { continue 'outer },
333 AttrError::UnknownMetaItem(
335 &["feature", "reason", "issue"]
345 AttrError::UnsupportedLiteral(
346 "unsupported literal",
354 match (feature, reason, issue) {
355 (Some(feature), reason, Some(issue)) => {
356 stab = Some(Stability {
360 if let Ok(issue) = issue.as_str().parse() {
363 span_err!(diagnostic, attr.span(), E0545,
364 "incorrect 'issue'");
371 const_stability: None,
376 handle_errors(sess, attr.span(), AttrError::MissingFeature);
380 span_err!(diagnostic, attr.span(), E0547, "missing 'issue'");
387 handle_errors(sess, attr.span(), AttrError::MultipleStabilityLevels);
391 let mut feature = None;
392 let mut since = None;
395 NestedMetaItemKind::MetaItem(mi) => {
396 match &*mi.name().as_str() {
397 "feature" => if !get(mi, &mut feature) { continue 'outer },
398 "since" => if !get(mi, &mut since) { continue 'outer },
403 AttrError::UnknownMetaItem(
404 mi.name(), &["since", "note"],
411 NestedMetaItemKind::Literal(lit) => {
415 AttrError::UnsupportedLiteral(
416 "unsupported literal",
425 match (feature, since) {
426 (Some(feature), Some(since)) => {
427 stab = Some(Stability {
433 const_stability: None,
438 handle_errors(sess, attr.span(), AttrError::MissingFeature);
442 handle_errors(sess, attr.span(), AttrError::MissingSince);
452 // Merge the deprecation info into the stability info
453 if let Some(rustc_depr) = rustc_depr {
454 if let Some(ref mut stab) = stab {
455 stab.rustc_depr = Some(rustc_depr);
457 span_err!(diagnostic, item_sp, E0549,
458 "rustc_deprecated attribute must be paired with \
459 either stable or unstable attribute");
463 // Merge the const-unstable info into the stability info
464 if let Some(feature) = rustc_const_unstable {
465 if let Some(ref mut stab) = stab {
466 stab.const_stability = Some(feature);
468 span_err!(diagnostic, item_sp, E0630,
469 "rustc_const_unstable attribute must be paired with \
470 either stable or unstable attribute");
474 // Merge the const-unstable info into the stability info
476 if let Some(ref mut stab) = stab {
477 stab.promotable = true;
479 span_err!(diagnostic, item_sp, E0717,
480 "rustc_promotable attribute must be paired with \
481 either stable or unstable attribute");
488 pub fn find_crate_name(attrs: &[Attribute]) -> Option<Symbol> {
489 super::first_attr_value_str_by_name(attrs, "crate_name")
492 /// Tests if a cfg-pattern matches the cfg set
493 pub fn cfg_matches(cfg: &ast::MetaItem, sess: &ParseSess, features: Option<&Features>) -> bool {
494 eval_condition(cfg, sess, &mut |cfg| {
495 if let (Some(feats), Some(gated_cfg)) = (features, GatedCfg::gate(cfg)) {
496 gated_cfg.check_and_emit(sess, feats);
498 let error = |span, msg| { sess.span_diagnostic.span_err(span, msg); true };
499 if cfg.ident.segments.len() != 1 {
500 return error(cfg.ident.span, "`cfg` predicate key must be an identifier");
503 MetaItemKind::List(..) => {
504 error(cfg.span, "unexpected parentheses after `cfg` predicate key")
506 MetaItemKind::NameValue(lit) if !lit.node.is_str() => {
510 AttrError::UnsupportedLiteral(
511 "literal in `cfg` predicate value must be a string",
512 lit.node.is_bytestr()
517 MetaItemKind::NameValue(..) | MetaItemKind::Word => {
518 sess.config.contains(&(cfg.name(), cfg.value_str()))
524 /// Evaluate a cfg-like condition (with `any` and `all`), using `eval` to
525 /// evaluate individual items.
526 pub fn eval_condition<F>(cfg: &ast::MetaItem, sess: &ParseSess, eval: &mut F)
528 where F: FnMut(&ast::MetaItem) -> bool
531 ast::MetaItemKind::List(ref mis) => {
532 for mi in mis.iter() {
533 if !mi.is_meta_item() {
537 AttrError::UnsupportedLiteral(
538 "unsupported literal",
546 // The unwraps below may look dangerous, but we've already asserted
547 // that they won't fail with the loop above.
548 match &*cfg.name().as_str() {
549 "any" => mis.iter().any(|mi| {
550 eval_condition(mi.meta_item().unwrap(), sess, eval)
552 "all" => mis.iter().all(|mi| {
553 eval_condition(mi.meta_item().unwrap(), sess, eval)
557 span_err!(sess.span_diagnostic, cfg.span, E0536, "expected 1 cfg-pattern");
561 !eval_condition(mis[0].meta_item().unwrap(), sess, eval)
564 span_err!(sess.span_diagnostic, cfg.span, E0537, "invalid predicate `{}`", p);
569 ast::MetaItemKind::Word | ast::MetaItemKind::NameValue(..) => {
576 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Debug, Eq, Hash)]
577 pub struct Deprecation {
578 pub since: Option<Symbol>,
579 pub note: Option<Symbol>,
582 /// Find the deprecation attribute. `None` if none exists.
583 pub fn find_deprecation(sess: &ParseSess, attrs: &[Attribute],
584 item_sp: Span) -> Option<Deprecation> {
585 find_deprecation_generic(sess, attrs.iter(), item_sp)
588 fn find_deprecation_generic<'a, I>(sess: &ParseSess,
591 -> Option<Deprecation>
592 where I: Iterator<Item = &'a Attribute>
594 let mut depr: Option<Deprecation> = None;
595 let diagnostic = &sess.span_diagnostic;
597 'outer: for attr in attrs_iter {
598 if attr.path != "deprecated" {
605 span_err!(diagnostic, item_sp, E0550, "multiple deprecated attributes");
609 depr = if let Some(metas) = attr.meta_item_list() {
610 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
612 handle_errors(sess, meta.span, AttrError::MultipleItem(meta.name()));
615 if let Some(v) = meta.value_str() {
619 if let Some(lit) = meta.name_value_literal() {
623 AttrError::UnsupportedLiteral(
624 "literal in `deprecated` \
625 value must be a string",
626 lit.node.is_bytestr()
630 span_err!(diagnostic, meta.span, E0551, "incorrect meta item");
637 let mut since = None;
641 NestedMetaItemKind::MetaItem(mi) => {
642 match &*mi.name().as_str() {
643 "since" => if !get(mi, &mut since) { continue 'outer },
644 "note" => if !get(mi, &mut note) { continue 'outer },
649 AttrError::UnknownMetaItem(mi.name(), &["since", "note"]),
655 NestedMetaItemKind::Literal(lit) => {
659 AttrError::UnsupportedLiteral(
660 "item in `deprecated` must be a key/value pair",
669 Some(Deprecation {since: since, note: note})
671 Some(Deprecation{since: None, note: None})
678 #[derive(PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
688 #[derive(Eq, Hash, PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
690 SignedInt(ast::IntTy),
691 UnsignedInt(ast::UintTy)
696 pub fn is_signed(self) -> bool {
697 use self::IntType::*;
700 SignedInt(..) => true,
701 UnsignedInt(..) => false
706 /// Parse #[repr(...)] forms.
708 /// Valid repr contents: any of the primitive integral type names (see
709 /// `int_type_of_word`, below) to specify enum discriminant type; `C`, to use
710 /// the same discriminant size that the corresponding C enum would or C
711 /// structure layout, `packed` to remove padding, and `transparent` to elegate representation
712 /// concerns to the only non-ZST field.
713 pub fn find_repr_attrs(sess: &ParseSess, attr: &Attribute) -> Vec<ReprAttr> {
714 use self::ReprAttr::*;
716 let mut acc = Vec::new();
717 let diagnostic = &sess.span_diagnostic;
718 if attr.path == "repr" {
719 if let Some(items) = attr.meta_item_list() {
722 if !item.is_meta_item() {
726 AttrError::UnsupportedLiteral(
727 "meta item in `repr` must be an identifier",
734 let mut recognised = false;
735 if let Some(mi) = item.word() {
736 let word = &*mi.name().as_str();
737 let hint = match word {
739 "packed" => Some(ReprPacked(1)),
740 "simd" => Some(ReprSimd),
741 "transparent" => Some(ReprTransparent),
742 _ => match int_type_of_word(word) {
743 Some(ity) => Some(ReprInt(ity)),
750 if let Some(h) = hint {
754 } else if let Some((name, value)) = item.name_value_literal() {
755 let parse_alignment = |node: &ast::LitKind| -> Result<u32, &'static str> {
756 if let ast::LitKind::Int(literal, ast::LitIntType::Unsuffixed) = node {
757 if literal.is_power_of_two() {
758 // rustc::ty::layout::Align restricts align to <= 2^29
759 if *literal <= 1 << 29 {
762 Err("larger than 2^29")
765 Err("not a power of two")
768 Err("not an unsuffixed integer")
772 let mut literal_error = None;
775 match parse_alignment(&value.node) {
776 Ok(literal) => acc.push(ReprAlign(literal)),
777 Err(message) => literal_error = Some(message)
780 else if name == "packed" {
782 match parse_alignment(&value.node) {
783 Ok(literal) => acc.push(ReprPacked(literal)),
784 Err(message) => literal_error = Some(message)
787 if let Some(literal_error) = literal_error {
788 span_err!(diagnostic, item.span, E0589,
789 "invalid `repr(align)` attribute: {}", literal_error);
792 if let Some(meta_item) = item.meta_item() {
793 if meta_item.name() == "align" {
794 if let MetaItemKind::NameValue(ref value) = meta_item.node {
796 let mut err = struct_span_err!(diagnostic, item.span, E0693,
797 "incorrect `repr(align)` attribute format");
799 ast::LitKind::Int(int, ast::LitIntType::Unsuffixed) => {
802 "use parentheses instead",
803 format!("align({})", int),
804 Applicability::MachineApplicable
807 ast::LitKind::Str(s, _) => {
810 "use parentheses instead",
811 format!("align({})", s),
812 Applicability::MachineApplicable
823 // Not a word we recognize
824 span_err!(diagnostic, item.span, E0552,
825 "unrecognized representation hint");
833 fn int_type_of_word(s: &str) -> Option<IntType> {
834 use self::IntType::*;
837 "i8" => Some(SignedInt(ast::IntTy::I8)),
838 "u8" => Some(UnsignedInt(ast::UintTy::U8)),
839 "i16" => Some(SignedInt(ast::IntTy::I16)),
840 "u16" => Some(UnsignedInt(ast::UintTy::U16)),
841 "i32" => Some(SignedInt(ast::IntTy::I32)),
842 "u32" => Some(UnsignedInt(ast::UintTy::U32)),
843 "i64" => Some(SignedInt(ast::IntTy::I64)),
844 "u64" => Some(UnsignedInt(ast::UintTy::U64)),
845 "i128" => Some(SignedInt(ast::IntTy::I128)),
846 "u128" => Some(UnsignedInt(ast::UintTy::U128)),
847 "isize" => Some(SignedInt(ast::IntTy::Isize)),
848 "usize" => Some(UnsignedInt(ast::UintTy::Usize)),