1 // Copyright 2012-2015 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 syntax::codemap::{Span, Spanned, spanned, dummy_spanned};
19 use syntax::codemap::BytePos;
20 use syntax::diagnostic::SpanHandler;
21 use syntax::attr as syntax_attr;
22 use syntax::parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
23 use syntax::parse::token::{InternedString, intern_and_get_ident};
24 use syntax::parse::token;
28 use std::collections::HashSet;
31 pub fn mark_used(attr: &Attribute) {
32 syntax_attr::mark_used(&unlower_attribute(attr))
35 pub trait AttrMetaMethods {
36 fn check_name(&self, name: &str) -> bool {
37 name == &self.name()[..]
40 /// Retrieve the name of the meta item, e.g. `foo` in `#[foo]`,
41 /// `#[foo="bar"]` and `#[foo(bar)]`
42 fn name(&self) -> InternedString;
44 /// Gets the string value if self is a MetaNameValue variant
45 /// containing a string, otherwise None.
46 fn value_str(&self) -> Option<InternedString>;
47 /// Gets a list of inner meta items from a list MetaItem type.
48 fn meta_item_list<'a>(&'a self) -> Option<&'a [P<MetaItem>]>;
50 fn span(&self) -> Span;
53 impl AttrMetaMethods for Attribute {
54 fn check_name(&self, name: &str) -> bool {
55 let matches = name == &self.name()[..];
57 syntax_attr::mark_used(&unlower_attribute(self));
61 fn name(&self) -> InternedString { self.meta().name() }
62 fn value_str(&self) -> Option<InternedString> {
63 self.meta().value_str()
65 fn meta_item_list<'a>(&'a self) -> Option<&'a [P<MetaItem>]> {
66 self.node.value.meta_item_list()
68 fn span(&self) -> Span { self.meta().span }
71 impl AttrMetaMethods for MetaItem {
72 fn name(&self) -> InternedString {
74 MetaWord(ref n) => (*n).clone(),
75 MetaNameValue(ref n, _) => (*n).clone(),
76 MetaList(ref n, _) => (*n).clone(),
80 fn value_str(&self) -> Option<InternedString> {
82 MetaNameValue(_, ref v) => {
84 hir::LitStr(ref s, _) => Some((*s).clone()),
92 fn meta_item_list<'a>(&'a self) -> Option<&'a [P<MetaItem>]> {
94 MetaList(_, ref l) => Some(&l[..]),
98 fn span(&self) -> Span { self.span }
101 // Annoying, but required to get test_cfg to work
102 impl AttrMetaMethods for P<MetaItem> {
103 fn name(&self) -> InternedString { (**self).name() }
104 fn value_str(&self) -> Option<InternedString> { (**self).value_str() }
105 fn meta_item_list<'a>(&'a self) -> Option<&'a [P<MetaItem>]> {
106 (**self).meta_item_list()
108 fn span(&self) -> Span { (**self).span() }
112 pub trait AttributeMethods {
113 fn meta<'a>(&'a self) -> &'a MetaItem;
114 fn with_desugared_doc<T, F>(&self, f: F) -> T where
115 F: FnOnce(&Attribute) -> T;
118 impl AttributeMethods for Attribute {
119 /// Extract the MetaItem from inside this Attribute.
120 fn meta<'a>(&'a self) -> &'a MetaItem {
124 /// Convert self to a normal #[doc="foo"] comment, if it is a
125 /// comment like `///` or `/** */`. (Returns self unchanged for
126 /// non-sugared doc attributes.)
127 fn with_desugared_doc<T, F>(&self, f: F) -> T where
128 F: FnOnce(&Attribute) -> T,
130 if self.node.is_sugared_doc {
131 let comment = self.value_str().unwrap();
132 let meta = mk_name_value_item_str(
133 InternedString::new("doc"),
134 token::intern_and_get_ident(&strip_doc_comment_decoration(
136 if self.node.style == hir::AttrOuter {
137 f(&mk_attr_outer(self.node.id, meta))
139 f(&mk_attr_inner(self.node.id, meta))
149 pub fn mk_name_value_item_str(name: InternedString, value: InternedString)
151 let value_lit = dummy_spanned(hir::LitStr(value, hir::CookedStr));
152 mk_name_value_item(name, value_lit)
155 pub fn mk_name_value_item(name: InternedString, value: hir::Lit)
157 P(dummy_spanned(MetaNameValue(name, value)))
160 pub fn mk_list_item(name: InternedString, items: Vec<P<MetaItem>>) -> P<MetaItem> {
161 P(dummy_spanned(MetaList(name, items)))
164 pub fn mk_word_item(name: InternedString) -> P<MetaItem> {
165 P(dummy_spanned(MetaWord(name)))
168 thread_local! { static NEXT_ATTR_ID: Cell<usize> = Cell::new(0) }
170 pub fn mk_attr_id() -> AttrId {
171 let id = NEXT_ATTR_ID.with(|slot| {
179 /// Returns an inner attribute with the given value.
180 pub fn mk_attr_inner(id: AttrId, item: P<MetaItem>) -> Attribute {
181 dummy_spanned(Attribute_ {
183 style: hir::AttrInner,
185 is_sugared_doc: false,
189 /// Returns an outer attribute with the given value.
190 pub fn mk_attr_outer(id: AttrId, item: P<MetaItem>) -> Attribute {
191 dummy_spanned(Attribute_ {
193 style: hir::AttrOuter,
195 is_sugared_doc: false,
199 pub fn mk_sugared_doc_attr(id: AttrId, text: InternedString, lo: BytePos,
202 let style = lower_attr_style(doc_comment_style(&text));
203 let lit = spanned(lo, hi, hir::LitStr(text, hir::CookedStr));
204 let attr = Attribute_ {
207 value: P(spanned(lo, hi, MetaNameValue(InternedString::new("doc"),
211 spanned(lo, hi, attr)
215 /// Check if `needle` occurs in `haystack` by a structural
216 /// comparison. This is slightly subtle, and relies on ignoring the
217 /// span included in the `==` comparison a plain MetaItem.
218 pub fn contains(haystack: &[P<MetaItem>], needle: &MetaItem) -> bool {
219 debug!("attr::contains (name={})", needle.name());
220 haystack.iter().any(|item| {
221 debug!(" testing: {}", item.name());
222 item.node == needle.node
226 pub fn contains_name<AM: AttrMetaMethods>(metas: &[AM], name: &str) -> bool {
227 debug!("attr::contains_name (name={})", name);
228 metas.iter().any(|item| {
229 debug!(" testing: {}", item.name());
230 item.check_name(name)
234 pub fn first_attr_value_str_by_name(attrs: &[Attribute], name: &str)
235 -> Option<InternedString> {
237 .find(|at| at.check_name(name))
238 .and_then(|at| at.value_str())
241 pub fn last_meta_item_value_str_by_name(items: &[P<MetaItem>], name: &str)
242 -> Option<InternedString> {
245 .find(|mi| mi.check_name(name))
246 .and_then(|i| i.value_str())
249 /* Higher-level applications */
251 pub fn sort_meta_items(items: Vec<P<MetaItem>>) -> Vec<P<MetaItem>> {
252 // This is sort of stupid here, but we need to sort by
253 // human-readable strings.
254 let mut v = items.into_iter()
255 .map(|mi| (mi.name(), mi))
256 .collect::<Vec<(InternedString, P<MetaItem>)>>();
258 v.sort_by(|&(ref a, _), &(ref b, _)| a.cmp(b));
260 // There doesn't seem to be a more optimal way to do this
261 v.into_iter().map(|(_, m)| m.map(|Spanned {node, span}| {
264 MetaList(n, mis) => MetaList(n, sort_meta_items(mis)),
272 pub fn find_crate_name(attrs: &[Attribute]) -> Option<InternedString> {
273 first_attr_value_str_by_name(attrs, "crate_name")
276 /// Find the value of #[export_name=*] attribute and check its validity.
277 pub fn find_export_name_attr(diag: &SpanHandler, attrs: &[Attribute]) -> Option<InternedString> {
278 attrs.iter().fold(None, |ia,attr| {
279 if attr.check_name("export_name") {
280 if let s@Some(_) = attr.value_str() {
283 diag.span_err(attr.span, "export_name attribute has invalid format");
284 diag.handler.help("use #[export_name=\"*\"]");
293 #[derive(Copy, Clone, PartialEq)]
294 pub enum InlineAttr {
301 /// Determine what `#[inline]` attribute is present in `attrs`, if any.
302 pub fn find_inline_attr(diagnostic: Option<&SpanHandler>, attrs: &[Attribute]) -> InlineAttr {
303 // FIXME (#2809)---validate the usage of #[inline] and #[inline]
304 attrs.iter().fold(InlineAttr::None, |ia,attr| {
305 match attr.node.value.node {
306 MetaWord(ref n) if *n == "inline" => {
307 syntax_attr::mark_used(&unlower_attribute(attr));
310 MetaList(ref n, ref items) if *n == "inline" => {
311 syntax_attr::mark_used(&unlower_attribute(attr));
312 if items.len() != 1 {
313 diagnostic.map(|d|{ d.span_err(attr.span, "expected one argument"); });
315 } else if contains_name(&items[..], "always") {
317 } else if contains_name(&items[..], "never") {
320 diagnostic.map(|d|{ d.span_err((*items[0]).span, "invalid argument"); });
329 /// True if `#[inline]` or `#[inline(always)]` is present in `attrs`.
330 pub fn requests_inline(attrs: &[Attribute]) -> bool {
331 match find_inline_attr(None, attrs) {
332 InlineAttr::Hint | InlineAttr::Always => true,
333 InlineAttr::None | InlineAttr::Never => false,
337 /// Represents the #[deprecated] and friends attributes.
338 #[derive(RustcEncodable, RustcDecodable, Clone, Debug, PartialEq, Eq, Hash)]
339 pub struct Stability {
340 pub level: StabilityLevel,
341 pub feature: InternedString,
342 pub since: Option<InternedString>,
343 pub deprecated_since: Option<InternedString>,
344 // The reason for the current stability level. If deprecated, the
345 // reason for deprecation.
346 pub reason: Option<InternedString>,
347 // The relevant rust-lang issue
348 pub issue: Option<u32>
351 /// The available stability levels.
352 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Debug, Copy, Eq, Hash)]
353 pub enum StabilityLevel {
358 impl fmt::Display for StabilityLevel {
359 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
360 fmt::Debug::fmt(self, f)
364 fn find_stability_generic<'a,
366 I: Iterator<Item=&'a AM>>
367 (diagnostic: &SpanHandler, attrs: I, item_sp: Span)
368 -> (Option<Stability>, Vec<&'a AM>) {
370 let mut stab: Option<Stability> = None;
371 let mut deprecated: Option<(Option<InternedString>, Option<InternedString>)> = None;
372 let mut used_attrs: Vec<&'a AM> = vec![];
374 'outer: for attr in attrs {
375 let tag = attr.name();
377 if tag != "deprecated" && tag != "unstable" && tag != "stable" {
378 continue // not a stability level
381 used_attrs.push(attr);
383 let (feature, since, reason, issue) = match attr.meta_item_list() {
385 let mut feature = None;
386 let mut since = None;
387 let mut reason = None;
388 let mut issue = None;
390 match &*meta.name() {
392 match meta.value_str() {
393 Some(v) => feature = Some(v),
395 diagnostic.span_err(meta.span, "incorrect meta item");
401 match meta.value_str() {
402 Some(v) => since = Some(v),
404 diagnostic.span_err(meta.span, "incorrect meta item");
410 match meta.value_str() {
411 Some(v) => reason = Some(v),
413 diagnostic.span_err(meta.span, "incorrect meta item");
419 match meta.value_str().and_then(|s| s.parse().ok()) {
420 Some(v) => issue = Some(v),
422 diagnostic.span_err(meta.span, "incorrect meta item");
430 (feature, since, reason, issue)
433 diagnostic.span_err(attr.span(), "incorrect stability attribute type");
438 // Deprecated tags don't require feature names
439 if feature == None && tag != "deprecated" {
440 diagnostic.span_err(attr.span(), "missing 'feature'");
443 // Unstable tags don't require a version
444 if since == None && tag != "unstable" {
445 diagnostic.span_err(attr.span(), "missing 'since'");
448 if tag == "unstable" || tag == "stable" {
450 diagnostic.span_err(item_sp, "multiple stability levels");
453 let level = match tag {
454 "unstable" => Unstable,
459 stab = Some(Stability {
461 feature: feature.unwrap_or(intern_and_get_ident("bogus")),
463 deprecated_since: None,
467 } else { // "deprecated"
468 if deprecated.is_some() {
469 diagnostic.span_err(item_sp, "multiple deprecated attributes");
472 deprecated = Some((since, reason));
476 // Merge the deprecation info into the stability info
477 if deprecated.is_some() {
480 let (since, reason) = deprecated.unwrap();
481 s.deprecated_since = since;
485 diagnostic.span_err(item_sp, "deprecated attribute must be paired with \
486 either stable or unstable attribute");
489 } else if stab.as_ref().map_or(false, |s| s.level == Unstable && s.issue.is_none()) {
490 // non-deprecated unstable items need to point to issues.
491 diagnostic.span_err(item_sp,
492 "non-deprecated unstable items need to point \
493 to an issue with `issue = \"NNN\"`");
499 /// Find the first stability attribute. `None` if none exists.
500 pub fn find_stability(diagnostic: &SpanHandler, attrs: &[Attribute],
501 item_sp: Span) -> Option<Stability> {
502 let (s, used) = find_stability_generic(diagnostic, attrs.iter(), item_sp);
503 for used in used { syntax_attr::mark_used(&unlower_attribute(used)) }
507 pub fn require_unique_names(diagnostic: &SpanHandler, metas: &[P<MetaItem>]) {
508 let mut set = HashSet::new();
510 let name = meta.name();
512 if !set.insert(name.clone()) {
513 panic!(diagnostic.span_fatal(meta.span,
514 &format!("duplicate meta item `{}`", name)));
520 /// Parse #[repr(...)] forms.
522 /// Valid repr contents: any of the primitive integral type names (see
523 /// `int_type_of_word`, below) to specify enum discriminant type; `C`, to use
524 /// the same discriminant size that the corresponding C enum would or C
525 /// structure layout, and `packed` to remove padding.
526 pub fn find_repr_attrs(diagnostic: &SpanHandler, attr: &Attribute) -> Vec<ReprAttr> {
527 let mut acc = Vec::new();
528 match attr.node.value.node {
529 hir::MetaList(ref s, ref items) if *s == "repr" => {
530 syntax_attr::mark_used(&unlower_attribute(attr));
533 hir::MetaWord(ref word) => {
534 let hint = match &word[..] {
535 // Can't use "extern" because it's not a lexical identifier.
536 "C" => Some(ReprExtern),
537 "packed" => Some(ReprPacked),
538 "simd" => Some(ReprSimd),
539 _ => match int_type_of_word(&word) {
540 Some(ity) => Some(ReprInt(item.span, ity)),
542 // Not a word we recognize
543 diagnostic.span_err(item.span,
544 "unrecognized representation hint");
551 Some(h) => acc.push(h),
556 _ => diagnostic.span_err(item.span, "unrecognized enum representation hint")
560 // Not a "repr" hint: ignore.
566 fn int_type_of_word(s: &str) -> Option<IntType> {
568 "i8" => Some(SignedInt(hir::TyI8)),
569 "u8" => Some(UnsignedInt(hir::TyU8)),
570 "i16" => Some(SignedInt(hir::TyI16)),
571 "u16" => Some(UnsignedInt(hir::TyU16)),
572 "i32" => Some(SignedInt(hir::TyI32)),
573 "u32" => Some(UnsignedInt(hir::TyU32)),
574 "i64" => Some(SignedInt(hir::TyI64)),
575 "u64" => Some(UnsignedInt(hir::TyU64)),
576 "isize" => Some(SignedInt(hir::TyIs)),
577 "usize" => Some(UnsignedInt(hir::TyUs)),
582 #[derive(PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
585 ReprInt(Span, IntType),
592 pub fn is_ffi_safe(&self) -> bool {
595 ReprInt(_sp, ity) => ity.is_ffi_safe(),
603 #[derive(Eq, Hash, PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
605 SignedInt(hir::IntTy),
606 UnsignedInt(hir::UintTy)
611 pub fn is_signed(self) -> bool {
613 SignedInt(..) => true,
614 UnsignedInt(..) => false
617 fn is_ffi_safe(self) -> bool {
619 SignedInt(hir::TyI8) | UnsignedInt(hir::TyU8) |
620 SignedInt(hir::TyI16) | UnsignedInt(hir::TyU16) |
621 SignedInt(hir::TyI32) | UnsignedInt(hir::TyU32) |
622 SignedInt(hir::TyI64) | UnsignedInt(hir::TyU64) => true,
623 SignedInt(hir::TyIs) | UnsignedInt(hir::TyUs) => false