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 parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
23 use parse::token::{InternedString, intern_and_get_ident};
27 use std::cell::{RefCell, Cell};
28 use std::collections::HashSet;
32 static USED_ATTRS: RefCell<Vec<u64>> = RefCell::new(Vec::new())
35 pub fn mark_used(attr: &Attribute) {
36 let AttrId(id) = attr.node.id;
37 USED_ATTRS.with(|slot| {
38 let idx = (id / 64) as usize;
40 if slot.borrow().len() <= idx {
41 slot.borrow_mut().resize(idx + 1, 0);
43 slot.borrow_mut()[idx] |= 1 << shift;
47 pub fn is_used(attr: &Attribute) -> bool {
48 let AttrId(id) = attr.node.id;
49 USED_ATTRS.with(|slot| {
50 let idx = (id / 64) as usize;
52 slot.borrow().get(idx).map(|bits| bits & (1 << shift) != 0)
57 pub trait AttrMetaMethods {
58 fn check_name(&self, name: &str) -> bool {
59 name == &self.name()[..]
62 /// Retrieve the name of the meta item, e.g. `foo` in `#[foo]`,
63 /// `#[foo="bar"]` and `#[foo(bar)]`
64 fn name(&self) -> InternedString;
66 /// Gets the string value if self is a MetaNameValue variant
67 /// containing a string, otherwise None.
68 fn value_str(&self) -> Option<InternedString>;
69 /// Gets a list of inner meta items from a list MetaItem type.
70 fn meta_item_list<'a>(&'a self) -> Option<&'a [P<MetaItem>]>;
72 fn span(&self) -> Span;
75 impl AttrMetaMethods for Attribute {
76 fn check_name(&self, name: &str) -> bool {
77 let matches = name == &self.name()[..];
83 fn name(&self) -> InternedString { self.meta().name() }
84 fn value_str(&self) -> Option<InternedString> {
85 self.meta().value_str()
87 fn meta_item_list<'a>(&'a self) -> Option<&'a [P<MetaItem>]> {
88 self.node.value.meta_item_list()
90 fn span(&self) -> Span { self.meta().span }
93 impl AttrMetaMethods for MetaItem {
94 fn name(&self) -> InternedString {
96 MetaWord(ref n) => (*n).clone(),
97 MetaNameValue(ref n, _) => (*n).clone(),
98 MetaList(ref n, _) => (*n).clone(),
102 fn value_str(&self) -> Option<InternedString> {
104 MetaNameValue(_, ref v) => {
106 ast::LitStr(ref s, _) => Some((*s).clone()),
114 fn meta_item_list<'a>(&'a self) -> Option<&'a [P<MetaItem>]> {
116 MetaList(_, ref l) => Some(&l[..]),
120 fn span(&self) -> Span { self.span }
123 // Annoying, but required to get test_cfg to work
124 impl AttrMetaMethods for P<MetaItem> {
125 fn name(&self) -> InternedString { (**self).name() }
126 fn value_str(&self) -> Option<InternedString> { (**self).value_str() }
127 fn meta_item_list<'a>(&'a self) -> Option<&'a [P<MetaItem>]> {
128 (**self).meta_item_list()
130 fn span(&self) -> Span { (**self).span() }
134 pub trait AttributeMethods {
135 fn meta<'a>(&'a self) -> &'a MetaItem;
136 fn with_desugared_doc<T, F>(&self, f: F) -> T where
137 F: FnOnce(&Attribute) -> T;
140 impl AttributeMethods for Attribute {
141 /// Extract the MetaItem from inside this Attribute.
142 fn meta<'a>(&'a self) -> &'a MetaItem {
146 /// Convert self to a normal #[doc="foo"] comment, if it is a
147 /// comment like `///` or `/** */`. (Returns self unchanged for
148 /// non-sugared doc attributes.)
149 fn with_desugared_doc<T, F>(&self, f: F) -> T where
150 F: FnOnce(&Attribute) -> T,
152 if self.node.is_sugared_doc {
153 let comment = self.value_str().unwrap();
154 let meta = mk_name_value_item_str(
155 InternedString::new("doc"),
156 token::intern_and_get_ident(&strip_doc_comment_decoration(
158 if self.node.style == ast::AttrOuter {
159 f(&mk_attr_outer(self.node.id, meta))
161 f(&mk_attr_inner(self.node.id, meta))
171 pub fn mk_name_value_item_str(name: InternedString, value: InternedString)
173 let value_lit = dummy_spanned(ast::LitStr(value, ast::CookedStr));
174 mk_name_value_item(name, value_lit)
177 pub fn mk_name_value_item(name: InternedString, value: ast::Lit)
179 P(dummy_spanned(MetaNameValue(name, value)))
182 pub fn mk_list_item(name: InternedString, items: Vec<P<MetaItem>>) -> P<MetaItem> {
183 P(dummy_spanned(MetaList(name, items)))
186 pub fn mk_word_item(name: InternedString) -> P<MetaItem> {
187 P(dummy_spanned(MetaWord(name)))
190 thread_local! { static NEXT_ATTR_ID: Cell<usize> = Cell::new(0) }
192 pub fn mk_attr_id() -> AttrId {
193 let id = NEXT_ATTR_ID.with(|slot| {
201 /// Returns an inner attribute with the given value.
202 pub fn mk_attr_inner(id: AttrId, item: P<MetaItem>) -> Attribute {
203 dummy_spanned(Attribute_ {
205 style: ast::AttrInner,
207 is_sugared_doc: false,
211 /// Returns an outer attribute with the given value.
212 pub fn mk_attr_outer(id: AttrId, item: P<MetaItem>) -> Attribute {
213 dummy_spanned(Attribute_ {
215 style: ast::AttrOuter,
217 is_sugared_doc: false,
221 pub fn mk_sugared_doc_attr(id: AttrId, text: InternedString, lo: BytePos,
224 let style = doc_comment_style(&text);
225 let lit = spanned(lo, hi, ast::LitStr(text, ast::CookedStr));
226 let attr = Attribute_ {
229 value: P(spanned(lo, hi, MetaNameValue(InternedString::new("doc"),
233 spanned(lo, hi, attr)
237 /// Check if `needle` occurs in `haystack` by a structural
238 /// comparison. This is slightly subtle, and relies on ignoring the
239 /// span included in the `==` comparison a plain MetaItem.
240 pub fn contains(haystack: &[P<MetaItem>], needle: &MetaItem) -> bool {
241 debug!("attr::contains (name={})", needle.name());
242 haystack.iter().any(|item| {
243 debug!(" testing: {}", item.name());
244 item.node == needle.node
248 pub fn contains_name<AM: AttrMetaMethods>(metas: &[AM], name: &str) -> bool {
249 debug!("attr::contains_name (name={})", name);
250 metas.iter().any(|item| {
251 debug!(" testing: {}", item.name());
252 item.check_name(name)
256 pub fn first_attr_value_str_by_name(attrs: &[Attribute], name: &str)
257 -> Option<InternedString> {
259 .find(|at| at.check_name(name))
260 .and_then(|at| at.value_str())
263 pub fn last_meta_item_value_str_by_name(items: &[P<MetaItem>], name: &str)
264 -> Option<InternedString> {
267 .find(|mi| mi.check_name(name))
268 .and_then(|i| i.value_str())
271 /* Higher-level applications */
273 pub fn sort_meta_items(items: Vec<P<MetaItem>>) -> Vec<P<MetaItem>> {
274 // This is sort of stupid here, but we need to sort by
275 // human-readable strings.
276 let mut v = items.into_iter()
277 .map(|mi| (mi.name(), mi))
278 .collect::<Vec<(InternedString, P<MetaItem>)>>();
280 v.sort_by(|&(ref a, _), &(ref b, _)| a.cmp(b));
282 // There doesn't seem to be a more optimal way to do this
283 v.into_iter().map(|(_, m)| m.map(|Spanned {node, span}| {
286 MetaList(n, mis) => MetaList(n, sort_meta_items(mis)),
294 pub fn find_crate_name(attrs: &[Attribute]) -> Option<InternedString> {
295 first_attr_value_str_by_name(attrs, "crate_name")
298 /// Find the value of #[export_name=*] attribute and check its validity.
299 pub fn find_export_name_attr(diag: &SpanHandler, attrs: &[Attribute]) -> Option<InternedString> {
300 attrs.iter().fold(None, |ia,attr| {
301 if attr.check_name("export_name") {
302 if let s@Some(_) = attr.value_str() {
305 diag.span_err(attr.span, "export_name attribute has invalid format");
306 diag.handler.help("use #[export_name=\"*\"]");
315 #[derive(Copy, Clone, PartialEq)]
316 pub enum InlineAttr {
323 /// Determine what `#[inline]` attribute is present in `attrs`, if any.
324 pub fn find_inline_attr(diagnostic: Option<&SpanHandler>, attrs: &[Attribute]) -> InlineAttr {
325 // FIXME (#2809)---validate the usage of #[inline] and #[inline]
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) -> bool {
362 ast::MetaList(ref pred, ref mis) if &pred[..] == "any" =>
363 mis.iter().any(|mi| cfg_matches(diagnostic, cfgs, &**mi)),
364 ast::MetaList(ref pred, ref mis) if &pred[..] == "all" =>
365 mis.iter().all(|mi| cfg_matches(diagnostic, cfgs, &**mi)),
366 ast::MetaList(ref pred, ref mis) if &pred[..] == "not" => {
368 diagnostic.span_err(cfg.span, "expected 1 cfg-pattern");
371 !cfg_matches(diagnostic, cfgs, &*mis[0])
373 ast::MetaList(ref pred, _) => {
374 diagnostic.span_err(cfg.span, &format!("invalid predicate `{}`", pred));
377 ast::MetaWord(_) | ast::MetaNameValue(..) => contains(cfgs, cfg),
381 /// Represents the #[deprecated] and friends attributes.
382 #[derive(RustcEncodable, RustcDecodable, Clone, Debug, PartialEq, Eq, Hash)]
383 pub struct Stability {
384 pub level: StabilityLevel,
385 pub feature: InternedString,
386 pub since: Option<InternedString>,
387 pub deprecated_since: Option<InternedString>,
388 // The reason for the current stability level. If deprecated, the
389 // reason for deprecation.
390 pub reason: Option<InternedString>,
391 // The relevant rust-lang issue
392 pub issue: Option<u32>
395 /// The available stability levels.
396 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Debug, Copy, Eq, Hash)]
397 pub enum StabilityLevel {
402 impl fmt::Display for StabilityLevel {
403 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
404 fmt::Debug::fmt(self, f)
408 fn find_stability_generic<'a,
410 I: Iterator<Item=&'a AM>>
411 (diagnostic: &SpanHandler, attrs: I, item_sp: Span)
412 -> (Option<Stability>, Vec<&'a AM>) {
414 let mut stab: Option<Stability> = None;
415 let mut deprecated: Option<(Option<InternedString>, Option<InternedString>)> = None;
416 let mut used_attrs: Vec<&'a AM> = vec![];
418 'outer: for attr in attrs {
419 let tag = attr.name();
421 if tag != "deprecated" && tag != "unstable" && tag != "stable" {
422 continue // not a stability level
425 used_attrs.push(attr);
427 let (feature, since, reason, issue) = match attr.meta_item_list() {
429 let mut feature = None;
430 let mut since = None;
431 let mut reason = None;
432 let mut issue = None;
434 match &*meta.name() {
436 match meta.value_str() {
437 Some(v) => feature = Some(v),
439 diagnostic.span_err(meta.span, "incorrect meta item");
445 match meta.value_str() {
446 Some(v) => since = Some(v),
448 diagnostic.span_err(meta.span, "incorrect meta item");
454 match meta.value_str() {
455 Some(v) => reason = Some(v),
457 diagnostic.span_err(meta.span, "incorrect meta item");
463 match meta.value_str().and_then(|s| s.parse().ok()) {
464 Some(v) => issue = Some(v),
466 diagnostic.span_err(meta.span, "incorrect meta item");
474 (feature, since, reason, issue)
477 diagnostic.span_err(attr.span(), "incorrect stability attribute type");
482 // Deprecated tags don't require feature names
483 if feature == None && tag != "deprecated" {
484 diagnostic.span_err(attr.span(), "missing 'feature'");
487 // Unstable tags don't require a version
488 if since == None && tag != "unstable" {
489 diagnostic.span_err(attr.span(), "missing 'since'");
492 if tag == "unstable" || tag == "stable" {
494 diagnostic.span_err(item_sp, "multiple stability levels");
497 let level = match tag {
498 "unstable" => Unstable,
503 stab = Some(Stability {
505 feature: feature.unwrap_or(intern_and_get_ident("bogus")),
507 deprecated_since: None,
511 } else { // "deprecated"
512 if deprecated.is_some() {
513 diagnostic.span_err(item_sp, "multiple deprecated attributes");
516 deprecated = Some((since, reason));
520 // Merge the deprecation info into the stability info
521 if deprecated.is_some() {
524 let (since, reason) = deprecated.unwrap();
525 s.deprecated_since = since;
529 diagnostic.span_err(item_sp, "deprecated attribute must be paired with \
530 either stable or unstable attribute");
533 } else if stab.as_ref().map_or(false, |s| s.level == Unstable && s.issue.is_none()) {
534 // non-deprecated unstable items need to point to issues.
535 diagnostic.span_err(item_sp,
536 "non-deprecated unstable items need to point \
537 to an issue with `issue = \"NNN\"`");
543 /// Find the first stability attribute. `None` if none exists.
544 pub fn find_stability(diagnostic: &SpanHandler, attrs: &[Attribute],
545 item_sp: Span) -> Option<Stability> {
546 let (s, used) = find_stability_generic(diagnostic, attrs.iter(), item_sp);
547 for used in used { mark_used(used) }
551 pub fn require_unique_names(diagnostic: &SpanHandler, metas: &[P<MetaItem>]) {
552 let mut set = HashSet::new();
554 let name = meta.name();
556 if !set.insert(name.clone()) {
557 panic!(diagnostic.span_fatal(meta.span,
558 &format!("duplicate meta item `{}`", name)));
564 /// Parse #[repr(...)] forms.
566 /// Valid repr contents: any of the primitive integral type names (see
567 /// `int_type_of_word`, below) to specify enum discriminant type; `C`, to use
568 /// the same discriminant size that the corresponding C enum would or C
569 /// structure layout, and `packed` to remove padding.
570 pub fn find_repr_attrs(diagnostic: &SpanHandler, attr: &Attribute) -> Vec<ReprAttr> {
571 let mut acc = Vec::new();
572 match attr.node.value.node {
573 ast::MetaList(ref s, ref items) if *s == "repr" => {
577 ast::MetaWord(ref word) => {
578 let hint = match &word[..] {
579 // Can't use "extern" because it's not a lexical identifier.
580 "C" => Some(ReprExtern),
581 "packed" => Some(ReprPacked),
582 "simd" => Some(ReprSimd),
583 _ => match int_type_of_word(&word) {
584 Some(ity) => Some(ReprInt(item.span, ity)),
586 // Not a word we recognize
587 diagnostic.span_err(item.span,
588 "unrecognized representation hint");
595 Some(h) => acc.push(h),
600 _ => diagnostic.span_err(item.span, "unrecognized enum representation hint")
604 // Not a "repr" hint: ignore.
610 fn int_type_of_word(s: &str) -> Option<IntType> {
612 "i8" => Some(SignedInt(ast::TyI8)),
613 "u8" => Some(UnsignedInt(ast::TyU8)),
614 "i16" => Some(SignedInt(ast::TyI16)),
615 "u16" => Some(UnsignedInt(ast::TyU16)),
616 "i32" => Some(SignedInt(ast::TyI32)),
617 "u32" => Some(UnsignedInt(ast::TyU32)),
618 "i64" => Some(SignedInt(ast::TyI64)),
619 "u64" => Some(UnsignedInt(ast::TyU64)),
620 "isize" => Some(SignedInt(ast::TyIs)),
621 "usize" => Some(UnsignedInt(ast::TyUs)),
626 #[derive(PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
629 ReprInt(Span, IntType),
636 pub fn is_ffi_safe(&self) -> bool {
639 ReprInt(_sp, ity) => ity.is_ffi_safe(),
647 #[derive(Eq, Hash, PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
649 SignedInt(ast::IntTy),
650 UnsignedInt(ast::UintTy)
655 pub fn is_signed(self) -> bool {
657 SignedInt(..) => true,
658 UnsignedInt(..) => false
661 fn is_ffi_safe(self) -> bool {
663 SignedInt(ast::TyI8) | UnsignedInt(ast::TyU8) |
664 SignedInt(ast::TyI16) | UnsignedInt(ast::TyU16) |
665 SignedInt(ast::TyI32) | UnsignedInt(ast::TyU32) |
666 SignedInt(ast::TyI64) | UnsignedInt(ast::TyU64) => true,
667 SignedInt(ast::TyIs) | UnsignedInt(ast::TyUs) => false