]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/attr.rs
remove implementation detail from doc
[rust.git] / src / libsyntax / attr.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 // Functions dealing with attributes and meta items
12
13 pub use self::StabilityLevel::*;
14 pub use self::ReprAttr::*;
15 pub use self::IntType::*;
16
17 use ast;
18 use ast::{AttrId, Attribute, Name, Ident};
19 use ast::{MetaItem, MetaItemKind, NestedMetaItem, NestedMetaItemKind};
20 use ast::{Lit, LitKind, Expr, ExprKind, Item, Local, Stmt, StmtKind};
21 use codemap::{Spanned, respan, dummy_spanned};
22 use syntax_pos::{Span, DUMMY_SP};
23 use errors::Handler;
24 use feature_gate::{Features, GatedCfg};
25 use parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
26 use parse::parser::Parser;
27 use parse::{self, ParseSess, PResult};
28 use parse::token::{self, Token};
29 use ptr::P;
30 use symbol::Symbol;
31 use tokenstream::{TokenStream, TokenTree, Delimited};
32 use util::ThinVec;
33
34 use std::cell::RefCell;
35 use std::iter;
36
37 thread_local! {
38     static USED_ATTRS: RefCell<Vec<u64>> = RefCell::new(Vec::new());
39     static KNOWN_ATTRS: RefCell<Vec<u64>> = RefCell::new(Vec::new());
40 }
41
42 enum AttrError {
43     MultipleItem(Name),
44     UnknownMetaItem(Name),
45     MissingSince,
46     MissingFeature,
47     MultipleStabilityLevels,
48     UnsupportedLiteral
49 }
50
51 fn handle_errors(diag: &Handler, span: Span, error: AttrError) {
52     match error {
53         AttrError::MultipleItem(item) => span_err!(diag, span, E0538,
54                                                    "multiple '{}' items", item),
55         AttrError::UnknownMetaItem(item) => span_err!(diag, span, E0541,
56                                                       "unknown meta item '{}'", item),
57         AttrError::MissingSince => span_err!(diag, span, E0542, "missing 'since'"),
58         AttrError::MissingFeature => span_err!(diag, span, E0546, "missing 'feature'"),
59         AttrError::MultipleStabilityLevels => span_err!(diag, span, E0544,
60                                                         "multiple stability levels"),
61         AttrError::UnsupportedLiteral => span_err!(diag, span, E0565, "unsupported literal"),
62     }
63 }
64
65 pub fn mark_used(attr: &Attribute) {
66     debug!("Marking {:?} as used.", attr);
67     let AttrId(id) = attr.id;
68     USED_ATTRS.with(|slot| {
69         let idx = (id / 64) as usize;
70         let shift = id % 64;
71         if slot.borrow().len() <= idx {
72             slot.borrow_mut().resize(idx + 1, 0);
73         }
74         slot.borrow_mut()[idx] |= 1 << shift;
75     });
76 }
77
78 pub fn is_used(attr: &Attribute) -> bool {
79     let AttrId(id) = attr.id;
80     USED_ATTRS.with(|slot| {
81         let idx = (id / 64) as usize;
82         let shift = id % 64;
83         slot.borrow().get(idx).map(|bits| bits & (1 << shift) != 0)
84             .unwrap_or(false)
85     })
86 }
87
88 pub fn mark_known(attr: &Attribute) {
89     debug!("Marking {:?} as known.", attr);
90     let AttrId(id) = attr.id;
91     KNOWN_ATTRS.with(|slot| {
92         let idx = (id / 64) as usize;
93         let shift = id % 64;
94         if slot.borrow().len() <= idx {
95             slot.borrow_mut().resize(idx + 1, 0);
96         }
97         slot.borrow_mut()[idx] |= 1 << shift;
98     });
99 }
100
101 pub fn is_known(attr: &Attribute) -> bool {
102     let AttrId(id) = attr.id;
103     KNOWN_ATTRS.with(|slot| {
104         let idx = (id / 64) as usize;
105         let shift = id % 64;
106         slot.borrow().get(idx).map(|bits| bits & (1 << shift) != 0)
107             .unwrap_or(false)
108     })
109 }
110
111 impl NestedMetaItem {
112     /// Returns the MetaItem if self is a NestedMetaItemKind::MetaItem.
113     pub fn meta_item(&self) -> Option<&MetaItem> {
114         match self.node {
115             NestedMetaItemKind::MetaItem(ref item) => Some(item),
116             _ => None
117         }
118     }
119
120     /// Returns the Lit if self is a NestedMetaItemKind::Literal.
121     pub fn literal(&self) -> Option<&Lit> {
122         match self.node {
123             NestedMetaItemKind::Literal(ref lit) => Some(lit),
124             _ => None
125         }
126     }
127
128     /// Returns the Span for `self`.
129     pub fn span(&self) -> Span {
130         self.span
131     }
132
133     /// Returns true if this list item is a MetaItem with a name of `name`.
134     pub fn check_name(&self, name: &str) -> bool {
135         self.meta_item().map_or(false, |meta_item| meta_item.check_name(name))
136     }
137
138     /// Returns the name of the meta item, e.g. `foo` in `#[foo]`,
139     /// `#[foo="bar"]` and `#[foo(bar)]`, if self is a MetaItem
140     pub fn name(&self) -> Option<Name> {
141         self.meta_item().and_then(|meta_item| Some(meta_item.name()))
142     }
143
144     /// Gets the string value if self is a MetaItem and the MetaItem is a
145     /// MetaItemKind::NameValue variant containing a string, otherwise None.
146     pub fn value_str(&self) -> Option<Symbol> {
147         self.meta_item().and_then(|meta_item| meta_item.value_str())
148     }
149
150     /// Returns a name and single literal value tuple of the MetaItem.
151     pub fn name_value_literal(&self) -> Option<(Name, &Lit)> {
152         self.meta_item().and_then(
153             |meta_item| meta_item.meta_item_list().and_then(
154                 |meta_item_list| {
155                     if meta_item_list.len() == 1 {
156                         let nested_item = &meta_item_list[0];
157                         if nested_item.is_literal() {
158                             Some((meta_item.name(), nested_item.literal().unwrap()))
159                         } else {
160                             None
161                         }
162                     }
163                     else {
164                         None
165                     }}))
166     }
167
168     /// Returns a MetaItem if self is a MetaItem with Kind Word.
169     pub fn word(&self) -> Option<&MetaItem> {
170         self.meta_item().and_then(|meta_item| if meta_item.is_word() {
171             Some(meta_item)
172         } else {
173             None
174         })
175     }
176
177     /// Gets a list of inner meta items from a list MetaItem type.
178     pub fn meta_item_list(&self) -> Option<&[NestedMetaItem]> {
179         self.meta_item().and_then(|meta_item| meta_item.meta_item_list())
180     }
181
182     /// Returns `true` if the variant is MetaItem.
183     pub fn is_meta_item(&self) -> bool {
184         self.meta_item().is_some()
185     }
186
187     /// Returns `true` if the variant is Literal.
188     pub fn is_literal(&self) -> bool {
189         self.literal().is_some()
190     }
191
192     /// Returns `true` if self is a MetaItem and the meta item is a word.
193     pub fn is_word(&self) -> bool {
194         self.word().is_some()
195     }
196
197     /// Returns `true` if self is a MetaItem and the meta item is a ValueString.
198     pub fn is_value_str(&self) -> bool {
199         self.value_str().is_some()
200     }
201
202     /// Returns `true` if self is a MetaItem and the meta item is a list.
203     pub fn is_meta_item_list(&self) -> bool {
204         self.meta_item_list().is_some()
205     }
206 }
207
208 impl Attribute {
209     pub fn check_name(&self, name: &str) -> bool {
210         let matches = self.path == name;
211         if matches {
212             mark_used(self);
213         }
214         matches
215     }
216
217     pub fn name(&self) -> Option<Name> {
218         match self.path.segments.len() {
219             1 => Some(self.path.segments[0].identifier.name),
220             _ => None,
221         }
222     }
223
224     pub fn value_str(&self) -> Option<Symbol> {
225         self.meta().and_then(|meta| meta.value_str())
226     }
227
228     pub fn meta_item_list(&self) -> Option<Vec<NestedMetaItem>> {
229         match self.meta() {
230             Some(MetaItem { node: MetaItemKind::List(list), .. }) => Some(list),
231             _ => None
232         }
233     }
234
235     pub fn is_word(&self) -> bool {
236         self.path.segments.len() == 1 && self.tokens.is_empty()
237     }
238
239     pub fn span(&self) -> Span {
240         self.span
241     }
242
243     pub fn is_meta_item_list(&self) -> bool {
244         self.meta_item_list().is_some()
245     }
246
247     /// Indicates if the attribute is a Value String.
248     pub fn is_value_str(&self) -> bool {
249         self.value_str().is_some()
250     }
251 }
252
253 impl MetaItem {
254     pub fn name(&self) -> Name {
255         self.name
256     }
257
258     pub fn value_str(&self) -> Option<Symbol> {
259         match self.node {
260             MetaItemKind::NameValue(ref v) => {
261                 match v.node {
262                     LitKind::Str(ref s, _) => Some(*s),
263                     _ => None,
264                 }
265             },
266             _ => None
267         }
268     }
269
270     pub fn meta_item_list(&self) -> Option<&[NestedMetaItem]> {
271         match self.node {
272             MetaItemKind::List(ref l) => Some(&l[..]),
273             _ => None
274         }
275     }
276
277     pub fn is_word(&self) -> bool {
278         match self.node {
279             MetaItemKind::Word => true,
280             _ => false,
281         }
282     }
283
284     pub fn span(&self) -> Span { self.span }
285
286     pub fn check_name(&self, name: &str) -> bool {
287         self.name() == name
288     }
289
290     pub fn is_value_str(&self) -> bool {
291         self.value_str().is_some()
292     }
293
294     pub fn is_meta_item_list(&self) -> bool {
295         self.meta_item_list().is_some()
296     }
297 }
298
299 impl Attribute {
300     /// Extract the MetaItem from inside this Attribute.
301     pub fn meta(&self) -> Option<MetaItem> {
302         let mut tokens = self.tokens.trees().peekable();
303         Some(MetaItem {
304             name: match self.path.segments.len() {
305                 1 => self.path.segments[0].identifier.name,
306                 _ => return None,
307             },
308             node: if let Some(node) = MetaItemKind::from_tokens(&mut tokens) {
309                 if tokens.peek().is_some() {
310                     return None;
311                 }
312                 node
313             } else {
314                 return None;
315             },
316             span: self.span,
317         })
318     }
319
320     pub fn parse<'a, T, F>(&self, sess: &'a ParseSess, mut f: F) -> PResult<'a, T>
321         where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
322     {
323         let mut parser = Parser::new(sess, self.tokens.clone(), None, false, false);
324         let result = f(&mut parser)?;
325         if parser.token != token::Eof {
326             parser.unexpected()?;
327         }
328         Ok(result)
329     }
330
331     pub fn parse_list<'a, T, F>(&self, sess: &'a ParseSess, mut f: F) -> PResult<'a, Vec<T>>
332         where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
333     {
334         if self.tokens.is_empty() {
335             return Ok(Vec::new());
336         }
337         self.parse(sess, |parser| {
338             parser.expect(&token::OpenDelim(token::Paren))?;
339             let mut list = Vec::new();
340             while !parser.eat(&token::CloseDelim(token::Paren)) {
341                 list.push(f(parser)?);
342                 if !parser.eat(&token::Comma) {
343                    parser.expect(&token::CloseDelim(token::Paren))?;
344                     break
345                 }
346             }
347             Ok(list)
348         })
349     }
350
351     pub fn parse_meta<'a>(&self, sess: &'a ParseSess) -> PResult<'a, MetaItem> {
352         if self.path.segments.len() > 1 {
353             sess.span_diagnostic.span_err(self.path.span, "expected ident, found path");
354         }
355
356         Ok(MetaItem {
357             name: self.path.segments.last().unwrap().identifier.name,
358             node: self.parse(sess, |parser| parser.parse_meta_item_kind())?,
359             span: self.span,
360         })
361     }
362
363     /// Convert self to a normal #[doc="foo"] comment, if it is a
364     /// comment like `///` or `/** */`. (Returns self unchanged for
365     /// non-sugared doc attributes.)
366     pub fn with_desugared_doc<T, F>(&self, f: F) -> T where
367         F: FnOnce(&Attribute) -> T,
368     {
369         if self.is_sugared_doc {
370             let comment = self.value_str().unwrap();
371             let meta = mk_name_value_item_str(
372                 Symbol::intern("doc"),
373                 Symbol::intern(&strip_doc_comment_decoration(&comment.as_str())));
374             let mut attr = if self.style == ast::AttrStyle::Outer {
375                 mk_attr_outer(self.span, self.id, meta)
376             } else {
377                 mk_attr_inner(self.span, self.id, meta)
378             };
379             attr.is_sugared_doc = true;
380             f(&attr)
381         } else {
382             f(self)
383         }
384     }
385 }
386
387 /* Constructors */
388
389 pub fn mk_name_value_item_str(name: Name, value: Symbol) -> MetaItem {
390     let value_lit = dummy_spanned(LitKind::Str(value, ast::StrStyle::Cooked));
391     mk_spanned_name_value_item(DUMMY_SP, name, value_lit)
392 }
393
394 pub fn mk_name_value_item(name: Name, value: ast::Lit) -> MetaItem {
395     mk_spanned_name_value_item(DUMMY_SP, name, value)
396 }
397
398 pub fn mk_list_item(name: Name, items: Vec<NestedMetaItem>) -> MetaItem {
399     mk_spanned_list_item(DUMMY_SP, name, items)
400 }
401
402 pub fn mk_list_word_item(name: Name) -> ast::NestedMetaItem {
403     dummy_spanned(NestedMetaItemKind::MetaItem(mk_spanned_word_item(DUMMY_SP, name)))
404 }
405
406 pub fn mk_word_item(name: Name) -> MetaItem {
407     mk_spanned_word_item(DUMMY_SP, name)
408 }
409
410 pub fn mk_spanned_name_value_item(sp: Span, name: Name, value: ast::Lit) -> MetaItem {
411     MetaItem { span: sp, name: name, node: MetaItemKind::NameValue(value) }
412 }
413
414 pub fn mk_spanned_list_item(sp: Span, name: Name, items: Vec<NestedMetaItem>) -> MetaItem {
415     MetaItem { span: sp, name: name, node: MetaItemKind::List(items) }
416 }
417
418 pub fn mk_spanned_word_item(sp: Span, name: Name) -> MetaItem {
419     MetaItem { span: sp, name: name, node: MetaItemKind::Word }
420 }
421
422 pub fn mk_attr_id() -> AttrId {
423     use std::sync::atomic::AtomicUsize;
424     use std::sync::atomic::Ordering;
425
426     static NEXT_ATTR_ID: AtomicUsize = AtomicUsize::new(0);
427
428     let id = NEXT_ATTR_ID.fetch_add(1, Ordering::SeqCst);
429     assert!(id != ::std::usize::MAX);
430     AttrId(id)
431 }
432
433 /// Returns an inner attribute with the given value.
434 pub fn mk_attr_inner(span: Span, id: AttrId, item: MetaItem) -> Attribute {
435     mk_spanned_attr_inner(span, id, item)
436 }
437
438 /// Returns an inner attribute with the given value and span.
439 pub fn mk_spanned_attr_inner(sp: Span, id: AttrId, item: MetaItem) -> Attribute {
440     Attribute {
441         id,
442         style: ast::AttrStyle::Inner,
443         path: ast::Path::from_ident(item.span, ast::Ident::with_empty_ctxt(item.name)),
444         tokens: item.node.tokens(item.span),
445         is_sugared_doc: false,
446         span: sp,
447     }
448 }
449
450
451 /// Returns an outer attribute with the given value.
452 pub fn mk_attr_outer(span: Span, id: AttrId, item: MetaItem) -> Attribute {
453     mk_spanned_attr_outer(span, id, item)
454 }
455
456 /// Returns an outer attribute with the given value and span.
457 pub fn mk_spanned_attr_outer(sp: Span, id: AttrId, item: MetaItem) -> Attribute {
458     Attribute {
459         id,
460         style: ast::AttrStyle::Outer,
461         path: ast::Path::from_ident(item.span, ast::Ident::with_empty_ctxt(item.name)),
462         tokens: item.node.tokens(item.span),
463         is_sugared_doc: false,
464         span: sp,
465     }
466 }
467
468 pub fn mk_sugared_doc_attr(id: AttrId, text: Symbol, span: Span) -> Attribute {
469     let style = doc_comment_style(&text.as_str());
470     let lit = respan(span, LitKind::Str(text, ast::StrStyle::Cooked));
471     Attribute {
472         id,
473         style,
474         path: ast::Path::from_ident(span, ast::Ident::from_str("doc")),
475         tokens: MetaItemKind::NameValue(lit).tokens(span),
476         is_sugared_doc: true,
477         span,
478     }
479 }
480
481 pub fn list_contains_name(items: &[NestedMetaItem], name: &str) -> bool {
482     items.iter().any(|item| {
483         item.check_name(name)
484     })
485 }
486
487 pub fn contains_name(attrs: &[Attribute], name: &str) -> bool {
488     attrs.iter().any(|item| {
489         item.check_name(name)
490     })
491 }
492
493 pub fn find_by_name<'a>(attrs: &'a [Attribute], name: &str) -> Option<&'a Attribute> {
494     attrs.iter().find(|attr| attr.check_name(name))
495 }
496
497 pub fn first_attr_value_str_by_name(attrs: &[Attribute], name: &str) -> Option<Symbol> {
498     attrs.iter()
499         .find(|at| at.check_name(name))
500         .and_then(|at| at.value_str())
501 }
502
503 /// Check if `attrs` contains an attribute like `#![feature(feature_name)]`.
504 /// This will not perform any "sanity checks" on the form of the attributes.
505 pub fn contains_feature_attr(attrs: &[Attribute], feature_name: &str) -> bool {
506     attrs.iter().any(|item| {
507         item.check_name("feature") &&
508         item.meta_item_list().map(|list| {
509             list.iter().any(|mi| {
510                 mi.word().map(|w| w.name() == feature_name)
511                          .unwrap_or(false)
512             })
513         }).unwrap_or(false)
514     })
515 }
516
517 /* Higher-level applications */
518
519 pub fn find_crate_name(attrs: &[Attribute]) -> Option<Symbol> {
520     first_attr_value_str_by_name(attrs, "crate_name")
521 }
522
523 #[derive(Copy, Clone, PartialEq)]
524 pub enum InlineAttr {
525     None,
526     Hint,
527     Always,
528     Never,
529 }
530
531 /// Determine what `#[inline]` attribute is present in `attrs`, if any.
532 pub fn find_inline_attr(diagnostic: Option<&Handler>, attrs: &[Attribute]) -> InlineAttr {
533     attrs.iter().fold(InlineAttr::None, |ia, attr| {
534         if attr.path != "inline" {
535             return ia;
536         }
537         let meta = match attr.meta() {
538             Some(meta) => meta.node,
539             None => return ia,
540         };
541         match meta {
542             MetaItemKind::Word => {
543                 mark_used(attr);
544                 InlineAttr::Hint
545             }
546             MetaItemKind::List(ref items) => {
547                 mark_used(attr);
548                 if items.len() != 1 {
549                     diagnostic.map(|d|{ span_err!(d, attr.span, E0534, "expected one argument"); });
550                     InlineAttr::None
551                 } else if list_contains_name(&items[..], "always") {
552                     InlineAttr::Always
553                 } else if list_contains_name(&items[..], "never") {
554                     InlineAttr::Never
555                 } else {
556                     diagnostic.map(|d| {
557                         span_err!(d, items[0].span, E0535, "invalid argument");
558                     });
559
560                     InlineAttr::None
561                 }
562             }
563             _ => ia,
564         }
565     })
566 }
567
568 /// True if `#[inline]` or `#[inline(always)]` is present in `attrs`.
569 pub fn requests_inline(attrs: &[Attribute]) -> bool {
570     match find_inline_attr(None, attrs) {
571         InlineAttr::Hint | InlineAttr::Always => true,
572         InlineAttr::None | InlineAttr::Never => false,
573     }
574 }
575
576 /// Tests if a cfg-pattern matches the cfg set
577 pub fn cfg_matches(cfg: &ast::MetaItem, sess: &ParseSess, features: Option<&Features>) -> bool {
578     eval_condition(cfg, sess, &mut |cfg| {
579         if let (Some(feats), Some(gated_cfg)) = (features, GatedCfg::gate(cfg)) {
580             gated_cfg.check_and_emit(sess, feats);
581         }
582         sess.config.contains(&(cfg.name(), cfg.value_str()))
583     })
584 }
585
586 /// Evaluate a cfg-like condition (with `any` and `all`), using `eval` to
587 /// evaluate individual items.
588 pub fn eval_condition<F>(cfg: &ast::MetaItem, sess: &ParseSess, eval: &mut F)
589                          -> bool
590     where F: FnMut(&ast::MetaItem) -> bool
591 {
592     match cfg.node {
593         ast::MetaItemKind::List(ref mis) => {
594             for mi in mis.iter() {
595                 if !mi.is_meta_item() {
596                     handle_errors(&sess.span_diagnostic, mi.span, AttrError::UnsupportedLiteral);
597                     return false;
598                 }
599             }
600
601             // The unwraps below may look dangerous, but we've already asserted
602             // that they won't fail with the loop above.
603             match &*cfg.name.as_str() {
604                 "any" => mis.iter().any(|mi| {
605                     eval_condition(mi.meta_item().unwrap(), sess, eval)
606                 }),
607                 "all" => mis.iter().all(|mi| {
608                     eval_condition(mi.meta_item().unwrap(), sess, eval)
609                 }),
610                 "not" => {
611                     if mis.len() != 1 {
612                         span_err!(sess.span_diagnostic, cfg.span, E0536, "expected 1 cfg-pattern");
613                         return false;
614                     }
615
616                     !eval_condition(mis[0].meta_item().unwrap(), sess, eval)
617                 },
618                 p => {
619                     span_err!(sess.span_diagnostic, cfg.span, E0537, "invalid predicate `{}`", p);
620                     false
621                 }
622             }
623         },
624         ast::MetaItemKind::Word | ast::MetaItemKind::NameValue(..) => {
625             eval(cfg)
626         }
627     }
628 }
629
630 /// Represents the #[stable], #[unstable], #[rustc_{deprecated,const_unstable}] attributes.
631 #[derive(RustcEncodable, RustcDecodable, Clone, Debug, PartialEq, Eq, Hash)]
632 pub struct Stability {
633     pub level: StabilityLevel,
634     pub feature: Symbol,
635     pub rustc_depr: Option<RustcDeprecation>,
636     pub rustc_const_unstable: Option<RustcConstUnstable>,
637 }
638
639 /// The available stability levels.
640 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Debug, Eq, Hash)]
641 pub enum StabilityLevel {
642     // Reason for the current stability level and the relevant rust-lang issue
643     Unstable { reason: Option<Symbol>, issue: u32 },
644     Stable { since: Symbol },
645 }
646
647 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Debug, Eq, Hash)]
648 pub struct RustcDeprecation {
649     pub since: Symbol,
650     pub reason: Symbol,
651 }
652
653 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Debug, Eq, Hash)]
654 pub struct RustcConstUnstable {
655     pub feature: Symbol,
656 }
657
658 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Debug, Eq, Hash)]
659 pub struct Deprecation {
660     pub since: Option<Symbol>,
661     pub note: Option<Symbol>,
662 }
663
664 impl StabilityLevel {
665     pub fn is_unstable(&self) -> bool { if let Unstable {..} = *self { true } else { false }}
666     pub fn is_stable(&self) -> bool { if let Stable {..} = *self { true } else { false }}
667 }
668
669 fn find_stability_generic<'a, I>(diagnostic: &Handler,
670                                  attrs_iter: I,
671                                  item_sp: Span)
672                                  -> Option<Stability>
673     where I: Iterator<Item = &'a Attribute>
674 {
675     let mut stab: Option<Stability> = None;
676     let mut rustc_depr: Option<RustcDeprecation> = None;
677     let mut rustc_const_unstable: Option<RustcConstUnstable> = None;
678
679     'outer: for attr in attrs_iter {
680         if ![
681             "rustc_deprecated",
682             "rustc_const_unstable",
683             "unstable",
684             "stable",
685         ].iter().any(|&s| attr.path == s) {
686             continue // not a stability level
687         }
688
689         mark_used(attr);
690
691         let meta = attr.meta();
692         if let Some(MetaItem { node: MetaItemKind::List(ref metas), .. }) = meta {
693             let meta = meta.as_ref().unwrap();
694             let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
695                 if item.is_some() {
696                     handle_errors(diagnostic, meta.span, AttrError::MultipleItem(meta.name()));
697                     return false
698                 }
699                 if let Some(v) = meta.value_str() {
700                     *item = Some(v);
701                     true
702                 } else {
703                     span_err!(diagnostic, meta.span, E0539, "incorrect meta item");
704                     false
705                 }
706             };
707
708             macro_rules! get_meta {
709                 ($($name:ident),+) => {
710                     $(
711                         let mut $name = None;
712                     )+
713                     for meta in metas {
714                         if let Some(mi) = meta.meta_item() {
715                             match &*mi.name().as_str() {
716                                 $(
717                                     stringify!($name)
718                                         => if !get(mi, &mut $name) { continue 'outer },
719                                 )+
720                                 _ => {
721                                     handle_errors(diagnostic, mi.span,
722                                                   AttrError::UnknownMetaItem(mi.name()));
723                                     continue 'outer
724                                 }
725                             }
726                         } else {
727                             handle_errors(diagnostic, meta.span, AttrError::UnsupportedLiteral);
728                             continue 'outer
729                         }
730                     }
731                 }
732             }
733
734             match &*meta.name.as_str() {
735                 "rustc_deprecated" => {
736                     if rustc_depr.is_some() {
737                         span_err!(diagnostic, item_sp, E0540,
738                                   "multiple rustc_deprecated attributes");
739                         continue 'outer
740                     }
741
742                     get_meta!(since, reason);
743
744                     match (since, reason) {
745                         (Some(since), Some(reason)) => {
746                             rustc_depr = Some(RustcDeprecation {
747                                 since,
748                                 reason,
749                             })
750                         }
751                         (None, _) => {
752                             handle_errors(diagnostic, attr.span(), AttrError::MissingSince);
753                             continue
754                         }
755                         _ => {
756                             span_err!(diagnostic, attr.span(), E0543, "missing 'reason'");
757                             continue
758                         }
759                     }
760                 }
761                 "rustc_const_unstable" => {
762                     if rustc_const_unstable.is_some() {
763                         span_err!(diagnostic, item_sp, E0553,
764                                   "multiple rustc_const_unstable attributes");
765                         continue 'outer
766                     }
767
768                     get_meta!(feature);
769                     if let Some(feature) = feature {
770                         rustc_const_unstable = Some(RustcConstUnstable {
771                             feature
772                         });
773                     } else {
774                         span_err!(diagnostic, attr.span(), E0629, "missing 'feature'");
775                         continue
776                     }
777                 }
778                 "unstable" => {
779                     if stab.is_some() {
780                         handle_errors(diagnostic, attr.span(), AttrError::MultipleStabilityLevels);
781                         break
782                     }
783
784                     let mut feature = None;
785                     let mut reason = None;
786                     let mut issue = None;
787                     for meta in metas {
788                         if let Some(mi) = meta.meta_item() {
789                             match &*mi.name().as_str() {
790                                 "feature" => if !get(mi, &mut feature) { continue 'outer },
791                                 "reason" => if !get(mi, &mut reason) { continue 'outer },
792                                 "issue" => if !get(mi, &mut issue) { continue 'outer },
793                                 _ => {
794                                     handle_errors(diagnostic, meta.span,
795                                                   AttrError::UnknownMetaItem(mi.name()));
796                                     continue 'outer
797                                 }
798                             }
799                         } else {
800                             handle_errors(diagnostic, meta.span, AttrError::UnsupportedLiteral);
801                             continue 'outer
802                         }
803                     }
804
805                     match (feature, reason, issue) {
806                         (Some(feature), reason, Some(issue)) => {
807                             stab = Some(Stability {
808                                 level: Unstable {
809                                     reason,
810                                     issue: {
811                                         if let Ok(issue) = issue.as_str().parse() {
812                                             issue
813                                         } else {
814                                             span_err!(diagnostic, attr.span(), E0545,
815                                                       "incorrect 'issue'");
816                                             continue
817                                         }
818                                     }
819                                 },
820                                 feature,
821                                 rustc_depr: None,
822                                 rustc_const_unstable: None,
823                             })
824                         }
825                         (None, _, _) => {
826                             handle_errors(diagnostic, attr.span(), AttrError::MissingFeature);
827                             continue
828                         }
829                         _ => {
830                             span_err!(diagnostic, attr.span(), E0547, "missing 'issue'");
831                             continue
832                         }
833                     }
834                 }
835                 "stable" => {
836                     if stab.is_some() {
837                         handle_errors(diagnostic, attr.span(), AttrError::MultipleStabilityLevels);
838                         break
839                     }
840
841                     let mut feature = None;
842                     let mut since = None;
843                     for meta in metas {
844                         if let NestedMetaItemKind::MetaItem(ref mi) = meta.node {
845                             match &*mi.name().as_str() {
846                                 "feature" => if !get(mi, &mut feature) { continue 'outer },
847                                 "since" => if !get(mi, &mut since) { continue 'outer },
848                                 _ => {
849                                     handle_errors(diagnostic, meta.span,
850                                                   AttrError::UnknownMetaItem(mi.name()));
851                                     continue 'outer
852                                 }
853                             }
854                         } else {
855                             handle_errors(diagnostic, meta.span, AttrError::UnsupportedLiteral);
856                             continue 'outer
857                         }
858                     }
859
860                     match (feature, since) {
861                         (Some(feature), Some(since)) => {
862                             stab = Some(Stability {
863                                 level: Stable {
864                                     since,
865                                 },
866                                 feature,
867                                 rustc_depr: None,
868                                 rustc_const_unstable: None,
869                             })
870                         }
871                         (None, _) => {
872                             handle_errors(diagnostic, attr.span(), AttrError::MissingFeature);
873                             continue
874                         }
875                         _ => {
876                             handle_errors(diagnostic, attr.span(), AttrError::MissingSince);
877                             continue
878                         }
879                     }
880                 }
881                 _ => unreachable!()
882             }
883         } else {
884             span_err!(diagnostic, attr.span(), E0548, "incorrect stability attribute type");
885             continue
886         }
887     }
888
889     // Merge the deprecation info into the stability info
890     if let Some(rustc_depr) = rustc_depr {
891         if let Some(ref mut stab) = stab {
892             stab.rustc_depr = Some(rustc_depr);
893         } else {
894             span_err!(diagnostic, item_sp, E0549,
895                       "rustc_deprecated attribute must be paired with \
896                        either stable or unstable attribute");
897         }
898     }
899
900     // Merge the const-unstable info into the stability info
901     if let Some(rustc_const_unstable) = rustc_const_unstable {
902         if let Some(ref mut stab) = stab {
903             stab.rustc_const_unstable = Some(rustc_const_unstable);
904         } else {
905             span_err!(diagnostic, item_sp, E0630,
906                       "rustc_const_unstable attribute must be paired with \
907                        either stable or unstable attribute");
908         }
909     }
910
911     stab
912 }
913
914 fn find_deprecation_generic<'a, I>(diagnostic: &Handler,
915                                    attrs_iter: I,
916                                    item_sp: Span)
917                                    -> Option<Deprecation>
918     where I: Iterator<Item = &'a Attribute>
919 {
920     let mut depr: Option<Deprecation> = None;
921
922     'outer: for attr in attrs_iter {
923         if attr.path != "deprecated" {
924             continue
925         }
926
927         mark_used(attr);
928
929         if depr.is_some() {
930             span_err!(diagnostic, item_sp, E0550, "multiple deprecated attributes");
931             break
932         }
933
934         depr = if let Some(metas) = attr.meta_item_list() {
935             let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
936                 if item.is_some() {
937                     handle_errors(diagnostic, meta.span, AttrError::MultipleItem(meta.name()));
938                     return false
939                 }
940                 if let Some(v) = meta.value_str() {
941                     *item = Some(v);
942                     true
943                 } else {
944                     span_err!(diagnostic, meta.span, E0551, "incorrect meta item");
945                     false
946                 }
947             };
948
949             let mut since = None;
950             let mut note = None;
951             for meta in metas {
952                 if let NestedMetaItemKind::MetaItem(ref mi) = meta.node {
953                     match &*mi.name().as_str() {
954                         "since" => if !get(mi, &mut since) { continue 'outer },
955                         "note" => if !get(mi, &mut note) { continue 'outer },
956                         _ => {
957                             handle_errors(diagnostic, meta.span,
958                                           AttrError::UnknownMetaItem(mi.name()));
959                             continue 'outer
960                         }
961                     }
962                 } else {
963                     handle_errors(diagnostic, meta.span, AttrError::UnsupportedLiteral);
964                     continue 'outer
965                 }
966             }
967
968             Some(Deprecation {since: since, note: note})
969         } else {
970             Some(Deprecation{since: None, note: None})
971         }
972     }
973
974     depr
975 }
976
977 /// Find the first stability attribute. `None` if none exists.
978 pub fn find_stability(diagnostic: &Handler, attrs: &[Attribute],
979                       item_sp: Span) -> Option<Stability> {
980     find_stability_generic(diagnostic, attrs.iter(), item_sp)
981 }
982
983 /// Find the deprecation attribute. `None` if none exists.
984 pub fn find_deprecation(diagnostic: &Handler, attrs: &[Attribute],
985                         item_sp: Span) -> Option<Deprecation> {
986     find_deprecation_generic(diagnostic, attrs.iter(), item_sp)
987 }
988
989
990 /// Parse #[repr(...)] forms.
991 ///
992 /// Valid repr contents: any of the primitive integral type names (see
993 /// `int_type_of_word`, below) to specify enum discriminant type; `C`, to use
994 /// the same discriminant size that the corresponding C enum would or C
995 /// structure layout, and `packed` to remove padding.
996 pub fn find_repr_attrs(diagnostic: &Handler, attr: &Attribute) -> Vec<ReprAttr> {
997     let mut acc = Vec::new();
998     if attr.path == "repr" {
999         if let Some(items) = attr.meta_item_list() {
1000             mark_used(attr);
1001             for item in items {
1002                 if !item.is_meta_item() {
1003                     handle_errors(diagnostic, item.span, AttrError::UnsupportedLiteral);
1004                     continue
1005                 }
1006
1007                 let mut recognised = false;
1008                 if let Some(mi) = item.word() {
1009                     let word = &*mi.name().as_str();
1010                     let hint = match word {
1011                         // Can't use "extern" because it's not a lexical identifier.
1012                         "C" => Some(ReprExtern),
1013                         "packed" => Some(ReprPacked),
1014                         "simd" => Some(ReprSimd),
1015                         _ => match int_type_of_word(word) {
1016                             Some(ity) => Some(ReprInt(ity)),
1017                             None => {
1018                                 None
1019                             }
1020                         }
1021                     };
1022
1023                     if let Some(h) = hint {
1024                         recognised = true;
1025                         acc.push(h);
1026                     }
1027                 } else if let Some((name, value)) = item.name_value_literal() {
1028                     if name == "align" {
1029                         recognised = true;
1030                         let mut align_error = None;
1031                         if let ast::LitKind::Int(align, ast::LitIntType::Unsuffixed) = value.node {
1032                             if align.is_power_of_two() {
1033                                 // rustc::ty::layout::Align restricts align to <= 2147483647
1034                                 if align <= 2147483647 {
1035                                     acc.push(ReprAlign(align as u32));
1036                                 } else {
1037                                     align_error = Some("larger than 2147483647");
1038                                 }
1039                             } else {
1040                                 align_error = Some("not a power of two");
1041                             }
1042                         } else {
1043                             align_error = Some("not an unsuffixed integer");
1044                         }
1045                         if let Some(align_error) = align_error {
1046                             span_err!(diagnostic, item.span, E0589,
1047                                       "invalid `repr(align)` attribute: {}", align_error);
1048                         }
1049                     }
1050                 }
1051                 if !recognised {
1052                     // Not a word we recognize
1053                     span_err!(diagnostic, item.span, E0552,
1054                               "unrecognized representation hint");
1055                 }
1056             }
1057         }
1058     }
1059     acc
1060 }
1061
1062 fn int_type_of_word(s: &str) -> Option<IntType> {
1063     match s {
1064         "i8" => Some(SignedInt(ast::IntTy::I8)),
1065         "u8" => Some(UnsignedInt(ast::UintTy::U8)),
1066         "i16" => Some(SignedInt(ast::IntTy::I16)),
1067         "u16" => Some(UnsignedInt(ast::UintTy::U16)),
1068         "i32" => Some(SignedInt(ast::IntTy::I32)),
1069         "u32" => Some(UnsignedInt(ast::UintTy::U32)),
1070         "i64" => Some(SignedInt(ast::IntTy::I64)),
1071         "u64" => Some(UnsignedInt(ast::UintTy::U64)),
1072         "i128" => Some(SignedInt(ast::IntTy::I128)),
1073         "u128" => Some(UnsignedInt(ast::UintTy::U128)),
1074         "isize" => Some(SignedInt(ast::IntTy::Isize)),
1075         "usize" => Some(UnsignedInt(ast::UintTy::Usize)),
1076         _ => None
1077     }
1078 }
1079
1080 #[derive(PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
1081 pub enum ReprAttr {
1082     ReprInt(IntType),
1083     ReprExtern,
1084     ReprPacked,
1085     ReprSimd,
1086     ReprAlign(u32),
1087 }
1088
1089 #[derive(Eq, Hash, PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
1090 pub enum IntType {
1091     SignedInt(ast::IntTy),
1092     UnsignedInt(ast::UintTy)
1093 }
1094
1095 impl IntType {
1096     #[inline]
1097     pub fn is_signed(self) -> bool {
1098         match self {
1099             SignedInt(..) => true,
1100             UnsignedInt(..) => false
1101         }
1102     }
1103 }
1104
1105 impl MetaItem {
1106     fn tokens(&self) -> TokenStream {
1107         let ident = TokenTree::Token(self.span, Token::Ident(Ident::with_empty_ctxt(self.name)));
1108         TokenStream::concat(vec![ident.into(), self.node.tokens(self.span)])
1109     }
1110
1111     fn from_tokens<I>(tokens: &mut iter::Peekable<I>) -> Option<MetaItem>
1112         where I: Iterator<Item = TokenTree>,
1113     {
1114         let (span, name) = match tokens.next() {
1115             Some(TokenTree::Token(span, Token::Ident(ident))) => (span, ident.name),
1116             Some(TokenTree::Token(_, Token::Interpolated(ref nt))) => match nt.0 {
1117                 token::Nonterminal::NtIdent(ident) => (ident.span, ident.node.name),
1118                 token::Nonterminal::NtMeta(ref meta) => return Some(meta.clone()),
1119                 _ => return None,
1120             },
1121             _ => return None,
1122         };
1123         let list_closing_paren_pos = tokens.peek().map(|tt| tt.span().hi());
1124         let node = MetaItemKind::from_tokens(tokens)?;
1125         let hi = match node {
1126             MetaItemKind::NameValue(ref lit) => lit.span.hi(),
1127             MetaItemKind::List(..) => list_closing_paren_pos.unwrap_or(span.hi()),
1128             _ => span.hi(),
1129         };
1130         Some(MetaItem { name, node, span: span.with_hi(hi) })
1131     }
1132 }
1133
1134 impl MetaItemKind {
1135     pub fn tokens(&self, span: Span) -> TokenStream {
1136         match *self {
1137             MetaItemKind::Word => TokenStream::empty(),
1138             MetaItemKind::NameValue(ref lit) => {
1139                 TokenStream::concat(vec![TokenTree::Token(span, Token::Eq).into(), lit.tokens()])
1140             }
1141             MetaItemKind::List(ref list) => {
1142                 let mut tokens = Vec::new();
1143                 for (i, item) in list.iter().enumerate() {
1144                     if i > 0 {
1145                         tokens.push(TokenTree::Token(span, Token::Comma).into());
1146                     }
1147                     tokens.push(item.node.tokens());
1148                 }
1149                 TokenTree::Delimited(span, Delimited {
1150                     delim: token::Paren,
1151                     tts: TokenStream::concat(tokens).into(),
1152                 }).into()
1153             }
1154         }
1155     }
1156
1157     fn from_tokens<I>(tokens: &mut iter::Peekable<I>) -> Option<MetaItemKind>
1158         where I: Iterator<Item = TokenTree>,
1159     {
1160         let delimited = match tokens.peek().cloned() {
1161             Some(TokenTree::Token(_, token::Eq)) => {
1162                 tokens.next();
1163                 return if let Some(TokenTree::Token(span, token)) = tokens.next() {
1164                     LitKind::from_token(token)
1165                         .map(|lit| MetaItemKind::NameValue(Spanned { node: lit, span: span }))
1166                 } else {
1167                     None
1168                 };
1169             }
1170             Some(TokenTree::Delimited(_, ref delimited)) if delimited.delim == token::Paren => {
1171                 tokens.next();
1172                 delimited.stream()
1173             }
1174             _ => return Some(MetaItemKind::Word),
1175         };
1176
1177         let mut tokens = delimited.into_trees().peekable();
1178         let mut result = Vec::new();
1179         while let Some(..) = tokens.peek() {
1180             let item = NestedMetaItemKind::from_tokens(&mut tokens)?;
1181             result.push(respan(item.span(), item));
1182             match tokens.next() {
1183                 None | Some(TokenTree::Token(_, Token::Comma)) => {}
1184                 _ => return None,
1185             }
1186         }
1187         Some(MetaItemKind::List(result))
1188     }
1189 }
1190
1191 impl NestedMetaItemKind {
1192     fn span(&self) -> Span {
1193         match *self {
1194             NestedMetaItemKind::MetaItem(ref item) => item.span,
1195             NestedMetaItemKind::Literal(ref lit) => lit.span,
1196         }
1197     }
1198
1199     fn tokens(&self) -> TokenStream {
1200         match *self {
1201             NestedMetaItemKind::MetaItem(ref item) => item.tokens(),
1202             NestedMetaItemKind::Literal(ref lit) => lit.tokens(),
1203         }
1204     }
1205
1206     fn from_tokens<I>(tokens: &mut iter::Peekable<I>) -> Option<NestedMetaItemKind>
1207         where I: Iterator<Item = TokenTree>,
1208     {
1209         if let Some(TokenTree::Token(span, token)) = tokens.peek().cloned() {
1210             if let Some(node) = LitKind::from_token(token) {
1211                 tokens.next();
1212                 return Some(NestedMetaItemKind::Literal(respan(span, node)));
1213             }
1214         }
1215
1216         MetaItem::from_tokens(tokens).map(NestedMetaItemKind::MetaItem)
1217     }
1218 }
1219
1220 impl Lit {
1221     fn tokens(&self) -> TokenStream {
1222         TokenTree::Token(self.span, self.node.token()).into()
1223     }
1224 }
1225
1226 impl LitKind {
1227     fn token(&self) -> Token {
1228         use std::ascii;
1229
1230         match *self {
1231             LitKind::Str(string, ast::StrStyle::Cooked) => {
1232                 let mut escaped = String::new();
1233                 for ch in string.as_str().chars() {
1234                     escaped.extend(ch.escape_unicode());
1235                 }
1236                 Token::Literal(token::Lit::Str_(Symbol::intern(&escaped)), None)
1237             }
1238             LitKind::Str(string, ast::StrStyle::Raw(n)) => {
1239                 Token::Literal(token::Lit::StrRaw(string, n), None)
1240             }
1241             LitKind::ByteStr(ref bytes) => {
1242                 let string = bytes.iter().cloned().flat_map(ascii::escape_default)
1243                     .map(Into::<char>::into).collect::<String>();
1244                 Token::Literal(token::Lit::ByteStr(Symbol::intern(&string)), None)
1245             }
1246             LitKind::Byte(byte) => {
1247                 let string: String = ascii::escape_default(byte).map(Into::<char>::into).collect();
1248                 Token::Literal(token::Lit::Byte(Symbol::intern(&string)), None)
1249             }
1250             LitKind::Char(ch) => {
1251                 let string: String = ch.escape_default().map(Into::<char>::into).collect();
1252                 Token::Literal(token::Lit::Char(Symbol::intern(&string)), None)
1253             }
1254             LitKind::Int(n, ty) => {
1255                 let suffix = match ty {
1256                     ast::LitIntType::Unsigned(ty) => Some(Symbol::intern(ty.ty_to_string())),
1257                     ast::LitIntType::Signed(ty) => Some(Symbol::intern(ty.ty_to_string())),
1258                     ast::LitIntType::Unsuffixed => None,
1259                 };
1260                 Token::Literal(token::Lit::Integer(Symbol::intern(&n.to_string())), suffix)
1261             }
1262             LitKind::Float(symbol, ty) => {
1263                 Token::Literal(token::Lit::Float(symbol), Some(Symbol::intern(ty.ty_to_string())))
1264             }
1265             LitKind::FloatUnsuffixed(symbol) => Token::Literal(token::Lit::Float(symbol), None),
1266             LitKind::Bool(value) => Token::Ident(Ident::with_empty_ctxt(Symbol::intern(if value {
1267                 "true"
1268             } else {
1269                 "false"
1270             }))),
1271         }
1272     }
1273
1274     fn from_token(token: Token) -> Option<LitKind> {
1275         match token {
1276             Token::Ident(ident) if ident.name == "true" => Some(LitKind::Bool(true)),
1277             Token::Ident(ident) if ident.name == "false" => Some(LitKind::Bool(false)),
1278             Token::Interpolated(ref nt) => match nt.0 {
1279                 token::NtExpr(ref v) => match v.node {
1280                     ExprKind::Lit(ref lit) => Some(lit.node.clone()),
1281                     _ => None,
1282                 },
1283                 _ => None,
1284             },
1285             Token::Literal(lit, suf) => {
1286                 let (suffix_illegal, result) = parse::lit_token(lit, suf, None);
1287                 if suffix_illegal && suf.is_some() {
1288                     return None;
1289                 }
1290                 result
1291             }
1292             _ => None,
1293         }
1294     }
1295 }
1296
1297 pub trait HasAttrs: Sized {
1298     fn attrs(&self) -> &[ast::Attribute];
1299     fn map_attrs<F: FnOnce(Vec<ast::Attribute>) -> Vec<ast::Attribute>>(self, f: F) -> Self;
1300 }
1301
1302 impl<T: HasAttrs> HasAttrs for Spanned<T> {
1303     fn attrs(&self) -> &[ast::Attribute] { self.node.attrs() }
1304     fn map_attrs<F: FnOnce(Vec<ast::Attribute>) -> Vec<ast::Attribute>>(self, f: F) -> Self {
1305         respan(self.span, self.node.map_attrs(f))
1306     }
1307 }
1308
1309 impl HasAttrs for Vec<Attribute> {
1310     fn attrs(&self) -> &[Attribute] {
1311         self
1312     }
1313     fn map_attrs<F: FnOnce(Vec<Attribute>) -> Vec<Attribute>>(self, f: F) -> Self {
1314         f(self)
1315     }
1316 }
1317
1318 impl HasAttrs for ThinVec<Attribute> {
1319     fn attrs(&self) -> &[Attribute] {
1320         self
1321     }
1322     fn map_attrs<F: FnOnce(Vec<Attribute>) -> Vec<Attribute>>(self, f: F) -> Self {
1323         f(self.into()).into()
1324     }
1325 }
1326
1327 impl<T: HasAttrs + 'static> HasAttrs for P<T> {
1328     fn attrs(&self) -> &[Attribute] {
1329         (**self).attrs()
1330     }
1331     fn map_attrs<F: FnOnce(Vec<Attribute>) -> Vec<Attribute>>(self, f: F) -> Self {
1332         self.map(|t| t.map_attrs(f))
1333     }
1334 }
1335
1336 impl HasAttrs for StmtKind {
1337     fn attrs(&self) -> &[Attribute] {
1338         match *self {
1339             StmtKind::Local(ref local) => local.attrs(),
1340             StmtKind::Item(..) => &[],
1341             StmtKind::Expr(ref expr) | StmtKind::Semi(ref expr) => expr.attrs(),
1342             StmtKind::Mac(ref mac) => {
1343                 let (_, _, ref attrs) = **mac;
1344                 attrs.attrs()
1345             }
1346         }
1347     }
1348
1349     fn map_attrs<F: FnOnce(Vec<Attribute>) -> Vec<Attribute>>(self, f: F) -> Self {
1350         match self {
1351             StmtKind::Local(local) => StmtKind::Local(local.map_attrs(f)),
1352             StmtKind::Item(..) => self,
1353             StmtKind::Expr(expr) => StmtKind::Expr(expr.map_attrs(f)),
1354             StmtKind::Semi(expr) => StmtKind::Semi(expr.map_attrs(f)),
1355             StmtKind::Mac(mac) => StmtKind::Mac(mac.map(|(mac, style, attrs)| {
1356                 (mac, style, attrs.map_attrs(f))
1357             })),
1358         }
1359     }
1360 }
1361
1362 impl HasAttrs for Stmt {
1363     fn attrs(&self) -> &[ast::Attribute] { self.node.attrs() }
1364     fn map_attrs<F: FnOnce(Vec<ast::Attribute>) -> Vec<ast::Attribute>>(self, f: F) -> Self {
1365         Stmt { id: self.id, node: self.node.map_attrs(f), span: self.span }
1366     }
1367 }
1368
1369 macro_rules! derive_has_attrs {
1370     ($($ty:path),*) => { $(
1371         impl HasAttrs for $ty {
1372             fn attrs(&self) -> &[Attribute] {
1373                 &self.attrs
1374             }
1375
1376             fn map_attrs<F>(mut self, f: F) -> Self
1377                 where F: FnOnce(Vec<Attribute>) -> Vec<Attribute>,
1378             {
1379                 self.attrs = self.attrs.map_attrs(f);
1380                 self
1381             }
1382         }
1383     )* }
1384 }
1385
1386 derive_has_attrs! {
1387     Item, Expr, Local, ast::ForeignItem, ast::StructField, ast::ImplItem, ast::TraitItem, ast::Arm,
1388     ast::Field, ast::FieldPat, ast::Variant_
1389 }