]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/attr/mod.rs
syntax: Switch function parameter order in `TokenTree::token`
[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, 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, TokenKind};
24 use crate::ptr::P;
25 use crate::symbol::{sym, 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(&self, name: Symbol) -> bool {
85         self.meta_item().map_or(false, |meta_item| meta_item.check_name(name))
86     }
87
88     /// For a single-segment meta-item returns its name, otherwise returns `None`.
89     pub fn ident(&self) -> Option<Ident> {
90         self.meta_item().and_then(|meta_item| meta_item.ident())
91     }
92     pub fn name_or_empty(&self) -> Symbol {
93         self.ident().unwrap_or(Ident::invalid()).name
94     }
95
96     /// Gets the string value if self is a MetaItem and the MetaItem is a
97     /// MetaItemKind::NameValue variant containing a string, otherwise None.
98     pub fn value_str(&self) -> Option<Symbol> {
99         self.meta_item().and_then(|meta_item| meta_item.value_str())
100     }
101
102     /// Returns a name and single literal value tuple of the MetaItem.
103     pub fn name_value_literal(&self) -> Option<(Name, &Lit)> {
104         self.meta_item().and_then(
105             |meta_item| meta_item.meta_item_list().and_then(
106                 |meta_item_list| {
107                     if meta_item_list.len() == 1 {
108                         if let Some(ident) = meta_item.ident() {
109                             if let Some(lit) = meta_item_list[0].literal() {
110                                 return Some((ident.name, lit));
111                             }
112                         }
113                     }
114                     None
115                 }))
116     }
117
118     /// Gets a list of inner meta items from a list MetaItem type.
119     pub fn meta_item_list(&self) -> Option<&[NestedMetaItem]> {
120         self.meta_item().and_then(|meta_item| meta_item.meta_item_list())
121     }
122
123     /// Returns `true` if the variant is MetaItem.
124     pub fn is_meta_item(&self) -> bool {
125         self.meta_item().is_some()
126     }
127
128     /// Returns `true` if the variant is Literal.
129     pub fn is_literal(&self) -> bool {
130         self.literal().is_some()
131     }
132
133     /// Returns `true` if self is a MetaItem and the meta item is a word.
134     pub fn is_word(&self) -> bool {
135         self.meta_item().map_or(false, |meta_item| meta_item.is_word())
136     }
137
138     /// Returns `true` if self is a MetaItem and the meta item is a ValueString.
139     pub fn is_value_str(&self) -> bool {
140         self.value_str().is_some()
141     }
142
143     /// Returns `true` if self is a MetaItem and the meta item is a list.
144     pub fn is_meta_item_list(&self) -> bool {
145         self.meta_item_list().is_some()
146     }
147 }
148
149 impl Attribute {
150     /// Returns `true` if the attribute's path matches the argument. If it matches, then the
151     /// attribute is marked as used.
152     ///
153     /// To check the attribute name without marking it used, use the `path` field directly.
154     pub fn check_name(&self, name: Symbol) -> bool {
155         let matches = self.path == name;
156         if matches {
157             mark_used(self);
158         }
159         matches
160     }
161
162     /// For a single-segment attribute returns its name, otherwise returns `None`.
163     pub fn ident(&self) -> Option<Ident> {
164         if self.path.segments.len() == 1 {
165             Some(self.path.segments[0].ident)
166         } else {
167             None
168         }
169     }
170     pub fn name_or_empty(&self) -> Symbol {
171         self.ident().unwrap_or(Ident::invalid()).name
172     }
173
174     pub fn value_str(&self) -> Option<Symbol> {
175         self.meta().and_then(|meta| meta.value_str())
176     }
177
178     pub fn meta_item_list(&self) -> Option<Vec<NestedMetaItem>> {
179         match self.meta() {
180             Some(MetaItem { node: MetaItemKind::List(list), .. }) => Some(list),
181             _ => None
182         }
183     }
184
185     pub fn is_word(&self) -> bool {
186         self.tokens.is_empty()
187     }
188
189     pub fn is_meta_item_list(&self) -> bool {
190         self.meta_item_list().is_some()
191     }
192
193     /// Indicates if the attribute is a Value String.
194     pub fn is_value_str(&self) -> bool {
195         self.value_str().is_some()
196     }
197 }
198
199 impl MetaItem {
200     /// For a single-segment meta-item returns its name, otherwise returns `None`.
201     pub fn ident(&self) -> Option<Ident> {
202         if self.path.segments.len() == 1 {
203             Some(self.path.segments[0].ident)
204         } else {
205             None
206         }
207     }
208     pub fn name_or_empty(&self) -> Symbol {
209         self.ident().unwrap_or(Ident::invalid()).name
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 check_name(&self, name: Symbol) -> bool {
248         self.path == name
249     }
250
251     pub fn is_value_str(&self) -> bool {
252         self.value_str().is_some()
253     }
254
255     pub fn is_meta_item_list(&self) -> bool {
256         self.meta_item_list().is_some()
257     }
258 }
259
260 impl Attribute {
261     /// Extracts the MetaItem from inside this Attribute.
262     pub fn meta(&self) -> Option<MetaItem> {
263         let mut tokens = self.tokens.trees().peekable();
264         Some(MetaItem {
265             path: self.path.clone(),
266             node: if let Some(node) = MetaItemKind::from_tokens(&mut tokens) {
267                 if tokens.peek().is_some() {
268                     return None;
269                 }
270                 node
271             } else {
272                 return None;
273             },
274             span: self.span,
275         })
276     }
277
278     pub fn parse<'a, T, F>(&self, sess: &'a ParseSess, mut f: F) -> PResult<'a, T>
279         where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
280     {
281         let mut parser = Parser::new(
282             sess,
283             self.tokens.clone(),
284             None,
285             false,
286             false,
287             Some("attribute"),
288         );
289         let result = f(&mut parser)?;
290         if parser.token != token::Eof {
291             parser.unexpected()?;
292         }
293         Ok(result)
294     }
295
296     pub fn parse_list<'a, T, F>(&self, sess: &'a ParseSess, mut f: F) -> PResult<'a, Vec<T>>
297         where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
298     {
299         if self.tokens.is_empty() {
300             return Ok(Vec::new());
301         }
302         self.parse(sess, |parser| {
303             parser.expect(&token::OpenDelim(token::Paren))?;
304             let mut list = Vec::new();
305             while !parser.eat(&token::CloseDelim(token::Paren)) {
306                 list.push(f(parser)?);
307                 if !parser.eat(&token::Comma) {
308                    parser.expect(&token::CloseDelim(token::Paren))?;
309                     break
310                 }
311             }
312             Ok(list)
313         })
314     }
315
316     pub fn parse_meta<'a>(&self, sess: &'a ParseSess) -> PResult<'a, MetaItem> {
317         Ok(MetaItem {
318             path: self.path.clone(),
319             node: self.parse(sess, |parser| parser.parse_meta_item_kind())?,
320             span: self.span,
321         })
322     }
323
324     /// Converts self to a normal #[doc="foo"] comment, if it is a
325     /// comment like `///` or `/** */`. (Returns self unchanged for
326     /// non-sugared doc attributes.)
327     pub fn with_desugared_doc<T, F>(&self, f: F) -> T where
328         F: FnOnce(&Attribute) -> T,
329     {
330         if self.is_sugared_doc {
331             let comment = self.value_str().unwrap();
332             let meta = mk_name_value_item_str(
333                 Ident::with_empty_ctxt(sym::doc),
334                 dummy_spanned(Symbol::intern(&strip_doc_comment_decoration(&comment.as_str()))));
335             let mut attr = if self.style == ast::AttrStyle::Outer {
336                 mk_attr_outer(self.span, self.id, meta)
337             } else {
338                 mk_attr_inner(self.span, self.id, meta)
339             };
340             attr.is_sugared_doc = true;
341             f(&attr)
342         } else {
343             f(self)
344         }
345     }
346 }
347
348 /* Constructors */
349
350 pub fn mk_name_value_item_str(ident: Ident, value: Spanned<Symbol>) -> MetaItem {
351     let lit_kind = LitKind::Str(value.node, ast::StrStyle::Cooked);
352     mk_name_value_item(ident.span.to(value.span), ident, lit_kind, value.span)
353 }
354
355 pub fn mk_name_value_item(span: Span, ident: Ident, lit_kind: LitKind, lit_span: Span) -> MetaItem {
356     let lit = Lit::from_lit_kind(lit_kind, lit_span);
357     MetaItem { path: Path::from_ident(ident), span, node: MetaItemKind::NameValue(lit) }
358 }
359
360 pub fn mk_list_item(span: Span, ident: Ident, items: Vec<NestedMetaItem>) -> MetaItem {
361     MetaItem { path: Path::from_ident(ident), span, node: MetaItemKind::List(items) }
362 }
363
364 pub fn mk_word_item(ident: Ident) -> MetaItem {
365     MetaItem { path: Path::from_ident(ident), span: ident.span, node: MetaItemKind::Word }
366 }
367
368 pub fn mk_nested_word_item(ident: Ident) -> NestedMetaItem {
369     NestedMetaItem::MetaItem(mk_word_item(ident))
370 }
371
372 pub fn mk_attr_id() -> AttrId {
373     use std::sync::atomic::AtomicUsize;
374     use std::sync::atomic::Ordering;
375
376     static NEXT_ATTR_ID: AtomicUsize = AtomicUsize::new(0);
377
378     let id = NEXT_ATTR_ID.fetch_add(1, Ordering::SeqCst);
379     assert!(id != ::std::usize::MAX);
380     AttrId(id)
381 }
382
383 /// Returns an inner attribute with the given value.
384 pub fn mk_attr_inner(span: Span, id: AttrId, item: MetaItem) -> Attribute {
385     mk_spanned_attr_inner(span, id, item)
386 }
387
388 /// Returns an inner attribute with the given value and span.
389 pub fn mk_spanned_attr_inner(sp: Span, id: AttrId, item: MetaItem) -> Attribute {
390     Attribute {
391         id,
392         style: ast::AttrStyle::Inner,
393         path: item.path,
394         tokens: item.node.tokens(item.span),
395         is_sugared_doc: false,
396         span: sp,
397     }
398 }
399
400 /// Returns an outer attribute with the given value.
401 pub fn mk_attr_outer(span: Span, id: AttrId, item: MetaItem) -> Attribute {
402     mk_spanned_attr_outer(span, id, item)
403 }
404
405 /// Returns an outer attribute with the given value and span.
406 pub fn mk_spanned_attr_outer(sp: Span, id: AttrId, item: MetaItem) -> Attribute {
407     Attribute {
408         id,
409         style: ast::AttrStyle::Outer,
410         path: item.path,
411         tokens: item.node.tokens(item.span),
412         is_sugared_doc: false,
413         span: sp,
414     }
415 }
416
417 pub fn mk_sugared_doc_attr(id: AttrId, text: Symbol, span: Span) -> Attribute {
418     let style = doc_comment_style(&text.as_str());
419     let lit_kind = LitKind::Str(text, ast::StrStyle::Cooked);
420     let lit = Lit::from_lit_kind(lit_kind, span);
421     Attribute {
422         id,
423         style,
424         path: Path::from_ident(Ident::with_empty_ctxt(sym::doc).with_span_pos(span)),
425         tokens: MetaItemKind::NameValue(lit).tokens(span),
426         is_sugared_doc: true,
427         span,
428     }
429 }
430
431 pub fn list_contains_name(items: &[NestedMetaItem], name: Symbol) -> bool {
432     items.iter().any(|item| {
433         item.check_name(name)
434     })
435 }
436
437 pub fn contains_name(attrs: &[Attribute], name: Symbol) -> bool {
438     attrs.iter().any(|item| {
439         item.check_name(name)
440     })
441 }
442
443 pub fn find_by_name<'a>(attrs: &'a [Attribute], name: Symbol) -> Option<&'a Attribute> {
444     attrs.iter().find(|attr| attr.check_name(name))
445 }
446
447 pub fn filter_by_name<'a>(attrs: &'a [Attribute], name: Symbol)
448     -> impl Iterator<Item = &'a Attribute> {
449     attrs.iter().filter(move |attr| attr.check_name(name))
450 }
451
452 pub fn first_attr_value_str_by_name(attrs: &[Attribute], name: Symbol) -> Option<Symbol> {
453     attrs.iter()
454         .find(|at| at.check_name(name))
455         .and_then(|at| at.value_str())
456 }
457
458 impl MetaItem {
459     fn tokens(&self) -> TokenStream {
460         let mut idents = vec![];
461         let mut last_pos = BytePos(0 as u32);
462         for (i, segment) in self.path.segments.iter().enumerate() {
463             let is_first = i == 0;
464             if !is_first {
465                 let mod_sep_span = Span::new(last_pos,
466                                              segment.ident.span.lo(),
467                                              segment.ident.span.ctxt());
468                 idents.push(TokenTree::token(token::ModSep, mod_sep_span).into());
469             }
470             idents.push(TokenTree::token(TokenKind::from_ast_ident(segment.ident),
471                                          segment.ident.span).into());
472             last_pos = segment.ident.span.hi();
473         }
474         self.node.tokens(self.span).append_to_tree_and_joint_vec(&mut idents);
475         TokenStream::new(idents)
476     }
477
478     fn from_tokens<I>(tokens: &mut iter::Peekable<I>) -> Option<MetaItem>
479         where I: Iterator<Item = TokenTree>,
480     {
481         // FIXME: Share code with `parse_path`.
482         let path = match tokens.next() {
483             Some(TokenTree::Token(Token { kind: kind @ token::Ident(..), span })) |
484             Some(TokenTree::Token(Token { kind: kind @ token::ModSep, span })) => 'arm: {
485                 let mut segments = if let token::Ident(name, _) = kind {
486                     if let Some(TokenTree::Token(Token { kind: token::ModSep, .. })) = tokens.peek() {
487                         tokens.next();
488                         vec![PathSegment::from_ident(Ident::new(name, span))]
489                     } else {
490                         break 'arm Path::from_ident(Ident::new(name, span));
491                     }
492                 } else {
493                     vec![PathSegment::path_root(span)]
494                 };
495                 loop {
496                     if let Some(TokenTree::Token(Token { kind: token::Ident(name, _), span })) = tokens.next() {
497                         segments.push(PathSegment::from_ident(Ident::new(name, span)));
498                     } else {
499                         return None;
500                     }
501                     if let Some(TokenTree::Token(Token { kind: token::ModSep, .. })) = tokens.peek() {
502                         tokens.next();
503                     } else {
504                         break;
505                     }
506                 }
507                 let span = span.with_hi(segments.last().unwrap().ident.span.hi());
508                 Path { span, segments }
509             }
510             Some(TokenTree::Token(Token { kind: token::Interpolated(nt), .. })) => match *nt {
511                 token::Nonterminal::NtIdent(ident, _) => Path::from_ident(ident),
512                 token::Nonterminal::NtMeta(ref meta) => return Some(meta.clone()),
513                 token::Nonterminal::NtPath(ref path) => path.clone(),
514                 _ => return None,
515             },
516             _ => return None,
517         };
518         let list_closing_paren_pos = tokens.peek().map(|tt| tt.span().hi());
519         let node = MetaItemKind::from_tokens(tokens)?;
520         let hi = match node {
521             MetaItemKind::NameValue(ref lit) => lit.span.hi(),
522             MetaItemKind::List(..) => list_closing_paren_pos.unwrap_or(path.span.hi()),
523             _ => path.span.hi(),
524         };
525         let span = path.span.with_hi(hi);
526         Some(MetaItem { path, node, span })
527     }
528 }
529
530 impl MetaItemKind {
531     pub fn tokens(&self, span: Span) -> TokenStream {
532         match *self {
533             MetaItemKind::Word => TokenStream::empty(),
534             MetaItemKind::NameValue(ref lit) => {
535                 let mut vec = vec![TokenTree::token(token::Eq, span).into()];
536                 lit.tokens().append_to_tree_and_joint_vec(&mut vec);
537                 TokenStream::new(vec)
538             }
539             MetaItemKind::List(ref list) => {
540                 let mut tokens = Vec::new();
541                 for (i, item) in list.iter().enumerate() {
542                     if i > 0 {
543                         tokens.push(TokenTree::token(token::Comma, span).into());
544                     }
545                     item.tokens().append_to_tree_and_joint_vec(&mut tokens);
546                 }
547                 TokenTree::Delimited(
548                     DelimSpan::from_single(span),
549                     token::Paren,
550                     TokenStream::new(tokens).into(),
551                 ).into()
552             }
553         }
554     }
555
556     fn from_tokens<I>(tokens: &mut iter::Peekable<I>) -> Option<MetaItemKind>
557         where I: Iterator<Item = TokenTree>,
558     {
559         let delimited = match tokens.peek().cloned() {
560             Some(TokenTree::Token(token)) if token == token::Eq => {
561                 tokens.next();
562                 return if let Some(TokenTree::Token(token)) = tokens.next() {
563                     Lit::from_token(&token).ok().map(MetaItemKind::NameValue)
564                 } else {
565                     None
566                 };
567             }
568             Some(TokenTree::Delimited(_, delim, ref tts)) if delim == token::Paren => {
569                 tokens.next();
570                 tts.clone()
571             }
572             _ => return Some(MetaItemKind::Word),
573         };
574
575         let mut tokens = delimited.into_trees().peekable();
576         let mut result = Vec::new();
577         while let Some(..) = tokens.peek() {
578             let item = NestedMetaItem::from_tokens(&mut tokens)?;
579             result.push(item);
580             match tokens.next() {
581                 None | Some(TokenTree::Token(Token { kind: token::Comma, .. })) => {}
582                 _ => return None,
583             }
584         }
585         Some(MetaItemKind::List(result))
586     }
587 }
588
589 impl NestedMetaItem {
590     pub fn span(&self) -> Span {
591         match *self {
592             NestedMetaItem::MetaItem(ref item) => item.span,
593             NestedMetaItem::Literal(ref lit) => lit.span,
594         }
595     }
596
597     fn tokens(&self) -> TokenStream {
598         match *self {
599             NestedMetaItem::MetaItem(ref item) => item.tokens(),
600             NestedMetaItem::Literal(ref lit) => lit.tokens(),
601         }
602     }
603
604     fn from_tokens<I>(tokens: &mut iter::Peekable<I>) -> Option<NestedMetaItem>
605         where I: Iterator<Item = TokenTree>,
606     {
607         if let Some(TokenTree::Token(token)) = tokens.peek() {
608             if let Ok(lit) = Lit::from_token(token) {
609                 tokens.next();
610                 return Some(NestedMetaItem::Literal(lit));
611             }
612         }
613
614         MetaItem::from_tokens(tokens).map(NestedMetaItem::MetaItem)
615     }
616 }
617
618 pub trait HasAttrs: Sized {
619     fn attrs(&self) -> &[ast::Attribute];
620     fn visit_attrs<F: FnOnce(&mut Vec<ast::Attribute>)>(&mut self, f: F);
621 }
622
623 impl<T: HasAttrs> HasAttrs for Spanned<T> {
624     fn attrs(&self) -> &[ast::Attribute] { self.node.attrs() }
625     fn visit_attrs<F: FnOnce(&mut Vec<ast::Attribute>)>(&mut self, f: F) {
626         self.node.visit_attrs(f);
627     }
628 }
629
630 impl HasAttrs for Vec<Attribute> {
631     fn attrs(&self) -> &[Attribute] {
632         self
633     }
634     fn visit_attrs<F: FnOnce(&mut Vec<Attribute>)>(&mut self, f: F) {
635         f(self)
636     }
637 }
638
639 impl HasAttrs for ThinVec<Attribute> {
640     fn attrs(&self) -> &[Attribute] {
641         self
642     }
643     fn visit_attrs<F: FnOnce(&mut Vec<Attribute>)>(&mut self, f: F) {
644         visit_clobber(self, |this| {
645             let mut vec = this.into();
646             f(&mut vec);
647             vec.into()
648         });
649     }
650 }
651
652 impl<T: HasAttrs + 'static> HasAttrs for P<T> {
653     fn attrs(&self) -> &[Attribute] {
654         (**self).attrs()
655     }
656     fn visit_attrs<F: FnOnce(&mut Vec<Attribute>)>(&mut self, f: F) {
657         (**self).visit_attrs(f);
658     }
659 }
660
661 impl HasAttrs for StmtKind {
662     fn attrs(&self) -> &[Attribute] {
663         match *self {
664             StmtKind::Local(ref local) => local.attrs(),
665             StmtKind::Item(..) => &[],
666             StmtKind::Expr(ref expr) | StmtKind::Semi(ref expr) => expr.attrs(),
667             StmtKind::Mac(ref mac) => {
668                 let (_, _, ref attrs) = **mac;
669                 attrs.attrs()
670             }
671         }
672     }
673
674     fn visit_attrs<F: FnOnce(&mut Vec<Attribute>)>(&mut self, f: F) {
675         match self {
676             StmtKind::Local(local) => local.visit_attrs(f),
677             StmtKind::Item(..) => {}
678             StmtKind::Expr(expr) => expr.visit_attrs(f),
679             StmtKind::Semi(expr) => expr.visit_attrs(f),
680             StmtKind::Mac(mac) => {
681                 let (_mac, _style, attrs) = mac.deref_mut();
682                 attrs.visit_attrs(f);
683             }
684         }
685     }
686 }
687
688 impl HasAttrs for Stmt {
689     fn attrs(&self) -> &[ast::Attribute] {
690         self.node.attrs()
691     }
692
693     fn visit_attrs<F: FnOnce(&mut Vec<ast::Attribute>)>(&mut self, f: F) {
694         self.node.visit_attrs(f);
695     }
696 }
697
698 impl HasAttrs for GenericParam {
699     fn attrs(&self) -> &[ast::Attribute] {
700         &self.attrs
701     }
702
703     fn visit_attrs<F: FnOnce(&mut Vec<Attribute>)>(&mut self, f: F) {
704         self.attrs.visit_attrs(f);
705     }
706 }
707
708 macro_rules! derive_has_attrs {
709     ($($ty:path),*) => { $(
710         impl HasAttrs for $ty {
711             fn attrs(&self) -> &[Attribute] {
712                 &self.attrs
713             }
714
715             fn visit_attrs<F: FnOnce(&mut Vec<Attribute>)>(&mut self, f: F) {
716                 self.attrs.visit_attrs(f);
717             }
718         }
719     )* }
720 }
721
722 derive_has_attrs! {
723     Item, Expr, Local, ast::ForeignItem, ast::StructField, ast::ImplItem, ast::TraitItem, ast::Arm,
724     ast::Field, ast::FieldPat, ast::Variant_
725 }
726
727 pub fn inject(mut krate: ast::Crate, parse_sess: &ParseSess, attrs: &[String]) -> ast::Crate {
728     for raw_attr in attrs {
729         let mut parser = parse::new_parser_from_source_str(
730             parse_sess,
731             FileName::cli_crate_attr_source_code(&raw_attr),
732             raw_attr.clone(),
733         );
734
735         let start_span = parser.span;
736         let (path, tokens) = panictry!(parser.parse_meta_item_unrestricted());
737         let end_span = parser.span;
738         if parser.token != token::Eof {
739             parse_sess.span_diagnostic
740                 .span_err(start_span.to(end_span), "invalid crate attribute");
741             continue;
742         }
743
744         krate.attrs.push(Attribute {
745             id: mk_attr_id(),
746             style: AttrStyle::Inner,
747             path,
748             tokens,
749             is_sugared_doc: false,
750             span: start_span.to(end_span),
751         });
752     }
753
754     krate
755 }