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