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, Name};
19 use ast::{MetaItem, MetaItemKind, NestedMetaItem, NestedMetaItemKind};
20 use ast::{Lit, Expr, Item, Local, Stmt, StmtKind};
21 use codemap::{Spanned, spanned, dummy_spanned, mk_sp};
22 use syntax_pos::{Span, BytePos, DUMMY_SP};
24 use feature_gate::{Features, GatedCfg};
25 use parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
31 use std::cell::{RefCell, Cell};
34 static USED_ATTRS: RefCell<Vec<u64>> = RefCell::new(Vec::new());
35 static KNOWN_ATTRS: RefCell<Vec<u64>> = RefCell::new(Vec::new());
40 UnknownMetaItem(Name),
43 MultipleStabilityLevels,
47 fn handle_errors(diag: &Handler, span: Span, error: AttrError) {
49 AttrError::MultipleItem(item) => span_err!(diag, span, E0538,
50 "multiple '{}' items", item),
51 AttrError::UnknownMetaItem(item) => span_err!(diag, span, E0541,
52 "unknown meta item '{}'", item),
53 AttrError::MissingSince => span_err!(diag, span, E0542, "missing 'since'"),
54 AttrError::MissingFeature => span_err!(diag, span, E0546, "missing 'feature'"),
55 AttrError::MultipleStabilityLevels => span_err!(diag, span, E0544,
56 "multiple stability levels"),
57 AttrError::UnsupportedLiteral => span_err!(diag, span, E0565, "unsupported literal"),
61 pub fn mark_used(attr: &Attribute) {
62 debug!("Marking {:?} as used.", attr);
63 let AttrId(id) = attr.id;
64 USED_ATTRS.with(|slot| {
65 let idx = (id / 64) as usize;
67 if slot.borrow().len() <= idx {
68 slot.borrow_mut().resize(idx + 1, 0);
70 slot.borrow_mut()[idx] |= 1 << shift;
74 pub fn is_used(attr: &Attribute) -> bool {
75 let AttrId(id) = attr.id;
76 USED_ATTRS.with(|slot| {
77 let idx = (id / 64) as usize;
79 slot.borrow().get(idx).map(|bits| bits & (1 << shift) != 0)
84 pub fn mark_known(attr: &Attribute) {
85 debug!("Marking {:?} as known.", attr);
86 let AttrId(id) = attr.id;
87 KNOWN_ATTRS.with(|slot| {
88 let idx = (id / 64) as usize;
90 if slot.borrow().len() <= idx {
91 slot.borrow_mut().resize(idx + 1, 0);
93 slot.borrow_mut()[idx] |= 1 << shift;
97 pub fn is_known(attr: &Attribute) -> bool {
98 let AttrId(id) = attr.id;
99 KNOWN_ATTRS.with(|slot| {
100 let idx = (id / 64) as usize;
102 slot.borrow().get(idx).map(|bits| bits & (1 << shift) != 0)
107 impl NestedMetaItem {
108 /// Returns the MetaItem if self is a NestedMetaItemKind::MetaItem.
109 pub fn meta_item(&self) -> Option<&MetaItem> {
111 NestedMetaItemKind::MetaItem(ref item) => Some(&item),
116 /// Returns the Lit if self is a NestedMetaItemKind::Literal.
117 pub fn literal(&self) -> Option<&Lit> {
119 NestedMetaItemKind::Literal(ref lit) => Some(&lit),
124 /// Returns the Span for `self`.
125 pub fn span(&self) -> Span {
129 /// Returns true if this list item is a MetaItem with a name of `name`.
130 pub fn check_name(&self, name: &str) -> bool {
131 self.meta_item().map_or(false, |meta_item| meta_item.check_name(name))
134 /// Returns the name of the meta item, e.g. `foo` in `#[foo]`,
135 /// `#[foo="bar"]` and `#[foo(bar)]`, if self is a MetaItem
136 pub fn name(&self) -> Option<Name> {
137 self.meta_item().and_then(|meta_item| Some(meta_item.name()))
140 /// Gets the string value if self is a MetaItem and the MetaItem is a
141 /// MetaItemKind::NameValue variant containing a string, otherwise None.
142 pub fn value_str(&self) -> Option<Symbol> {
143 self.meta_item().and_then(|meta_item| meta_item.value_str())
146 /// Returns a MetaItem if self is a MetaItem with Kind Word.
147 pub fn word(&self) -> Option<&MetaItem> {
148 self.meta_item().and_then(|meta_item| if meta_item.is_word() {
155 /// Gets a list of inner meta items from a list MetaItem type.
156 pub fn meta_item_list(&self) -> Option<&[NestedMetaItem]> {
157 self.meta_item().and_then(|meta_item| meta_item.meta_item_list())
160 /// Returns `true` if the variant is MetaItem.
161 pub fn is_meta_item(&self) -> bool {
162 self.meta_item().is_some()
165 /// Returns `true` if the variant is Literal.
166 pub fn is_literal(&self) -> bool {
167 self.literal().is_some()
170 /// Returns `true` if self is a MetaItem and the meta item is a word.
171 pub fn is_word(&self) -> bool {
172 self.word().is_some()
175 /// Returns `true` if self is a MetaItem and the meta item is a ValueString.
176 pub fn is_value_str(&self) -> bool {
177 self.value_str().is_some()
180 /// Returns `true` if self is a MetaItem and the meta item is a list.
181 pub fn is_meta_item_list(&self) -> bool {
182 self.meta_item_list().is_some()
187 pub fn check_name(&self, name: &str) -> bool {
188 let matches = self.name() == name;
195 pub fn name(&self) -> Name { self.meta().name() }
197 pub fn value_str(&self) -> Option<Symbol> {
198 self.meta().value_str()
201 pub fn meta_item_list(&self) -> Option<&[NestedMetaItem]> {
202 self.meta().meta_item_list()
205 pub fn is_word(&self) -> bool { self.meta().is_word() }
207 pub fn span(&self) -> Span { self.meta().span }
209 pub fn is_meta_item_list(&self) -> bool {
210 self.meta_item_list().is_some()
213 /// Indicates if the attribute is a Value String.
214 pub fn is_value_str(&self) -> bool {
215 self.value_str().is_some()
220 pub fn name(&self) -> Name {
224 pub fn value_str(&self) -> Option<Symbol> {
226 MetaItemKind::NameValue(ref v) => {
228 ast::LitKind::Str(ref s, _) => Some((*s).clone()),
236 pub fn meta_item_list(&self) -> Option<&[NestedMetaItem]> {
238 MetaItemKind::List(ref l) => Some(&l[..]),
243 pub fn is_word(&self) -> bool {
245 MetaItemKind::Word => true,
250 pub fn span(&self) -> Span { self.span }
252 pub fn check_name(&self, name: &str) -> bool {
256 pub fn is_value_str(&self) -> bool {
257 self.value_str().is_some()
260 pub fn is_meta_item_list(&self) -> bool {
261 self.meta_item_list().is_some()
266 /// Extract the MetaItem from inside this Attribute.
267 pub fn meta(&self) -> &MetaItem {
271 /// Convert self to a normal #[doc="foo"] comment, if it is a
272 /// comment like `///` or `/** */`. (Returns self unchanged for
273 /// non-sugared doc attributes.)
274 pub fn with_desugared_doc<T, F>(&self, f: F) -> T where
275 F: FnOnce(&Attribute) -> T,
277 if self.is_sugared_doc {
278 let comment = self.value_str().unwrap();
279 let meta = mk_name_value_item_str(
280 Symbol::intern("doc"),
281 Symbol::intern(&strip_doc_comment_decoration(&comment.as_str())));
282 if self.style == ast::AttrStyle::Outer {
283 f(&mk_attr_outer(self.span, self.id, meta))
285 f(&mk_attr_inner(self.span, self.id, meta))
295 pub fn mk_name_value_item_str(name: Name, value: Symbol) -> MetaItem {
296 let value_lit = dummy_spanned(ast::LitKind::Str(value, ast::StrStyle::Cooked));
297 mk_spanned_name_value_item(DUMMY_SP, name, value_lit)
300 pub fn mk_name_value_item(name: Name, value: ast::Lit) -> MetaItem {
301 mk_spanned_name_value_item(DUMMY_SP, name, value)
304 pub fn mk_list_item(name: Name, items: Vec<NestedMetaItem>) -> MetaItem {
305 mk_spanned_list_item(DUMMY_SP, name, items)
308 pub fn mk_list_word_item(name: Name) -> ast::NestedMetaItem {
309 dummy_spanned(NestedMetaItemKind::MetaItem(mk_spanned_word_item(DUMMY_SP, name)))
312 pub fn mk_word_item(name: Name) -> MetaItem {
313 mk_spanned_word_item(DUMMY_SP, name)
316 pub fn mk_spanned_name_value_item(sp: Span, name: Name, value: ast::Lit) -> MetaItem {
317 MetaItem { span: sp, name: name, node: MetaItemKind::NameValue(value) }
320 pub fn mk_spanned_list_item(sp: Span, name: Name, items: Vec<NestedMetaItem>) -> MetaItem {
321 MetaItem { span: sp, name: name, node: MetaItemKind::List(items) }
324 pub fn mk_spanned_word_item(sp: Span, name: Name) -> MetaItem {
325 MetaItem { span: sp, name: name, node: MetaItemKind::Word }
330 thread_local! { static NEXT_ATTR_ID: Cell<usize> = Cell::new(0) }
332 pub fn mk_attr_id() -> AttrId {
333 let id = NEXT_ATTR_ID.with(|slot| {
341 /// Returns an inner attribute with the given value.
342 pub fn mk_attr_inner(span: Span, id: AttrId, item: MetaItem) -> Attribute {
343 mk_spanned_attr_inner(span, id, item)
346 /// Returns an innter attribute with the given value and span.
347 pub fn mk_spanned_attr_inner(sp: Span, id: AttrId, item: MetaItem) -> Attribute {
350 style: ast::AttrStyle::Inner,
352 is_sugared_doc: false,
358 /// Returns an outer attribute with the given value.
359 pub fn mk_attr_outer(span: Span, id: AttrId, item: MetaItem) -> Attribute {
360 mk_spanned_attr_outer(span, id, item)
363 /// Returns an outer attribute with the given value and span.
364 pub fn mk_spanned_attr_outer(sp: Span, id: AttrId, item: MetaItem) -> Attribute {
367 style: ast::AttrStyle::Outer,
369 is_sugared_doc: false,
374 pub fn mk_sugared_doc_attr(id: AttrId, text: Symbol, lo: BytePos, hi: BytePos)
376 let style = doc_comment_style(&text.as_str());
377 let lit = spanned(lo, hi, ast::LitKind::Str(text, ast::StrStyle::Cooked));
383 name: Symbol::intern("doc"),
384 node: MetaItemKind::NameValue(lit),
386 is_sugared_doc: true,
391 pub fn list_contains_name(items: &[NestedMetaItem], name: &str) -> bool {
392 debug!("attr::list_contains_name (name={})", name);
393 items.iter().any(|item| {
394 debug!(" testing: {:?}", item.name());
395 item.check_name(name)
399 pub fn contains_name(attrs: &[Attribute], name: &str) -> bool {
400 debug!("attr::contains_name (name={})", name);
401 attrs.iter().any(|item| {
402 debug!(" testing: {}", item.name());
403 item.check_name(name)
407 pub fn first_attr_value_str_by_name(attrs: &[Attribute], name: &str) -> Option<Symbol> {
409 .find(|at| at.check_name(name))
410 .and_then(|at| at.value_str())
413 /* Higher-level applications */
415 pub fn find_crate_name(attrs: &[Attribute]) -> Option<Symbol> {
416 first_attr_value_str_by_name(attrs, "crate_name")
419 /// Find the value of #[export_name=*] attribute and check its validity.
420 pub fn find_export_name_attr(diag: &Handler, attrs: &[Attribute]) -> Option<Symbol> {
421 attrs.iter().fold(None, |ia,attr| {
422 if attr.check_name("export_name") {
423 if let s@Some(_) = attr.value_str() {
426 struct_span_err!(diag, attr.span, E0558,
427 "export_name attribute has invalid format")
428 .span_label(attr.span,
429 &format!("did you mean #[export_name=\"*\"]?"))
439 pub fn contains_extern_indicator(diag: &Handler, attrs: &[Attribute]) -> bool {
440 contains_name(attrs, "no_mangle") ||
441 find_export_name_attr(diag, attrs).is_some()
444 #[derive(Copy, Clone, PartialEq)]
445 pub enum InlineAttr {
452 /// Determine what `#[inline]` attribute is present in `attrs`, if any.
453 pub fn find_inline_attr(diagnostic: Option<&Handler>, attrs: &[Attribute]) -> InlineAttr {
454 attrs.iter().fold(InlineAttr::None, |ia, attr| {
455 match attr.value.node {
456 _ if attr.value.name != "inline" => ia,
457 MetaItemKind::Word => {
461 MetaItemKind::List(ref items) => {
463 if items.len() != 1 {
464 diagnostic.map(|d|{ span_err!(d, attr.span, E0534, "expected one argument"); });
466 } else if list_contains_name(&items[..], "always") {
468 } else if list_contains_name(&items[..], "never") {
472 span_err!(d, items[0].span, E0535, "invalid argument");
483 /// True if `#[inline]` or `#[inline(always)]` is present in `attrs`.
484 pub fn requests_inline(attrs: &[Attribute]) -> bool {
485 match find_inline_attr(None, attrs) {
486 InlineAttr::Hint | InlineAttr::Always => true,
487 InlineAttr::None | InlineAttr::Never => false,
491 /// Tests if a cfg-pattern matches the cfg set
492 pub fn cfg_matches(cfg: &ast::MetaItem, sess: &ParseSess, features: Option<&Features>) -> bool {
494 ast::MetaItemKind::List(ref mis) => {
495 for mi in mis.iter() {
496 if !mi.is_meta_item() {
497 handle_errors(&sess.span_diagnostic, mi.span, AttrError::UnsupportedLiteral);
502 // The unwraps below may look dangerous, but we've already asserted
503 // that they won't fail with the loop above.
504 match &*cfg.name.as_str() {
505 "any" => mis.iter().any(|mi| {
506 cfg_matches(mi.meta_item().unwrap(), sess, features)
508 "all" => mis.iter().all(|mi| {
509 cfg_matches(mi.meta_item().unwrap(), sess, features)
513 span_err!(sess.span_diagnostic, cfg.span, E0536, "expected 1 cfg-pattern");
517 !cfg_matches(mis[0].meta_item().unwrap(), sess, features)
520 span_err!(sess.span_diagnostic, cfg.span, E0537, "invalid predicate `{}`", p);
525 ast::MetaItemKind::Word | ast::MetaItemKind::NameValue(..) => {
526 if let (Some(feats), Some(gated_cfg)) = (features, GatedCfg::gate(cfg)) {
527 gated_cfg.check_and_emit(sess, feats);
529 sess.config.contains(&(cfg.name(), cfg.value_str()))
534 /// Represents the #[stable], #[unstable] and #[rustc_deprecated] attributes.
535 #[derive(RustcEncodable, RustcDecodable, Clone, Debug, PartialEq, Eq, Hash)]
536 pub struct Stability {
537 pub level: StabilityLevel,
539 pub rustc_depr: Option<RustcDeprecation>,
542 /// The available stability levels.
543 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Debug, Eq, Hash)]
544 pub enum StabilityLevel {
545 // Reason for the current stability level and the relevant rust-lang issue
546 Unstable { reason: Option<Symbol>, issue: u32 },
547 Stable { since: Symbol },
550 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Debug, Eq, Hash)]
551 pub struct RustcDeprecation {
556 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Debug, Eq, Hash)]
557 pub struct Deprecation {
558 pub since: Option<Symbol>,
559 pub note: Option<Symbol>,
562 impl StabilityLevel {
563 pub fn is_unstable(&self) -> bool { if let Unstable {..} = *self { true } else { false }}
564 pub fn is_stable(&self) -> bool { if let Stable {..} = *self { true } else { false }}
567 fn find_stability_generic<'a, I>(diagnostic: &Handler,
571 where I: Iterator<Item = &'a Attribute>
573 let mut stab: Option<Stability> = None;
574 let mut rustc_depr: Option<RustcDeprecation> = None;
576 'outer: for attr in attrs_iter {
577 let tag = attr.name();
578 if tag != "rustc_deprecated" && tag != "unstable" && tag != "stable" {
579 continue // not a stability level
584 if let Some(metas) = attr.meta_item_list() {
585 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
587 handle_errors(diagnostic, meta.span, AttrError::MultipleItem(meta.name()));
590 if let Some(v) = meta.value_str() {
594 span_err!(diagnostic, meta.span, E0539, "incorrect meta item");
599 match &*tag.as_str() {
600 "rustc_deprecated" => {
601 if rustc_depr.is_some() {
602 span_err!(diagnostic, item_sp, E0540,
603 "multiple rustc_deprecated attributes");
607 let mut since = None;
608 let mut reason = None;
610 if let Some(mi) = meta.meta_item() {
611 match &*mi.name().as_str() {
612 "since" => if !get(mi, &mut since) { continue 'outer },
613 "reason" => if !get(mi, &mut reason) { continue 'outer },
615 handle_errors(diagnostic, mi.span,
616 AttrError::UnknownMetaItem(mi.name()));
621 handle_errors(diagnostic, meta.span, AttrError::UnsupportedLiteral);
626 match (since, reason) {
627 (Some(since), Some(reason)) => {
628 rustc_depr = Some(RustcDeprecation {
634 handle_errors(diagnostic, attr.span(), AttrError::MissingSince);
638 span_err!(diagnostic, attr.span(), E0543, "missing 'reason'");
645 handle_errors(diagnostic, attr.span(), AttrError::MultipleStabilityLevels);
649 let mut feature = None;
650 let mut reason = None;
651 let mut issue = None;
653 if let Some(mi) = meta.meta_item() {
654 match &*mi.name().as_str() {
655 "feature" => if !get(mi, &mut feature) { continue 'outer },
656 "reason" => if !get(mi, &mut reason) { continue 'outer },
657 "issue" => if !get(mi, &mut issue) { continue 'outer },
659 handle_errors(diagnostic, meta.span,
660 AttrError::UnknownMetaItem(mi.name()));
665 handle_errors(diagnostic, meta.span, AttrError::UnsupportedLiteral);
670 match (feature, reason, issue) {
671 (Some(feature), reason, Some(issue)) => {
672 stab = Some(Stability {
676 if let Ok(issue) = issue.as_str().parse() {
679 span_err!(diagnostic, attr.span(), E0545,
680 "incorrect 'issue'");
690 handle_errors(diagnostic, attr.span(), AttrError::MissingFeature);
694 span_err!(diagnostic, attr.span(), E0547, "missing 'issue'");
701 handle_errors(diagnostic, attr.span(), AttrError::MultipleStabilityLevels);
705 let mut feature = None;
706 let mut since = None;
708 if let NestedMetaItemKind::MetaItem(ref mi) = meta.node {
709 match &*mi.name().as_str() {
710 "feature" => if !get(mi, &mut feature) { continue 'outer },
711 "since" => if !get(mi, &mut since) { continue 'outer },
713 handle_errors(diagnostic, meta.span,
714 AttrError::UnknownMetaItem(mi.name()));
719 handle_errors(diagnostic, meta.span, AttrError::UnsupportedLiteral);
724 match (feature, since) {
725 (Some(feature), Some(since)) => {
726 stab = Some(Stability {
735 handle_errors(diagnostic, attr.span(), AttrError::MissingFeature);
739 handle_errors(diagnostic, attr.span(), AttrError::MissingSince);
747 span_err!(diagnostic, attr.span(), E0548, "incorrect stability attribute type");
752 // Merge the deprecation info into the stability info
753 if let Some(rustc_depr) = rustc_depr {
754 if let Some(ref mut stab) = stab {
755 stab.rustc_depr = Some(rustc_depr);
757 span_err!(diagnostic, item_sp, E0549,
758 "rustc_deprecated attribute must be paired with \
759 either stable or unstable attribute");
766 fn find_deprecation_generic<'a, I>(diagnostic: &Handler,
769 -> Option<Deprecation>
770 where I: Iterator<Item = &'a Attribute>
772 let mut depr: Option<Deprecation> = None;
774 'outer: for attr in attrs_iter {
775 if attr.name() != "deprecated" {
782 span_err!(diagnostic, item_sp, E0550, "multiple deprecated attributes");
786 depr = if let Some(metas) = attr.meta_item_list() {
787 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
789 handle_errors(diagnostic, meta.span, AttrError::MultipleItem(meta.name()));
792 if let Some(v) = meta.value_str() {
796 span_err!(diagnostic, meta.span, E0551, "incorrect meta item");
801 let mut since = None;
804 if let NestedMetaItemKind::MetaItem(ref mi) = meta.node {
805 match &*mi.name().as_str() {
806 "since" => if !get(mi, &mut since) { continue 'outer },
807 "note" => if !get(mi, &mut note) { continue 'outer },
809 handle_errors(diagnostic, meta.span,
810 AttrError::UnknownMetaItem(mi.name()));
815 handle_errors(diagnostic, meta.span, AttrError::UnsupportedLiteral);
820 Some(Deprecation {since: since, note: note})
822 Some(Deprecation{since: None, note: None})
829 /// Find the first stability attribute. `None` if none exists.
830 pub fn find_stability(diagnostic: &Handler, attrs: &[Attribute],
831 item_sp: Span) -> Option<Stability> {
832 find_stability_generic(diagnostic, attrs.iter(), item_sp)
835 /// Find the deprecation attribute. `None` if none exists.
836 pub fn find_deprecation(diagnostic: &Handler, attrs: &[Attribute],
837 item_sp: Span) -> Option<Deprecation> {
838 find_deprecation_generic(diagnostic, attrs.iter(), item_sp)
842 /// Parse #[repr(...)] forms.
844 /// Valid repr contents: any of the primitive integral type names (see
845 /// `int_type_of_word`, below) to specify enum discriminant type; `C`, to use
846 /// the same discriminant size that the corresponding C enum would or C
847 /// structure layout, and `packed` to remove padding.
848 pub fn find_repr_attrs(diagnostic: &Handler, attr: &Attribute) -> Vec<ReprAttr> {
849 let mut acc = Vec::new();
850 match attr.value.node {
851 ast::MetaItemKind::List(ref items) if attr.value.name == "repr" => {
854 if !item.is_meta_item() {
855 handle_errors(diagnostic, item.span, AttrError::UnsupportedLiteral);
859 if let Some(mi) = item.word() {
860 let word = &*mi.name().as_str();
861 let hint = match word {
862 // Can't use "extern" because it's not a lexical identifier.
863 "C" => Some(ReprExtern),
864 "packed" => Some(ReprPacked),
865 "simd" => Some(ReprSimd),
866 _ => match int_type_of_word(word) {
867 Some(ity) => Some(ReprInt(ity)),
869 // Not a word we recognize
870 span_err!(diagnostic, item.span, E0552,
871 "unrecognized representation hint");
877 if let Some(h) = hint {
881 span_err!(diagnostic, item.span, E0553,
882 "unrecognized enum representation hint");
886 // Not a "repr" hint: ignore.
892 fn int_type_of_word(s: &str) -> Option<IntType> {
894 "i8" => Some(SignedInt(ast::IntTy::I8)),
895 "u8" => Some(UnsignedInt(ast::UintTy::U8)),
896 "i16" => Some(SignedInt(ast::IntTy::I16)),
897 "u16" => Some(UnsignedInt(ast::UintTy::U16)),
898 "i32" => Some(SignedInt(ast::IntTy::I32)),
899 "u32" => Some(UnsignedInt(ast::UintTy::U32)),
900 "i64" => Some(SignedInt(ast::IntTy::I64)),
901 "u64" => Some(UnsignedInt(ast::UintTy::U64)),
902 "i128" => Some(SignedInt(ast::IntTy::I128)),
903 "u128" => Some(UnsignedInt(ast::UintTy::U128)),
904 "isize" => Some(SignedInt(ast::IntTy::Is)),
905 "usize" => Some(UnsignedInt(ast::UintTy::Us)),
910 #[derive(PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
918 #[derive(Eq, Hash, PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
920 SignedInt(ast::IntTy),
921 UnsignedInt(ast::UintTy)
926 pub fn is_signed(self) -> bool {
928 SignedInt(..) => true,
929 UnsignedInt(..) => false
934 pub trait HasAttrs: Sized {
935 fn attrs(&self) -> &[ast::Attribute];
936 fn map_attrs<F: FnOnce(Vec<ast::Attribute>) -> Vec<ast::Attribute>>(self, f: F) -> Self;
939 impl<T: HasAttrs> HasAttrs for Spanned<T> {
940 fn attrs(&self) -> &[ast::Attribute] { self.node.attrs() }
941 fn map_attrs<F: FnOnce(Vec<ast::Attribute>) -> Vec<ast::Attribute>>(self, f: F) -> Self {
942 Spanned { node: self.node.map_attrs(f), span: self.span }
946 impl HasAttrs for Vec<Attribute> {
947 fn attrs(&self) -> &[Attribute] {
950 fn map_attrs<F: FnOnce(Vec<Attribute>) -> Vec<Attribute>>(self, f: F) -> Self {
955 impl HasAttrs for ThinVec<Attribute> {
956 fn attrs(&self) -> &[Attribute] {
959 fn map_attrs<F: FnOnce(Vec<Attribute>) -> Vec<Attribute>>(self, f: F) -> Self {
960 f(self.into()).into()
964 impl<T: HasAttrs + 'static> HasAttrs for P<T> {
965 fn attrs(&self) -> &[Attribute] {
968 fn map_attrs<F: FnOnce(Vec<Attribute>) -> Vec<Attribute>>(self, f: F) -> Self {
969 self.map(|t| t.map_attrs(f))
973 impl HasAttrs for StmtKind {
974 fn attrs(&self) -> &[Attribute] {
976 StmtKind::Local(ref local) => local.attrs(),
977 StmtKind::Item(..) => &[],
978 StmtKind::Expr(ref expr) | StmtKind::Semi(ref expr) => expr.attrs(),
979 StmtKind::Mac(ref mac) => {
980 let (_, _, ref attrs) = **mac;
986 fn map_attrs<F: FnOnce(Vec<Attribute>) -> Vec<Attribute>>(self, f: F) -> Self {
988 StmtKind::Local(local) => StmtKind::Local(local.map_attrs(f)),
989 StmtKind::Item(..) => self,
990 StmtKind::Expr(expr) => StmtKind::Expr(expr.map_attrs(f)),
991 StmtKind::Semi(expr) => StmtKind::Semi(expr.map_attrs(f)),
992 StmtKind::Mac(mac) => StmtKind::Mac(mac.map(|(mac, style, attrs)| {
993 (mac, style, attrs.map_attrs(f))
999 impl HasAttrs for Stmt {
1000 fn attrs(&self) -> &[ast::Attribute] { self.node.attrs() }
1001 fn map_attrs<F: FnOnce(Vec<ast::Attribute>) -> Vec<ast::Attribute>>(self, f: F) -> Self {
1002 Stmt { id: self.id, node: self.node.map_attrs(f), span: self.span }
1006 macro_rules! derive_has_attrs {
1007 ($($ty:path),*) => { $(
1008 impl HasAttrs for $ty {
1009 fn attrs(&self) -> &[Attribute] {
1013 fn map_attrs<F>(mut self, f: F) -> Self
1014 where F: FnOnce(Vec<Attribute>) -> Vec<Attribute>,
1016 self.attrs = self.attrs.map_attrs(f);
1024 Item, Expr, Local, ast::ForeignItem, ast::StructField, ast::ImplItem, ast::TraitItem, ast::Arm,
1025 ast::Field, ast::FieldPat, ast::Variant_