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