1 // Copyright 2012-2014 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 // Functions dealing with attributes and meta items
13 pub use self::StabilityLevel::*;
14 pub use self::ReprAttr::*;
15 pub use self::IntType::*;
18 use ast::{AttrId, Attribute, Attribute_, MetaItem, MetaWord, MetaNameValue, MetaList};
19 use codemap::{Span, Spanned, spanned, dummy_spanned};
21 use diagnostic::SpanHandler;
22 use feature_gate::GatedCfg;
23 use parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
24 use parse::token::{InternedString, intern_and_get_ident};
28 use std::cell::{RefCell, Cell};
29 use std::collections::HashSet;
33 static USED_ATTRS: RefCell<Vec<u64>> = RefCell::new(Vec::new())
36 pub fn mark_used(attr: &Attribute) {
37 let AttrId(id) = attr.node.id;
38 USED_ATTRS.with(|slot| {
39 let idx = (id / 64) as usize;
41 if slot.borrow().len() <= idx {
42 slot.borrow_mut().resize(idx + 1, 0);
44 slot.borrow_mut()[idx] |= 1 << shift;
48 pub fn is_used(attr: &Attribute) -> bool {
49 let AttrId(id) = attr.node.id;
50 USED_ATTRS.with(|slot| {
51 let idx = (id / 64) as usize;
53 slot.borrow().get(idx).map(|bits| bits & (1 << shift) != 0)
58 pub trait AttrMetaMethods {
59 fn check_name(&self, name: &str) -> bool {
60 name == &self.name()[..]
63 /// Retrieve the name of the meta item, e.g. `foo` in `#[foo]`,
64 /// `#[foo="bar"]` and `#[foo(bar)]`
65 fn name(&self) -> InternedString;
67 /// Gets the string value if self is a MetaNameValue variant
68 /// containing a string, otherwise None.
69 fn value_str(&self) -> Option<InternedString>;
70 /// Gets a list of inner meta items from a list MetaItem type.
71 fn meta_item_list<'a>(&'a self) -> Option<&'a [P<MetaItem>]>;
73 fn span(&self) -> Span;
76 impl AttrMetaMethods for Attribute {
77 fn check_name(&self, name: &str) -> bool {
78 let matches = name == &self.name()[..];
84 fn name(&self) -> InternedString { self.meta().name() }
85 fn value_str(&self) -> Option<InternedString> {
86 self.meta().value_str()
88 fn meta_item_list<'a>(&'a self) -> Option<&'a [P<MetaItem>]> {
89 self.node.value.meta_item_list()
91 fn span(&self) -> Span { self.meta().span }
94 impl AttrMetaMethods for MetaItem {
95 fn name(&self) -> InternedString {
97 MetaWord(ref n) => (*n).clone(),
98 MetaNameValue(ref n, _) => (*n).clone(),
99 MetaList(ref n, _) => (*n).clone(),
103 fn value_str(&self) -> Option<InternedString> {
105 MetaNameValue(_, ref v) => {
107 ast::LitStr(ref s, _) => Some((*s).clone()),
115 fn meta_item_list<'a>(&'a self) -> Option<&'a [P<MetaItem>]> {
117 MetaList(_, ref l) => Some(&l[..]),
121 fn span(&self) -> Span { self.span }
124 // Annoying, but required to get test_cfg to work
125 impl AttrMetaMethods for P<MetaItem> {
126 fn name(&self) -> InternedString { (**self).name() }
127 fn value_str(&self) -> Option<InternedString> { (**self).value_str() }
128 fn meta_item_list<'a>(&'a self) -> Option<&'a [P<MetaItem>]> {
129 (**self).meta_item_list()
131 fn span(&self) -> Span { (**self).span() }
135 pub trait AttributeMethods {
136 fn meta<'a>(&'a self) -> &'a MetaItem;
137 fn with_desugared_doc<T, F>(&self, f: F) -> T where
138 F: FnOnce(&Attribute) -> T;
141 impl AttributeMethods for Attribute {
142 /// Extract the MetaItem from inside this Attribute.
143 fn meta<'a>(&'a self) -> &'a MetaItem {
147 /// Convert self to a normal #[doc="foo"] comment, if it is a
148 /// comment like `///` or `/** */`. (Returns self unchanged for
149 /// non-sugared doc attributes.)
150 fn with_desugared_doc<T, F>(&self, f: F) -> T where
151 F: FnOnce(&Attribute) -> T,
153 if self.node.is_sugared_doc {
154 let comment = self.value_str().unwrap();
155 let meta = mk_name_value_item_str(
156 InternedString::new("doc"),
157 token::intern_and_get_ident(&strip_doc_comment_decoration(
159 if self.node.style == ast::AttrStyle::Outer {
160 f(&mk_attr_outer(self.node.id, meta))
162 f(&mk_attr_inner(self.node.id, meta))
172 pub fn mk_name_value_item_str(name: InternedString, value: InternedString)
174 let value_lit = dummy_spanned(ast::LitStr(value, ast::CookedStr));
175 mk_name_value_item(name, value_lit)
178 pub fn mk_name_value_item(name: InternedString, value: ast::Lit)
180 P(dummy_spanned(MetaNameValue(name, value)))
183 pub fn mk_list_item(name: InternedString, items: Vec<P<MetaItem>>) -> P<MetaItem> {
184 P(dummy_spanned(MetaList(name, items)))
187 pub fn mk_word_item(name: InternedString) -> P<MetaItem> {
188 P(dummy_spanned(MetaWord(name)))
191 thread_local! { static NEXT_ATTR_ID: Cell<usize> = Cell::new(0) }
193 pub fn mk_attr_id() -> AttrId {
194 let id = NEXT_ATTR_ID.with(|slot| {
202 /// Returns an inner attribute with the given value.
203 pub fn mk_attr_inner(id: AttrId, item: P<MetaItem>) -> Attribute {
204 dummy_spanned(Attribute_ {
206 style: ast::AttrStyle::Inner,
208 is_sugared_doc: false,
212 /// Returns an outer attribute with the given value.
213 pub fn mk_attr_outer(id: AttrId, item: P<MetaItem>) -> Attribute {
214 dummy_spanned(Attribute_ {
216 style: ast::AttrStyle::Outer,
218 is_sugared_doc: false,
222 pub fn mk_sugared_doc_attr(id: AttrId, text: InternedString, lo: BytePos,
225 let style = doc_comment_style(&text);
226 let lit = spanned(lo, hi, ast::LitStr(text, ast::CookedStr));
227 let attr = Attribute_ {
230 value: P(spanned(lo, hi, MetaNameValue(InternedString::new("doc"),
234 spanned(lo, hi, attr)
238 /// Check if `needle` occurs in `haystack` by a structural
239 /// comparison. This is slightly subtle, and relies on ignoring the
240 /// span included in the `==` comparison a plain MetaItem.
241 pub fn contains(haystack: &[P<MetaItem>], needle: &MetaItem) -> bool {
242 debug!("attr::contains (name={})", needle.name());
243 haystack.iter().any(|item| {
244 debug!(" testing: {}", item.name());
245 item.node == needle.node
249 pub fn contains_name<AM: AttrMetaMethods>(metas: &[AM], name: &str) -> bool {
250 debug!("attr::contains_name (name={})", name);
251 metas.iter().any(|item| {
252 debug!(" testing: {}", item.name());
253 item.check_name(name)
257 pub fn first_attr_value_str_by_name(attrs: &[Attribute], name: &str)
258 -> Option<InternedString> {
260 .find(|at| at.check_name(name))
261 .and_then(|at| at.value_str())
264 pub fn last_meta_item_value_str_by_name(items: &[P<MetaItem>], name: &str)
265 -> Option<InternedString> {
268 .find(|mi| mi.check_name(name))
269 .and_then(|i| i.value_str())
272 /* Higher-level applications */
274 pub fn sort_meta_items(items: Vec<P<MetaItem>>) -> Vec<P<MetaItem>> {
275 // This is sort of stupid here, but we need to sort by
276 // human-readable strings.
277 let mut v = items.into_iter()
278 .map(|mi| (mi.name(), mi))
279 .collect::<Vec<(InternedString, P<MetaItem>)>>();
281 v.sort_by(|&(ref a, _), &(ref b, _)| a.cmp(b));
283 // There doesn't seem to be a more optimal way to do this
284 v.into_iter().map(|(_, m)| m.map(|Spanned {node, span}| {
287 MetaList(n, mis) => MetaList(n, sort_meta_items(mis)),
295 pub fn find_crate_name(attrs: &[Attribute]) -> Option<InternedString> {
296 first_attr_value_str_by_name(attrs, "crate_name")
299 /// Find the value of #[export_name=*] attribute and check its validity.
300 pub fn find_export_name_attr(diag: &SpanHandler, attrs: &[Attribute]) -> Option<InternedString> {
301 attrs.iter().fold(None, |ia,attr| {
302 if attr.check_name("export_name") {
303 if let s@Some(_) = attr.value_str() {
306 diag.span_err(attr.span, "export_name attribute has invalid format");
307 diag.handler.help("use #[export_name=\"*\"]");
316 #[derive(Copy, Clone, PartialEq)]
317 pub enum InlineAttr {
324 /// Determine what `#[inline]` attribute is present in `attrs`, if any.
325 pub fn find_inline_attr(diagnostic: Option<&SpanHandler>, attrs: &[Attribute]) -> InlineAttr {
326 attrs.iter().fold(InlineAttr::None, |ia,attr| {
327 match attr.node.value.node {
328 MetaWord(ref n) if *n == "inline" => {
332 MetaList(ref n, ref items) if *n == "inline" => {
334 if items.len() != 1 {
335 diagnostic.map(|d|{ d.span_err(attr.span, "expected one argument"); });
337 } else if contains_name(&items[..], "always") {
339 } else if contains_name(&items[..], "never") {
342 diagnostic.map(|d|{ d.span_err((*items[0]).span, "invalid argument"); });
351 /// True if `#[inline]` or `#[inline(always)]` is present in `attrs`.
352 pub fn requests_inline(attrs: &[Attribute]) -> bool {
353 match find_inline_attr(None, attrs) {
354 InlineAttr::Hint | InlineAttr::Always => true,
355 InlineAttr::None | InlineAttr::Never => false,
359 /// Tests if a cfg-pattern matches the cfg set
360 pub fn cfg_matches(diagnostic: &SpanHandler, cfgs: &[P<MetaItem>], cfg: &ast::MetaItem,
361 feature_gated_cfgs: &mut Vec<GatedCfg>) -> bool {
363 ast::MetaList(ref pred, ref mis) if &pred[..] == "any" =>
364 mis.iter().any(|mi| cfg_matches(diagnostic, cfgs, &**mi, feature_gated_cfgs)),
365 ast::MetaList(ref pred, ref mis) if &pred[..] == "all" =>
366 mis.iter().all(|mi| cfg_matches(diagnostic, cfgs, &**mi, feature_gated_cfgs)),
367 ast::MetaList(ref pred, ref mis) if &pred[..] == "not" => {
369 diagnostic.span_err(cfg.span, "expected 1 cfg-pattern");
372 !cfg_matches(diagnostic, cfgs, &*mis[0], feature_gated_cfgs)
374 ast::MetaList(ref pred, _) => {
375 diagnostic.span_err(cfg.span, &format!("invalid predicate `{}`", pred));
378 ast::MetaWord(_) | ast::MetaNameValue(..) => {
379 feature_gated_cfgs.extend(GatedCfg::gate(cfg));
385 /// Represents the #[deprecated] and friends attributes.
386 #[derive(RustcEncodable, RustcDecodable, Clone, Debug, PartialEq, Eq, Hash)]
387 pub struct Stability {
388 pub level: StabilityLevel,
389 pub feature: InternedString,
390 pub since: Option<InternedString>,
391 pub deprecated_since: Option<InternedString>,
392 // The reason for the current stability level. If deprecated, the
393 // reason for deprecation.
394 pub reason: Option<InternedString>,
395 // The relevant rust-lang issue
396 pub issue: Option<u32>
399 /// The available stability levels.
400 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Debug, Copy, Eq, Hash)]
401 pub enum StabilityLevel {
406 impl fmt::Display for StabilityLevel {
407 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
408 fmt::Debug::fmt(self, f)
412 fn find_stability_generic<'a,
414 I: Iterator<Item=&'a AM>>
415 (diagnostic: &SpanHandler, attrs: I, item_sp: Span)
416 -> (Option<Stability>, Vec<&'a AM>) {
418 let mut stab: Option<Stability> = None;
419 let mut deprecated: Option<(Option<InternedString>, Option<InternedString>)> = None;
420 let mut used_attrs: Vec<&'a AM> = vec![];
422 'outer: for attr in attrs {
423 let tag = attr.name();
425 if tag != "deprecated" && tag != "unstable" && tag != "stable" {
426 continue // not a stability level
429 used_attrs.push(attr);
431 let (feature, since, reason, issue) = match attr.meta_item_list() {
433 let mut feature = None;
434 let mut since = None;
435 let mut reason = None;
436 let mut issue = None;
438 match &*meta.name() {
440 match meta.value_str() {
441 Some(v) => feature = Some(v),
443 diagnostic.span_err(meta.span, "incorrect meta item");
449 match meta.value_str() {
450 Some(v) => since = Some(v),
452 diagnostic.span_err(meta.span, "incorrect meta item");
458 match meta.value_str() {
459 Some(v) => reason = Some(v),
461 diagnostic.span_err(meta.span, "incorrect meta item");
467 match meta.value_str().and_then(|s| s.parse().ok()) {
468 Some(v) => issue = Some(v),
470 diagnostic.span_err(meta.span, "incorrect meta item");
478 (feature, since, reason, issue)
481 diagnostic.span_err(attr.span(), "incorrect stability attribute type");
486 // Deprecated tags don't require feature names
487 if feature == None && tag != "deprecated" {
488 diagnostic.span_err(attr.span(), "missing 'feature'");
491 // Unstable tags don't require a version
492 if since == None && tag != "unstable" {
493 diagnostic.span_err(attr.span(), "missing 'since'");
496 if tag == "unstable" || tag == "stable" {
498 diagnostic.span_err(item_sp, "multiple stability levels");
501 let level = match tag {
502 "unstable" => Unstable,
507 stab = Some(Stability {
509 feature: feature.unwrap_or(intern_and_get_ident("bogus")),
511 deprecated_since: None,
515 } else { // "deprecated"
516 if deprecated.is_some() {
517 diagnostic.span_err(item_sp, "multiple deprecated attributes");
520 deprecated = Some((since, reason));
524 // Merge the deprecation info into the stability info
525 if deprecated.is_some() {
528 let (since, reason) = deprecated.unwrap();
529 s.deprecated_since = since;
533 diagnostic.span_err(item_sp, "deprecated attribute must be paired with \
534 either stable or unstable attribute");
537 } else if stab.as_ref().map_or(false, |s| s.level == Unstable && s.issue.is_none()) {
538 // non-deprecated unstable items need to point to issues.
539 diagnostic.span_err(item_sp,
540 "non-deprecated unstable items need to point \
541 to an issue with `issue = \"NNN\"`");
547 /// Find the first stability attribute. `None` if none exists.
548 pub fn find_stability(diagnostic: &SpanHandler, attrs: &[Attribute],
549 item_sp: Span) -> Option<Stability> {
550 let (s, used) = find_stability_generic(diagnostic, attrs.iter(), item_sp);
551 for used in used { mark_used(used) }
555 pub fn require_unique_names(diagnostic: &SpanHandler, metas: &[P<MetaItem>]) {
556 let mut set = HashSet::new();
558 let name = meta.name();
560 if !set.insert(name.clone()) {
561 panic!(diagnostic.span_fatal(meta.span,
562 &format!("duplicate meta item `{}`", name)));
568 /// Parse #[repr(...)] forms.
570 /// Valid repr contents: any of the primitive integral type names (see
571 /// `int_type_of_word`, below) to specify enum discriminant type; `C`, to use
572 /// the same discriminant size that the corresponding C enum would or C
573 /// structure layout, and `packed` to remove padding.
574 pub fn find_repr_attrs(diagnostic: &SpanHandler, attr: &Attribute) -> Vec<ReprAttr> {
575 let mut acc = Vec::new();
576 match attr.node.value.node {
577 ast::MetaList(ref s, ref items) if *s == "repr" => {
581 ast::MetaWord(ref word) => {
582 let hint = match &word[..] {
583 // Can't use "extern" because it's not a lexical identifier.
584 "C" => Some(ReprExtern),
585 "packed" => Some(ReprPacked),
586 "simd" => Some(ReprSimd),
587 _ => match int_type_of_word(&word) {
588 Some(ity) => Some(ReprInt(item.span, ity)),
590 // Not a word we recognize
591 diagnostic.span_err(item.span,
592 "unrecognized representation hint");
599 Some(h) => acc.push(h),
604 _ => diagnostic.span_err(item.span, "unrecognized enum representation hint")
608 // Not a "repr" hint: ignore.
614 fn int_type_of_word(s: &str) -> Option<IntType> {
616 "i8" => Some(SignedInt(ast::TyI8)),
617 "u8" => Some(UnsignedInt(ast::TyU8)),
618 "i16" => Some(SignedInt(ast::TyI16)),
619 "u16" => Some(UnsignedInt(ast::TyU16)),
620 "i32" => Some(SignedInt(ast::TyI32)),
621 "u32" => Some(UnsignedInt(ast::TyU32)),
622 "i64" => Some(SignedInt(ast::TyI64)),
623 "u64" => Some(UnsignedInt(ast::TyU64)),
624 "isize" => Some(SignedInt(ast::TyIs)),
625 "usize" => Some(UnsignedInt(ast::TyUs)),
630 #[derive(PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
633 ReprInt(Span, IntType),
640 pub fn is_ffi_safe(&self) -> bool {
643 ReprInt(_sp, ity) => ity.is_ffi_safe(),
651 #[derive(Eq, Hash, PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
653 SignedInt(ast::IntTy),
654 UnsignedInt(ast::UintTy)
659 pub fn is_signed(self) -> bool {
661 SignedInt(..) => true,
662 UnsignedInt(..) => false
665 fn is_ffi_safe(self) -> bool {
667 SignedInt(ast::TyI8) | UnsignedInt(ast::TyU8) |
668 SignedInt(ast::TyI16) | UnsignedInt(ast::TyU16) |
669 SignedInt(ast::TyI32) | UnsignedInt(ast::TyU32) |
670 SignedInt(ast::TyI64) | UnsignedInt(ast::TyU64) => true,
671 SignedInt(ast::TyIs) | UnsignedInt(ast::TyUs) => false