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