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_};
19 use ast::{MetaItem, MetaItemKind, NestedMetaItem, NestedMetaItemKind};
20 use ast::{Lit, Expr, Item, Local, Stmt, StmtKind};
21 use codemap::{respan, spanned, dummy_spanned};
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};
26 use parse::token::InternedString;
27 use parse::{ParseSess, token};
31 use std::cell::{RefCell, Cell};
32 use std::collections::HashSet;
35 static USED_ATTRS: RefCell<Vec<u64>> = RefCell::new(Vec::new())
39 MultipleItem(InternedString),
40 UnknownMetaItem(InternedString),
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.node.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.node.id;
76 USED_ATTRS.with(|slot| {
77 let idx = (id / 64) as usize;
79 slot.borrow().get(idx).map(|bits| bits & (1 << shift) != 0)
85 /// Returns the MetaItem if self is a NestedMetaItemKind::MetaItem.
86 pub fn meta_item(&self) -> Option<&P<MetaItem>> {
88 NestedMetaItemKind::MetaItem(ref item) => Some(&item),
93 /// Returns the Lit if self is a NestedMetaItemKind::Literal.
94 pub fn literal(&self) -> Option<&Lit> {
96 NestedMetaItemKind::Literal(ref lit) => Some(&lit),
101 /// Returns the Span for `self`.
102 pub fn span(&self) -> Span {
106 /// Returns true if this list item is a MetaItem with a name of `name`.
107 pub fn check_name(&self, name: &str) -> bool {
108 self.meta_item().map_or(false, |meta_item| meta_item.check_name(name))
111 /// Returns the name of the meta item, e.g. `foo` in `#[foo]`,
112 /// `#[foo="bar"]` and `#[foo(bar)]`, if self is a MetaItem
113 pub fn name(&self) -> Option<InternedString> {
114 self.meta_item().and_then(|meta_item| Some(meta_item.name()))
117 /// Gets the string value if self is a MetaItem and the MetaItem is a
118 /// MetaItemKind::NameValue variant containing a string, otherwise None.
119 pub fn value_str(&self) -> Option<InternedString> {
120 self.meta_item().and_then(|meta_item| meta_item.value_str())
123 /// Returns a MetaItem if self is a MetaItem with Kind Word.
124 pub fn word(&self) -> Option<&P<MetaItem>> {
125 self.meta_item().and_then(|meta_item| if meta_item.is_word() {
132 /// Gets a list of inner meta items from a list MetaItem type.
133 pub fn meta_item_list(&self) -> Option<&[NestedMetaItem]> {
134 self.meta_item().and_then(|meta_item| meta_item.meta_item_list())
137 /// Returns `true` if the variant is MetaItem.
138 pub fn is_meta_item(&self) -> bool {
139 self.meta_item().is_some()
142 /// Returns `true` if the variant is Literal.
143 pub fn is_literal(&self) -> bool {
144 self.literal().is_some()
147 /// Returns `true` if self is a MetaItem and the meta item is a word.
148 pub fn is_word(&self) -> bool {
149 self.word().is_some()
152 /// Returns `true` if self is a MetaItem and the meta item is a ValueString.
153 pub fn is_value_str(&self) -> bool {
154 self.value_str().is_some()
157 /// Returns `true` if self is a MetaItem and the meta item is a list.
158 pub fn is_meta_item_list(&self) -> bool {
159 self.meta_item_list().is_some()
164 pub fn check_name(&self, name: &str) -> bool {
165 let matches = name == &self.name()[..];
172 pub fn name(&self) -> InternedString { self.meta().name() }
174 pub fn value_str(&self) -> Option<InternedString> {
175 self.meta().value_str()
178 pub fn meta_item_list(&self) -> Option<&[NestedMetaItem]> {
179 self.meta().meta_item_list()
182 pub fn is_word(&self) -> bool { self.meta().is_word() }
184 pub fn span(&self) -> Span { self.meta().span }
186 pub fn is_meta_item_list(&self) -> bool {
187 self.meta_item_list().is_some()
190 /// Indicates if the attribute is a Value String.
191 pub fn is_value_str(&self) -> bool {
192 self.value_str().is_some()
197 pub fn name(&self) -> InternedString {
199 MetaItemKind::Word(ref n) => (*n).clone(),
200 MetaItemKind::NameValue(ref n, _) => (*n).clone(),
201 MetaItemKind::List(ref n, _) => (*n).clone(),
205 pub fn value_str(&self) -> Option<InternedString> {
207 MetaItemKind::NameValue(_, ref v) => {
209 ast::LitKind::Str(ref s, _) => Some((*s).clone()),
217 pub fn meta_item_list(&self) -> Option<&[NestedMetaItem]> {
219 MetaItemKind::List(_, ref l) => Some(&l[..]),
224 pub fn is_word(&self) -> bool {
226 MetaItemKind::Word(_) => true,
231 pub fn span(&self) -> Span { self.span }
233 pub fn check_name(&self, name: &str) -> bool {
234 name == &self.name()[..]
237 pub fn is_value_str(&self) -> bool {
238 self.value_str().is_some()
241 pub fn is_meta_item_list(&self) -> bool {
242 self.meta_item_list().is_some()
247 /// Extract the MetaItem from inside this Attribute.
248 pub fn meta(&self) -> &MetaItem {
252 /// Convert self to a normal #[doc="foo"] comment, if it is a
253 /// comment like `///` or `/** */`. (Returns self unchanged for
254 /// non-sugared doc attributes.)
255 pub fn with_desugared_doc<T, F>(&self, f: F) -> T where
256 F: FnOnce(&Attribute) -> T,
258 if self.node.is_sugared_doc {
259 let comment = self.value_str().unwrap();
260 let meta = mk_name_value_item_str(
261 InternedString::new("doc"),
262 token::intern_and_get_ident(&strip_doc_comment_decoration(
264 if self.node.style == ast::AttrStyle::Outer {
265 f(&mk_attr_outer(self.node.id, meta))
267 f(&mk_attr_inner(self.node.id, meta))
277 pub fn mk_name_value_item_str(name: InternedString, value: InternedString)
279 let value_lit = dummy_spanned(ast::LitKind::Str(value, ast::StrStyle::Cooked));
280 mk_spanned_name_value_item(DUMMY_SP, name, value_lit)
283 pub fn mk_name_value_item(name: InternedString, value: ast::Lit)
285 mk_spanned_name_value_item(DUMMY_SP, name, value)
288 pub fn mk_list_item(name: InternedString, items: Vec<NestedMetaItem>) -> P<MetaItem> {
289 mk_spanned_list_item(DUMMY_SP, name, items)
292 pub fn mk_list_word_item(name: InternedString) -> ast::NestedMetaItem {
293 dummy_spanned(NestedMetaItemKind::MetaItem(mk_spanned_word_item(DUMMY_SP, name)))
296 pub fn mk_word_item(name: InternedString) -> P<MetaItem> {
297 mk_spanned_word_item(DUMMY_SP, name)
300 pub fn mk_spanned_name_value_item(sp: Span, name: InternedString, value: ast::Lit)
302 P(respan(sp, MetaItemKind::NameValue(name, value)))
305 pub fn mk_spanned_list_item(sp: Span, name: InternedString, items: Vec<NestedMetaItem>)
307 P(respan(sp, MetaItemKind::List(name, items)))
310 pub fn mk_spanned_word_item(sp: Span, name: InternedString) -> P<MetaItem> {
311 P(respan(sp, MetaItemKind::Word(name)))
316 thread_local! { static NEXT_ATTR_ID: Cell<usize> = Cell::new(0) }
318 pub fn mk_attr_id() -> AttrId {
319 let id = NEXT_ATTR_ID.with(|slot| {
327 /// Returns an inner attribute with the given value.
328 pub fn mk_attr_inner(id: AttrId, item: P<MetaItem>) -> Attribute {
329 mk_spanned_attr_inner(DUMMY_SP, id, item)
332 /// Returns an innter attribute with the given value and span.
333 pub fn mk_spanned_attr_inner(sp: Span, id: AttrId, item: P<MetaItem>) -> Attribute {
337 style: ast::AttrStyle::Inner,
339 is_sugared_doc: false,
344 /// Returns an outer attribute with the given value.
345 pub fn mk_attr_outer(id: AttrId, item: P<MetaItem>) -> Attribute {
346 mk_spanned_attr_outer(DUMMY_SP, id, item)
349 /// Returns an outer attribute with the given value and span.
350 pub fn mk_spanned_attr_outer(sp: Span, id: AttrId, item: P<MetaItem>) -> Attribute {
354 style: ast::AttrStyle::Outer,
356 is_sugared_doc: false,
360 pub fn mk_doc_attr_outer(id: AttrId, item: P<MetaItem>, is_sugared_doc: bool) -> Attribute {
361 dummy_spanned(Attribute_ {
363 style: ast::AttrStyle::Outer,
365 is_sugared_doc: is_sugared_doc,
369 pub fn mk_sugared_doc_attr(id: AttrId, text: InternedString, lo: BytePos,
372 let style = doc_comment_style(&text);
373 let lit = spanned(lo, hi, ast::LitKind::Str(text, ast::StrStyle::Cooked));
374 let attr = Attribute_ {
377 value: P(spanned(lo, hi, MetaItemKind::NameValue(InternedString::new("doc"), lit))),
380 spanned(lo, hi, attr)
384 /// Check if `needle` occurs in `haystack` by a structural
385 /// comparison. This is slightly subtle, and relies on ignoring the
386 /// span included in the `==` comparison a plain MetaItem.
387 pub fn contains(haystack: &[P<MetaItem>], needle: &MetaItem) -> bool {
388 debug!("attr::contains (name={})", needle.name());
389 haystack.iter().any(|item| {
390 debug!(" testing: {}", item.name());
391 item.node == needle.node
395 pub fn list_contains_name(items: &[NestedMetaItem], name: &str) -> bool {
396 debug!("attr::list_contains_name (name={})", name);
397 items.iter().any(|item| {
398 debug!(" testing: {:?}", item.name());
399 item.check_name(name)
403 pub fn contains_name(attrs: &[Attribute], name: &str) -> bool {
404 debug!("attr::contains_name (name={})", name);
405 attrs.iter().any(|item| {
406 debug!(" testing: {}", item.name());
407 item.check_name(name)
411 pub fn first_attr_value_str_by_name(attrs: &[Attribute], name: &str)
412 -> Option<InternedString> {
414 .find(|at| at.check_name(name))
415 .and_then(|at| at.value_str())
418 pub fn last_meta_item_value_str_by_name(items: &[P<MetaItem>], name: &str)
419 -> Option<InternedString> {
422 .find(|mi| mi.check_name(name))
423 .and_then(|i| i.value_str())
426 /* Higher-level applications */
428 pub fn find_crate_name(attrs: &[Attribute]) -> Option<InternedString> {
429 first_attr_value_str_by_name(attrs, "crate_name")
432 /// Find the value of #[export_name=*] attribute and check its validity.
433 pub fn find_export_name_attr(diag: &Handler, attrs: &[Attribute]) -> Option<InternedString> {
434 attrs.iter().fold(None, |ia,attr| {
435 if attr.check_name("export_name") {
436 if let s@Some(_) = attr.value_str() {
439 struct_span_err!(diag, attr.span, E0558,
440 "export_name attribute has invalid format")
441 .span_label(attr.span,
442 &format!("did you mean #[export_name=\"*\"]?"))
452 pub fn contains_extern_indicator(diag: &Handler, attrs: &[Attribute]) -> bool {
453 contains_name(attrs, "no_mangle") ||
454 find_export_name_attr(diag, attrs).is_some()
457 #[derive(Copy, Clone, PartialEq)]
458 pub enum InlineAttr {
465 /// Determine what `#[inline]` attribute is present in `attrs`, if any.
466 pub fn find_inline_attr(diagnostic: Option<&Handler>, attrs: &[Attribute]) -> InlineAttr {
467 attrs.iter().fold(InlineAttr::None, |ia,attr| {
468 match attr.node.value.node {
469 MetaItemKind::Word(ref n) if n == "inline" => {
473 MetaItemKind::List(ref n, ref items) if n == "inline" => {
475 if items.len() != 1 {
476 diagnostic.map(|d|{ span_err!(d, attr.span, E0534, "expected one argument"); });
478 } else if list_contains_name(&items[..], "always") {
480 } else if list_contains_name(&items[..], "never") {
484 span_err!(d, items[0].span, E0535, "invalid argument");
495 /// True if `#[inline]` or `#[inline(always)]` is present in `attrs`.
496 pub fn requests_inline(attrs: &[Attribute]) -> bool {
497 match find_inline_attr(None, attrs) {
498 InlineAttr::Hint | InlineAttr::Always => true,
499 InlineAttr::None | InlineAttr::Never => false,
503 /// Tests if a cfg-pattern matches the cfg set
504 pub fn cfg_matches(cfgs: &[P<MetaItem>], cfg: &ast::MetaItem,
506 features: Option<&Features>)
509 ast::MetaItemKind::List(ref pred, ref mis) => {
510 for mi in mis.iter() {
511 if !mi.is_meta_item() {
512 handle_errors(&sess.span_diagnostic, mi.span, AttrError::UnsupportedLiteral);
517 // The unwraps below may look dangerous, but we've already asserted
518 // that they won't fail with the loop above.
520 "any" => mis.iter().any(|mi| {
521 cfg_matches(cfgs, mi.meta_item().unwrap(), sess, features)
523 "all" => mis.iter().all(|mi| {
524 cfg_matches(cfgs, mi.meta_item().unwrap(), sess, features)
528 span_err!(sess.span_diagnostic, cfg.span, E0536, "expected 1 cfg-pattern");
532 !cfg_matches(cfgs, mis[0].meta_item().unwrap(), sess, features)
535 span_err!(sess.span_diagnostic, cfg.span, E0537, "invalid predicate `{}`", p);
540 ast::MetaItemKind::Word(_) | ast::MetaItemKind::NameValue(..) => {
541 if let (Some(feats), Some(gated_cfg)) = (features, GatedCfg::gate(cfg)) {
542 gated_cfg.check_and_emit(sess, feats);
549 /// Represents the #[stable], #[unstable] and #[rustc_deprecated] attributes.
550 #[derive(RustcEncodable, RustcDecodable, Clone, Debug, PartialEq, Eq, Hash)]
551 pub struct Stability {
552 pub level: StabilityLevel,
553 pub feature: InternedString,
554 pub rustc_depr: Option<RustcDeprecation>,
557 /// The available stability levels.
558 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Debug, Eq, Hash)]
559 pub enum StabilityLevel {
560 // Reason for the current stability level and the relevant rust-lang issue
561 Unstable { reason: Option<InternedString>, issue: u32 },
562 Stable { since: InternedString },
565 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Debug, Eq, Hash)]
566 pub struct RustcDeprecation {
567 pub since: InternedString,
568 pub reason: InternedString,
571 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Debug, Eq, Hash)]
572 pub struct Deprecation {
573 pub since: Option<InternedString>,
574 pub note: Option<InternedString>,
577 impl StabilityLevel {
578 pub fn is_unstable(&self) -> bool { if let Unstable {..} = *self { true } else { false }}
579 pub fn is_stable(&self) -> bool { if let Stable {..} = *self { true } else { false }}
582 fn find_stability_generic<'a, I>(diagnostic: &Handler,
586 where I: Iterator<Item = &'a Attribute>
588 let mut stab: Option<Stability> = None;
589 let mut rustc_depr: Option<RustcDeprecation> = None;
591 'outer: for attr in attrs_iter {
592 let tag = attr.name();
594 if tag != "rustc_deprecated" && tag != "unstable" && tag != "stable" {
595 continue // not a stability level
600 if let Some(metas) = attr.meta_item_list() {
601 let get = |meta: &MetaItem, item: &mut Option<InternedString>| {
603 handle_errors(diagnostic, meta.span, AttrError::MultipleItem(meta.name()));
606 if let Some(v) = meta.value_str() {
610 span_err!(diagnostic, meta.span, E0539, "incorrect meta item");
616 "rustc_deprecated" => {
617 if rustc_depr.is_some() {
618 span_err!(diagnostic, item_sp, E0540,
619 "multiple rustc_deprecated attributes");
623 let mut since = None;
624 let mut reason = None;
626 if let Some(mi) = meta.meta_item() {
628 "since" => if !get(mi, &mut since) { continue 'outer },
629 "reason" => if !get(mi, &mut reason) { continue 'outer },
631 handle_errors(diagnostic, mi.span,
632 AttrError::UnknownMetaItem(mi.name()));
637 handle_errors(diagnostic, meta.span, AttrError::UnsupportedLiteral);
642 match (since, reason) {
643 (Some(since), Some(reason)) => {
644 rustc_depr = Some(RustcDeprecation {
650 handle_errors(diagnostic, attr.span(), AttrError::MissingSince);
654 span_err!(diagnostic, attr.span(), E0543, "missing 'reason'");
661 handle_errors(diagnostic, attr.span(), AttrError::MultipleStabilityLevels);
665 let mut feature = None;
666 let mut reason = None;
667 let mut issue = None;
669 if let Some(mi) = meta.meta_item() {
671 "feature" => if !get(mi, &mut feature) { continue 'outer },
672 "reason" => if !get(mi, &mut reason) { continue 'outer },
673 "issue" => if !get(mi, &mut issue) { continue 'outer },
675 handle_errors(diagnostic, meta.span,
676 AttrError::UnknownMetaItem(mi.name()));
681 handle_errors(diagnostic, meta.span, AttrError::UnsupportedLiteral);
686 match (feature, reason, issue) {
687 (Some(feature), reason, Some(issue)) => {
688 stab = Some(Stability {
692 if let Ok(issue) = issue.parse() {
695 span_err!(diagnostic, attr.span(), E0545,
696 "incorrect 'issue'");
706 handle_errors(diagnostic, attr.span(), AttrError::MissingFeature);
710 span_err!(diagnostic, attr.span(), E0547, "missing 'issue'");
717 handle_errors(diagnostic, attr.span(), AttrError::MultipleStabilityLevels);
721 let mut feature = None;
722 let mut since = None;
724 if let NestedMetaItemKind::MetaItem(ref mi) = meta.node {
726 "feature" => if !get(mi, &mut feature) { continue 'outer },
727 "since" => if !get(mi, &mut since) { continue 'outer },
729 handle_errors(diagnostic, meta.span,
730 AttrError::UnknownMetaItem(mi.name()));
735 handle_errors(diagnostic, meta.span, AttrError::UnsupportedLiteral);
740 match (feature, since) {
741 (Some(feature), Some(since)) => {
742 stab = Some(Stability {
751 handle_errors(diagnostic, attr.span(), AttrError::MissingFeature);
755 handle_errors(diagnostic, attr.span(), AttrError::MissingSince);
763 span_err!(diagnostic, attr.span(), E0548, "incorrect stability attribute type");
768 // Merge the deprecation info into the stability info
769 if let Some(rustc_depr) = rustc_depr {
770 if let Some(ref mut stab) = stab {
771 if let Unstable {reason: ref mut reason @ None, ..} = stab.level {
772 *reason = Some(rustc_depr.reason.clone())
774 stab.rustc_depr = Some(rustc_depr);
776 span_err!(diagnostic, item_sp, E0549,
777 "rustc_deprecated attribute must be paired with \
778 either stable or unstable attribute");
785 fn find_deprecation_generic<'a, I>(diagnostic: &Handler,
788 -> Option<Deprecation>
789 where I: Iterator<Item = &'a Attribute>
791 let mut depr: Option<Deprecation> = None;
793 'outer: for attr in attrs_iter {
794 if attr.name() != "deprecated" {
801 span_err!(diagnostic, item_sp, E0550, "multiple deprecated attributes");
805 depr = if let Some(metas) = attr.meta_item_list() {
806 let get = |meta: &MetaItem, item: &mut Option<InternedString>| {
808 handle_errors(diagnostic, meta.span, AttrError::MultipleItem(meta.name()));
811 if let Some(v) = meta.value_str() {
815 span_err!(diagnostic, meta.span, E0551, "incorrect meta item");
820 let mut since = None;
823 if let NestedMetaItemKind::MetaItem(ref mi) = meta.node {
825 "since" => if !get(mi, &mut since) { continue 'outer },
826 "note" => if !get(mi, &mut note) { continue 'outer },
828 handle_errors(diagnostic, meta.span,
829 AttrError::UnknownMetaItem(mi.name()));
834 handle_errors(diagnostic, meta.span, AttrError::UnsupportedLiteral);
839 Some(Deprecation {since: since, note: note})
841 Some(Deprecation{since: None, note: None})
848 /// Find the first stability attribute. `None` if none exists.
849 pub fn find_stability(diagnostic: &Handler, attrs: &[Attribute],
850 item_sp: Span) -> Option<Stability> {
851 find_stability_generic(diagnostic, attrs.iter(), item_sp)
854 /// Find the deprecation attribute. `None` if none exists.
855 pub fn find_deprecation(diagnostic: &Handler, attrs: &[Attribute],
856 item_sp: Span) -> Option<Deprecation> {
857 find_deprecation_generic(diagnostic, attrs.iter(), item_sp)
860 pub fn require_unique_names(diagnostic: &Handler, metas: &[P<MetaItem>]) {
861 let mut set = HashSet::new();
863 let name = meta.name();
865 if !set.insert(name.clone()) {
866 panic!(diagnostic.span_fatal(meta.span,
867 &format!("duplicate meta item `{}`", name)));
873 /// Parse #[repr(...)] forms.
875 /// Valid repr contents: any of the primitive integral type names (see
876 /// `int_type_of_word`, below) to specify enum discriminant type; `C`, to use
877 /// the same discriminant size that the corresponding C enum would or C
878 /// structure layout, and `packed` to remove padding.
879 pub fn find_repr_attrs(diagnostic: &Handler, attr: &Attribute) -> Vec<ReprAttr> {
880 let mut acc = Vec::new();
881 match attr.node.value.node {
882 ast::MetaItemKind::List(ref s, ref items) if s == "repr" => {
885 if !item.is_meta_item() {
886 handle_errors(diagnostic, item.span, AttrError::UnsupportedLiteral);
890 if let Some(mi) = item.word() {
891 let word = &*mi.name();
892 let hint = match word {
893 // Can't use "extern" because it's not a lexical identifier.
894 "C" => Some(ReprExtern),
895 "packed" => Some(ReprPacked),
896 "simd" => Some(ReprSimd),
897 _ => match int_type_of_word(word) {
898 Some(ity) => Some(ReprInt(item.span, ity)),
900 // Not a word we recognize
901 span_err!(diagnostic, item.span, E0552,
902 "unrecognized representation hint");
908 if let Some(h) = hint {
912 span_err!(diagnostic, item.span, E0553,
913 "unrecognized enum representation hint");
917 // Not a "repr" hint: ignore.
923 fn int_type_of_word(s: &str) -> Option<IntType> {
925 "i8" => Some(SignedInt(ast::IntTy::I8)),
926 "u8" => Some(UnsignedInt(ast::UintTy::U8)),
927 "i16" => Some(SignedInt(ast::IntTy::I16)),
928 "u16" => Some(UnsignedInt(ast::UintTy::U16)),
929 "i32" => Some(SignedInt(ast::IntTy::I32)),
930 "u32" => Some(UnsignedInt(ast::UintTy::U32)),
931 "i64" => Some(SignedInt(ast::IntTy::I64)),
932 "u64" => Some(UnsignedInt(ast::UintTy::U64)),
933 "isize" => Some(SignedInt(ast::IntTy::Is)),
934 "usize" => Some(UnsignedInt(ast::UintTy::Us)),
939 #[derive(PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
942 ReprInt(Span, IntType),
949 pub fn is_ffi_safe(&self) -> bool {
952 ReprInt(_sp, ity) => ity.is_ffi_safe(),
960 #[derive(Eq, Hash, PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
962 SignedInt(ast::IntTy),
963 UnsignedInt(ast::UintTy)
968 pub fn is_signed(self) -> bool {
970 SignedInt(..) => true,
971 UnsignedInt(..) => false
974 fn is_ffi_safe(self) -> bool {
976 SignedInt(ast::IntTy::I8) | UnsignedInt(ast::UintTy::U8) |
977 SignedInt(ast::IntTy::I16) | UnsignedInt(ast::UintTy::U16) |
978 SignedInt(ast::IntTy::I32) | UnsignedInt(ast::UintTy::U32) |
979 SignedInt(ast::IntTy::I64) | UnsignedInt(ast::UintTy::U64) => true,
980 SignedInt(ast::IntTy::Is) | UnsignedInt(ast::UintTy::Us) => false
985 pub trait HasAttrs: Sized {
986 fn attrs(&self) -> &[ast::Attribute];
987 fn map_attrs<F: FnOnce(Vec<ast::Attribute>) -> Vec<ast::Attribute>>(self, f: F) -> Self;
990 impl HasAttrs for Vec<Attribute> {
991 fn attrs(&self) -> &[Attribute] {
994 fn map_attrs<F: FnOnce(Vec<Attribute>) -> Vec<Attribute>>(self, f: F) -> Self {
999 impl HasAttrs for ThinVec<Attribute> {
1000 fn attrs(&self) -> &[Attribute] {
1003 fn map_attrs<F: FnOnce(Vec<Attribute>) -> Vec<Attribute>>(self, f: F) -> Self {
1004 f(self.into()).into()
1008 impl<T: HasAttrs + 'static> HasAttrs for P<T> {
1009 fn attrs(&self) -> &[Attribute] {
1012 fn map_attrs<F: FnOnce(Vec<Attribute>) -> Vec<Attribute>>(self, f: F) -> Self {
1013 self.map(|t| t.map_attrs(f))
1017 impl HasAttrs for StmtKind {
1018 fn attrs(&self) -> &[Attribute] {
1020 StmtKind::Local(ref local) => local.attrs(),
1021 StmtKind::Item(..) => &[],
1022 StmtKind::Expr(ref expr) | StmtKind::Semi(ref expr) => expr.attrs(),
1023 StmtKind::Mac(ref mac) => {
1024 let (_, _, ref attrs) = **mac;
1030 fn map_attrs<F: FnOnce(Vec<Attribute>) -> Vec<Attribute>>(self, f: F) -> Self {
1032 StmtKind::Local(local) => StmtKind::Local(local.map_attrs(f)),
1033 StmtKind::Item(..) => self,
1034 StmtKind::Expr(expr) => StmtKind::Expr(expr.map_attrs(f)),
1035 StmtKind::Semi(expr) => StmtKind::Semi(expr.map_attrs(f)),
1036 StmtKind::Mac(mac) => StmtKind::Mac(mac.map(|(mac, style, attrs)| {
1037 (mac, style, attrs.map_attrs(f))
1043 macro_rules! derive_has_attrs_from_field {
1044 ($($ty:path),*) => { derive_has_attrs_from_field!($($ty: .attrs),*); };
1045 ($($ty:path : $(.$field:ident)*),*) => { $(
1046 impl HasAttrs for $ty {
1047 fn attrs(&self) -> &[Attribute] {
1048 self $(.$field)* .attrs()
1051 fn map_attrs<F>(mut self, f: F) -> Self
1052 where F: FnOnce(Vec<Attribute>) -> Vec<Attribute>,
1054 self $(.$field)* = self $(.$field)* .map_attrs(f);
1061 derive_has_attrs_from_field! {
1062 Item, Expr, Local, ast::ForeignItem, ast::StructField, ast::ImplItem, ast::TraitItem, ast::Arm
1065 derive_has_attrs_from_field! { Stmt: .node, ast::Variant: .node.attrs }