]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/attr/mod.rs
4e27d6c15258bedef5e7e59e773f36533eac7ce4
[rust.git] / src / libsyntax / attr / mod.rs
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.
4 //
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.
10
11 //! Functions dealing with attributes and meta items
12
13 mod builtin;
14
15 pub use self::builtin::{
16     cfg_matches, contains_feature_attr, eval_condition, find_crate_name, find_deprecation,
17     find_repr_attrs, find_stability, find_unwind_attr, Deprecation, InlineAttr, IntType, ReprAttr,
18     RustcConstUnstable, RustcDeprecation, Stability, StabilityLevel, UnwindAttr,
19 };
20 pub use self::IntType::*;
21 pub use self::ReprAttr::*;
22 pub use self::StabilityLevel::*;
23
24 use ast;
25 use ast::{AttrId, Attribute, Name, Ident, Path, PathSegment};
26 use ast::{MetaItem, MetaItemKind, NestedMetaItem, NestedMetaItemKind};
27 use ast::{Lit, LitKind, Expr, ExprKind, Item, Local, Stmt, StmtKind, GenericParam};
28 use codemap::{BytePos, Spanned, respan, dummy_spanned};
29 use syntax_pos::Span;
30 use parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
31 use parse::parser::Parser;
32 use parse::{self, ParseSess, PResult};
33 use parse::token::{self, Token};
34 use ptr::P;
35 use symbol::Symbol;
36 use tokenstream::{TokenStream, TokenTree, Delimited};
37 use util::ThinVec;
38 use GLOBALS;
39
40 use std::iter;
41
42 pub fn mark_used(attr: &Attribute) {
43     debug!("Marking {:?} as used.", attr);
44     let AttrId(id) = attr.id;
45     GLOBALS.with(|globals| {
46         let mut slot = globals.used_attrs.lock();
47         let idx = (id / 64) as usize;
48         let shift = id % 64;
49         if slot.len() <= idx {
50             slot.resize(idx + 1, 0);
51         }
52         slot[idx] |= 1 << shift;
53     });
54 }
55
56 pub fn is_used(attr: &Attribute) -> bool {
57     let AttrId(id) = attr.id;
58     GLOBALS.with(|globals| {
59         let slot = globals.used_attrs.lock();
60         let idx = (id / 64) as usize;
61         let shift = id % 64;
62         slot.get(idx).map(|bits| bits & (1 << shift) != 0)
63             .unwrap_or(false)
64     })
65 }
66
67 pub fn mark_known(attr: &Attribute) {
68     debug!("Marking {:?} as known.", attr);
69     let AttrId(id) = attr.id;
70     GLOBALS.with(|globals| {
71         let mut slot = globals.known_attrs.lock();
72         let idx = (id / 64) as usize;
73         let shift = id % 64;
74         if slot.len() <= idx {
75             slot.resize(idx + 1, 0);
76         }
77         slot[idx] |= 1 << shift;
78     });
79 }
80
81 pub fn is_known(attr: &Attribute) -> bool {
82     let AttrId(id) = attr.id;
83     GLOBALS.with(|globals| {
84         let slot = globals.known_attrs.lock();
85         let idx = (id / 64) as usize;
86         let shift = id % 64;
87         slot.get(idx).map(|bits| bits & (1 << shift) != 0)
88             .unwrap_or(false)
89     })
90 }
91
92 const RUST_KNOWN_TOOL: &[&str] = &["clippy", "rustfmt"];
93
94 pub fn is_known_tool(attr: &Attribute) -> bool {
95     let tool_name =
96         attr.path.segments.iter().next().expect("empty path in attribute").ident.name;
97     RUST_KNOWN_TOOL.contains(&tool_name.as_str().as_ref())
98 }
99
100 impl NestedMetaItem {
101     /// Returns the MetaItem if self is a NestedMetaItemKind::MetaItem.
102     pub fn meta_item(&self) -> Option<&MetaItem> {
103         match self.node {
104             NestedMetaItemKind::MetaItem(ref item) => Some(item),
105             _ => None
106         }
107     }
108
109     /// Returns the Lit if self is a NestedMetaItemKind::Literal.
110     pub fn literal(&self) -> Option<&Lit> {
111         match self.node {
112             NestedMetaItemKind::Literal(ref lit) => Some(lit),
113             _ => None
114         }
115     }
116
117     /// Returns the Span for `self`.
118     pub fn span(&self) -> Span {
119         self.span
120     }
121
122     /// Returns true if this list item is a MetaItem with a name of `name`.
123     pub fn check_name(&self, name: &str) -> bool {
124         self.meta_item().map_or(false, |meta_item| meta_item.check_name(name))
125     }
126
127     /// Returns the name of the meta item, e.g. `foo` in `#[foo]`,
128     /// `#[foo="bar"]` and `#[foo(bar)]`, if self is a MetaItem
129     pub fn name(&self) -> Option<Name> {
130         self.meta_item().and_then(|meta_item| Some(meta_item.name()))
131     }
132
133     /// Gets the string value if self is a MetaItem and the MetaItem is a
134     /// MetaItemKind::NameValue variant containing a string, otherwise None.
135     pub fn value_str(&self) -> Option<Symbol> {
136         self.meta_item().and_then(|meta_item| meta_item.value_str())
137     }
138
139     /// Returns a name and single literal value tuple of the MetaItem.
140     pub fn name_value_literal(&self) -> Option<(Name, &Lit)> {
141         self.meta_item().and_then(
142             |meta_item| meta_item.meta_item_list().and_then(
143                 |meta_item_list| {
144                     if meta_item_list.len() == 1 {
145                         let nested_item = &meta_item_list[0];
146                         if nested_item.is_literal() {
147                             Some((meta_item.name(), nested_item.literal().unwrap()))
148                         } else {
149                             None
150                         }
151                     }
152                     else {
153                         None
154                     }}))
155     }
156
157     /// Returns a MetaItem if self is a MetaItem with Kind Word.
158     pub fn word(&self) -> Option<&MetaItem> {
159         self.meta_item().and_then(|meta_item| if meta_item.is_word() {
160             Some(meta_item)
161         } else {
162             None
163         })
164     }
165
166     /// Gets a list of inner meta items from a list MetaItem type.
167     pub fn meta_item_list(&self) -> Option<&[NestedMetaItem]> {
168         self.meta_item().and_then(|meta_item| meta_item.meta_item_list())
169     }
170
171     /// Returns `true` if the variant is MetaItem.
172     pub fn is_meta_item(&self) -> bool {
173         self.meta_item().is_some()
174     }
175
176     /// Returns `true` if the variant is Literal.
177     pub fn is_literal(&self) -> bool {
178         self.literal().is_some()
179     }
180
181     /// Returns `true` if self is a MetaItem and the meta item is a word.
182     pub fn is_word(&self) -> bool {
183         self.word().is_some()
184     }
185
186     /// Returns `true` if self is a MetaItem and the meta item is a ValueString.
187     pub fn is_value_str(&self) -> bool {
188         self.value_str().is_some()
189     }
190
191     /// Returns `true` if self is a MetaItem and the meta item is a list.
192     pub fn is_meta_item_list(&self) -> bool {
193         self.meta_item_list().is_some()
194     }
195 }
196
197 fn name_from_path(path: &Path) -> Name {
198     path.segments.last().expect("empty path in attribute").ident.name
199 }
200
201 impl Attribute {
202     pub fn check_name(&self, name: &str) -> bool {
203         let matches = self.path == name;
204         if matches {
205             mark_used(self);
206         }
207         matches
208     }
209
210     /// Returns the **last** segment of the name of this attribute.
211     /// E.g. `foo` for `#[foo]`, `skip` for `#[rustfmt::skip]`.
212     pub fn name(&self) -> Name {
213         name_from_path(&self.path)
214     }
215
216     pub fn value_str(&self) -> Option<Symbol> {
217         self.meta().and_then(|meta| meta.value_str())
218     }
219
220     pub fn meta_item_list(&self) -> Option<Vec<NestedMetaItem>> {
221         match self.meta() {
222             Some(MetaItem { node: MetaItemKind::List(list), .. }) => Some(list),
223             _ => None
224         }
225     }
226
227     pub fn is_word(&self) -> bool {
228         self.path.segments.len() == 1 && self.tokens.is_empty()
229     }
230
231     pub fn span(&self) -> Span {
232         self.span
233     }
234
235     pub fn is_meta_item_list(&self) -> bool {
236         self.meta_item_list().is_some()
237     }
238
239     /// Indicates if the attribute is a Value String.
240     pub fn is_value_str(&self) -> bool {
241         self.value_str().is_some()
242     }
243
244     pub fn is_scoped(&self) -> bool {
245         self.path.segments.len() > 1
246     }
247 }
248
249 impl MetaItem {
250     pub fn name(&self) -> Name {
251         name_from_path(&self.ident)
252     }
253
254     pub fn value_str(&self) -> Option<Symbol> {
255         match self.node {
256             MetaItemKind::NameValue(ref v) => {
257                 match v.node {
258                     LitKind::Str(ref s, _) => Some(*s),
259                     _ => None,
260                 }
261             },
262             _ => None
263         }
264     }
265
266     pub fn meta_item_list(&self) -> Option<&[NestedMetaItem]> {
267         match self.node {
268             MetaItemKind::List(ref l) => Some(&l[..]),
269             _ => None
270         }
271     }
272
273     pub fn is_word(&self) -> bool {
274         match self.node {
275             MetaItemKind::Word => true,
276             _ => false,
277         }
278     }
279
280     pub fn span(&self) -> Span { self.span }
281
282     pub fn check_name(&self, name: &str) -> bool {
283         self.name() == name
284     }
285
286     pub fn is_value_str(&self) -> bool {
287         self.value_str().is_some()
288     }
289
290     pub fn is_meta_item_list(&self) -> bool {
291         self.meta_item_list().is_some()
292     }
293 }
294
295 impl Attribute {
296     /// Extract the MetaItem from inside this Attribute.
297     pub fn meta(&self) -> Option<MetaItem> {
298         let mut tokens = self.tokens.trees().peekable();
299         Some(MetaItem {
300             ident: self.path.clone(),
301             node: if let Some(node) = MetaItemKind::from_tokens(&mut tokens) {
302                 if tokens.peek().is_some() {
303                     return None;
304                 }
305                 node
306             } else {
307                 return None;
308             },
309             span: self.span,
310         })
311     }
312
313     pub fn parse<'a, T, F>(&self, sess: &'a ParseSess, mut f: F) -> PResult<'a, T>
314         where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
315     {
316         let mut parser = Parser::new(sess, self.tokens.clone(), None, false, false);
317         let result = f(&mut parser)?;
318         if parser.token != token::Eof {
319             parser.unexpected()?;
320         }
321         Ok(result)
322     }
323
324     pub fn parse_list<'a, T, F>(&self, sess: &'a ParseSess, mut f: F) -> PResult<'a, Vec<T>>
325         where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
326     {
327         if self.tokens.is_empty() {
328             return Ok(Vec::new());
329         }
330         self.parse(sess, |parser| {
331             parser.expect(&token::OpenDelim(token::Paren))?;
332             let mut list = Vec::new();
333             while !parser.eat(&token::CloseDelim(token::Paren)) {
334                 list.push(f(parser)?);
335                 if !parser.eat(&token::Comma) {
336                    parser.expect(&token::CloseDelim(token::Paren))?;
337                     break
338                 }
339             }
340             Ok(list)
341         })
342     }
343
344     pub fn parse_meta<'a>(&self, sess: &'a ParseSess) -> PResult<'a, MetaItem> {
345         Ok(MetaItem {
346             ident: self.path.clone(),
347             node: self.parse(sess, |parser| parser.parse_meta_item_kind())?,
348             span: self.span,
349         })
350     }
351
352     /// Convert self to a normal #[doc="foo"] comment, if it is a
353     /// comment like `///` or `/** */`. (Returns self unchanged for
354     /// non-sugared doc attributes.)
355     pub fn with_desugared_doc<T, F>(&self, f: F) -> T where
356         F: FnOnce(&Attribute) -> T,
357     {
358         if self.is_sugared_doc {
359             let comment = self.value_str().unwrap();
360             let meta = mk_name_value_item_str(
361                 Ident::from_str("doc"),
362                 dummy_spanned(Symbol::intern(&strip_doc_comment_decoration(&comment.as_str()))));
363             let mut attr = if self.style == ast::AttrStyle::Outer {
364                 mk_attr_outer(self.span, self.id, meta)
365             } else {
366                 mk_attr_inner(self.span, self.id, meta)
367             };
368             attr.is_sugared_doc = true;
369             f(&attr)
370         } else {
371             f(self)
372         }
373     }
374 }
375
376 /* Constructors */
377
378 pub fn mk_name_value_item_str(ident: Ident, value: Spanned<Symbol>) -> MetaItem {
379     let value = respan(value.span, LitKind::Str(value.node, ast::StrStyle::Cooked));
380     mk_name_value_item(ident.span.to(value.span), ident, value)
381 }
382
383 pub fn mk_name_value_item(span: Span, ident: Ident, value: ast::Lit) -> MetaItem {
384     MetaItem { ident: Path::from_ident(ident), span, node: MetaItemKind::NameValue(value) }
385 }
386
387 pub fn mk_list_item(span: Span, ident: Ident, items: Vec<NestedMetaItem>) -> MetaItem {
388     MetaItem { ident: Path::from_ident(ident), span, node: MetaItemKind::List(items) }
389 }
390
391 pub fn mk_word_item(ident: Ident) -> MetaItem {
392     MetaItem { ident: Path::from_ident(ident), span: ident.span, node: MetaItemKind::Word }
393 }
394
395 pub fn mk_nested_word_item(ident: Ident) -> NestedMetaItem {
396     respan(ident.span, NestedMetaItemKind::MetaItem(mk_word_item(ident)))
397 }
398
399 pub fn mk_attr_id() -> AttrId {
400     use std::sync::atomic::AtomicUsize;
401     use std::sync::atomic::Ordering;
402
403     static NEXT_ATTR_ID: AtomicUsize = AtomicUsize::new(0);
404
405     let id = NEXT_ATTR_ID.fetch_add(1, Ordering::SeqCst);
406     assert!(id != ::std::usize::MAX);
407     AttrId(id)
408 }
409
410 /// Returns an inner attribute with the given value.
411 pub fn mk_attr_inner(span: Span, id: AttrId, item: MetaItem) -> Attribute {
412     mk_spanned_attr_inner(span, id, item)
413 }
414
415 /// Returns an inner attribute with the given value and span.
416 pub fn mk_spanned_attr_inner(sp: Span, id: AttrId, item: MetaItem) -> Attribute {
417     Attribute {
418         id,
419         style: ast::AttrStyle::Inner,
420         path: item.ident,
421         tokens: item.node.tokens(item.span),
422         is_sugared_doc: false,
423         span: sp,
424     }
425 }
426
427 /// Returns an outer attribute with the given value.
428 pub fn mk_attr_outer(span: Span, id: AttrId, item: MetaItem) -> Attribute {
429     mk_spanned_attr_outer(span, id, item)
430 }
431
432 /// Returns an outer attribute with the given value and span.
433 pub fn mk_spanned_attr_outer(sp: Span, id: AttrId, item: MetaItem) -> Attribute {
434     Attribute {
435         id,
436         style: ast::AttrStyle::Outer,
437         path: item.ident,
438         tokens: item.node.tokens(item.span),
439         is_sugared_doc: false,
440         span: sp,
441     }
442 }
443
444 pub fn mk_sugared_doc_attr(id: AttrId, text: Symbol, span: Span) -> Attribute {
445     let style = doc_comment_style(&text.as_str());
446     let lit = respan(span, LitKind::Str(text, ast::StrStyle::Cooked));
447     Attribute {
448         id,
449         style,
450         path: Path::from_ident(Ident::from_str("doc").with_span_pos(span)),
451         tokens: MetaItemKind::NameValue(lit).tokens(span),
452         is_sugared_doc: true,
453         span,
454     }
455 }
456
457 pub fn list_contains_name(items: &[NestedMetaItem], name: &str) -> bool {
458     items.iter().any(|item| {
459         item.check_name(name)
460     })
461 }
462
463 pub fn contains_name(attrs: &[Attribute], name: &str) -> bool {
464     attrs.iter().any(|item| {
465         item.check_name(name)
466     })
467 }
468
469 pub fn find_by_name<'a>(attrs: &'a [Attribute], name: &str) -> Option<&'a Attribute> {
470     attrs.iter().find(|attr| attr.check_name(name))
471 }
472
473 pub fn first_attr_value_str_by_name(attrs: &[Attribute], name: &str) -> Option<Symbol> {
474     attrs.iter()
475         .find(|at| at.check_name(name))
476         .and_then(|at| at.value_str())
477 }
478
479 impl MetaItem {
480     fn tokens(&self) -> TokenStream {
481         let mut idents = vec![];
482         let mut last_pos = BytePos(0 as u32);
483         for (i, segment) in self.ident.segments.iter().enumerate() {
484             let is_first = i == 0;
485             if !is_first {
486                 let mod_sep_span = Span::new(last_pos,
487                                              segment.ident.span.lo(),
488                                              segment.ident.span.ctxt());
489                 idents.push(TokenTree::Token(mod_sep_span, Token::ModSep).into());
490             }
491             idents.push(TokenTree::Token(segment.ident.span,
492                                          Token::from_ast_ident(segment.ident)).into());
493             last_pos = segment.ident.span.hi();
494         }
495         idents.push(self.node.tokens(self.span));
496         TokenStream::concat(idents)
497     }
498
499     fn from_tokens<I>(tokens: &mut iter::Peekable<I>) -> Option<MetaItem>
500         where I: Iterator<Item = TokenTree>,
501     {
502         // FIXME: Share code with `parse_path`.
503         let ident = match tokens.next() {
504             Some(TokenTree::Token(span, Token::Ident(ident, _))) => {
505                 if let Some(TokenTree::Token(_, Token::ModSep)) = tokens.peek() {
506                     let mut segments = vec![PathSegment::from_ident(ident.with_span_pos(span))];
507                     tokens.next();
508                     loop {
509                         if let Some(TokenTree::Token(span,
510                                                      Token::Ident(ident, _))) = tokens.next() {
511                             segments.push(PathSegment::from_ident(ident.with_span_pos(span)));
512                         } else {
513                             return None;
514                         }
515                         if let Some(TokenTree::Token(_, Token::ModSep)) = tokens.peek() {
516                             tokens.next();
517                         } else {
518                             break;
519                         }
520                     }
521                     let span = span.with_hi(segments.last().unwrap().ident.span.hi());
522                     Path { span, segments }
523                 } else {
524                     Path::from_ident(ident.with_span_pos(span))
525                 }
526             }
527             Some(TokenTree::Token(_, Token::Interpolated(ref nt))) => match nt.0 {
528                 token::Nonterminal::NtIdent(ident, _) => Path::from_ident(ident),
529                 token::Nonterminal::NtMeta(ref meta) => return Some(meta.clone()),
530                 token::Nonterminal::NtPath(ref path) => path.clone(),
531                 _ => return None,
532             },
533             _ => return None,
534         };
535         let list_closing_paren_pos = tokens.peek().map(|tt| tt.span().hi());
536         let node = MetaItemKind::from_tokens(tokens)?;
537         let hi = match node {
538             MetaItemKind::NameValue(ref lit) => lit.span.hi(),
539             MetaItemKind::List(..) => list_closing_paren_pos.unwrap_or(ident.span.hi()),
540             _ => ident.span.hi(),
541         };
542         let span = ident.span.with_hi(hi);
543         Some(MetaItem { ident, node, span })
544     }
545 }
546
547 impl MetaItemKind {
548     pub fn tokens(&self, span: Span) -> TokenStream {
549         match *self {
550             MetaItemKind::Word => TokenStream::empty(),
551             MetaItemKind::NameValue(ref lit) => {
552                 TokenStream::concat(vec![TokenTree::Token(span, Token::Eq).into(), lit.tokens()])
553             }
554             MetaItemKind::List(ref list) => {
555                 let mut tokens = Vec::new();
556                 for (i, item) in list.iter().enumerate() {
557                     if i > 0 {
558                         tokens.push(TokenTree::Token(span, Token::Comma).into());
559                     }
560                     tokens.push(item.node.tokens());
561                 }
562                 TokenTree::Delimited(span, Delimited {
563                     delim: token::Paren,
564                     tts: TokenStream::concat(tokens).into(),
565                 }).into()
566             }
567         }
568     }
569
570     fn from_tokens<I>(tokens: &mut iter::Peekable<I>) -> Option<MetaItemKind>
571         where I: Iterator<Item = TokenTree>,
572     {
573         let delimited = match tokens.peek().cloned() {
574             Some(TokenTree::Token(_, token::Eq)) => {
575                 tokens.next();
576                 return if let Some(TokenTree::Token(span, token)) = tokens.next() {
577                     LitKind::from_token(token)
578                         .map(|lit| MetaItemKind::NameValue(Spanned { node: lit, span: span }))
579                 } else {
580                     None
581                 };
582             }
583             Some(TokenTree::Delimited(_, ref delimited)) if delimited.delim == token::Paren => {
584                 tokens.next();
585                 delimited.stream()
586             }
587             _ => return Some(MetaItemKind::Word),
588         };
589
590         let mut tokens = delimited.into_trees().peekable();
591         let mut result = Vec::new();
592         while let Some(..) = tokens.peek() {
593             let item = NestedMetaItemKind::from_tokens(&mut tokens)?;
594             result.push(respan(item.span(), item));
595             match tokens.next() {
596                 None | Some(TokenTree::Token(_, Token::Comma)) => {}
597                 _ => return None,
598             }
599         }
600         Some(MetaItemKind::List(result))
601     }
602 }
603
604 impl NestedMetaItemKind {
605     fn span(&self) -> Span {
606         match *self {
607             NestedMetaItemKind::MetaItem(ref item) => item.span,
608             NestedMetaItemKind::Literal(ref lit) => lit.span,
609         }
610     }
611
612     fn tokens(&self) -> TokenStream {
613         match *self {
614             NestedMetaItemKind::MetaItem(ref item) => item.tokens(),
615             NestedMetaItemKind::Literal(ref lit) => lit.tokens(),
616         }
617     }
618
619     fn from_tokens<I>(tokens: &mut iter::Peekable<I>) -> Option<NestedMetaItemKind>
620         where I: Iterator<Item = TokenTree>,
621     {
622         if let Some(TokenTree::Token(span, token)) = tokens.peek().cloned() {
623             if let Some(node) = LitKind::from_token(token) {
624                 tokens.next();
625                 return Some(NestedMetaItemKind::Literal(respan(span, node)));
626             }
627         }
628
629         MetaItem::from_tokens(tokens).map(NestedMetaItemKind::MetaItem)
630     }
631 }
632
633 impl Lit {
634     fn tokens(&self) -> TokenStream {
635         TokenTree::Token(self.span, self.node.token()).into()
636     }
637 }
638
639 impl LitKind {
640     fn token(&self) -> Token {
641         use std::ascii;
642
643         match *self {
644             LitKind::Str(string, ast::StrStyle::Cooked) => {
645                 let escaped = string.as_str().escape_default();
646                 Token::Literal(token::Lit::Str_(Symbol::intern(&escaped)), None)
647             }
648             LitKind::Str(string, ast::StrStyle::Raw(n)) => {
649                 Token::Literal(token::Lit::StrRaw(string, n), None)
650             }
651             LitKind::ByteStr(ref bytes) => {
652                 let string = bytes.iter().cloned().flat_map(ascii::escape_default)
653                     .map(Into::<char>::into).collect::<String>();
654                 Token::Literal(token::Lit::ByteStr(Symbol::intern(&string)), None)
655             }
656             LitKind::Byte(byte) => {
657                 let string: String = ascii::escape_default(byte).map(Into::<char>::into).collect();
658                 Token::Literal(token::Lit::Byte(Symbol::intern(&string)), None)
659             }
660             LitKind::Char(ch) => {
661                 let string: String = ch.escape_default().map(Into::<char>::into).collect();
662                 Token::Literal(token::Lit::Char(Symbol::intern(&string)), None)
663             }
664             LitKind::Int(n, ty) => {
665                 let suffix = match ty {
666                     ast::LitIntType::Unsigned(ty) => Some(Symbol::intern(ty.ty_to_string())),
667                     ast::LitIntType::Signed(ty) => Some(Symbol::intern(ty.ty_to_string())),
668                     ast::LitIntType::Unsuffixed => None,
669                 };
670                 Token::Literal(token::Lit::Integer(Symbol::intern(&n.to_string())), suffix)
671             }
672             LitKind::Float(symbol, ty) => {
673                 Token::Literal(token::Lit::Float(symbol), Some(Symbol::intern(ty.ty_to_string())))
674             }
675             LitKind::FloatUnsuffixed(symbol) => Token::Literal(token::Lit::Float(symbol), None),
676             LitKind::Bool(value) => Token::Ident(Ident::with_empty_ctxt(Symbol::intern(if value {
677                 "true"
678             } else {
679                 "false"
680             })), false),
681         }
682     }
683
684     fn from_token(token: Token) -> Option<LitKind> {
685         match token {
686             Token::Ident(ident, false) if ident.name == "true" => Some(LitKind::Bool(true)),
687             Token::Ident(ident, false) if ident.name == "false" => Some(LitKind::Bool(false)),
688             Token::Interpolated(ref nt) => match nt.0 {
689                 token::NtExpr(ref v) | token::NtLiteral(ref v) => match v.node {
690                     ExprKind::Lit(ref lit) => Some(lit.node.clone()),
691                     _ => None,
692                 },
693                 _ => None,
694             },
695             Token::Literal(lit, suf) => {
696                 let (suffix_illegal, result) = parse::lit_token(lit, suf, None);
697                 if suffix_illegal && suf.is_some() {
698                     return None;
699                 }
700                 result
701             }
702             _ => None,
703         }
704     }
705 }
706
707 pub trait HasAttrs: Sized {
708     fn attrs(&self) -> &[ast::Attribute];
709     fn map_attrs<F: FnOnce(Vec<ast::Attribute>) -> Vec<ast::Attribute>>(self, f: F) -> Self;
710 }
711
712 impl<T: HasAttrs> HasAttrs for Spanned<T> {
713     fn attrs(&self) -> &[ast::Attribute] { self.node.attrs() }
714     fn map_attrs<F: FnOnce(Vec<ast::Attribute>) -> Vec<ast::Attribute>>(self, f: F) -> Self {
715         respan(self.span, self.node.map_attrs(f))
716     }
717 }
718
719 impl HasAttrs for Vec<Attribute> {
720     fn attrs(&self) -> &[Attribute] {
721         self
722     }
723     fn map_attrs<F: FnOnce(Vec<Attribute>) -> Vec<Attribute>>(self, f: F) -> Self {
724         f(self)
725     }
726 }
727
728 impl HasAttrs for ThinVec<Attribute> {
729     fn attrs(&self) -> &[Attribute] {
730         self
731     }
732     fn map_attrs<F: FnOnce(Vec<Attribute>) -> Vec<Attribute>>(self, f: F) -> Self {
733         f(self.into()).into()
734     }
735 }
736
737 impl<T: HasAttrs + 'static> HasAttrs for P<T> {
738     fn attrs(&self) -> &[Attribute] {
739         (**self).attrs()
740     }
741     fn map_attrs<F: FnOnce(Vec<Attribute>) -> Vec<Attribute>>(self, f: F) -> Self {
742         self.map(|t| t.map_attrs(f))
743     }
744 }
745
746 impl HasAttrs for StmtKind {
747     fn attrs(&self) -> &[Attribute] {
748         match *self {
749             StmtKind::Local(ref local) => local.attrs(),
750             StmtKind::Item(..) => &[],
751             StmtKind::Expr(ref expr) | StmtKind::Semi(ref expr) => expr.attrs(),
752             StmtKind::Mac(ref mac) => {
753                 let (_, _, ref attrs) = **mac;
754                 attrs.attrs()
755             }
756         }
757     }
758
759     fn map_attrs<F: FnOnce(Vec<Attribute>) -> Vec<Attribute>>(self, f: F) -> Self {
760         match self {
761             StmtKind::Local(local) => StmtKind::Local(local.map_attrs(f)),
762             StmtKind::Item(..) => self,
763             StmtKind::Expr(expr) => StmtKind::Expr(expr.map_attrs(f)),
764             StmtKind::Semi(expr) => StmtKind::Semi(expr.map_attrs(f)),
765             StmtKind::Mac(mac) => StmtKind::Mac(mac.map(|(mac, style, attrs)| {
766                 (mac, style, attrs.map_attrs(f))
767             })),
768         }
769     }
770 }
771
772 impl HasAttrs for Stmt {
773     fn attrs(&self) -> &[ast::Attribute] { self.node.attrs() }
774     fn map_attrs<F: FnOnce(Vec<ast::Attribute>) -> Vec<ast::Attribute>>(self, f: F) -> Self {
775         Stmt { id: self.id, node: self.node.map_attrs(f), span: self.span }
776     }
777 }
778
779 impl HasAttrs for GenericParam {
780     fn attrs(&self) -> &[ast::Attribute] {
781         &self.attrs
782     }
783
784     fn map_attrs<F: FnOnce(Vec<Attribute>) -> Vec<Attribute>>(mut self, f: F) -> Self {
785         self.attrs = self.attrs.map_attrs(f);
786         self
787     }
788 }
789
790 macro_rules! derive_has_attrs {
791     ($($ty:path),*) => { $(
792         impl HasAttrs for $ty {
793             fn attrs(&self) -> &[Attribute] {
794                 &self.attrs
795             }
796
797             fn map_attrs<F>(mut self, f: F) -> Self
798                 where F: FnOnce(Vec<Attribute>) -> Vec<Attribute>,
799             {
800                 self.attrs = self.attrs.map_attrs(f);
801                 self
802             }
803         }
804     )* }
805 }
806
807 derive_has_attrs! {
808     Item, Expr, Local, ast::ForeignItem, ast::StructField, ast::ImplItem, ast::TraitItem, ast::Arm,
809     ast::Field, ast::FieldPat, ast::Variant_
810 }