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 hir::{AttrId, Attribute, Attribute_, MetaItem, MetaWord, MetaNameValue, MetaList};
19 use lowering::{lower_attr_style, unlower_attribute};
20 use syntax::codemap::{Span, Spanned, spanned, dummy_spanned};
21 use syntax::codemap::BytePos;
22 use syntax::diagnostic::SpanHandler;
23 use syntax::attr as syntax_attr;
24 use syntax::parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
25 use syntax::parse::token::{InternedString, intern_and_get_ident};
26 use syntax::parse::token;
30 use std::collections::HashSet;
33 pub fn mark_used(attr: &Attribute) {
34 syntax_attr::mark_used(&unlower_attribute(attr))
37 pub trait AttrMetaMethods {
38 fn check_name(&self, name: &str) -> bool {
39 name == &self.name()[..]
42 /// Retrieve the name of the meta item, e.g. `foo` in `#[foo]`,
43 /// `#[foo="bar"]` and `#[foo(bar)]`
44 fn name(&self) -> InternedString;
46 /// Gets the string value if self is a MetaNameValue variant
47 /// containing a string, otherwise None.
48 fn value_str(&self) -> Option<InternedString>;
49 /// Gets a list of inner meta items from a list MetaItem type.
50 fn meta_item_list<'a>(&'a self) -> Option<&'a [P<MetaItem>]>;
52 fn span(&self) -> Span;
55 impl AttrMetaMethods for Attribute {
56 fn check_name(&self, name: &str) -> bool {
57 let matches = name == &self.name()[..];
59 syntax_attr::mark_used(&unlower_attribute(self));
63 fn name(&self) -> InternedString { self.meta().name() }
64 fn value_str(&self) -> Option<InternedString> {
65 self.meta().value_str()
67 fn meta_item_list<'a>(&'a self) -> Option<&'a [P<MetaItem>]> {
68 self.node.value.meta_item_list()
70 fn span(&self) -> Span { self.meta().span }
73 impl AttrMetaMethods for MetaItem {
74 fn name(&self) -> InternedString {
76 MetaWord(ref n) => (*n).clone(),
77 MetaNameValue(ref n, _) => (*n).clone(),
78 MetaList(ref n, _) => (*n).clone(),
82 fn value_str(&self) -> Option<InternedString> {
84 MetaNameValue(_, ref v) => {
86 hir::LitStr(ref s, _) => Some((*s).clone()),
94 fn meta_item_list<'a>(&'a self) -> Option<&'a [P<MetaItem>]> {
96 MetaList(_, ref l) => Some(&l[..]),
100 fn span(&self) -> Span { self.span }
103 // Annoying, but required to get test_cfg to work
104 impl AttrMetaMethods for P<MetaItem> {
105 fn name(&self) -> InternedString { (**self).name() }
106 fn value_str(&self) -> Option<InternedString> { (**self).value_str() }
107 fn meta_item_list<'a>(&'a self) -> Option<&'a [P<MetaItem>]> {
108 (**self).meta_item_list()
110 fn span(&self) -> Span { (**self).span() }
114 pub trait AttributeMethods {
115 fn meta<'a>(&'a self) -> &'a MetaItem;
116 fn with_desugared_doc<T, F>(&self, f: F) -> T where
117 F: FnOnce(&Attribute) -> T;
120 impl AttributeMethods for Attribute {
121 /// Extract the MetaItem from inside this Attribute.
122 fn meta<'a>(&'a self) -> &'a MetaItem {
126 /// Convert self to a normal #[doc="foo"] comment, if it is a
127 /// comment like `///` or `/** */`. (Returns self unchanged for
128 /// non-sugared doc attributes.)
129 fn with_desugared_doc<T, F>(&self, f: F) -> T where
130 F: FnOnce(&Attribute) -> T,
132 if self.node.is_sugared_doc {
133 let comment = self.value_str().unwrap();
134 let meta = mk_name_value_item_str(
135 InternedString::new("doc"),
136 token::intern_and_get_ident(&strip_doc_comment_decoration(
138 if self.node.style == hir::AttrOuter {
139 f(&mk_attr_outer(self.node.id, meta))
141 f(&mk_attr_inner(self.node.id, meta))
151 pub fn mk_name_value_item_str(name: InternedString, value: InternedString)
153 let value_lit = dummy_spanned(hir::LitStr(value, hir::CookedStr));
154 mk_name_value_item(name, value_lit)
157 pub fn mk_name_value_item(name: InternedString, value: hir::Lit)
159 P(dummy_spanned(MetaNameValue(name, value)))
162 pub fn mk_list_item(name: InternedString, items: Vec<P<MetaItem>>) -> P<MetaItem> {
163 P(dummy_spanned(MetaList(name, items)))
166 pub fn mk_word_item(name: InternedString) -> P<MetaItem> {
167 P(dummy_spanned(MetaWord(name)))
170 thread_local! { static NEXT_ATTR_ID: Cell<usize> = Cell::new(0) }
172 pub fn mk_attr_id() -> AttrId {
173 let id = NEXT_ATTR_ID.with(|slot| {
181 /// Returns an inner attribute with the given value.
182 pub fn mk_attr_inner(id: AttrId, item: P<MetaItem>) -> Attribute {
183 dummy_spanned(Attribute_ {
185 style: hir::AttrInner,
187 is_sugared_doc: false,
191 /// Returns an outer attribute with the given value.
192 pub fn mk_attr_outer(id: AttrId, item: P<MetaItem>) -> Attribute {
193 dummy_spanned(Attribute_ {
195 style: hir::AttrOuter,
197 is_sugared_doc: false,
201 pub fn mk_sugared_doc_attr(id: AttrId, text: InternedString, lo: BytePos,
204 let style = lower_attr_style(doc_comment_style(&text));
205 let lit = spanned(lo, hi, hir::LitStr(text, hir::CookedStr));
206 let attr = Attribute_ {
209 value: P(spanned(lo, hi, MetaNameValue(InternedString::new("doc"),
213 spanned(lo, hi, attr)
217 /// Check if `needle` occurs in `haystack` by a structural
218 /// comparison. This is slightly subtle, and relies on ignoring the
219 /// span included in the `==` comparison a plain MetaItem.
220 pub fn contains(haystack: &[P<MetaItem>], needle: &MetaItem) -> bool {
221 debug!("attr::contains (name={})", needle.name());
222 haystack.iter().any(|item| {
223 debug!(" testing: {}", item.name());
224 item.node == needle.node
228 pub fn contains_name<AM: AttrMetaMethods>(metas: &[AM], name: &str) -> bool {
229 debug!("attr::contains_name (name={})", name);
230 metas.iter().any(|item| {
231 debug!(" testing: {}", item.name());
232 item.check_name(name)
236 pub fn first_attr_value_str_by_name(attrs: &[Attribute], name: &str)
237 -> Option<InternedString> {
239 .find(|at| at.check_name(name))
240 .and_then(|at| at.value_str())
243 pub fn last_meta_item_value_str_by_name(items: &[P<MetaItem>], name: &str)
244 -> Option<InternedString> {
247 .find(|mi| mi.check_name(name))
248 .and_then(|i| i.value_str())
251 /* Higher-level applications */
253 pub fn sort_meta_items(items: Vec<P<MetaItem>>) -> Vec<P<MetaItem>> {
254 // This is sort of stupid here, but we need to sort by
255 // human-readable strings.
256 let mut v = items.into_iter()
257 .map(|mi| (mi.name(), mi))
258 .collect::<Vec<(InternedString, P<MetaItem>)>>();
260 v.sort_by(|&(ref a, _), &(ref b, _)| a.cmp(b));
262 // There doesn't seem to be a more optimal way to do this
263 v.into_iter().map(|(_, m)| m.map(|Spanned {node, span}| {
266 MetaList(n, mis) => MetaList(n, sort_meta_items(mis)),
274 pub fn find_crate_name(attrs: &[Attribute]) -> Option<InternedString> {
275 first_attr_value_str_by_name(attrs, "crate_name")
278 /// Find the value of #[export_name=*] attribute and check its validity.
279 pub fn find_export_name_attr(diag: &SpanHandler, attrs: &[Attribute]) -> Option<InternedString> {
280 attrs.iter().fold(None, |ia,attr| {
281 if attr.check_name("export_name") {
282 if let s@Some(_) = attr.value_str() {
285 diag.span_err(attr.span, "export_name attribute has invalid format");
286 diag.handler.help("use #[export_name=\"*\"]");
295 #[derive(Copy, Clone, PartialEq)]
296 pub enum InlineAttr {
303 /// Determine what `#[inline]` attribute is present in `attrs`, if any.
304 pub fn find_inline_attr(diagnostic: Option<&SpanHandler>, attrs: &[Attribute]) -> InlineAttr {
305 // FIXME (#2809)---validate the usage of #[inline] and #[inline]
306 attrs.iter().fold(InlineAttr::None, |ia,attr| {
307 match attr.node.value.node {
308 MetaWord(ref n) if *n == "inline" => {
309 syntax_attr::mark_used(&unlower_attribute(attr));
312 MetaList(ref n, ref items) if *n == "inline" => {
313 syntax_attr::mark_used(&unlower_attribute(attr));
314 if items.len() != 1 {
315 diagnostic.map(|d|{ d.span_err(attr.span, "expected one argument"); });
317 } else if contains_name(&items[..], "always") {
319 } else if contains_name(&items[..], "never") {
322 diagnostic.map(|d|{ d.span_err((*items[0]).span, "invalid argument"); });
331 /// True if `#[inline]` or `#[inline(always)]` is present in `attrs`.
332 pub fn requests_inline(attrs: &[Attribute]) -> bool {
333 match find_inline_attr(None, attrs) {
334 InlineAttr::Hint | InlineAttr::Always => true,
335 InlineAttr::None | InlineAttr::Never => false,
339 /// Represents the #[deprecated] and friends attributes.
340 #[derive(RustcEncodable, RustcDecodable, Clone, Debug, PartialEq, Eq, Hash)]
341 pub struct Stability {
342 pub level: StabilityLevel,
343 pub feature: InternedString,
344 pub since: Option<InternedString>,
345 pub deprecated_since: Option<InternedString>,
346 // The reason for the current stability level. If deprecated, the
347 // reason for deprecation.
348 pub reason: Option<InternedString>,
349 // The relevant rust-lang issue
350 pub issue: Option<u32>
353 /// The available stability levels.
354 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Debug, Copy, Eq, Hash)]
355 pub enum StabilityLevel {
360 impl fmt::Display for StabilityLevel {
361 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
362 fmt::Debug::fmt(self, f)
366 fn find_stability_generic<'a,
368 I: Iterator<Item=&'a AM>>
369 (diagnostic: &SpanHandler, attrs: I, item_sp: Span)
370 -> (Option<Stability>, Vec<&'a AM>) {
372 let mut stab: Option<Stability> = None;
373 let mut deprecated: Option<(Option<InternedString>, Option<InternedString>)> = None;
374 let mut used_attrs: Vec<&'a AM> = vec![];
376 'outer: for attr in attrs {
377 let tag = attr.name();
379 if tag != "deprecated" && tag != "unstable" && tag != "stable" {
380 continue // not a stability level
383 used_attrs.push(attr);
385 let (feature, since, reason, issue) = match attr.meta_item_list() {
387 let mut feature = None;
388 let mut since = None;
389 let mut reason = None;
390 let mut issue = None;
392 match &*meta.name() {
394 match meta.value_str() {
395 Some(v) => feature = Some(v),
397 diagnostic.span_err(meta.span, "incorrect meta item");
403 match meta.value_str() {
404 Some(v) => since = Some(v),
406 diagnostic.span_err(meta.span, "incorrect meta item");
412 match meta.value_str() {
413 Some(v) => reason = Some(v),
415 diagnostic.span_err(meta.span, "incorrect meta item");
421 match meta.value_str().and_then(|s| s.parse().ok()) {
422 Some(v) => issue = Some(v),
424 diagnostic.span_err(meta.span, "incorrect meta item");
432 (feature, since, reason, issue)
435 diagnostic.span_err(attr.span(), "incorrect stability attribute type");
440 // Deprecated tags don't require feature names
441 if feature == None && tag != "deprecated" {
442 diagnostic.span_err(attr.span(), "missing 'feature'");
445 // Unstable tags don't require a version
446 if since == None && tag != "unstable" {
447 diagnostic.span_err(attr.span(), "missing 'since'");
450 if tag == "unstable" || tag == "stable" {
452 diagnostic.span_err(item_sp, "multiple stability levels");
455 let level = match tag {
456 "unstable" => Unstable,
461 stab = Some(Stability {
463 feature: feature.unwrap_or(intern_and_get_ident("bogus")),
465 deprecated_since: None,
469 } else { // "deprecated"
470 if deprecated.is_some() {
471 diagnostic.span_err(item_sp, "multiple deprecated attributes");
474 deprecated = Some((since, reason));
478 // Merge the deprecation info into the stability info
479 if deprecated.is_some() {
482 let (since, reason) = deprecated.unwrap();
483 s.deprecated_since = since;
487 diagnostic.span_err(item_sp, "deprecated attribute must be paired with \
488 either stable or unstable attribute");
491 } else if stab.as_ref().map_or(false, |s| s.level == Unstable && s.issue.is_none()) {
492 // non-deprecated unstable items need to point to issues.
493 diagnostic.span_err(item_sp,
494 "non-deprecated unstable items need to point \
495 to an issue with `issue = \"NNN\"`");
501 /// Find the first stability attribute. `None` if none exists.
502 pub fn find_stability(diagnostic: &SpanHandler, attrs: &[Attribute],
503 item_sp: Span) -> Option<Stability> {
504 let (s, used) = find_stability_generic(diagnostic, attrs.iter(), item_sp);
505 for used in used { syntax_attr::mark_used(&unlower_attribute(used)) }
509 pub fn require_unique_names(diagnostic: &SpanHandler, metas: &[P<MetaItem>]) {
510 let mut set = HashSet::new();
512 let name = meta.name();
514 if !set.insert(name.clone()) {
515 panic!(diagnostic.span_fatal(meta.span,
516 &format!("duplicate meta item `{}`", name)));
522 /// Parse #[repr(...)] forms.
524 /// Valid repr contents: any of the primitive integral type names (see
525 /// `int_type_of_word`, below) to specify enum discriminant type; `C`, to use
526 /// the same discriminant size that the corresponding C enum would or C
527 /// structure layout, and `packed` to remove padding.
528 pub fn find_repr_attrs(diagnostic: &SpanHandler, attr: &Attribute) -> Vec<ReprAttr> {
529 let mut acc = Vec::new();
530 match attr.node.value.node {
531 hir::MetaList(ref s, ref items) if *s == "repr" => {
532 syntax_attr::mark_used(&unlower_attribute(attr));
535 hir::MetaWord(ref word) => {
536 let hint = match &word[..] {
537 // Can't use "extern" because it's not a lexical identifier.
538 "C" => Some(ReprExtern),
539 "packed" => Some(ReprPacked),
540 "simd" => Some(ReprSimd),
541 _ => match int_type_of_word(&word) {
542 Some(ity) => Some(ReprInt(item.span, ity)),
544 // Not a word we recognize
545 diagnostic.span_err(item.span,
546 "unrecognized representation hint");
553 Some(h) => acc.push(h),
558 _ => diagnostic.span_err(item.span, "unrecognized enum representation hint")
562 // Not a "repr" hint: ignore.
568 fn int_type_of_word(s: &str) -> Option<IntType> {
570 "i8" => Some(SignedInt(hir::TyI8)),
571 "u8" => Some(UnsignedInt(hir::TyU8)),
572 "i16" => Some(SignedInt(hir::TyI16)),
573 "u16" => Some(UnsignedInt(hir::TyU16)),
574 "i32" => Some(SignedInt(hir::TyI32)),
575 "u32" => Some(UnsignedInt(hir::TyU32)),
576 "i64" => Some(SignedInt(hir::TyI64)),
577 "u64" => Some(UnsignedInt(hir::TyU64)),
578 "isize" => Some(SignedInt(hir::TyIs)),
579 "usize" => Some(UnsignedInt(hir::TyUs)),
584 #[derive(PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
587 ReprInt(Span, IntType),
594 pub fn is_ffi_safe(&self) -> bool {
597 ReprInt(_sp, ity) => ity.is_ffi_safe(),
605 #[derive(Eq, Hash, PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
607 SignedInt(hir::IntTy),
608 UnsignedInt(hir::UintTy)
613 pub fn is_signed(self) -> bool {
615 SignedInt(..) => true,
616 UnsignedInt(..) => false
619 fn is_ffi_safe(self) -> bool {
621 SignedInt(hir::TyI8) | UnsignedInt(hir::TyU8) |
622 SignedInt(hir::TyI16) | UnsignedInt(hir::TyU16) |
623 SignedInt(hir::TyI32) | UnsignedInt(hir::TyU32) |
624 SignedInt(hir::TyI64) | UnsignedInt(hir::TyU64) => true,
625 SignedInt(hir::TyIs) | UnsignedInt(hir::TyUs) => false