]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/attr.rs
Auto merge of #43700 - gaurikholkar:struct_lifetimes, r=nikomatsakis
[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, Cell};
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             if self.style == ast::AttrStyle::Outer {
375                 f(&mk_attr_outer(self.span, self.id, meta))
376             } else {
377                 f(&mk_attr_inner(self.span, self.id, meta))
378             }
379         } else {
380             f(self)
381         }
382     }
383 }
384
385 /* Constructors */
386
387 pub fn mk_name_value_item_str(name: Name, value: Symbol) -> MetaItem {
388     let value_lit = dummy_spanned(LitKind::Str(value, ast::StrStyle::Cooked));
389     mk_spanned_name_value_item(DUMMY_SP, name, value_lit)
390 }
391
392 pub fn mk_name_value_item(name: Name, value: ast::Lit) -> MetaItem {
393     mk_spanned_name_value_item(DUMMY_SP, name, value)
394 }
395
396 pub fn mk_list_item(name: Name, items: Vec<NestedMetaItem>) -> MetaItem {
397     mk_spanned_list_item(DUMMY_SP, name, items)
398 }
399
400 pub fn mk_list_word_item(name: Name) -> ast::NestedMetaItem {
401     dummy_spanned(NestedMetaItemKind::MetaItem(mk_spanned_word_item(DUMMY_SP, name)))
402 }
403
404 pub fn mk_word_item(name: Name) -> MetaItem {
405     mk_spanned_word_item(DUMMY_SP, name)
406 }
407
408 pub fn mk_spanned_name_value_item(sp: Span, name: Name, value: ast::Lit) -> MetaItem {
409     MetaItem { span: sp, name: name, node: MetaItemKind::NameValue(value) }
410 }
411
412 pub fn mk_spanned_list_item(sp: Span, name: Name, items: Vec<NestedMetaItem>) -> MetaItem {
413     MetaItem { span: sp, name: name, node: MetaItemKind::List(items) }
414 }
415
416 pub fn mk_spanned_word_item(sp: Span, name: Name) -> MetaItem {
417     MetaItem { span: sp, name: name, node: MetaItemKind::Word }
418 }
419
420
421
422 thread_local! { static NEXT_ATTR_ID: Cell<usize> = Cell::new(0) }
423
424 pub fn mk_attr_id() -> AttrId {
425     let id = NEXT_ATTR_ID.with(|slot| {
426         let r = slot.get();
427         slot.set(r + 1);
428         r
429     });
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 first_attr_value_str_by_name(attrs: &[Attribute], name: &str) -> Option<Symbol> {
494     attrs.iter()
495         .find(|at| at.check_name(name))
496         .and_then(|at| at.value_str())
497 }
498
499 /* Higher-level applications */
500
501 pub fn find_crate_name(attrs: &[Attribute]) -> Option<Symbol> {
502     first_attr_value_str_by_name(attrs, "crate_name")
503 }
504
505 /// Find the value of #[export_name=*] attribute and check its validity.
506 pub fn find_export_name_attr(diag: &Handler, attrs: &[Attribute]) -> Option<Symbol> {
507     attrs.iter().fold(None, |ia,attr| {
508         if attr.check_name("export_name") {
509             if let s@Some(_) = attr.value_str() {
510                 s
511             } else {
512                 struct_span_err!(diag, attr.span, E0558,
513                                  "export_name attribute has invalid format")
514                     .span_label(attr.span, "did you mean #[export_name=\"*\"]?")
515                     .emit();
516                 None
517             }
518         } else {
519             ia
520         }
521     })
522 }
523
524 pub fn contains_extern_indicator(diag: &Handler, attrs: &[Attribute]) -> bool {
525     contains_name(attrs, "no_mangle") ||
526         find_export_name_attr(diag, attrs).is_some()
527 }
528
529 #[derive(Copy, Clone, PartialEq)]
530 pub enum InlineAttr {
531     None,
532     Hint,
533     Always,
534     Never,
535 }
536
537 /// Determine what `#[inline]` attribute is present in `attrs`, if any.
538 pub fn find_inline_attr(diagnostic: Option<&Handler>, attrs: &[Attribute]) -> InlineAttr {
539     attrs.iter().fold(InlineAttr::None, |ia, attr| {
540         if attr.path != "inline" {
541             return ia;
542         }
543         let meta = match attr.meta() {
544             Some(meta) => meta.node,
545             None => return ia,
546         };
547         match meta {
548             MetaItemKind::Word => {
549                 mark_used(attr);
550                 InlineAttr::Hint
551             }
552             MetaItemKind::List(ref items) => {
553                 mark_used(attr);
554                 if items.len() != 1 {
555                     diagnostic.map(|d|{ span_err!(d, attr.span, E0534, "expected one argument"); });
556                     InlineAttr::None
557                 } else if list_contains_name(&items[..], "always") {
558                     InlineAttr::Always
559                 } else if list_contains_name(&items[..], "never") {
560                     InlineAttr::Never
561                 } else {
562                     diagnostic.map(|d| {
563                         span_err!(d, items[0].span, E0535, "invalid argument");
564                     });
565
566                     InlineAttr::None
567                 }
568             }
569             _ => ia,
570         }
571     })
572 }
573
574 /// True if `#[inline]` or `#[inline(always)]` is present in `attrs`.
575 pub fn requests_inline(attrs: &[Attribute]) -> bool {
576     match find_inline_attr(None, attrs) {
577         InlineAttr::Hint | InlineAttr::Always => true,
578         InlineAttr::None | InlineAttr::Never => false,
579     }
580 }
581
582 /// Tests if a cfg-pattern matches the cfg set
583 pub fn cfg_matches(cfg: &ast::MetaItem, sess: &ParseSess, features: Option<&Features>) -> bool {
584     match cfg.node {
585         ast::MetaItemKind::List(ref mis) => {
586             for mi in mis.iter() {
587                 if !mi.is_meta_item() {
588                     handle_errors(&sess.span_diagnostic, mi.span, AttrError::UnsupportedLiteral);
589                     return false;
590                 }
591             }
592
593             // The unwraps below may look dangerous, but we've already asserted
594             // that they won't fail with the loop above.
595             match &*cfg.name.as_str() {
596                 "any" => mis.iter().any(|mi| {
597                     cfg_matches(mi.meta_item().unwrap(), sess, features)
598                 }),
599                 "all" => mis.iter().all(|mi| {
600                     cfg_matches(mi.meta_item().unwrap(), sess, features)
601                 }),
602                 "not" => {
603                     if mis.len() != 1 {
604                         span_err!(sess.span_diagnostic, cfg.span, E0536, "expected 1 cfg-pattern");
605                         return false;
606                     }
607
608                     !cfg_matches(mis[0].meta_item().unwrap(), sess, features)
609                 },
610                 p => {
611                     span_err!(sess.span_diagnostic, cfg.span, E0537, "invalid predicate `{}`", p);
612                     false
613                 }
614             }
615         },
616         ast::MetaItemKind::Word | ast::MetaItemKind::NameValue(..) => {
617             if let (Some(feats), Some(gated_cfg)) = (features, GatedCfg::gate(cfg)) {
618                 gated_cfg.check_and_emit(sess, feats);
619             }
620             sess.config.contains(&(cfg.name(), cfg.value_str()))
621         }
622     }
623 }
624
625 /// Represents the #[stable], #[unstable] and #[rustc_deprecated] attributes.
626 #[derive(RustcEncodable, RustcDecodable, Clone, Debug, PartialEq, Eq, Hash)]
627 pub struct Stability {
628     pub level: StabilityLevel,
629     pub feature: Symbol,
630     pub rustc_depr: Option<RustcDeprecation>,
631 }
632
633 /// The available stability levels.
634 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Debug, Eq, Hash)]
635 pub enum StabilityLevel {
636     // Reason for the current stability level and the relevant rust-lang issue
637     Unstable { reason: Option<Symbol>, issue: u32 },
638     Stable { since: Symbol },
639 }
640
641 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Debug, Eq, Hash)]
642 pub struct RustcDeprecation {
643     pub since: Symbol,
644     pub reason: Symbol,
645 }
646
647 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Debug, Eq, Hash)]
648 pub struct Deprecation {
649     pub since: Option<Symbol>,
650     pub note: Option<Symbol>,
651 }
652
653 impl StabilityLevel {
654     pub fn is_unstable(&self) -> bool { if let Unstable {..} = *self { true } else { false }}
655     pub fn is_stable(&self) -> bool { if let Stable {..} = *self { true } else { false }}
656 }
657
658 fn find_stability_generic<'a, I>(diagnostic: &Handler,
659                                  attrs_iter: I,
660                                  item_sp: Span)
661                                  -> Option<Stability>
662     where I: Iterator<Item = &'a Attribute>
663 {
664     let mut stab: Option<Stability> = None;
665     let mut rustc_depr: Option<RustcDeprecation> = None;
666
667     'outer: for attr in attrs_iter {
668         if attr.path != "rustc_deprecated" && attr.path != "unstable" && attr.path != "stable" {
669             continue // not a stability level
670         }
671
672         mark_used(attr);
673
674         let meta = attr.meta();
675         if let Some(MetaItem { node: MetaItemKind::List(ref metas), .. }) = meta {
676             let meta = meta.as_ref().unwrap();
677             let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
678                 if item.is_some() {
679                     handle_errors(diagnostic, meta.span, AttrError::MultipleItem(meta.name()));
680                     return false
681                 }
682                 if let Some(v) = meta.value_str() {
683                     *item = Some(v);
684                     true
685                 } else {
686                     span_err!(diagnostic, meta.span, E0539, "incorrect meta item");
687                     false
688                 }
689             };
690
691             match &*meta.name.as_str() {
692                 "rustc_deprecated" => {
693                     if rustc_depr.is_some() {
694                         span_err!(diagnostic, item_sp, E0540,
695                                   "multiple rustc_deprecated attributes");
696                         break
697                     }
698
699                     let mut since = None;
700                     let mut reason = None;
701                     for meta in metas {
702                         if let Some(mi) = meta.meta_item() {
703                             match &*mi.name().as_str() {
704                                 "since" => if !get(mi, &mut since) { continue 'outer },
705                                 "reason" => if !get(mi, &mut reason) { continue 'outer },
706                                 _ => {
707                                     handle_errors(diagnostic, mi.span,
708                                                   AttrError::UnknownMetaItem(mi.name()));
709                                     continue 'outer
710                                 }
711                             }
712                         } else {
713                             handle_errors(diagnostic, meta.span, AttrError::UnsupportedLiteral);
714                             continue 'outer
715                         }
716                     }
717
718                     match (since, reason) {
719                         (Some(since), Some(reason)) => {
720                             rustc_depr = Some(RustcDeprecation {
721                                 since,
722                                 reason,
723                             })
724                         }
725                         (None, _) => {
726                             handle_errors(diagnostic, attr.span(), AttrError::MissingSince);
727                             continue
728                         }
729                         _ => {
730                             span_err!(diagnostic, attr.span(), E0543, "missing 'reason'");
731                             continue
732                         }
733                     }
734                 }
735                 "unstable" => {
736                     if stab.is_some() {
737                         handle_errors(diagnostic, attr.span(), AttrError::MultipleStabilityLevels);
738                         break
739                     }
740
741                     let mut feature = None;
742                     let mut reason = None;
743                     let mut issue = None;
744                     for meta in metas {
745                         if let Some(mi) = meta.meta_item() {
746                             match &*mi.name().as_str() {
747                                 "feature" => if !get(mi, &mut feature) { continue 'outer },
748                                 "reason" => if !get(mi, &mut reason) { continue 'outer },
749                                 "issue" => if !get(mi, &mut issue) { continue 'outer },
750                                 _ => {
751                                     handle_errors(diagnostic, meta.span,
752                                                   AttrError::UnknownMetaItem(mi.name()));
753                                     continue 'outer
754                                 }
755                             }
756                         } else {
757                             handle_errors(diagnostic, meta.span, AttrError::UnsupportedLiteral);
758                             continue 'outer
759                         }
760                     }
761
762                     match (feature, reason, issue) {
763                         (Some(feature), reason, Some(issue)) => {
764                             stab = Some(Stability {
765                                 level: Unstable {
766                                     reason,
767                                     issue: {
768                                         if let Ok(issue) = issue.as_str().parse() {
769                                             issue
770                                         } else {
771                                             span_err!(diagnostic, attr.span(), E0545,
772                                                       "incorrect 'issue'");
773                                             continue
774                                         }
775                                     }
776                                 },
777                                 feature,
778                                 rustc_depr: None,
779                             })
780                         }
781                         (None, _, _) => {
782                             handle_errors(diagnostic, attr.span(), AttrError::MissingFeature);
783                             continue
784                         }
785                         _ => {
786                             span_err!(diagnostic, attr.span(), E0547, "missing 'issue'");
787                             continue
788                         }
789                     }
790                 }
791                 "stable" => {
792                     if stab.is_some() {
793                         handle_errors(diagnostic, attr.span(), AttrError::MultipleStabilityLevels);
794                         break
795                     }
796
797                     let mut feature = None;
798                     let mut since = None;
799                     for meta in metas {
800                         if let NestedMetaItemKind::MetaItem(ref mi) = meta.node {
801                             match &*mi.name().as_str() {
802                                 "feature" => if !get(mi, &mut feature) { continue 'outer },
803                                 "since" => if !get(mi, &mut since) { continue 'outer },
804                                 _ => {
805                                     handle_errors(diagnostic, meta.span,
806                                                   AttrError::UnknownMetaItem(mi.name()));
807                                     continue 'outer
808                                 }
809                             }
810                         } else {
811                             handle_errors(diagnostic, meta.span, AttrError::UnsupportedLiteral);
812                             continue 'outer
813                         }
814                     }
815
816                     match (feature, since) {
817                         (Some(feature), Some(since)) => {
818                             stab = Some(Stability {
819                                 level: Stable {
820                                     since,
821                                 },
822                                 feature,
823                                 rustc_depr: None,
824                             })
825                         }
826                         (None, _) => {
827                             handle_errors(diagnostic, attr.span(), AttrError::MissingFeature);
828                             continue
829                         }
830                         _ => {
831                             handle_errors(diagnostic, attr.span(), AttrError::MissingSince);
832                             continue
833                         }
834                     }
835                 }
836                 _ => unreachable!()
837             }
838         } else {
839             span_err!(diagnostic, attr.span(), E0548, "incorrect stability attribute type");
840             continue
841         }
842     }
843
844     // Merge the deprecation info into the stability info
845     if let Some(rustc_depr) = rustc_depr {
846         if let Some(ref mut stab) = stab {
847             stab.rustc_depr = Some(rustc_depr);
848         } else {
849             span_err!(diagnostic, item_sp, E0549,
850                       "rustc_deprecated attribute must be paired with \
851                        either stable or unstable attribute");
852         }
853     }
854
855     stab
856 }
857
858 fn find_deprecation_generic<'a, I>(diagnostic: &Handler,
859                                    attrs_iter: I,
860                                    item_sp: Span)
861                                    -> Option<Deprecation>
862     where I: Iterator<Item = &'a Attribute>
863 {
864     let mut depr: Option<Deprecation> = None;
865
866     'outer: for attr in attrs_iter {
867         if attr.path != "deprecated" {
868             continue
869         }
870
871         mark_used(attr);
872
873         if depr.is_some() {
874             span_err!(diagnostic, item_sp, E0550, "multiple deprecated attributes");
875             break
876         }
877
878         depr = if let Some(metas) = attr.meta_item_list() {
879             let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
880                 if item.is_some() {
881                     handle_errors(diagnostic, meta.span, AttrError::MultipleItem(meta.name()));
882                     return false
883                 }
884                 if let Some(v) = meta.value_str() {
885                     *item = Some(v);
886                     true
887                 } else {
888                     span_err!(diagnostic, meta.span, E0551, "incorrect meta item");
889                     false
890                 }
891             };
892
893             let mut since = None;
894             let mut note = None;
895             for meta in metas {
896                 if let NestedMetaItemKind::MetaItem(ref mi) = meta.node {
897                     match &*mi.name().as_str() {
898                         "since" => if !get(mi, &mut since) { continue 'outer },
899                         "note" => if !get(mi, &mut note) { continue 'outer },
900                         _ => {
901                             handle_errors(diagnostic, meta.span,
902                                           AttrError::UnknownMetaItem(mi.name()));
903                             continue 'outer
904                         }
905                     }
906                 } else {
907                     handle_errors(diagnostic, meta.span, AttrError::UnsupportedLiteral);
908                     continue 'outer
909                 }
910             }
911
912             Some(Deprecation {since: since, note: note})
913         } else {
914             Some(Deprecation{since: None, note: None})
915         }
916     }
917
918     depr
919 }
920
921 /// Find the first stability attribute. `None` if none exists.
922 pub fn find_stability(diagnostic: &Handler, attrs: &[Attribute],
923                       item_sp: Span) -> Option<Stability> {
924     find_stability_generic(diagnostic, attrs.iter(), item_sp)
925 }
926
927 /// Find the deprecation attribute. `None` if none exists.
928 pub fn find_deprecation(diagnostic: &Handler, attrs: &[Attribute],
929                         item_sp: Span) -> Option<Deprecation> {
930     find_deprecation_generic(diagnostic, attrs.iter(), item_sp)
931 }
932
933
934 /// Parse #[repr(...)] forms.
935 ///
936 /// Valid repr contents: any of the primitive integral type names (see
937 /// `int_type_of_word`, below) to specify enum discriminant type; `C`, to use
938 /// the same discriminant size that the corresponding C enum would or C
939 /// structure layout, and `packed` to remove padding.
940 pub fn find_repr_attrs(diagnostic: &Handler, attr: &Attribute) -> Vec<ReprAttr> {
941     let mut acc = Vec::new();
942     if attr.path == "repr" {
943         if let Some(items) = attr.meta_item_list() {
944             mark_used(attr);
945             for item in items {
946                 if !item.is_meta_item() {
947                     handle_errors(diagnostic, item.span, AttrError::UnsupportedLiteral);
948                     continue
949                 }
950
951                 let mut recognised = false;
952                 if let Some(mi) = item.word() {
953                     let word = &*mi.name().as_str();
954                     let hint = match word {
955                         // Can't use "extern" because it's not a lexical identifier.
956                         "C" => Some(ReprExtern),
957                         "packed" => Some(ReprPacked),
958                         "simd" => Some(ReprSimd),
959                         _ => match int_type_of_word(word) {
960                             Some(ity) => Some(ReprInt(ity)),
961                             None => {
962                                 None
963                             }
964                         }
965                     };
966
967                     if let Some(h) = hint {
968                         recognised = true;
969                         acc.push(h);
970                     }
971                 } else if let Some((name, value)) = item.name_value_literal() {
972                     if name == "align" {
973                         recognised = true;
974                         let mut align_error = None;
975                         if let ast::LitKind::Int(align, ast::LitIntType::Unsuffixed) = value.node {
976                             if align.is_power_of_two() {
977                                 // rustc::ty::layout::Align restricts align to <= 2147483647
978                                 if align <= 2147483647 {
979                                     acc.push(ReprAlign(align as u32));
980                                 } else {
981                                     align_error = Some("larger than 2147483647");
982                                 }
983                             } else {
984                                 align_error = Some("not a power of two");
985                             }
986                         } else {
987                             align_error = Some("not an unsuffixed integer");
988                         }
989                         if let Some(align_error) = align_error {
990                             span_err!(diagnostic, item.span, E0589,
991                                       "invalid `repr(align)` attribute: {}", align_error);
992                         }
993                     }
994                 }
995                 if !recognised {
996                     // Not a word we recognize
997                     span_err!(diagnostic, item.span, E0552,
998                               "unrecognized representation hint");
999                 }
1000             }
1001         }
1002     }
1003     acc
1004 }
1005
1006 fn int_type_of_word(s: &str) -> Option<IntType> {
1007     match s {
1008         "i8" => Some(SignedInt(ast::IntTy::I8)),
1009         "u8" => Some(UnsignedInt(ast::UintTy::U8)),
1010         "i16" => Some(SignedInt(ast::IntTy::I16)),
1011         "u16" => Some(UnsignedInt(ast::UintTy::U16)),
1012         "i32" => Some(SignedInt(ast::IntTy::I32)),
1013         "u32" => Some(UnsignedInt(ast::UintTy::U32)),
1014         "i64" => Some(SignedInt(ast::IntTy::I64)),
1015         "u64" => Some(UnsignedInt(ast::UintTy::U64)),
1016         "i128" => Some(SignedInt(ast::IntTy::I128)),
1017         "u128" => Some(UnsignedInt(ast::UintTy::U128)),
1018         "isize" => Some(SignedInt(ast::IntTy::Is)),
1019         "usize" => Some(UnsignedInt(ast::UintTy::Us)),
1020         _ => None
1021     }
1022 }
1023
1024 #[derive(PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
1025 pub enum ReprAttr {
1026     ReprInt(IntType),
1027     ReprExtern,
1028     ReprPacked,
1029     ReprSimd,
1030     ReprAlign(u32),
1031 }
1032
1033 #[derive(Eq, Hash, PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
1034 pub enum IntType {
1035     SignedInt(ast::IntTy),
1036     UnsignedInt(ast::UintTy)
1037 }
1038
1039 impl IntType {
1040     #[inline]
1041     pub fn is_signed(self) -> bool {
1042         match self {
1043             SignedInt(..) => true,
1044             UnsignedInt(..) => false
1045         }
1046     }
1047 }
1048
1049 impl MetaItem {
1050     fn tokens(&self) -> TokenStream {
1051         let ident = TokenTree::Token(self.span, Token::Ident(Ident::with_empty_ctxt(self.name)));
1052         TokenStream::concat(vec![ident.into(), self.node.tokens(self.span)])
1053     }
1054
1055     fn from_tokens<I>(tokens: &mut iter::Peekable<I>) -> Option<MetaItem>
1056         where I: Iterator<Item = TokenTree>,
1057     {
1058         let (mut span, name) = match tokens.next() {
1059             Some(TokenTree::Token(span, Token::Ident(ident))) => (span, ident.name),
1060             Some(TokenTree::Token(_, Token::Interpolated(ref nt))) => match nt.0 {
1061                 token::Nonterminal::NtIdent(ident) => (ident.span, ident.node.name),
1062                 token::Nonterminal::NtMeta(ref meta) => return Some(meta.clone()),
1063                 _ => return None,
1064             },
1065             _ => return None,
1066         };
1067         let list_closing_paren_pos = tokens.peek().map(|tt| tt.span().hi);
1068         let node = match MetaItemKind::from_tokens(tokens) {
1069             Some(node) => node,
1070             _ => return None,
1071         };
1072         span.hi = match node {
1073             MetaItemKind::NameValue(ref lit) => lit.span.hi,
1074             MetaItemKind::List(..) => list_closing_paren_pos.unwrap_or(span.hi),
1075             _ => span.hi,
1076         };
1077         Some(MetaItem { name: name, span: span, node: node })
1078     }
1079 }
1080
1081 impl MetaItemKind {
1082     pub fn tokens(&self, span: Span) -> TokenStream {
1083         match *self {
1084             MetaItemKind::Word => TokenStream::empty(),
1085             MetaItemKind::NameValue(ref lit) => {
1086                 TokenStream::concat(vec![TokenTree::Token(span, Token::Eq).into(), lit.tokens()])
1087             }
1088             MetaItemKind::List(ref list) => {
1089                 let mut tokens = Vec::new();
1090                 for (i, item) in list.iter().enumerate() {
1091                     if i > 0 {
1092                         tokens.push(TokenTree::Token(span, Token::Comma).into());
1093                     }
1094                     tokens.push(item.node.tokens());
1095                 }
1096                 TokenTree::Delimited(span, Delimited {
1097                     delim: token::Paren,
1098                     tts: TokenStream::concat(tokens).into(),
1099                 }).into()
1100             }
1101         }
1102     }
1103
1104     fn from_tokens<I>(tokens: &mut iter::Peekable<I>) -> Option<MetaItemKind>
1105         where I: Iterator<Item = TokenTree>,
1106     {
1107         let delimited = match tokens.peek().cloned() {
1108             Some(TokenTree::Token(_, token::Eq)) => {
1109                 tokens.next();
1110                 return if let Some(TokenTree::Token(span, token)) = tokens.next() {
1111                     LitKind::from_token(token)
1112                         .map(|lit| MetaItemKind::NameValue(Spanned { node: lit, span: span }))
1113                 } else {
1114                     None
1115                 };
1116             }
1117             Some(TokenTree::Delimited(_, ref delimited)) if delimited.delim == token::Paren => {
1118                 tokens.next();
1119                 delimited.stream()
1120             }
1121             _ => return Some(MetaItemKind::Word),
1122         };
1123
1124         let mut tokens = delimited.into_trees().peekable();
1125         let mut result = Vec::new();
1126         while let Some(..) = tokens.peek() {
1127             match NestedMetaItemKind::from_tokens(&mut tokens) {
1128                 Some(item) => result.push(respan(item.span(), item)),
1129                 None => return None,
1130             }
1131             match tokens.next() {
1132                 None | Some(TokenTree::Token(_, Token::Comma)) => {}
1133                 _ => return None,
1134             }
1135         }
1136         Some(MetaItemKind::List(result))
1137     }
1138 }
1139
1140 impl NestedMetaItemKind {
1141     fn span(&self) -> Span {
1142         match *self {
1143             NestedMetaItemKind::MetaItem(ref item) => item.span,
1144             NestedMetaItemKind::Literal(ref lit) => lit.span,
1145         }
1146     }
1147
1148     fn tokens(&self) -> TokenStream {
1149         match *self {
1150             NestedMetaItemKind::MetaItem(ref item) => item.tokens(),
1151             NestedMetaItemKind::Literal(ref lit) => lit.tokens(),
1152         }
1153     }
1154
1155     fn from_tokens<I>(tokens: &mut iter::Peekable<I>) -> Option<NestedMetaItemKind>
1156         where I: Iterator<Item = TokenTree>,
1157     {
1158         if let Some(TokenTree::Token(span, token)) = tokens.peek().cloned() {
1159             if let Some(node) = LitKind::from_token(token) {
1160                 tokens.next();
1161                 return Some(NestedMetaItemKind::Literal(respan(span, node)));
1162             }
1163         }
1164
1165         MetaItem::from_tokens(tokens).map(NestedMetaItemKind::MetaItem)
1166     }
1167 }
1168
1169 impl Lit {
1170     fn tokens(&self) -> TokenStream {
1171         TokenTree::Token(self.span, self.node.token()).into()
1172     }
1173 }
1174
1175 impl LitKind {
1176     fn token(&self) -> Token {
1177         use std::ascii;
1178
1179         match *self {
1180             LitKind::Str(string, ast::StrStyle::Cooked) => {
1181                 let mut escaped = String::new();
1182                 for ch in string.as_str().chars() {
1183                     escaped.extend(ch.escape_unicode());
1184                 }
1185                 Token::Literal(token::Lit::Str_(Symbol::intern(&escaped)), None)
1186             }
1187             LitKind::Str(string, ast::StrStyle::Raw(n)) => {
1188                 Token::Literal(token::Lit::StrRaw(string, n), None)
1189             }
1190             LitKind::ByteStr(ref bytes) => {
1191                 let string = bytes.iter().cloned().flat_map(ascii::escape_default)
1192                     .map(Into::<char>::into).collect::<String>();
1193                 Token::Literal(token::Lit::ByteStr(Symbol::intern(&string)), None)
1194             }
1195             LitKind::Byte(byte) => {
1196                 let string: String = ascii::escape_default(byte).map(Into::<char>::into).collect();
1197                 Token::Literal(token::Lit::Byte(Symbol::intern(&string)), None)
1198             }
1199             LitKind::Char(ch) => {
1200                 let string: String = ch.escape_default().map(Into::<char>::into).collect();
1201                 Token::Literal(token::Lit::Char(Symbol::intern(&string)), None)
1202             }
1203             LitKind::Int(n, ty) => {
1204                 let suffix = match ty {
1205                     ast::LitIntType::Unsigned(ty) => Some(Symbol::intern(ty.ty_to_string())),
1206                     ast::LitIntType::Signed(ty) => Some(Symbol::intern(ty.ty_to_string())),
1207                     ast::LitIntType::Unsuffixed => None,
1208                 };
1209                 Token::Literal(token::Lit::Integer(Symbol::intern(&n.to_string())), suffix)
1210             }
1211             LitKind::Float(symbol, ty) => {
1212                 Token::Literal(token::Lit::Float(symbol), Some(Symbol::intern(ty.ty_to_string())))
1213             }
1214             LitKind::FloatUnsuffixed(symbol) => Token::Literal(token::Lit::Float(symbol), None),
1215             LitKind::Bool(value) => Token::Ident(Ident::with_empty_ctxt(Symbol::intern(if value {
1216                 "true"
1217             } else {
1218                 "false"
1219             }))),
1220         }
1221     }
1222
1223     fn from_token(token: Token) -> Option<LitKind> {
1224         match token {
1225             Token::Ident(ident) if ident.name == "true" => Some(LitKind::Bool(true)),
1226             Token::Ident(ident) if ident.name == "false" => Some(LitKind::Bool(false)),
1227             Token::Interpolated(ref nt) => match nt.0 {
1228                 token::NtExpr(ref v) => match v.node {
1229                     ExprKind::Lit(ref lit) => Some(lit.node.clone()),
1230                     _ => None,
1231                 },
1232                 _ => None,
1233             },
1234             Token::Literal(lit, suf) => {
1235                 let (suffix_illegal, result) = parse::lit_token(lit, suf, None);
1236                 if suffix_illegal && suf.is_some() {
1237                     return None;
1238                 }
1239                 result
1240             }
1241             _ => None,
1242         }
1243     }
1244 }
1245
1246 pub trait HasAttrs: Sized {
1247     fn attrs(&self) -> &[ast::Attribute];
1248     fn map_attrs<F: FnOnce(Vec<ast::Attribute>) -> Vec<ast::Attribute>>(self, f: F) -> Self;
1249 }
1250
1251 impl<T: HasAttrs> HasAttrs for Spanned<T> {
1252     fn attrs(&self) -> &[ast::Attribute] { self.node.attrs() }
1253     fn map_attrs<F: FnOnce(Vec<ast::Attribute>) -> Vec<ast::Attribute>>(self, f: F) -> Self {
1254         respan(self.span, self.node.map_attrs(f))
1255     }
1256 }
1257
1258 impl HasAttrs for Vec<Attribute> {
1259     fn attrs(&self) -> &[Attribute] {
1260         self
1261     }
1262     fn map_attrs<F: FnOnce(Vec<Attribute>) -> Vec<Attribute>>(self, f: F) -> Self {
1263         f(self)
1264     }
1265 }
1266
1267 impl HasAttrs for ThinVec<Attribute> {
1268     fn attrs(&self) -> &[Attribute] {
1269         self
1270     }
1271     fn map_attrs<F: FnOnce(Vec<Attribute>) -> Vec<Attribute>>(self, f: F) -> Self {
1272         f(self.into()).into()
1273     }
1274 }
1275
1276 impl<T: HasAttrs + 'static> HasAttrs for P<T> {
1277     fn attrs(&self) -> &[Attribute] {
1278         (**self).attrs()
1279     }
1280     fn map_attrs<F: FnOnce(Vec<Attribute>) -> Vec<Attribute>>(self, f: F) -> Self {
1281         self.map(|t| t.map_attrs(f))
1282     }
1283 }
1284
1285 impl HasAttrs for StmtKind {
1286     fn attrs(&self) -> &[Attribute] {
1287         match *self {
1288             StmtKind::Local(ref local) => local.attrs(),
1289             StmtKind::Item(..) => &[],
1290             StmtKind::Expr(ref expr) | StmtKind::Semi(ref expr) => expr.attrs(),
1291             StmtKind::Mac(ref mac) => {
1292                 let (_, _, ref attrs) = **mac;
1293                 attrs.attrs()
1294             }
1295         }
1296     }
1297
1298     fn map_attrs<F: FnOnce(Vec<Attribute>) -> Vec<Attribute>>(self, f: F) -> Self {
1299         match self {
1300             StmtKind::Local(local) => StmtKind::Local(local.map_attrs(f)),
1301             StmtKind::Item(..) => self,
1302             StmtKind::Expr(expr) => StmtKind::Expr(expr.map_attrs(f)),
1303             StmtKind::Semi(expr) => StmtKind::Semi(expr.map_attrs(f)),
1304             StmtKind::Mac(mac) => StmtKind::Mac(mac.map(|(mac, style, attrs)| {
1305                 (mac, style, attrs.map_attrs(f))
1306             })),
1307         }
1308     }
1309 }
1310
1311 impl HasAttrs for Stmt {
1312     fn attrs(&self) -> &[ast::Attribute] { self.node.attrs() }
1313     fn map_attrs<F: FnOnce(Vec<ast::Attribute>) -> Vec<ast::Attribute>>(self, f: F) -> Self {
1314         Stmt { id: self.id, node: self.node.map_attrs(f), span: self.span }
1315     }
1316 }
1317
1318 macro_rules! derive_has_attrs {
1319     ($($ty:path),*) => { $(
1320         impl HasAttrs for $ty {
1321             fn attrs(&self) -> &[Attribute] {
1322                 &self.attrs
1323             }
1324
1325             fn map_attrs<F>(mut self, f: F) -> Self
1326                 where F: FnOnce(Vec<Attribute>) -> Vec<Attribute>,
1327             {
1328                 self.attrs = self.attrs.map_attrs(f);
1329                 self
1330             }
1331         }
1332     )* }
1333 }
1334
1335 derive_has_attrs! {
1336     Item, Expr, Local, ast::ForeignItem, ast::StructField, ast::ImplItem, ast::TraitItem, ast::Arm,
1337     ast::Field, ast::FieldPat, ast::Variant_
1338 }