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