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