1 // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Parsing and validation of builtin attributes
13 use ast::{self, Attribute, MetaItem, Name, NestedMetaItemKind};
14 use errors::{Applicability, Handler};
15 use feature_gate::{Features, GatedCfg};
17 use syntax_pos::{symbol::Symbol, Span};
19 use super::{list_contains_name, mark_used, MetaItemKind};
23 UnknownMetaItem(Name, &'static [&'static str]),
26 MultipleStabilityLevels,
30 fn handle_errors(diag: &Handler, span: Span, error: AttrError) {
32 AttrError::MultipleItem(item) => span_err!(diag, span, E0538,
33 "multiple '{}' items", item),
34 AttrError::UnknownMetaItem(item, expected) => {
35 let expected = expected
37 .map(|name| format!("`{}`", name))
39 struct_span_err!(diag, span, E0541, "unknown meta item '{}'", item)
40 .span_label(span, format!("expected one of {}", expected.join(", ")))
43 AttrError::MissingSince => span_err!(diag, span, E0542, "missing 'since'"),
44 AttrError::MissingFeature => span_err!(diag, span, E0546, "missing 'feature'"),
45 AttrError::MultipleStabilityLevels => span_err!(diag, span, E0544,
46 "multiple stability levels"),
47 AttrError::UnsupportedLiteral => span_err!(diag, span, E0565, "unsupported literal"),
51 #[derive(Copy, Clone, Hash, PartialEq, RustcEncodable, RustcDecodable)]
59 #[derive(Copy, Clone, PartialEq)]
65 /// Determine what `#[unwind]` attribute is present in `attrs`, if any.
66 pub fn find_unwind_attr(diagnostic: Option<&Handler>, attrs: &[Attribute]) -> Option<UnwindAttr> {
67 let syntax_error = |attr: &Attribute| {
70 span_err!(d, attr.span, E0633, "malformed `#[unwind]` attribute");
75 attrs.iter().fold(None, |ia, attr| {
76 if attr.path != "unwind" {
79 let meta = match attr.meta() {
80 Some(meta) => meta.node,
84 MetaItemKind::Word => {
87 MetaItemKind::List(ref items) => {
91 } else if list_contains_name(&items[..], "allowed") {
92 Some(UnwindAttr::Allowed)
93 } else if list_contains_name(&items[..], "aborts") {
94 Some(UnwindAttr::Aborts)
104 /// Represents the #[stable], #[unstable], #[rustc_{deprecated,const_unstable}] attributes.
105 #[derive(RustcEncodable, RustcDecodable, Clone, Debug, PartialEq, Eq, Hash)]
106 pub struct Stability {
107 pub level: StabilityLevel,
109 pub rustc_depr: Option<RustcDeprecation>,
110 pub rustc_const_unstable: Option<RustcConstUnstable>,
113 /// The available stability levels.
114 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Debug, Eq, Hash)]
115 pub enum StabilityLevel {
116 // Reason for the current stability level and the relevant rust-lang issue
117 Unstable { reason: Option<Symbol>, issue: u32 },
118 Stable { since: Symbol },
121 impl StabilityLevel {
122 pub fn is_unstable(&self) -> bool {
123 if let StabilityLevel::Unstable {..} = *self {
129 pub fn is_stable(&self) -> bool {
130 if let StabilityLevel::Stable {..} = *self {
138 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Debug, Eq, Hash)]
139 pub struct RustcDeprecation {
144 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Debug, Eq, Hash)]
145 pub struct RustcConstUnstable {
149 /// Check if `attrs` contains an attribute like `#![feature(feature_name)]`.
150 /// This will not perform any "sanity checks" on the form of the attributes.
151 pub fn contains_feature_attr(attrs: &[Attribute], feature_name: &str) -> bool {
152 attrs.iter().any(|item| {
153 item.check_name("feature") &&
154 item.meta_item_list().map(|list| {
155 list.iter().any(|mi| {
156 mi.word().map(|w| w.name() == feature_name)
163 /// Find the first stability attribute. `None` if none exists.
164 pub fn find_stability(diagnostic: &Handler, attrs: &[Attribute],
165 item_sp: Span) -> Option<Stability> {
166 find_stability_generic(diagnostic, attrs.iter(), item_sp)
169 fn find_stability_generic<'a, I>(diagnostic: &Handler,
173 where I: Iterator<Item = &'a Attribute>
175 use self::StabilityLevel::*;
177 let mut stab: Option<Stability> = None;
178 let mut rustc_depr: Option<RustcDeprecation> = None;
179 let mut rustc_const_unstable: Option<RustcConstUnstable> = None;
181 'outer: for attr in attrs_iter {
184 "rustc_const_unstable",
187 ].iter().any(|&s| attr.path == s) {
188 continue // not a stability level
193 let meta = attr.meta();
194 if let Some(MetaItem { node: MetaItemKind::List(ref metas), .. }) = meta {
195 let meta = meta.as_ref().unwrap();
196 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
198 handle_errors(diagnostic, meta.span, AttrError::MultipleItem(meta.name()));
201 if let Some(v) = meta.value_str() {
205 span_err!(diagnostic, meta.span, E0539, "incorrect meta item");
210 macro_rules! get_meta {
211 ($($name:ident),+) => {
213 let mut $name = None;
216 if let Some(mi) = meta.meta_item() {
217 match &*mi.name().as_str() {
220 => if !get(mi, &mut $name) { continue 'outer },
223 let expected = &[ $( stringify!($name) ),+ ];
227 AttrError::UnknownMetaItem(mi.name(), expected));
232 handle_errors(diagnostic, meta.span, AttrError::UnsupportedLiteral);
239 match &*meta.name().as_str() {
240 "rustc_deprecated" => {
241 if rustc_depr.is_some() {
242 span_err!(diagnostic, item_sp, E0540,
243 "multiple rustc_deprecated attributes");
247 get_meta!(since, reason);
249 match (since, reason) {
250 (Some(since), Some(reason)) => {
251 rustc_depr = Some(RustcDeprecation {
257 handle_errors(diagnostic, attr.span(), AttrError::MissingSince);
261 span_err!(diagnostic, attr.span(), E0543, "missing 'reason'");
266 "rustc_const_unstable" => {
267 if rustc_const_unstable.is_some() {
268 span_err!(diagnostic, item_sp, E0553,
269 "multiple rustc_const_unstable attributes");
274 if let Some(feature) = feature {
275 rustc_const_unstable = Some(RustcConstUnstable {
279 span_err!(diagnostic, attr.span(), E0629, "missing 'feature'");
285 handle_errors(diagnostic, attr.span(), AttrError::MultipleStabilityLevels);
289 let mut feature = None;
290 let mut reason = None;
291 let mut issue = None;
293 if let Some(mi) = meta.meta_item() {
294 match &*mi.name().as_str() {
295 "feature" => if !get(mi, &mut feature) { continue 'outer },
296 "reason" => if !get(mi, &mut reason) { continue 'outer },
297 "issue" => if !get(mi, &mut issue) { continue 'outer },
302 AttrError::UnknownMetaItem(
304 &["feature", "reason", "issue"]
311 handle_errors(diagnostic, meta.span, AttrError::UnsupportedLiteral);
316 match (feature, reason, issue) {
317 (Some(feature), reason, Some(issue)) => {
318 stab = Some(Stability {
322 if let Ok(issue) = issue.as_str().parse() {
325 span_err!(diagnostic, attr.span(), E0545,
326 "incorrect 'issue'");
333 rustc_const_unstable: None,
337 handle_errors(diagnostic, attr.span(), AttrError::MissingFeature);
341 span_err!(diagnostic, attr.span(), E0547, "missing 'issue'");
348 handle_errors(diagnostic, attr.span(), AttrError::MultipleStabilityLevels);
352 let mut feature = None;
353 let mut since = None;
355 if let NestedMetaItemKind::MetaItem(ref mi) = meta.node {
356 match &*mi.name().as_str() {
357 "feature" => if !get(mi, &mut feature) { continue 'outer },
358 "since" => if !get(mi, &mut since) { continue 'outer },
363 AttrError::UnknownMetaItem(mi.name(), &["since", "note"]),
369 handle_errors(diagnostic, meta.span, AttrError::UnsupportedLiteral);
374 match (feature, since) {
375 (Some(feature), Some(since)) => {
376 stab = Some(Stability {
382 rustc_const_unstable: None,
386 handle_errors(diagnostic, attr.span(), AttrError::MissingFeature);
390 handle_errors(diagnostic, attr.span(), AttrError::MissingSince);
398 span_err!(diagnostic, attr.span(), E0548, "incorrect stability attribute type");
403 // Merge the deprecation info into the stability info
404 if let Some(rustc_depr) = rustc_depr {
405 if let Some(ref mut stab) = stab {
406 stab.rustc_depr = Some(rustc_depr);
408 span_err!(diagnostic, item_sp, E0549,
409 "rustc_deprecated attribute must be paired with \
410 either stable or unstable attribute");
414 // Merge the const-unstable info into the stability info
415 if let Some(rustc_const_unstable) = rustc_const_unstable {
416 if let Some(ref mut stab) = stab {
417 stab.rustc_const_unstable = Some(rustc_const_unstable);
419 span_err!(diagnostic, item_sp, E0630,
420 "rustc_const_unstable attribute must be paired with \
421 either stable or unstable attribute");
428 pub fn find_crate_name(attrs: &[Attribute]) -> Option<Symbol> {
429 super::first_attr_value_str_by_name(attrs, "crate_name")
432 /// Tests if a cfg-pattern matches the cfg set
433 pub fn cfg_matches(cfg: &ast::MetaItem, sess: &ParseSess, features: Option<&Features>) -> bool {
434 eval_condition(cfg, sess, &mut |cfg| {
435 if let (Some(feats), Some(gated_cfg)) = (features, GatedCfg::gate(cfg)) {
436 gated_cfg.check_and_emit(sess, feats);
438 sess.config.contains(&(cfg.name(), cfg.value_str()))
442 /// Evaluate a cfg-like condition (with `any` and `all`), using `eval` to
443 /// evaluate individual items.
444 pub fn eval_condition<F>(cfg: &ast::MetaItem, sess: &ParseSess, eval: &mut F)
446 where F: FnMut(&ast::MetaItem) -> bool
449 ast::MetaItemKind::List(ref mis) => {
450 for mi in mis.iter() {
451 if !mi.is_meta_item() {
452 handle_errors(&sess.span_diagnostic, mi.span, AttrError::UnsupportedLiteral);
457 // The unwraps below may look dangerous, but we've already asserted
458 // that they won't fail with the loop above.
459 match &*cfg.name().as_str() {
460 "any" => mis.iter().any(|mi| {
461 eval_condition(mi.meta_item().unwrap(), sess, eval)
463 "all" => mis.iter().all(|mi| {
464 eval_condition(mi.meta_item().unwrap(), sess, eval)
468 span_err!(sess.span_diagnostic, cfg.span, E0536, "expected 1 cfg-pattern");
472 !eval_condition(mis[0].meta_item().unwrap(), sess, eval)
475 span_err!(sess.span_diagnostic, cfg.span, E0537, "invalid predicate `{}`", p);
480 ast::MetaItemKind::Word | ast::MetaItemKind::NameValue(..) => {
487 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Debug, Eq, Hash)]
488 pub struct Deprecation {
489 pub since: Option<Symbol>,
490 pub note: Option<Symbol>,
493 /// Find the deprecation attribute. `None` if none exists.
494 pub fn find_deprecation(diagnostic: &Handler, attrs: &[Attribute],
495 item_sp: Span) -> Option<Deprecation> {
496 find_deprecation_generic(diagnostic, attrs.iter(), item_sp)
499 fn find_deprecation_generic<'a, I>(diagnostic: &Handler,
502 -> Option<Deprecation>
503 where I: Iterator<Item = &'a Attribute>
505 let mut depr: Option<Deprecation> = None;
507 'outer: for attr in attrs_iter {
508 if attr.path != "deprecated" {
515 span_err!(diagnostic, item_sp, E0550, "multiple deprecated attributes");
519 depr = if let Some(metas) = attr.meta_item_list() {
520 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
522 handle_errors(diagnostic, meta.span, AttrError::MultipleItem(meta.name()));
525 if let Some(v) = meta.value_str() {
529 span_err!(diagnostic, meta.span, E0551, "incorrect meta item");
534 let mut since = None;
537 if let NestedMetaItemKind::MetaItem(ref mi) = meta.node {
538 match &*mi.name().as_str() {
539 "since" => if !get(mi, &mut since) { continue 'outer },
540 "note" => if !get(mi, &mut note) { continue 'outer },
545 AttrError::UnknownMetaItem(mi.name(), &["since", "note"]),
551 handle_errors(diagnostic, meta.span, AttrError::UnsupportedLiteral);
556 Some(Deprecation {since: since, note: note})
558 Some(Deprecation{since: None, note: None})
565 #[derive(PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
575 #[derive(Eq, Hash, PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
577 SignedInt(ast::IntTy),
578 UnsignedInt(ast::UintTy)
583 pub fn is_signed(self) -> bool {
584 use self::IntType::*;
587 SignedInt(..) => true,
588 UnsignedInt(..) => false
593 /// Parse #[repr(...)] forms.
595 /// Valid repr contents: any of the primitive integral type names (see
596 /// `int_type_of_word`, below) to specify enum discriminant type; `C`, to use
597 /// the same discriminant size that the corresponding C enum would or C
598 /// structure layout, `packed` to remove padding, and `transparent` to elegate representation
599 /// concerns to the only non-ZST field.
600 pub fn find_repr_attrs(diagnostic: &Handler, attr: &Attribute) -> Vec<ReprAttr> {
601 use self::ReprAttr::*;
603 let mut acc = Vec::new();
604 if attr.path == "repr" {
605 if let Some(items) = attr.meta_item_list() {
608 if !item.is_meta_item() {
609 handle_errors(diagnostic, item.span, AttrError::UnsupportedLiteral);
613 let mut recognised = false;
614 if let Some(mi) = item.word() {
615 let word = &*mi.name().as_str();
616 let hint = match word {
618 "packed" => Some(ReprPacked(1)),
619 "simd" => Some(ReprSimd),
620 "transparent" => Some(ReprTransparent),
621 _ => match int_type_of_word(word) {
622 Some(ity) => Some(ReprInt(ity)),
629 if let Some(h) = hint {
633 } else if let Some((name, value)) = item.name_value_literal() {
634 let parse_alignment = |node: &ast::LitKind| -> Result<u32, &'static str> {
635 if let ast::LitKind::Int(literal, ast::LitIntType::Unsuffixed) = node {
636 if literal.is_power_of_two() {
637 // rustc::ty::layout::Align restricts align to <= 2^29
638 if *literal <= 1 << 29 {
641 Err("larger than 2^29")
644 Err("not a power of two")
647 Err("not an unsuffixed integer")
651 let mut literal_error = None;
654 match parse_alignment(&value.node) {
655 Ok(literal) => acc.push(ReprAlign(literal)),
656 Err(message) => literal_error = Some(message)
659 else if name == "packed" {
661 match parse_alignment(&value.node) {
662 Ok(literal) => acc.push(ReprPacked(literal)),
663 Err(message) => literal_error = Some(message)
666 if let Some(literal_error) = literal_error {
667 span_err!(diagnostic, item.span, E0589,
668 "invalid `repr(align)` attribute: {}", literal_error);
671 if let Some(meta_item) = item.meta_item() {
672 if meta_item.name() == "align" {
673 if let MetaItemKind::NameValue(ref value) = meta_item.node {
675 let mut err = struct_span_err!(diagnostic, item.span, E0693,
676 "incorrect `repr(align)` attribute format");
678 ast::LitKind::Int(int, ast::LitIntType::Unsuffixed) => {
679 err.span_suggestion_with_applicability(
681 "use parentheses instead",
682 format!("align({})", int),
683 Applicability::MachineApplicable
686 ast::LitKind::Str(s, _) => {
687 err.span_suggestion_with_applicability(
689 "use parentheses instead",
690 format!("align({})", s),
691 Applicability::MachineApplicable
702 // Not a word we recognize
703 span_err!(diagnostic, item.span, E0552,
704 "unrecognized representation hint");
712 fn int_type_of_word(s: &str) -> Option<IntType> {
713 use self::IntType::*;
716 "i8" => Some(SignedInt(ast::IntTy::I8)),
717 "u8" => Some(UnsignedInt(ast::UintTy::U8)),
718 "i16" => Some(SignedInt(ast::IntTy::I16)),
719 "u16" => Some(UnsignedInt(ast::UintTy::U16)),
720 "i32" => Some(SignedInt(ast::IntTy::I32)),
721 "u32" => Some(UnsignedInt(ast::UintTy::U32)),
722 "i64" => Some(SignedInt(ast::IntTy::I64)),
723 "u64" => Some(UnsignedInt(ast::UintTy::U64)),
724 "i128" => Some(SignedInt(ast::IntTy::I128)),
725 "u128" => Some(UnsignedInt(ast::UintTy::U128)),
726 "isize" => Some(SignedInt(ast::IntTy::Isize)),
727 "usize" => Some(UnsignedInt(ast::UintTy::Usize)),