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, Ident};
19 use ast::{MetaItem, MetaItemKind, NestedMetaItem, NestedMetaItemKind};
20 use ast::{Lit, LitKind, Expr, ExprKind, Item, Local, Stmt, StmtKind};
21 use codemap::{Spanned, respan, dummy_spanned};
22 use syntax_pos::{Span, DUMMY_SP};
24 use feature_gate::{Features, GatedCfg};
25 use parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
26 use parse::parser::Parser;
27 use parse::{self, ParseSess, PResult};
28 use parse::token::{self, Token};
31 use tokenstream::{TokenStream, TokenTree, Delimited};
39 UnknownMetaItem(Name),
42 MultipleStabilityLevels,
46 fn handle_errors(diag: &Handler, span: Span, error: AttrError) {
48 AttrError::MultipleItem(item) => span_err!(diag, span, E0538,
49 "multiple '{}' items", item),
50 AttrError::UnknownMetaItem(item) => span_err!(diag, span, E0541,
51 "unknown meta item '{}'", item),
52 AttrError::MissingSince => span_err!(diag, span, E0542, "missing 'since'"),
53 AttrError::MissingFeature => span_err!(diag, span, E0546, "missing 'feature'"),
54 AttrError::MultipleStabilityLevels => span_err!(diag, span, E0544,
55 "multiple stability levels"),
56 AttrError::UnsupportedLiteral => span_err!(diag, span, E0565, "unsupported literal"),
60 pub fn mark_used(attr: &Attribute) {
61 debug!("Marking {:?} as used.", attr);
62 let AttrId(id) = attr.id;
63 GLOBALS.with(|globals| {
64 let mut slot = globals.used_attrs.lock();
65 let idx = (id / 64) as usize;
67 if slot.len() <= idx {
68 slot.resize(idx + 1, 0);
70 slot[idx] |= 1 << shift;
74 pub fn is_used(attr: &Attribute) -> bool {
75 let AttrId(id) = attr.id;
76 GLOBALS.with(|globals| {
77 let slot = globals.used_attrs.lock();
78 let idx = (id / 64) as usize;
80 slot.get(idx).map(|bits| bits & (1 << shift) != 0)
85 pub fn mark_known(attr: &Attribute) {
86 debug!("Marking {:?} as known.", attr);
87 let AttrId(id) = attr.id;
88 GLOBALS.with(|globals| {
89 let mut slot = globals.known_attrs.lock();
90 let idx = (id / 64) as usize;
92 if slot.len() <= idx {
93 slot.resize(idx + 1, 0);
95 slot[idx] |= 1 << shift;
99 pub fn is_known(attr: &Attribute) -> bool {
100 let AttrId(id) = attr.id;
101 GLOBALS.with(|globals| {
102 let slot = globals.known_attrs.lock();
103 let idx = (id / 64) as usize;
105 slot.get(idx).map(|bits| bits & (1 << shift) != 0)
110 impl NestedMetaItem {
111 /// Returns the MetaItem if self is a NestedMetaItemKind::MetaItem.
112 pub fn meta_item(&self) -> Option<&MetaItem> {
114 NestedMetaItemKind::MetaItem(ref item) => Some(item),
119 /// Returns the Lit if self is a NestedMetaItemKind::Literal.
120 pub fn literal(&self) -> Option<&Lit> {
122 NestedMetaItemKind::Literal(ref lit) => Some(lit),
127 /// Returns the Span for `self`.
128 pub fn span(&self) -> Span {
132 /// Returns true if this list item is a MetaItem with a name of `name`.
133 pub fn check_name(&self, name: &str) -> bool {
134 self.meta_item().map_or(false, |meta_item| meta_item.check_name(name))
137 /// Returns the name of the meta item, e.g. `foo` in `#[foo]`,
138 /// `#[foo="bar"]` and `#[foo(bar)]`, if self is a MetaItem
139 pub fn name(&self) -> Option<Name> {
140 self.meta_item().and_then(|meta_item| Some(meta_item.name()))
143 /// Gets the string value if self is a MetaItem and the MetaItem is a
144 /// MetaItemKind::NameValue variant containing a string, otherwise None.
145 pub fn value_str(&self) -> Option<Symbol> {
146 self.meta_item().and_then(|meta_item| meta_item.value_str())
149 /// Returns a name and single literal value tuple of the MetaItem.
150 pub fn name_value_literal(&self) -> Option<(Name, &Lit)> {
151 self.meta_item().and_then(
152 |meta_item| meta_item.meta_item_list().and_then(
154 if meta_item_list.len() == 1 {
155 let nested_item = &meta_item_list[0];
156 if nested_item.is_literal() {
157 Some((meta_item.name(), nested_item.literal().unwrap()))
167 /// Returns a MetaItem if self is a MetaItem with Kind Word.
168 pub fn word(&self) -> Option<&MetaItem> {
169 self.meta_item().and_then(|meta_item| if meta_item.is_word() {
176 /// Gets a list of inner meta items from a list MetaItem type.
177 pub fn meta_item_list(&self) -> Option<&[NestedMetaItem]> {
178 self.meta_item().and_then(|meta_item| meta_item.meta_item_list())
181 /// Returns `true` if the variant is MetaItem.
182 pub fn is_meta_item(&self) -> bool {
183 self.meta_item().is_some()
186 /// Returns `true` if the variant is Literal.
187 pub fn is_literal(&self) -> bool {
188 self.literal().is_some()
191 /// Returns `true` if self is a MetaItem and the meta item is a word.
192 pub fn is_word(&self) -> bool {
193 self.word().is_some()
196 /// Returns `true` if self is a MetaItem and the meta item is a ValueString.
197 pub fn is_value_str(&self) -> bool {
198 self.value_str().is_some()
201 /// Returns `true` if self is a MetaItem and the meta item is a list.
202 pub fn is_meta_item_list(&self) -> bool {
203 self.meta_item_list().is_some()
208 pub fn check_name(&self, name: &str) -> bool {
209 let matches = self.path == name;
216 pub fn name(&self) -> Option<Name> {
217 match self.path.segments.len() {
218 1 => Some(self.path.segments[0].ident.name),
223 pub fn value_str(&self) -> Option<Symbol> {
224 self.meta().and_then(|meta| meta.value_str())
227 pub fn meta_item_list(&self) -> Option<Vec<NestedMetaItem>> {
229 Some(MetaItem { node: MetaItemKind::List(list), .. }) => Some(list),
234 pub fn is_word(&self) -> bool {
235 self.path.segments.len() == 1 && self.tokens.is_empty()
238 pub fn span(&self) -> Span {
242 pub fn is_meta_item_list(&self) -> bool {
243 self.meta_item_list().is_some()
246 /// Indicates if the attribute is a Value String.
247 pub fn is_value_str(&self) -> bool {
248 self.value_str().is_some()
253 pub fn name(&self) -> Name {
257 pub fn value_str(&self) -> Option<Symbol> {
259 MetaItemKind::NameValue(ref v) => {
261 LitKind::Str(ref s, _) => Some(*s),
269 pub fn meta_item_list(&self) -> Option<&[NestedMetaItem]> {
271 MetaItemKind::List(ref l) => Some(&l[..]),
276 pub fn is_word(&self) -> bool {
278 MetaItemKind::Word => true,
283 pub fn span(&self) -> Span { self.span }
285 pub fn check_name(&self, name: &str) -> bool {
289 pub fn is_value_str(&self) -> bool {
290 self.value_str().is_some()
293 pub fn is_meta_item_list(&self) -> bool {
294 self.meta_item_list().is_some()
299 /// Extract the MetaItem from inside this Attribute.
300 pub fn meta(&self) -> Option<MetaItem> {
301 let mut tokens = self.tokens.trees().peekable();
303 name: match self.path.segments.len() {
304 1 => self.path.segments[0].ident.name,
307 node: if let Some(node) = MetaItemKind::from_tokens(&mut tokens) {
308 if tokens.peek().is_some() {
319 pub fn parse<'a, T, F>(&self, sess: &'a ParseSess, mut f: F) -> PResult<'a, T>
320 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
322 let mut parser = Parser::new(sess, self.tokens.clone(), None, false, false);
323 let result = f(&mut parser)?;
324 if parser.token != token::Eof {
325 parser.unexpected()?;
330 pub fn parse_list<'a, T, F>(&self, sess: &'a ParseSess, mut f: F) -> PResult<'a, Vec<T>>
331 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
333 if self.tokens.is_empty() {
334 return Ok(Vec::new());
336 self.parse(sess, |parser| {
337 parser.expect(&token::OpenDelim(token::Paren))?;
338 let mut list = Vec::new();
339 while !parser.eat(&token::CloseDelim(token::Paren)) {
340 list.push(f(parser)?);
341 if !parser.eat(&token::Comma) {
342 parser.expect(&token::CloseDelim(token::Paren))?;
350 pub fn parse_meta<'a>(&self, sess: &'a ParseSess) -> PResult<'a, MetaItem> {
351 if self.path.segments.len() > 1 {
352 sess.span_diagnostic.span_err(self.path.span, "expected ident, found path");
356 name: self.path.segments.last().unwrap().ident.name,
357 node: self.parse(sess, |parser| parser.parse_meta_item_kind())?,
362 /// Convert self to a normal #[doc="foo"] comment, if it is a
363 /// comment like `///` or `/** */`. (Returns self unchanged for
364 /// non-sugared doc attributes.)
365 pub fn with_desugared_doc<T, F>(&self, f: F) -> T where
366 F: FnOnce(&Attribute) -> T,
368 if self.is_sugared_doc {
369 let comment = self.value_str().unwrap();
370 let meta = mk_name_value_item_str(
371 Symbol::intern("doc"),
372 Symbol::intern(&strip_doc_comment_decoration(&comment.as_str())));
373 let mut attr = if self.style == ast::AttrStyle::Outer {
374 mk_attr_outer(self.span, self.id, meta)
376 mk_attr_inner(self.span, self.id, meta)
378 attr.is_sugared_doc = true;
388 pub fn mk_name_value_item_str(name: Name, value: Symbol) -> MetaItem {
389 let value_lit = dummy_spanned(LitKind::Str(value, ast::StrStyle::Cooked));
390 mk_spanned_name_value_item(DUMMY_SP, name, value_lit)
393 pub fn mk_name_value_item(name: Name, value: ast::Lit) -> MetaItem {
394 mk_spanned_name_value_item(DUMMY_SP, name, value)
397 pub fn mk_list_item(name: Name, items: Vec<NestedMetaItem>) -> MetaItem {
398 mk_spanned_list_item(DUMMY_SP, name, items)
401 pub fn mk_list_word_item(name: Name) -> ast::NestedMetaItem {
402 dummy_spanned(NestedMetaItemKind::MetaItem(mk_spanned_word_item(DUMMY_SP, name)))
405 pub fn mk_word_item(name: Name) -> MetaItem {
406 mk_spanned_word_item(DUMMY_SP, name)
409 pub fn mk_spanned_name_value_item(sp: Span, name: Name, value: ast::Lit) -> MetaItem {
410 MetaItem { span: sp, name: name, node: MetaItemKind::NameValue(value) }
413 pub fn mk_spanned_list_item(sp: Span, name: Name, items: Vec<NestedMetaItem>) -> MetaItem {
414 MetaItem { span: sp, name: name, node: MetaItemKind::List(items) }
417 pub fn mk_spanned_word_item(sp: Span, name: Name) -> MetaItem {
418 MetaItem { span: sp, name: name, node: MetaItemKind::Word }
421 pub fn mk_attr_id() -> AttrId {
422 use std::sync::atomic::AtomicUsize;
423 use std::sync::atomic::Ordering;
425 static NEXT_ATTR_ID: AtomicUsize = AtomicUsize::new(0);
427 let id = NEXT_ATTR_ID.fetch_add(1, Ordering::SeqCst);
428 assert!(id != ::std::usize::MAX);
432 /// Returns an inner attribute with the given value.
433 pub fn mk_attr_inner(span: Span, id: AttrId, item: MetaItem) -> Attribute {
434 mk_spanned_attr_inner(span, id, item)
437 /// Returns an inner attribute with the given value and span.
438 pub fn mk_spanned_attr_inner(sp: Span, id: AttrId, item: MetaItem) -> Attribute {
439 let ident = ast::Ident::with_empty_ctxt(item.name).with_span_pos(item.span);
442 style: ast::AttrStyle::Inner,
443 path: ast::Path::from_ident(ident),
444 tokens: item.node.tokens(item.span),
445 is_sugared_doc: false,
451 /// Returns an outer attribute with the given value.
452 pub fn mk_attr_outer(span: Span, id: AttrId, item: MetaItem) -> Attribute {
453 mk_spanned_attr_outer(span, id, item)
456 /// Returns an outer attribute with the given value and span.
457 pub fn mk_spanned_attr_outer(sp: Span, id: AttrId, item: MetaItem) -> Attribute {
458 let ident = ast::Ident::with_empty_ctxt(item.name).with_span_pos(item.span);
461 style: ast::AttrStyle::Outer,
462 path: ast::Path::from_ident(ident),
463 tokens: item.node.tokens(item.span),
464 is_sugared_doc: false,
469 pub fn mk_sugared_doc_attr(id: AttrId, text: Symbol, span: Span) -> Attribute {
470 let style = doc_comment_style(&text.as_str());
471 let lit = respan(span, LitKind::Str(text, ast::StrStyle::Cooked));
475 path: ast::Path::from_ident(ast::Ident::from_str("doc").with_span_pos(span)),
476 tokens: MetaItemKind::NameValue(lit).tokens(span),
477 is_sugared_doc: true,
482 pub fn list_contains_name(items: &[NestedMetaItem], name: &str) -> bool {
483 items.iter().any(|item| {
484 item.check_name(name)
488 pub fn contains_name(attrs: &[Attribute], name: &str) -> bool {
489 attrs.iter().any(|item| {
490 item.check_name(name)
494 pub fn find_by_name<'a>(attrs: &'a [Attribute], name: &str) -> Option<&'a Attribute> {
495 attrs.iter().find(|attr| attr.check_name(name))
498 pub fn first_attr_value_str_by_name(attrs: &[Attribute], name: &str) -> Option<Symbol> {
500 .find(|at| at.check_name(name))
501 .and_then(|at| at.value_str())
504 /// Check if `attrs` contains an attribute like `#![feature(feature_name)]`.
505 /// This will not perform any "sanity checks" on the form of the attributes.
506 pub fn contains_feature_attr(attrs: &[Attribute], feature_name: &str) -> bool {
507 attrs.iter().any(|item| {
508 item.check_name("feature") &&
509 item.meta_item_list().map(|list| {
510 list.iter().any(|mi| {
511 mi.word().map(|w| w.name() == feature_name)
518 /* Higher-level applications */
520 pub fn find_crate_name(attrs: &[Attribute]) -> Option<Symbol> {
521 first_attr_value_str_by_name(attrs, "crate_name")
524 #[derive(Copy, Clone, Hash, PartialEq, RustcEncodable, RustcDecodable)]
525 pub enum InlineAttr {
532 #[derive(Copy, Clone, PartialEq)]
533 pub enum UnwindAttr {
538 /// Determine what `#[unwind]` attribute is present in `attrs`, if any.
539 pub fn find_unwind_attr(diagnostic: Option<&Handler>, attrs: &[Attribute]) -> Option<UnwindAttr> {
540 let syntax_error = |attr: &Attribute| {
543 span_err!(d, attr.span, E0633, "malformed `#[unwind]` attribute");
548 attrs.iter().fold(None, |ia, attr| {
549 if attr.path != "unwind" {
552 let meta = match attr.meta() {
553 Some(meta) => meta.node,
557 MetaItemKind::Word => {
560 MetaItemKind::List(ref items) => {
562 if items.len() != 1 {
564 } else if list_contains_name(&items[..], "allowed") {
565 Some(UnwindAttr::Allowed)
566 } else if list_contains_name(&items[..], "aborts") {
567 Some(UnwindAttr::Aborts)
578 /// Tests if a cfg-pattern matches the cfg set
579 pub fn cfg_matches(cfg: &ast::MetaItem, sess: &ParseSess, features: Option<&Features>) -> bool {
580 eval_condition(cfg, sess, &mut |cfg| {
581 if let (Some(feats), Some(gated_cfg)) = (features, GatedCfg::gate(cfg)) {
582 gated_cfg.check_and_emit(sess, feats);
584 sess.config.contains(&(cfg.name(), cfg.value_str()))
588 /// Evaluate a cfg-like condition (with `any` and `all`), using `eval` to
589 /// evaluate individual items.
590 pub fn eval_condition<F>(cfg: &ast::MetaItem, sess: &ParseSess, eval: &mut F)
592 where F: FnMut(&ast::MetaItem) -> bool
595 ast::MetaItemKind::List(ref mis) => {
596 for mi in mis.iter() {
597 if !mi.is_meta_item() {
598 handle_errors(&sess.span_diagnostic, mi.span, AttrError::UnsupportedLiteral);
603 // The unwraps below may look dangerous, but we've already asserted
604 // that they won't fail with the loop above.
605 match &*cfg.name.as_str() {
606 "any" => mis.iter().any(|mi| {
607 eval_condition(mi.meta_item().unwrap(), sess, eval)
609 "all" => mis.iter().all(|mi| {
610 eval_condition(mi.meta_item().unwrap(), sess, eval)
614 span_err!(sess.span_diagnostic, cfg.span, E0536, "expected 1 cfg-pattern");
618 !eval_condition(mis[0].meta_item().unwrap(), sess, eval)
621 span_err!(sess.span_diagnostic, cfg.span, E0537, "invalid predicate `{}`", p);
626 ast::MetaItemKind::Word | ast::MetaItemKind::NameValue(..) => {
632 /// Represents the #[stable], #[unstable], #[rustc_{deprecated,const_unstable}] attributes.
633 #[derive(RustcEncodable, RustcDecodable, Clone, Debug, PartialEq, Eq, Hash)]
634 pub struct Stability {
635 pub level: StabilityLevel,
637 pub rustc_depr: Option<RustcDeprecation>,
638 pub rustc_const_unstable: Option<RustcConstUnstable>,
641 /// The available stability levels.
642 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Debug, Eq, Hash)]
643 pub enum StabilityLevel {
644 // Reason for the current stability level and the relevant rust-lang issue
645 Unstable { reason: Option<Symbol>, issue: u32 },
646 Stable { since: Symbol },
649 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Debug, Eq, Hash)]
650 pub struct RustcDeprecation {
655 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Debug, Eq, Hash)]
656 pub struct RustcConstUnstable {
660 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Debug, Eq, Hash)]
661 pub struct Deprecation {
662 pub since: Option<Symbol>,
663 pub note: Option<Symbol>,
666 impl StabilityLevel {
667 pub fn is_unstable(&self) -> bool { if let Unstable {..} = *self { true } else { false }}
668 pub fn is_stable(&self) -> bool { if let Stable {..} = *self { true } else { false }}
671 fn find_stability_generic<'a, I>(diagnostic: &Handler,
675 where I: Iterator<Item = &'a Attribute>
677 let mut stab: Option<Stability> = None;
678 let mut rustc_depr: Option<RustcDeprecation> = None;
679 let mut rustc_const_unstable: Option<RustcConstUnstable> = None;
681 'outer: for attr in attrs_iter {
684 "rustc_const_unstable",
687 ].iter().any(|&s| attr.path == s) {
688 continue // not a stability level
693 let meta = attr.meta();
694 if let Some(MetaItem { node: MetaItemKind::List(ref metas), .. }) = meta {
695 let meta = meta.as_ref().unwrap();
696 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
698 handle_errors(diagnostic, meta.span, AttrError::MultipleItem(meta.name()));
701 if let Some(v) = meta.value_str() {
705 span_err!(diagnostic, meta.span, E0539, "incorrect meta item");
710 macro_rules! get_meta {
711 ($($name:ident),+) => {
713 let mut $name = None;
716 if let Some(mi) = meta.meta_item() {
717 match &*mi.name().as_str() {
720 => if !get(mi, &mut $name) { continue 'outer },
723 handle_errors(diagnostic, mi.span,
724 AttrError::UnknownMetaItem(mi.name()));
729 handle_errors(diagnostic, meta.span, AttrError::UnsupportedLiteral);
736 match &*meta.name.as_str() {
737 "rustc_deprecated" => {
738 if rustc_depr.is_some() {
739 span_err!(diagnostic, item_sp, E0540,
740 "multiple rustc_deprecated attributes");
744 get_meta!(since, reason);
746 match (since, reason) {
747 (Some(since), Some(reason)) => {
748 rustc_depr = Some(RustcDeprecation {
754 handle_errors(diagnostic, attr.span(), AttrError::MissingSince);
758 span_err!(diagnostic, attr.span(), E0543, "missing 'reason'");
763 "rustc_const_unstable" => {
764 if rustc_const_unstable.is_some() {
765 span_err!(diagnostic, item_sp, E0553,
766 "multiple rustc_const_unstable attributes");
771 if let Some(feature) = feature {
772 rustc_const_unstable = Some(RustcConstUnstable {
776 span_err!(diagnostic, attr.span(), E0629, "missing 'feature'");
782 handle_errors(diagnostic, attr.span(), AttrError::MultipleStabilityLevels);
786 let mut feature = None;
787 let mut reason = None;
788 let mut issue = None;
790 if let Some(mi) = meta.meta_item() {
791 match &*mi.name().as_str() {
792 "feature" => if !get(mi, &mut feature) { continue 'outer },
793 "reason" => if !get(mi, &mut reason) { continue 'outer },
794 "issue" => if !get(mi, &mut issue) { continue 'outer },
796 handle_errors(diagnostic, meta.span,
797 AttrError::UnknownMetaItem(mi.name()));
802 handle_errors(diagnostic, meta.span, AttrError::UnsupportedLiteral);
807 match (feature, reason, issue) {
808 (Some(feature), reason, Some(issue)) => {
809 stab = Some(Stability {
813 if let Ok(issue) = issue.as_str().parse() {
816 span_err!(diagnostic, attr.span(), E0545,
817 "incorrect 'issue'");
824 rustc_const_unstable: None,
828 handle_errors(diagnostic, attr.span(), AttrError::MissingFeature);
832 span_err!(diagnostic, attr.span(), E0547, "missing 'issue'");
839 handle_errors(diagnostic, attr.span(), AttrError::MultipleStabilityLevels);
843 let mut feature = None;
844 let mut since = None;
846 if let NestedMetaItemKind::MetaItem(ref mi) = meta.node {
847 match &*mi.name().as_str() {
848 "feature" => if !get(mi, &mut feature) { continue 'outer },
849 "since" => if !get(mi, &mut since) { continue 'outer },
851 handle_errors(diagnostic, meta.span,
852 AttrError::UnknownMetaItem(mi.name()));
857 handle_errors(diagnostic, meta.span, AttrError::UnsupportedLiteral);
862 match (feature, since) {
863 (Some(feature), Some(since)) => {
864 stab = Some(Stability {
870 rustc_const_unstable: None,
874 handle_errors(diagnostic, attr.span(), AttrError::MissingFeature);
878 handle_errors(diagnostic, attr.span(), AttrError::MissingSince);
886 span_err!(diagnostic, attr.span(), E0548, "incorrect stability attribute type");
891 // Merge the deprecation info into the stability info
892 if let Some(rustc_depr) = rustc_depr {
893 if let Some(ref mut stab) = stab {
894 stab.rustc_depr = Some(rustc_depr);
896 span_err!(diagnostic, item_sp, E0549,
897 "rustc_deprecated attribute must be paired with \
898 either stable or unstable attribute");
902 // Merge the const-unstable info into the stability info
903 if let Some(rustc_const_unstable) = rustc_const_unstable {
904 if let Some(ref mut stab) = stab {
905 stab.rustc_const_unstable = Some(rustc_const_unstable);
907 span_err!(diagnostic, item_sp, E0630,
908 "rustc_const_unstable attribute must be paired with \
909 either stable or unstable attribute");
916 fn find_deprecation_generic<'a, I>(diagnostic: &Handler,
919 -> Option<Deprecation>
920 where I: Iterator<Item = &'a Attribute>
922 let mut depr: Option<Deprecation> = None;
924 'outer: for attr in attrs_iter {
925 if attr.path != "deprecated" {
932 span_err!(diagnostic, item_sp, E0550, "multiple deprecated attributes");
936 depr = if let Some(metas) = attr.meta_item_list() {
937 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
939 handle_errors(diagnostic, meta.span, AttrError::MultipleItem(meta.name()));
942 if let Some(v) = meta.value_str() {
946 span_err!(diagnostic, meta.span, E0551, "incorrect meta item");
951 let mut since = None;
954 if let NestedMetaItemKind::MetaItem(ref mi) = meta.node {
955 match &*mi.name().as_str() {
956 "since" => if !get(mi, &mut since) { continue 'outer },
957 "note" => if !get(mi, &mut note) { continue 'outer },
959 handle_errors(diagnostic, meta.span,
960 AttrError::UnknownMetaItem(mi.name()));
965 handle_errors(diagnostic, meta.span, AttrError::UnsupportedLiteral);
970 Some(Deprecation {since: since, note: note})
972 Some(Deprecation{since: None, note: None})
979 /// Find the first stability attribute. `None` if none exists.
980 pub fn find_stability(diagnostic: &Handler, attrs: &[Attribute],
981 item_sp: Span) -> Option<Stability> {
982 find_stability_generic(diagnostic, attrs.iter(), item_sp)
985 /// Find the deprecation attribute. `None` if none exists.
986 pub fn find_deprecation(diagnostic: &Handler, attrs: &[Attribute],
987 item_sp: Span) -> Option<Deprecation> {
988 find_deprecation_generic(diagnostic, attrs.iter(), item_sp)
992 /// Parse #[repr(...)] forms.
994 /// Valid repr contents: any of the primitive integral type names (see
995 /// `int_type_of_word`, below) to specify enum discriminant type; `C`, to use
996 /// the same discriminant size that the corresponding C enum would or C
997 /// structure layout, `packed` to remove padding, and `transparent` to elegate representation
998 /// concerns to the only non-ZST field.
999 pub fn find_repr_attrs(diagnostic: &Handler, attr: &Attribute) -> Vec<ReprAttr> {
1000 let mut acc = Vec::new();
1001 if attr.path == "repr" {
1002 if let Some(items) = attr.meta_item_list() {
1005 if !item.is_meta_item() {
1006 handle_errors(diagnostic, item.span, AttrError::UnsupportedLiteral);
1010 let mut recognised = false;
1011 if let Some(mi) = item.word() {
1012 let word = &*mi.name().as_str();
1013 let hint = match word {
1015 "packed" => Some(ReprPacked),
1016 "simd" => Some(ReprSimd),
1017 "transparent" => Some(ReprTransparent),
1018 _ => match int_type_of_word(word) {
1019 Some(ity) => Some(ReprInt(ity)),
1026 if let Some(h) = hint {
1030 } else if let Some((name, value)) = item.name_value_literal() {
1031 if name == "align" {
1033 let mut align_error = None;
1034 if let ast::LitKind::Int(align, ast::LitIntType::Unsuffixed) = value.node {
1035 if align.is_power_of_two() {
1036 // rustc::ty::layout::Align restricts align to <= 2147483647
1037 if align <= 2147483647 {
1038 acc.push(ReprAlign(align as u32));
1040 align_error = Some("larger than 2147483647");
1043 align_error = Some("not a power of two");
1046 align_error = Some("not an unsuffixed integer");
1048 if let Some(align_error) = align_error {
1049 span_err!(diagnostic, item.span, E0589,
1050 "invalid `repr(align)` attribute: {}", align_error);
1055 // Not a word we recognize
1056 span_err!(diagnostic, item.span, E0552,
1057 "unrecognized representation hint");
1065 fn int_type_of_word(s: &str) -> Option<IntType> {
1067 "i8" => Some(SignedInt(ast::IntTy::I8)),
1068 "u8" => Some(UnsignedInt(ast::UintTy::U8)),
1069 "i16" => Some(SignedInt(ast::IntTy::I16)),
1070 "u16" => Some(UnsignedInt(ast::UintTy::U16)),
1071 "i32" => Some(SignedInt(ast::IntTy::I32)),
1072 "u32" => Some(UnsignedInt(ast::UintTy::U32)),
1073 "i64" => Some(SignedInt(ast::IntTy::I64)),
1074 "u64" => Some(UnsignedInt(ast::UintTy::U64)),
1075 "i128" => Some(SignedInt(ast::IntTy::I128)),
1076 "u128" => Some(UnsignedInt(ast::UintTy::U128)),
1077 "isize" => Some(SignedInt(ast::IntTy::Isize)),
1078 "usize" => Some(UnsignedInt(ast::UintTy::Usize)),
1083 #[derive(PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
1093 #[derive(Eq, Hash, PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
1095 SignedInt(ast::IntTy),
1096 UnsignedInt(ast::UintTy)
1101 pub fn is_signed(self) -> bool {
1103 SignedInt(..) => true,
1104 UnsignedInt(..) => false
1110 fn tokens(&self) -> TokenStream {
1111 let ident = TokenTree::Token(self.span,
1112 Token::from_ast_ident(Ident::with_empty_ctxt(self.name)));
1113 TokenStream::concat(vec![ident.into(), self.node.tokens(self.span)])
1116 fn from_tokens<I>(tokens: &mut iter::Peekable<I>) -> Option<MetaItem>
1117 where I: Iterator<Item = TokenTree>,
1119 let (span, name) = match tokens.next() {
1120 Some(TokenTree::Token(span, Token::Ident(ident, _))) => (span, ident.name),
1121 Some(TokenTree::Token(_, Token::Interpolated(ref nt))) => match nt.0 {
1122 token::Nonterminal::NtIdent(ident, _) => (ident.span, ident.name),
1123 token::Nonterminal::NtMeta(ref meta) => return Some(meta.clone()),
1128 let list_closing_paren_pos = tokens.peek().map(|tt| tt.span().hi());
1129 let node = MetaItemKind::from_tokens(tokens)?;
1130 let hi = match node {
1131 MetaItemKind::NameValue(ref lit) => lit.span.hi(),
1132 MetaItemKind::List(..) => list_closing_paren_pos.unwrap_or(span.hi()),
1135 Some(MetaItem { name, node, span: span.with_hi(hi) })
1140 pub fn tokens(&self, span: Span) -> TokenStream {
1142 MetaItemKind::Word => TokenStream::empty(),
1143 MetaItemKind::NameValue(ref lit) => {
1144 TokenStream::concat(vec![TokenTree::Token(span, Token::Eq).into(), lit.tokens()])
1146 MetaItemKind::List(ref list) => {
1147 let mut tokens = Vec::new();
1148 for (i, item) in list.iter().enumerate() {
1150 tokens.push(TokenTree::Token(span, Token::Comma).into());
1152 tokens.push(item.node.tokens());
1154 TokenTree::Delimited(span, Delimited {
1155 delim: token::Paren,
1156 tts: TokenStream::concat(tokens).into(),
1162 fn from_tokens<I>(tokens: &mut iter::Peekable<I>) -> Option<MetaItemKind>
1163 where I: Iterator<Item = TokenTree>,
1165 let delimited = match tokens.peek().cloned() {
1166 Some(TokenTree::Token(_, token::Eq)) => {
1168 return if let Some(TokenTree::Token(span, token)) = tokens.next() {
1169 LitKind::from_token(token)
1170 .map(|lit| MetaItemKind::NameValue(Spanned { node: lit, span: span }))
1175 Some(TokenTree::Delimited(_, ref delimited)) if delimited.delim == token::Paren => {
1179 _ => return Some(MetaItemKind::Word),
1182 let mut tokens = delimited.into_trees().peekable();
1183 let mut result = Vec::new();
1184 while let Some(..) = tokens.peek() {
1185 let item = NestedMetaItemKind::from_tokens(&mut tokens)?;
1186 result.push(respan(item.span(), item));
1187 match tokens.next() {
1188 None | Some(TokenTree::Token(_, Token::Comma)) => {}
1192 Some(MetaItemKind::List(result))
1196 impl NestedMetaItemKind {
1197 fn span(&self) -> Span {
1199 NestedMetaItemKind::MetaItem(ref item) => item.span,
1200 NestedMetaItemKind::Literal(ref lit) => lit.span,
1204 fn tokens(&self) -> TokenStream {
1206 NestedMetaItemKind::MetaItem(ref item) => item.tokens(),
1207 NestedMetaItemKind::Literal(ref lit) => lit.tokens(),
1211 fn from_tokens<I>(tokens: &mut iter::Peekable<I>) -> Option<NestedMetaItemKind>
1212 where I: Iterator<Item = TokenTree>,
1214 if let Some(TokenTree::Token(span, token)) = tokens.peek().cloned() {
1215 if let Some(node) = LitKind::from_token(token) {
1217 return Some(NestedMetaItemKind::Literal(respan(span, node)));
1221 MetaItem::from_tokens(tokens).map(NestedMetaItemKind::MetaItem)
1226 fn tokens(&self) -> TokenStream {
1227 TokenTree::Token(self.span, self.node.token()).into()
1232 fn token(&self) -> Token {
1236 LitKind::Str(string, ast::StrStyle::Cooked) => {
1237 let mut escaped = String::new();
1238 for ch in string.as_str().chars() {
1239 escaped.extend(ch.escape_unicode());
1241 Token::Literal(token::Lit::Str_(Symbol::intern(&escaped)), None)
1243 LitKind::Str(string, ast::StrStyle::Raw(n)) => {
1244 Token::Literal(token::Lit::StrRaw(string, n), None)
1246 LitKind::ByteStr(ref bytes) => {
1247 let string = bytes.iter().cloned().flat_map(ascii::escape_default)
1248 .map(Into::<char>::into).collect::<String>();
1249 Token::Literal(token::Lit::ByteStr(Symbol::intern(&string)), None)
1251 LitKind::Byte(byte) => {
1252 let string: String = ascii::escape_default(byte).map(Into::<char>::into).collect();
1253 Token::Literal(token::Lit::Byte(Symbol::intern(&string)), None)
1255 LitKind::Char(ch) => {
1256 let string: String = ch.escape_default().map(Into::<char>::into).collect();
1257 Token::Literal(token::Lit::Char(Symbol::intern(&string)), None)
1259 LitKind::Int(n, ty) => {
1260 let suffix = match ty {
1261 ast::LitIntType::Unsigned(ty) => Some(Symbol::intern(ty.ty_to_string())),
1262 ast::LitIntType::Signed(ty) => Some(Symbol::intern(ty.ty_to_string())),
1263 ast::LitIntType::Unsuffixed => None,
1265 Token::Literal(token::Lit::Integer(Symbol::intern(&n.to_string())), suffix)
1267 LitKind::Float(symbol, ty) => {
1268 Token::Literal(token::Lit::Float(symbol), Some(Symbol::intern(ty.ty_to_string())))
1270 LitKind::FloatUnsuffixed(symbol) => Token::Literal(token::Lit::Float(symbol), None),
1271 LitKind::Bool(value) => Token::Ident(Ident::with_empty_ctxt(Symbol::intern(if value {
1279 fn from_token(token: Token) -> Option<LitKind> {
1281 Token::Ident(ident, false) if ident.name == "true" => Some(LitKind::Bool(true)),
1282 Token::Ident(ident, false) if ident.name == "false" => Some(LitKind::Bool(false)),
1283 Token::Interpolated(ref nt) => match nt.0 {
1284 token::NtExpr(ref v) => match v.node {
1285 ExprKind::Lit(ref lit) => Some(lit.node.clone()),
1290 Token::Literal(lit, suf) => {
1291 let (suffix_illegal, result) = parse::lit_token(lit, suf, None);
1292 if suffix_illegal && suf.is_some() {
1302 pub trait HasAttrs: Sized {
1303 fn attrs(&self) -> &[ast::Attribute];
1304 fn map_attrs<F: FnOnce(Vec<ast::Attribute>) -> Vec<ast::Attribute>>(self, f: F) -> Self;
1307 impl<T: HasAttrs> HasAttrs for Spanned<T> {
1308 fn attrs(&self) -> &[ast::Attribute] { self.node.attrs() }
1309 fn map_attrs<F: FnOnce(Vec<ast::Attribute>) -> Vec<ast::Attribute>>(self, f: F) -> Self {
1310 respan(self.span, self.node.map_attrs(f))
1314 impl HasAttrs for Vec<Attribute> {
1315 fn attrs(&self) -> &[Attribute] {
1318 fn map_attrs<F: FnOnce(Vec<Attribute>) -> Vec<Attribute>>(self, f: F) -> Self {
1323 impl HasAttrs for ThinVec<Attribute> {
1324 fn attrs(&self) -> &[Attribute] {
1327 fn map_attrs<F: FnOnce(Vec<Attribute>) -> Vec<Attribute>>(self, f: F) -> Self {
1328 f(self.into()).into()
1332 impl<T: HasAttrs + 'static> HasAttrs for P<T> {
1333 fn attrs(&self) -> &[Attribute] {
1336 fn map_attrs<F: FnOnce(Vec<Attribute>) -> Vec<Attribute>>(self, f: F) -> Self {
1337 self.map(|t| t.map_attrs(f))
1341 impl HasAttrs for StmtKind {
1342 fn attrs(&self) -> &[Attribute] {
1344 StmtKind::Local(ref local) => local.attrs(),
1345 StmtKind::Item(..) => &[],
1346 StmtKind::Expr(ref expr) | StmtKind::Semi(ref expr) => expr.attrs(),
1347 StmtKind::Mac(ref mac) => {
1348 let (_, _, ref attrs) = **mac;
1354 fn map_attrs<F: FnOnce(Vec<Attribute>) -> Vec<Attribute>>(self, f: F) -> Self {
1356 StmtKind::Local(local) => StmtKind::Local(local.map_attrs(f)),
1357 StmtKind::Item(..) => self,
1358 StmtKind::Expr(expr) => StmtKind::Expr(expr.map_attrs(f)),
1359 StmtKind::Semi(expr) => StmtKind::Semi(expr.map_attrs(f)),
1360 StmtKind::Mac(mac) => StmtKind::Mac(mac.map(|(mac, style, attrs)| {
1361 (mac, style, attrs.map_attrs(f))
1367 impl HasAttrs for Stmt {
1368 fn attrs(&self) -> &[ast::Attribute] { self.node.attrs() }
1369 fn map_attrs<F: FnOnce(Vec<ast::Attribute>) -> Vec<ast::Attribute>>(self, f: F) -> Self {
1370 Stmt { id: self.id, node: self.node.map_attrs(f), span: self.span }
1374 macro_rules! derive_has_attrs {
1375 ($($ty:path),*) => { $(
1376 impl HasAttrs for $ty {
1377 fn attrs(&self) -> &[Attribute] {
1381 fn map_attrs<F>(mut self, f: F) -> Self
1382 where F: FnOnce(Vec<Attribute>) -> Vec<Attribute>,
1384 self.attrs = self.attrs.map_attrs(f);
1392 Item, Expr, Local, ast::ForeignItem, ast::StructField, ast::ImplItem, ast::TraitItem, ast::Arm,
1393 ast::Field, ast::FieldPat, ast::Variant_