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