]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/attr/mod.rs
Rollup merge of #60719 - varkor:xpy-test-folder, r=Mark-Simulacrum
[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};
24 use crate::ptr::P;
25 use crate::symbol::{keywords, 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(keywords::Invalid.ident()).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(keywords::Invalid.ident()).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(keywords::Invalid.ident()).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(sess, self.tokens.clone(), None, false, false);
282         let result = f(&mut parser)?;
283         if parser.token != token::Eof {
284             parser.unexpected()?;
285         }
286         Ok(result)
287     }
288
289     pub fn parse_list<'a, T, F>(&self, sess: &'a ParseSess, mut f: F) -> PResult<'a, Vec<T>>
290         where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
291     {
292         if self.tokens.is_empty() {
293             return Ok(Vec::new());
294         }
295         self.parse(sess, |parser| {
296             parser.expect(&token::OpenDelim(token::Paren))?;
297             let mut list = Vec::new();
298             while !parser.eat(&token::CloseDelim(token::Paren)) {
299                 list.push(f(parser)?);
300                 if !parser.eat(&token::Comma) {
301                    parser.expect(&token::CloseDelim(token::Paren))?;
302                     break
303                 }
304             }
305             Ok(list)
306         })
307     }
308
309     pub fn parse_meta<'a>(&self, sess: &'a ParseSess) -> PResult<'a, MetaItem> {
310         Ok(MetaItem {
311             path: self.path.clone(),
312             node: self.parse(sess, |parser| parser.parse_meta_item_kind())?,
313             span: self.span,
314         })
315     }
316
317     /// Converts self to a normal #[doc="foo"] comment, if it is a
318     /// comment like `///` or `/** */`. (Returns self unchanged for
319     /// non-sugared doc attributes.)
320     pub fn with_desugared_doc<T, F>(&self, f: F) -> T where
321         F: FnOnce(&Attribute) -> T,
322     {
323         if self.is_sugared_doc {
324             let comment = self.value_str().unwrap();
325             let meta = mk_name_value_item_str(
326                 Ident::from_str("doc"),
327                 dummy_spanned(Symbol::intern(&strip_doc_comment_decoration(&comment.as_str()))));
328             let mut attr = if self.style == ast::AttrStyle::Outer {
329                 mk_attr_outer(self.span, self.id, meta)
330             } else {
331                 mk_attr_inner(self.span, self.id, meta)
332             };
333             attr.is_sugared_doc = true;
334             f(&attr)
335         } else {
336             f(self)
337         }
338     }
339 }
340
341 /* Constructors */
342
343 pub fn mk_name_value_item_str(ident: Ident, value: Spanned<Symbol>) -> MetaItem {
344     let lit_kind = LitKind::Str(value.node, ast::StrStyle::Cooked);
345     mk_name_value_item(ident.span.to(value.span), ident, lit_kind, value.span)
346 }
347
348 pub fn mk_name_value_item(span: Span, ident: Ident, lit_kind: LitKind, lit_span: Span) -> MetaItem {
349     let lit = Lit::from_lit_kind(lit_kind, lit_span);
350     MetaItem { path: Path::from_ident(ident), span, node: MetaItemKind::NameValue(lit) }
351 }
352
353 pub fn mk_list_item(span: Span, ident: Ident, items: Vec<NestedMetaItem>) -> MetaItem {
354     MetaItem { path: Path::from_ident(ident), span, node: MetaItemKind::List(items) }
355 }
356
357 pub fn mk_word_item(ident: Ident) -> MetaItem {
358     MetaItem { path: Path::from_ident(ident), span: ident.span, node: MetaItemKind::Word }
359 }
360
361 pub fn mk_nested_word_item(ident: Ident) -> NestedMetaItem {
362     NestedMetaItem::MetaItem(mk_word_item(ident))
363 }
364
365 pub fn mk_attr_id() -> AttrId {
366     use std::sync::atomic::AtomicUsize;
367     use std::sync::atomic::Ordering;
368
369     static NEXT_ATTR_ID: AtomicUsize = AtomicUsize::new(0);
370
371     let id = NEXT_ATTR_ID.fetch_add(1, Ordering::SeqCst);
372     assert!(id != ::std::usize::MAX);
373     AttrId(id)
374 }
375
376 /// Returns an inner attribute with the given value.
377 pub fn mk_attr_inner(span: Span, id: AttrId, item: MetaItem) -> Attribute {
378     mk_spanned_attr_inner(span, id, item)
379 }
380
381 /// Returns an inner attribute with the given value and span.
382 pub fn mk_spanned_attr_inner(sp: Span, id: AttrId, item: MetaItem) -> Attribute {
383     Attribute {
384         id,
385         style: ast::AttrStyle::Inner,
386         path: item.path,
387         tokens: item.node.tokens(item.span),
388         is_sugared_doc: false,
389         span: sp,
390     }
391 }
392
393 /// Returns an outer attribute with the given value.
394 pub fn mk_attr_outer(span: Span, id: AttrId, item: MetaItem) -> Attribute {
395     mk_spanned_attr_outer(span, id, item)
396 }
397
398 /// Returns an outer attribute with the given value and span.
399 pub fn mk_spanned_attr_outer(sp: Span, id: AttrId, item: MetaItem) -> Attribute {
400     Attribute {
401         id,
402         style: ast::AttrStyle::Outer,
403         path: item.path,
404         tokens: item.node.tokens(item.span),
405         is_sugared_doc: false,
406         span: sp,
407     }
408 }
409
410 pub fn mk_sugared_doc_attr(id: AttrId, text: Symbol, span: Span) -> Attribute {
411     let style = doc_comment_style(&text.as_str());
412     let lit_kind = LitKind::Str(text, ast::StrStyle::Cooked);
413     let lit = Lit::from_lit_kind(lit_kind, span);
414     Attribute {
415         id,
416         style,
417         path: Path::from_ident(Ident::from_str("doc").with_span_pos(span)),
418         tokens: MetaItemKind::NameValue(lit).tokens(span),
419         is_sugared_doc: true,
420         span,
421     }
422 }
423
424 pub fn list_contains_name(items: &[NestedMetaItem], name: Symbol) -> bool {
425     items.iter().any(|item| {
426         item.check_name(name)
427     })
428 }
429
430 pub fn contains_name(attrs: &[Attribute], name: Symbol) -> bool {
431     attrs.iter().any(|item| {
432         item.check_name(name)
433     })
434 }
435
436 pub fn find_by_name<'a>(attrs: &'a [Attribute], name: Symbol) -> Option<&'a Attribute> {
437     attrs.iter().find(|attr| attr.check_name(name))
438 }
439
440 pub fn filter_by_name<'a>(attrs: &'a [Attribute], name: Symbol)
441     -> impl Iterator<Item = &'a Attribute> {
442     attrs.iter().filter(move |attr| attr.check_name(name))
443 }
444
445 pub fn first_attr_value_str_by_name(attrs: &[Attribute], name: Symbol) -> Option<Symbol> {
446     attrs.iter()
447         .find(|at| at.check_name(name))
448         .and_then(|at| at.value_str())
449 }
450
451 impl MetaItem {
452     fn tokens(&self) -> TokenStream {
453         let mut idents = vec![];
454         let mut last_pos = BytePos(0 as u32);
455         for (i, segment) in self.path.segments.iter().enumerate() {
456             let is_first = i == 0;
457             if !is_first {
458                 let mod_sep_span = Span::new(last_pos,
459                                              segment.ident.span.lo(),
460                                              segment.ident.span.ctxt());
461                 idents.push(TokenTree::Token(mod_sep_span, Token::ModSep).into());
462             }
463             idents.push(TokenTree::Token(segment.ident.span,
464                                          Token::from_ast_ident(segment.ident)).into());
465             last_pos = segment.ident.span.hi();
466         }
467         self.node.tokens(self.span).append_to_tree_and_joint_vec(&mut idents);
468         TokenStream::new(idents)
469     }
470
471     fn from_tokens<I>(tokens: &mut iter::Peekable<I>) -> Option<MetaItem>
472         where I: Iterator<Item = TokenTree>,
473     {
474         // FIXME: Share code with `parse_path`.
475         let path = match tokens.next() {
476             Some(TokenTree::Token(span, token @ Token::Ident(..))) |
477             Some(TokenTree::Token(span, token @ Token::ModSep)) => 'arm: {
478                 let mut segments = if let Token::Ident(ident, _) = token {
479                     if let Some(TokenTree::Token(_, Token::ModSep)) = tokens.peek() {
480                         tokens.next();
481                         vec![PathSegment::from_ident(ident.with_span_pos(span))]
482                     } else {
483                         break 'arm Path::from_ident(ident.with_span_pos(span));
484                     }
485                 } else {
486                     vec![PathSegment::path_root(span)]
487                 };
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             }
504             Some(TokenTree::Token(_, Token::Interpolated(nt))) => match *nt {
505                 token::Nonterminal::NtIdent(ident, _) => Path::from_ident(ident),
506                 token::Nonterminal::NtMeta(ref meta) => return Some(meta.clone()),
507                 token::Nonterminal::NtPath(ref path) => path.clone(),
508                 _ => return None,
509             },
510             _ => return None,
511         };
512         let list_closing_paren_pos = tokens.peek().map(|tt| tt.span().hi());
513         let node = MetaItemKind::from_tokens(tokens)?;
514         let hi = match node {
515             MetaItemKind::NameValue(ref lit) => lit.span.hi(),
516             MetaItemKind::List(..) => list_closing_paren_pos.unwrap_or(path.span.hi()),
517             _ => path.span.hi(),
518         };
519         let span = path.span.with_hi(hi);
520         Some(MetaItem { path, node, span })
521     }
522 }
523
524 impl MetaItemKind {
525     pub fn tokens(&self, span: Span) -> TokenStream {
526         match *self {
527             MetaItemKind::Word => TokenStream::empty(),
528             MetaItemKind::NameValue(ref lit) => {
529                 let mut vec = vec![TokenTree::Token(span, Token::Eq).into()];
530                 lit.tokens().append_to_tree_and_joint_vec(&mut vec);
531                 TokenStream::new(vec)
532             }
533             MetaItemKind::List(ref list) => {
534                 let mut tokens = Vec::new();
535                 for (i, item) in list.iter().enumerate() {
536                     if i > 0 {
537                         tokens.push(TokenTree::Token(span, Token::Comma).into());
538                     }
539                     item.tokens().append_to_tree_and_joint_vec(&mut tokens);
540                 }
541                 TokenTree::Delimited(
542                     DelimSpan::from_single(span),
543                     token::Paren,
544                     TokenStream::new(tokens).into(),
545                 ).into()
546             }
547         }
548     }
549
550     fn from_tokens<I>(tokens: &mut iter::Peekable<I>) -> Option<MetaItemKind>
551         where I: Iterator<Item = TokenTree>,
552     {
553         let delimited = match tokens.peek().cloned() {
554             Some(TokenTree::Token(_, token::Eq)) => {
555                 tokens.next();
556                 return if let Some(TokenTree::Token(span, token)) = tokens.next() {
557                     Lit::from_token(&token, span, None).map(MetaItemKind::NameValue)
558                 } else {
559                     None
560                 };
561             }
562             Some(TokenTree::Delimited(_, delim, ref tts)) if delim == token::Paren => {
563                 tokens.next();
564                 tts.clone()
565             }
566             _ => return Some(MetaItemKind::Word),
567         };
568
569         let mut tokens = delimited.into_trees().peekable();
570         let mut result = Vec::new();
571         while let Some(..) = tokens.peek() {
572             let item = NestedMetaItem::from_tokens(&mut tokens)?;
573             result.push(item);
574             match tokens.next() {
575                 None | Some(TokenTree::Token(_, Token::Comma)) => {}
576                 _ => return None,
577             }
578         }
579         Some(MetaItemKind::List(result))
580     }
581 }
582
583 impl NestedMetaItem {
584     pub fn span(&self) -> Span {
585         match *self {
586             NestedMetaItem::MetaItem(ref item) => item.span,
587             NestedMetaItem::Literal(ref lit) => lit.span,
588         }
589     }
590
591     fn tokens(&self) -> TokenStream {
592         match *self {
593             NestedMetaItem::MetaItem(ref item) => item.tokens(),
594             NestedMetaItem::Literal(ref lit) => lit.tokens(),
595         }
596     }
597
598     fn from_tokens<I>(tokens: &mut iter::Peekable<I>) -> Option<NestedMetaItem>
599         where I: Iterator<Item = TokenTree>,
600     {
601         if let Some(TokenTree::Token(span, token)) = tokens.peek().cloned() {
602             if let Some(lit) = Lit::from_token(&token, span, None) {
603                 tokens.next();
604                 return Some(NestedMetaItem::Literal(lit));
605             }
606         }
607
608         MetaItem::from_tokens(tokens).map(NestedMetaItem::MetaItem)
609     }
610 }
611
612 pub trait HasAttrs: Sized {
613     fn attrs(&self) -> &[ast::Attribute];
614     fn visit_attrs<F: FnOnce(&mut Vec<ast::Attribute>)>(&mut self, f: F);
615 }
616
617 impl<T: HasAttrs> HasAttrs for Spanned<T> {
618     fn attrs(&self) -> &[ast::Attribute] { self.node.attrs() }
619     fn visit_attrs<F: FnOnce(&mut Vec<ast::Attribute>)>(&mut self, f: F) {
620         self.node.visit_attrs(f);
621     }
622 }
623
624 impl HasAttrs for Vec<Attribute> {
625     fn attrs(&self) -> &[Attribute] {
626         self
627     }
628     fn visit_attrs<F: FnOnce(&mut Vec<Attribute>)>(&mut self, f: F) {
629         f(self)
630     }
631 }
632
633 impl HasAttrs for ThinVec<Attribute> {
634     fn attrs(&self) -> &[Attribute] {
635         self
636     }
637     fn visit_attrs<F: FnOnce(&mut Vec<Attribute>)>(&mut self, f: F) {
638         visit_clobber(self, |this| {
639             let mut vec = this.into();
640             f(&mut vec);
641             vec.into()
642         });
643     }
644 }
645
646 impl<T: HasAttrs + 'static> HasAttrs for P<T> {
647     fn attrs(&self) -> &[Attribute] {
648         (**self).attrs()
649     }
650     fn visit_attrs<F: FnOnce(&mut Vec<Attribute>)>(&mut self, f: F) {
651         (**self).visit_attrs(f);
652     }
653 }
654
655 impl HasAttrs for StmtKind {
656     fn attrs(&self) -> &[Attribute] {
657         match *self {
658             StmtKind::Local(ref local) => local.attrs(),
659             StmtKind::Item(..) => &[],
660             StmtKind::Expr(ref expr) | StmtKind::Semi(ref expr) => expr.attrs(),
661             StmtKind::Mac(ref mac) => {
662                 let (_, _, ref attrs) = **mac;
663                 attrs.attrs()
664             }
665         }
666     }
667
668     fn visit_attrs<F: FnOnce(&mut Vec<Attribute>)>(&mut self, f: F) {
669         match self {
670             StmtKind::Local(local) => local.visit_attrs(f),
671             StmtKind::Item(..) => {}
672             StmtKind::Expr(expr) => expr.visit_attrs(f),
673             StmtKind::Semi(expr) => expr.visit_attrs(f),
674             StmtKind::Mac(mac) => {
675                 let (_mac, _style, attrs) = mac.deref_mut();
676                 attrs.visit_attrs(f);
677             }
678         }
679     }
680 }
681
682 impl HasAttrs for Stmt {
683     fn attrs(&self) -> &[ast::Attribute] {
684         self.node.attrs()
685     }
686
687     fn visit_attrs<F: FnOnce(&mut Vec<ast::Attribute>)>(&mut self, f: F) {
688         self.node.visit_attrs(f);
689     }
690 }
691
692 impl HasAttrs for GenericParam {
693     fn attrs(&self) -> &[ast::Attribute] {
694         &self.attrs
695     }
696
697     fn visit_attrs<F: FnOnce(&mut Vec<Attribute>)>(&mut self, f: F) {
698         self.attrs.visit_attrs(f);
699     }
700 }
701
702 macro_rules! derive_has_attrs {
703     ($($ty:path),*) => { $(
704         impl HasAttrs for $ty {
705             fn attrs(&self) -> &[Attribute] {
706                 &self.attrs
707             }
708
709             fn visit_attrs<F: FnOnce(&mut Vec<Attribute>)>(&mut self, f: F) {
710                 self.attrs.visit_attrs(f);
711             }
712         }
713     )* }
714 }
715
716 derive_has_attrs! {
717     Item, Expr, Local, ast::ForeignItem, ast::StructField, ast::ImplItem, ast::TraitItem, ast::Arm,
718     ast::Field, ast::FieldPat, ast::Variant_
719 }
720
721 pub fn inject(mut krate: ast::Crate, parse_sess: &ParseSess, attrs: &[String]) -> ast::Crate {
722     for raw_attr in attrs {
723         let mut parser = parse::new_parser_from_source_str(
724             parse_sess,
725             FileName::cli_crate_attr_source_code(&raw_attr),
726             raw_attr.clone(),
727         );
728
729         let start_span = parser.span;
730         let (path, tokens) = panictry!(parser.parse_meta_item_unrestricted());
731         let end_span = parser.span;
732         if parser.token != token::Eof {
733             parse_sess.span_diagnostic
734                 .span_err(start_span.to(end_span), "invalid crate attribute");
735             continue;
736         }
737
738         krate.attrs.push(Attribute {
739             id: mk_attr_id(),
740             style: AttrStyle::Inner,
741             path,
742             tokens,
743             is_sugared_doc: false,
744             span: start_span.to(end_span),
745         });
746     }
747
748     krate
749 }