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