]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/attr.rs
Auto merge of #35856 - phimuemue:master, r=brson
[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, Attribute_};
19 use ast::{MetaItem, MetaItemKind, NestedMetaItem, NestedMetaItemKind};
20 use ast::{Lit, Expr, Item, Local, Stmt, StmtKind};
21 use codemap::{respan, spanned, dummy_spanned};
22 use syntax_pos::{Span, BytePos, 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::token::InternedString;
27 use parse::{ParseSess, token};
28 use ptr::P;
29 use util::ThinVec;
30
31 use std::cell::{RefCell, Cell};
32 use std::collections::HashSet;
33
34 thread_local! {
35     static USED_ATTRS: RefCell<Vec<u64>> = RefCell::new(Vec::new())
36 }
37
38 enum AttrError {
39     MultipleItem(InternedString),
40     UnknownMetaItem(InternedString),
41     MissingSince,
42     MissingFeature,
43     MultipleStabilityLevels,
44     UnsupportedLiteral
45 }
46
47 fn handle_errors(diag: &Handler, span: Span, error: AttrError) {
48     match error {
49         AttrError::MultipleItem(item) => span_err!(diag, span, E0538,
50                                                    "multiple '{}' items", item),
51         AttrError::UnknownMetaItem(item) => span_err!(diag, span, E0541,
52                                                       "unknown meta item '{}'", item),
53         AttrError::MissingSince => span_err!(diag, span, E0542, "missing 'since'"),
54         AttrError::MissingFeature => span_err!(diag, span, E0546, "missing 'feature'"),
55         AttrError::MultipleStabilityLevels => span_err!(diag, span, E0544,
56                                                         "multiple stability levels"),
57         AttrError::UnsupportedLiteral => span_err!(diag, span, E0565, "unsupported literal"),
58     }
59 }
60
61 pub fn mark_used(attr: &Attribute) {
62     debug!("Marking {:?} as used.", attr);
63     let AttrId(id) = attr.node.id;
64     USED_ATTRS.with(|slot| {
65         let idx = (id / 64) as usize;
66         let shift = id % 64;
67         if slot.borrow().len() <= idx {
68             slot.borrow_mut().resize(idx + 1, 0);
69         }
70         slot.borrow_mut()[idx] |= 1 << shift;
71     });
72 }
73
74 pub fn is_used(attr: &Attribute) -> bool {
75     let AttrId(id) = attr.node.id;
76     USED_ATTRS.with(|slot| {
77         let idx = (id / 64) as usize;
78         let shift = id % 64;
79         slot.borrow().get(idx).map(|bits| bits & (1 << shift) != 0)
80             .unwrap_or(false)
81     })
82 }
83
84 impl NestedMetaItem {
85     /// Returns the MetaItem if self is a NestedMetaItemKind::MetaItem.
86     pub fn meta_item(&self) -> Option<&P<MetaItem>> {
87         match self.node {
88             NestedMetaItemKind::MetaItem(ref item) => Some(&item),
89             _ => None
90         }
91     }
92
93     /// Returns the Lit if self is a NestedMetaItemKind::Literal.
94     pub fn literal(&self) -> Option<&Lit> {
95         match self.node {
96             NestedMetaItemKind::Literal(ref lit) => Some(&lit),
97             _ => None
98         }
99     }
100
101     /// Returns the Span for `self`.
102     pub fn span(&self) -> Span {
103         self.span
104     }
105
106     /// Returns true if this list item is a MetaItem with a name of `name`.
107     pub fn check_name(&self, name: &str) -> bool {
108         self.meta_item().map_or(false, |meta_item| meta_item.check_name(name))
109     }
110
111     /// Returns the name of the meta item, e.g. `foo` in `#[foo]`,
112     /// `#[foo="bar"]` and `#[foo(bar)]`, if self is a MetaItem
113     pub fn name(&self) -> Option<InternedString> {
114         self.meta_item().and_then(|meta_item| Some(meta_item.name()))
115     }
116
117     /// Gets the string value if self is a MetaItem and the MetaItem is a
118     /// MetaItemKind::NameValue variant containing a string, otherwise None.
119     pub fn value_str(&self) -> Option<InternedString> {
120         self.meta_item().and_then(|meta_item| meta_item.value_str())
121     }
122
123     /// Returns a MetaItem if self is a MetaItem with Kind Word.
124     pub fn word(&self) -> Option<&P<MetaItem>> {
125         self.meta_item().and_then(|meta_item| if meta_item.is_word() {
126             Some(meta_item)
127         } else {
128             None
129         })
130     }
131
132     /// Gets a list of inner meta items from a list MetaItem type.
133     pub fn meta_item_list(&self) -> Option<&[NestedMetaItem]> {
134         self.meta_item().and_then(|meta_item| meta_item.meta_item_list())
135     }
136
137     /// Returns `true` if the variant is MetaItem.
138     pub fn is_meta_item(&self) -> bool {
139         self.meta_item().is_some()
140     }
141
142     /// Returns `true` if the variant is Literal.
143     pub fn is_literal(&self) -> bool {
144         self.literal().is_some()
145     }
146
147     /// Returns `true` if self is a MetaItem and the meta item is a word.
148     pub fn is_word(&self) -> bool {
149         self.word().is_some()
150     }
151
152     /// Returns `true` if self is a MetaItem and the meta item is a ValueString.
153     pub fn is_value_str(&self) -> bool {
154         self.value_str().is_some()
155     }
156
157     /// Returns `true` if self is a MetaItem and the meta item is a list.
158     pub fn is_meta_item_list(&self) -> bool {
159         self.meta_item_list().is_some()
160     }
161 }
162
163 impl Attribute {
164     pub fn check_name(&self, name: &str) -> bool {
165         let matches = name == &self.name()[..];
166         if matches {
167             mark_used(self);
168         }
169         matches
170     }
171
172     pub fn name(&self) -> InternedString { self.meta().name() }
173
174     pub fn value_str(&self) -> Option<InternedString> {
175         self.meta().value_str()
176     }
177
178     pub fn meta_item_list(&self) -> Option<&[NestedMetaItem]> {
179         self.meta().meta_item_list()
180     }
181
182     pub fn is_word(&self) -> bool { self.meta().is_word() }
183
184     pub fn span(&self) -> Span { self.meta().span }
185
186     pub fn is_meta_item_list(&self) -> bool {
187         self.meta_item_list().is_some()
188     }
189
190     /// Indicates if the attribute is a Value String.
191     pub fn is_value_str(&self) -> bool {
192         self.value_str().is_some()
193     }
194 }
195
196 impl MetaItem {
197     pub fn name(&self) -> InternedString {
198         match self.node {
199             MetaItemKind::Word(ref n) => (*n).clone(),
200             MetaItemKind::NameValue(ref n, _) => (*n).clone(),
201             MetaItemKind::List(ref n, _) => (*n).clone(),
202         }
203     }
204
205     pub fn value_str(&self) -> Option<InternedString> {
206         match self.node {
207             MetaItemKind::NameValue(_, ref v) => {
208                 match v.node {
209                     ast::LitKind::Str(ref s, _) => Some((*s).clone()),
210                     _ => None,
211                 }
212             },
213             _ => None
214         }
215     }
216
217     pub fn meta_item_list(&self) -> Option<&[NestedMetaItem]> {
218         match self.node {
219             MetaItemKind::List(_, ref l) => Some(&l[..]),
220             _ => None
221         }
222     }
223
224     pub fn is_word(&self) -> bool {
225         match self.node {
226             MetaItemKind::Word(_) => true,
227             _ => false,
228         }
229     }
230
231     pub fn span(&self) -> Span { self.span }
232
233     pub fn check_name(&self, name: &str) -> bool {
234         name == &self.name()[..]
235     }
236
237     pub fn is_value_str(&self) -> bool {
238         self.value_str().is_some()
239     }
240
241     pub fn is_meta_item_list(&self) -> bool {
242         self.meta_item_list().is_some()
243     }
244 }
245
246 impl Attribute {
247     /// Extract the MetaItem from inside this Attribute.
248     pub fn meta(&self) -> &MetaItem {
249         &self.node.value
250     }
251
252     /// Convert self to a normal #[doc="foo"] comment, if it is a
253     /// comment like `///` or `/** */`. (Returns self unchanged for
254     /// non-sugared doc attributes.)
255     pub fn with_desugared_doc<T, F>(&self, f: F) -> T where
256         F: FnOnce(&Attribute) -> T,
257     {
258         if self.node.is_sugared_doc {
259             let comment = self.value_str().unwrap();
260             let meta = mk_name_value_item_str(
261                 InternedString::new("doc"),
262                 token::intern_and_get_ident(&strip_doc_comment_decoration(
263                         &comment)));
264             if self.node.style == ast::AttrStyle::Outer {
265                 f(&mk_attr_outer(self.node.id, meta))
266             } else {
267                 f(&mk_attr_inner(self.node.id, meta))
268             }
269         } else {
270             f(self)
271         }
272     }
273 }
274
275 /* Constructors */
276
277 pub fn mk_name_value_item_str(name: InternedString, value: InternedString)
278                               -> P<MetaItem> {
279     let value_lit = dummy_spanned(ast::LitKind::Str(value, ast::StrStyle::Cooked));
280     mk_spanned_name_value_item(DUMMY_SP, name, value_lit)
281 }
282
283 pub fn mk_name_value_item(name: InternedString, value: ast::Lit)
284                           -> P<MetaItem> {
285     mk_spanned_name_value_item(DUMMY_SP, name, value)
286 }
287
288 pub fn mk_list_item(name: InternedString, items: Vec<NestedMetaItem>) -> P<MetaItem> {
289     mk_spanned_list_item(DUMMY_SP, name, items)
290 }
291
292 pub fn mk_list_word_item(name: InternedString) -> ast::NestedMetaItem {
293     dummy_spanned(NestedMetaItemKind::MetaItem(mk_spanned_word_item(DUMMY_SP, name)))
294 }
295
296 pub fn mk_word_item(name: InternedString) -> P<MetaItem> {
297     mk_spanned_word_item(DUMMY_SP, name)
298 }
299
300 pub fn mk_spanned_name_value_item(sp: Span, name: InternedString, value: ast::Lit)
301                           -> P<MetaItem> {
302     P(respan(sp, MetaItemKind::NameValue(name, value)))
303 }
304
305 pub fn mk_spanned_list_item(sp: Span, name: InternedString, items: Vec<NestedMetaItem>)
306                             -> P<MetaItem> {
307     P(respan(sp, MetaItemKind::List(name, items)))
308 }
309
310 pub fn mk_spanned_word_item(sp: Span, name: InternedString) -> P<MetaItem> {
311     P(respan(sp, MetaItemKind::Word(name)))
312 }
313
314
315
316 thread_local! { static NEXT_ATTR_ID: Cell<usize> = Cell::new(0) }
317
318 pub fn mk_attr_id() -> AttrId {
319     let id = NEXT_ATTR_ID.with(|slot| {
320         let r = slot.get();
321         slot.set(r + 1);
322         r
323     });
324     AttrId(id)
325 }
326
327 /// Returns an inner attribute with the given value.
328 pub fn mk_attr_inner(id: AttrId, item: P<MetaItem>) -> Attribute {
329     mk_spanned_attr_inner(DUMMY_SP, id, item)
330 }
331
332 /// Returns an innter attribute with the given value and span.
333 pub fn mk_spanned_attr_inner(sp: Span, id: AttrId, item: P<MetaItem>) -> Attribute {
334     respan(sp,
335            Attribute_ {
336             id: id,
337             style: ast::AttrStyle::Inner,
338             value: item,
339             is_sugared_doc: false,
340           })
341 }
342
343
344 /// Returns an outer attribute with the given value.
345 pub fn mk_attr_outer(id: AttrId, item: P<MetaItem>) -> Attribute {
346     mk_spanned_attr_outer(DUMMY_SP, id, item)
347 }
348
349 /// Returns an outer attribute with the given value and span.
350 pub fn mk_spanned_attr_outer(sp: Span, id: AttrId, item: P<MetaItem>) -> Attribute {
351     respan(sp,
352            Attribute_ {
353             id: id,
354             style: ast::AttrStyle::Outer,
355             value: item,
356             is_sugared_doc: false,
357           })
358 }
359
360 pub fn mk_doc_attr_outer(id: AttrId, item: P<MetaItem>, is_sugared_doc: bool) -> Attribute {
361     dummy_spanned(Attribute_ {
362         id: id,
363         style: ast::AttrStyle::Outer,
364         value: item,
365         is_sugared_doc: is_sugared_doc,
366     })
367 }
368
369 pub fn mk_sugared_doc_attr(id: AttrId, text: InternedString, lo: BytePos,
370                            hi: BytePos)
371                            -> Attribute {
372     let style = doc_comment_style(&text);
373     let lit = spanned(lo, hi, ast::LitKind::Str(text, ast::StrStyle::Cooked));
374     let attr = Attribute_ {
375         id: id,
376         style: style,
377         value: P(spanned(lo, hi, MetaItemKind::NameValue(InternedString::new("doc"), lit))),
378         is_sugared_doc: true
379     };
380     spanned(lo, hi, attr)
381 }
382
383 /* Searching */
384 /// Check if `needle` occurs in `haystack` by a structural
385 /// comparison. This is slightly subtle, and relies on ignoring the
386 /// span included in the `==` comparison a plain MetaItem.
387 pub fn contains(haystack: &[P<MetaItem>], needle: &MetaItem) -> bool {
388     debug!("attr::contains (name={})", needle.name());
389     haystack.iter().any(|item| {
390         debug!("  testing: {}", item.name());
391         item.node == needle.node
392     })
393 }
394
395 pub fn list_contains_name(items: &[NestedMetaItem], name: &str) -> bool {
396     debug!("attr::list_contains_name (name={})", name);
397     items.iter().any(|item| {
398         debug!("  testing: {:?}", item.name());
399         item.check_name(name)
400     })
401 }
402
403 pub fn contains_name(attrs: &[Attribute], name: &str) -> bool {
404     debug!("attr::contains_name (name={})", name);
405     attrs.iter().any(|item| {
406         debug!("  testing: {}", item.name());
407         item.check_name(name)
408     })
409 }
410
411 pub fn first_attr_value_str_by_name(attrs: &[Attribute], name: &str)
412                                  -> Option<InternedString> {
413     attrs.iter()
414         .find(|at| at.check_name(name))
415         .and_then(|at| at.value_str())
416 }
417
418 pub fn last_meta_item_value_str_by_name(items: &[P<MetaItem>], name: &str)
419                                      -> Option<InternedString> {
420     items.iter()
421          .rev()
422          .find(|mi| mi.check_name(name))
423          .and_then(|i| i.value_str())
424 }
425
426 /* Higher-level applications */
427
428 pub fn find_crate_name(attrs: &[Attribute]) -> Option<InternedString> {
429     first_attr_value_str_by_name(attrs, "crate_name")
430 }
431
432 /// Find the value of #[export_name=*] attribute and check its validity.
433 pub fn find_export_name_attr(diag: &Handler, attrs: &[Attribute]) -> Option<InternedString> {
434     attrs.iter().fold(None, |ia,attr| {
435         if attr.check_name("export_name") {
436             if let s@Some(_) = attr.value_str() {
437                 s
438             } else {
439                 struct_span_err!(diag, attr.span, E0558,
440                                  "export_name attribute has invalid format")
441                     .span_label(attr.span,
442                                 &format!("did you mean #[export_name=\"*\"]?"))
443                     .emit();
444                 None
445             }
446         } else {
447             ia
448         }
449     })
450 }
451
452 pub fn contains_extern_indicator(diag: &Handler, attrs: &[Attribute]) -> bool {
453     contains_name(attrs, "no_mangle") ||
454         find_export_name_attr(diag, attrs).is_some()
455 }
456
457 #[derive(Copy, Clone, PartialEq)]
458 pub enum InlineAttr {
459     None,
460     Hint,
461     Always,
462     Never,
463 }
464
465 /// Determine what `#[inline]` attribute is present in `attrs`, if any.
466 pub fn find_inline_attr(diagnostic: Option<&Handler>, attrs: &[Attribute]) -> InlineAttr {
467     attrs.iter().fold(InlineAttr::None, |ia,attr| {
468         match attr.node.value.node {
469             MetaItemKind::Word(ref n) if n == "inline" => {
470                 mark_used(attr);
471                 InlineAttr::Hint
472             }
473             MetaItemKind::List(ref n, ref items) if n == "inline" => {
474                 mark_used(attr);
475                 if items.len() != 1 {
476                     diagnostic.map(|d|{ span_err!(d, attr.span, E0534, "expected one argument"); });
477                     InlineAttr::None
478                 } else if list_contains_name(&items[..], "always") {
479                     InlineAttr::Always
480                 } else if list_contains_name(&items[..], "never") {
481                     InlineAttr::Never
482                 } else {
483                     diagnostic.map(|d| {
484                         span_err!(d, items[0].span, E0535, "invalid argument");
485                     });
486
487                     InlineAttr::None
488                 }
489             }
490             _ => ia,
491         }
492     })
493 }
494
495 /// True if `#[inline]` or `#[inline(always)]` is present in `attrs`.
496 pub fn requests_inline(attrs: &[Attribute]) -> bool {
497     match find_inline_attr(None, attrs) {
498         InlineAttr::Hint | InlineAttr::Always => true,
499         InlineAttr::None | InlineAttr::Never => false,
500     }
501 }
502
503 /// Tests if a cfg-pattern matches the cfg set
504 pub fn cfg_matches(cfgs: &[P<MetaItem>], cfg: &ast::MetaItem,
505                    sess: &ParseSess,
506                    features: Option<&Features>)
507                    -> bool {
508     match cfg.node {
509         ast::MetaItemKind::List(ref pred, ref mis) => {
510             for mi in mis.iter() {
511                 if !mi.is_meta_item() {
512                     handle_errors(&sess.span_diagnostic, mi.span, AttrError::UnsupportedLiteral);
513                     return false;
514                 }
515             }
516
517             // The unwraps below may look dangerous, but we've already asserted
518             // that they won't fail with the loop above.
519             match &pred[..] {
520                 "any" => mis.iter().any(|mi| {
521                     cfg_matches(cfgs, mi.meta_item().unwrap(), sess, features)
522                 }),
523                 "all" => mis.iter().all(|mi| {
524                     cfg_matches(cfgs, mi.meta_item().unwrap(), sess, features)
525                 }),
526                 "not" => {
527                     if mis.len() != 1 {
528                         span_err!(sess.span_diagnostic, cfg.span, E0536, "expected 1 cfg-pattern");
529                         return false;
530                     }
531
532                     !cfg_matches(cfgs, mis[0].meta_item().unwrap(), sess, features)
533                 },
534                 p => {
535                     span_err!(sess.span_diagnostic, cfg.span, E0537, "invalid predicate `{}`", p);
536                     false
537                 }
538             }
539         },
540         ast::MetaItemKind::Word(_) | ast::MetaItemKind::NameValue(..) => {
541             if let (Some(feats), Some(gated_cfg)) = (features, GatedCfg::gate(cfg)) {
542                 gated_cfg.check_and_emit(sess, feats);
543             }
544             contains(cfgs, cfg)
545         }
546     }
547 }
548
549 /// Represents the #[stable], #[unstable] and #[rustc_deprecated] attributes.
550 #[derive(RustcEncodable, RustcDecodable, Clone, Debug, PartialEq, Eq, Hash)]
551 pub struct Stability {
552     pub level: StabilityLevel,
553     pub feature: InternedString,
554     pub rustc_depr: Option<RustcDeprecation>,
555 }
556
557 /// The available stability levels.
558 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Debug, Eq, Hash)]
559 pub enum StabilityLevel {
560     // Reason for the current stability level and the relevant rust-lang issue
561     Unstable { reason: Option<InternedString>, issue: u32 },
562     Stable { since: InternedString },
563 }
564
565 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Debug, Eq, Hash)]
566 pub struct RustcDeprecation {
567     pub since: InternedString,
568     pub reason: InternedString,
569 }
570
571 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Debug, Eq, Hash)]
572 pub struct Deprecation {
573     pub since: Option<InternedString>,
574     pub note: Option<InternedString>,
575 }
576
577 impl StabilityLevel {
578     pub fn is_unstable(&self) -> bool { if let Unstable {..} = *self { true } else { false }}
579     pub fn is_stable(&self) -> bool { if let Stable {..} = *self { true } else { false }}
580 }
581
582 fn find_stability_generic<'a, I>(diagnostic: &Handler,
583                                  attrs_iter: I,
584                                  item_sp: Span)
585                                  -> Option<Stability>
586     where I: Iterator<Item = &'a Attribute>
587 {
588     let mut stab: Option<Stability> = None;
589     let mut rustc_depr: Option<RustcDeprecation> = None;
590
591     'outer: for attr in attrs_iter {
592         let tag = attr.name();
593         let tag = &*tag;
594         if tag != "rustc_deprecated" && tag != "unstable" && tag != "stable" {
595             continue // not a stability level
596         }
597
598         mark_used(attr);
599
600         if let Some(metas) = attr.meta_item_list() {
601             let get = |meta: &MetaItem, item: &mut Option<InternedString>| {
602                 if item.is_some() {
603                     handle_errors(diagnostic, meta.span, AttrError::MultipleItem(meta.name()));
604                     return false
605                 }
606                 if let Some(v) = meta.value_str() {
607                     *item = Some(v);
608                     true
609                 } else {
610                     span_err!(diagnostic, meta.span, E0539, "incorrect meta item");
611                     false
612                 }
613             };
614
615             match tag {
616                 "rustc_deprecated" => {
617                     if rustc_depr.is_some() {
618                         span_err!(diagnostic, item_sp, E0540,
619                                   "multiple rustc_deprecated attributes");
620                         break
621                     }
622
623                     let mut since = None;
624                     let mut reason = None;
625                     for meta in metas {
626                         if let Some(mi) = meta.meta_item() {
627                             match &*mi.name() {
628                                 "since" => if !get(mi, &mut since) { continue 'outer },
629                                 "reason" => if !get(mi, &mut reason) { continue 'outer },
630                                 _ => {
631                                     handle_errors(diagnostic, mi.span,
632                                                   AttrError::UnknownMetaItem(mi.name()));
633                                     continue 'outer
634                                 }
635                             }
636                         } else {
637                             handle_errors(diagnostic, meta.span, AttrError::UnsupportedLiteral);
638                             continue 'outer
639                         }
640                     }
641
642                     match (since, reason) {
643                         (Some(since), Some(reason)) => {
644                             rustc_depr = Some(RustcDeprecation {
645                                 since: since,
646                                 reason: reason,
647                             })
648                         }
649                         (None, _) => {
650                             handle_errors(diagnostic, attr.span(), AttrError::MissingSince);
651                             continue
652                         }
653                         _ => {
654                             span_err!(diagnostic, attr.span(), E0543, "missing 'reason'");
655                             continue
656                         }
657                     }
658                 }
659                 "unstable" => {
660                     if stab.is_some() {
661                         handle_errors(diagnostic, attr.span(), AttrError::MultipleStabilityLevels);
662                         break
663                     }
664
665                     let mut feature = None;
666                     let mut reason = None;
667                     let mut issue = None;
668                     for meta in metas {
669                         if let Some(mi) = meta.meta_item() {
670                             match &*mi.name() {
671                                 "feature" => if !get(mi, &mut feature) { continue 'outer },
672                                 "reason" => if !get(mi, &mut reason) { continue 'outer },
673                                 "issue" => if !get(mi, &mut issue) { continue 'outer },
674                                 _ => {
675                                     handle_errors(diagnostic, meta.span,
676                                                   AttrError::UnknownMetaItem(mi.name()));
677                                     continue 'outer
678                                 }
679                             }
680                         } else {
681                             handle_errors(diagnostic, meta.span, AttrError::UnsupportedLiteral);
682                             continue 'outer
683                         }
684                     }
685
686                     match (feature, reason, issue) {
687                         (Some(feature), reason, Some(issue)) => {
688                             stab = Some(Stability {
689                                 level: Unstable {
690                                     reason: reason,
691                                     issue: {
692                                         if let Ok(issue) = issue.parse() {
693                                             issue
694                                         } else {
695                                             span_err!(diagnostic, attr.span(), E0545,
696                                                       "incorrect 'issue'");
697                                             continue
698                                         }
699                                     }
700                                 },
701                                 feature: feature,
702                                 rustc_depr: None,
703                             })
704                         }
705                         (None, _, _) => {
706                             handle_errors(diagnostic, attr.span(), AttrError::MissingFeature);
707                             continue
708                         }
709                         _ => {
710                             span_err!(diagnostic, attr.span(), E0547, "missing 'issue'");
711                             continue
712                         }
713                     }
714                 }
715                 "stable" => {
716                     if stab.is_some() {
717                         handle_errors(diagnostic, attr.span(), AttrError::MultipleStabilityLevels);
718                         break
719                     }
720
721                     let mut feature = None;
722                     let mut since = None;
723                     for meta in metas {
724                         if let NestedMetaItemKind::MetaItem(ref mi) = meta.node {
725                             match &*mi.name() {
726                                 "feature" => if !get(mi, &mut feature) { continue 'outer },
727                                 "since" => if !get(mi, &mut since) { continue 'outer },
728                                 _ => {
729                                     handle_errors(diagnostic, meta.span,
730                                                   AttrError::UnknownMetaItem(mi.name()));
731                                     continue 'outer
732                                 }
733                             }
734                         } else {
735                             handle_errors(diagnostic, meta.span, AttrError::UnsupportedLiteral);
736                             continue 'outer
737                         }
738                     }
739
740                     match (feature, since) {
741                         (Some(feature), Some(since)) => {
742                             stab = Some(Stability {
743                                 level: Stable {
744                                     since: since,
745                                 },
746                                 feature: feature,
747                                 rustc_depr: None,
748                             })
749                         }
750                         (None, _) => {
751                             handle_errors(diagnostic, attr.span(), AttrError::MissingFeature);
752                             continue
753                         }
754                         _ => {
755                             handle_errors(diagnostic, attr.span(), AttrError::MissingSince);
756                             continue
757                         }
758                     }
759                 }
760                 _ => unreachable!()
761             }
762         } else {
763             span_err!(diagnostic, attr.span(), E0548, "incorrect stability attribute type");
764             continue
765         }
766     }
767
768     // Merge the deprecation info into the stability info
769     if let Some(rustc_depr) = rustc_depr {
770         if let Some(ref mut stab) = stab {
771             if let Unstable {reason: ref mut reason @ None, ..} = stab.level {
772                 *reason = Some(rustc_depr.reason.clone())
773             }
774             stab.rustc_depr = Some(rustc_depr);
775         } else {
776             span_err!(diagnostic, item_sp, E0549,
777                       "rustc_deprecated attribute must be paired with \
778                        either stable or unstable attribute");
779         }
780     }
781
782     stab
783 }
784
785 fn find_deprecation_generic<'a, I>(diagnostic: &Handler,
786                                    attrs_iter: I,
787                                    item_sp: Span)
788                                    -> Option<Deprecation>
789     where I: Iterator<Item = &'a Attribute>
790 {
791     let mut depr: Option<Deprecation> = None;
792
793     'outer: for attr in attrs_iter {
794         if attr.name() != "deprecated" {
795             continue
796         }
797
798         mark_used(attr);
799
800         if depr.is_some() {
801             span_err!(diagnostic, item_sp, E0550, "multiple deprecated attributes");
802             break
803         }
804
805         depr = if let Some(metas) = attr.meta_item_list() {
806             let get = |meta: &MetaItem, item: &mut Option<InternedString>| {
807                 if item.is_some() {
808                     handle_errors(diagnostic, meta.span, AttrError::MultipleItem(meta.name()));
809                     return false
810                 }
811                 if let Some(v) = meta.value_str() {
812                     *item = Some(v);
813                     true
814                 } else {
815                     span_err!(diagnostic, meta.span, E0551, "incorrect meta item");
816                     false
817                 }
818             };
819
820             let mut since = None;
821             let mut note = None;
822             for meta in metas {
823                 if let NestedMetaItemKind::MetaItem(ref mi) = meta.node {
824                     match &*mi.name() {
825                         "since" => if !get(mi, &mut since) { continue 'outer },
826                         "note" => if !get(mi, &mut note) { continue 'outer },
827                         _ => {
828                             handle_errors(diagnostic, meta.span,
829                                           AttrError::UnknownMetaItem(mi.name()));
830                             continue 'outer
831                         }
832                     }
833                 } else {
834                     handle_errors(diagnostic, meta.span, AttrError::UnsupportedLiteral);
835                     continue 'outer
836                 }
837             }
838
839             Some(Deprecation {since: since, note: note})
840         } else {
841             Some(Deprecation{since: None, note: None})
842         }
843     }
844
845     depr
846 }
847
848 /// Find the first stability attribute. `None` if none exists.
849 pub fn find_stability(diagnostic: &Handler, attrs: &[Attribute],
850                       item_sp: Span) -> Option<Stability> {
851     find_stability_generic(diagnostic, attrs.iter(), item_sp)
852 }
853
854 /// Find the deprecation attribute. `None` if none exists.
855 pub fn find_deprecation(diagnostic: &Handler, attrs: &[Attribute],
856                         item_sp: Span) -> Option<Deprecation> {
857     find_deprecation_generic(diagnostic, attrs.iter(), item_sp)
858 }
859
860 pub fn require_unique_names(diagnostic: &Handler, metas: &[P<MetaItem>]) {
861     let mut set = HashSet::new();
862     for meta in metas {
863         let name = meta.name();
864
865         if !set.insert(name.clone()) {
866             panic!(diagnostic.span_fatal(meta.span,
867                                          &format!("duplicate meta item `{}`", name)));
868         }
869     }
870 }
871
872
873 /// Parse #[repr(...)] forms.
874 ///
875 /// Valid repr contents: any of the primitive integral type names (see
876 /// `int_type_of_word`, below) to specify enum discriminant type; `C`, to use
877 /// the same discriminant size that the corresponding C enum would or C
878 /// structure layout, and `packed` to remove padding.
879 pub fn find_repr_attrs(diagnostic: &Handler, attr: &Attribute) -> Vec<ReprAttr> {
880     let mut acc = Vec::new();
881     match attr.node.value.node {
882         ast::MetaItemKind::List(ref s, ref items) if s == "repr" => {
883             mark_used(attr);
884             for item in items {
885                 if !item.is_meta_item() {
886                     handle_errors(diagnostic, item.span, AttrError::UnsupportedLiteral);
887                     continue
888                 }
889
890                 if let Some(mi) = item.word() {
891                     let word = &*mi.name();
892                     let hint = match word {
893                         // Can't use "extern" because it's not a lexical identifier.
894                         "C" => Some(ReprExtern),
895                         "packed" => Some(ReprPacked),
896                         "simd" => Some(ReprSimd),
897                         _ => match int_type_of_word(word) {
898                             Some(ity) => Some(ReprInt(item.span, ity)),
899                             None => {
900                                 // Not a word we recognize
901                                 span_err!(diagnostic, item.span, E0552,
902                                           "unrecognized representation hint");
903                                 None
904                             }
905                         }
906                     };
907
908                     if let Some(h) = hint {
909                         acc.push(h);
910                     }
911                 } else {
912                     span_err!(diagnostic, item.span, E0553,
913                               "unrecognized enum representation hint");
914                 }
915             }
916         }
917         // Not a "repr" hint: ignore.
918         _ => { }
919     }
920     acc
921 }
922
923 fn int_type_of_word(s: &str) -> Option<IntType> {
924     match s {
925         "i8" => Some(SignedInt(ast::IntTy::I8)),
926         "u8" => Some(UnsignedInt(ast::UintTy::U8)),
927         "i16" => Some(SignedInt(ast::IntTy::I16)),
928         "u16" => Some(UnsignedInt(ast::UintTy::U16)),
929         "i32" => Some(SignedInt(ast::IntTy::I32)),
930         "u32" => Some(UnsignedInt(ast::UintTy::U32)),
931         "i64" => Some(SignedInt(ast::IntTy::I64)),
932         "u64" => Some(UnsignedInt(ast::UintTy::U64)),
933         "isize" => Some(SignedInt(ast::IntTy::Is)),
934         "usize" => Some(UnsignedInt(ast::UintTy::Us)),
935         _ => None
936     }
937 }
938
939 #[derive(PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
940 pub enum ReprAttr {
941     ReprAny,
942     ReprInt(Span, IntType),
943     ReprExtern,
944     ReprPacked,
945     ReprSimd,
946 }
947
948 impl ReprAttr {
949     pub fn is_ffi_safe(&self) -> bool {
950         match *self {
951             ReprAny => false,
952             ReprInt(_sp, ity) => ity.is_ffi_safe(),
953             ReprExtern => true,
954             ReprPacked => false,
955             ReprSimd => true,
956         }
957     }
958 }
959
960 #[derive(Eq, Hash, PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
961 pub enum IntType {
962     SignedInt(ast::IntTy),
963     UnsignedInt(ast::UintTy)
964 }
965
966 impl IntType {
967     #[inline]
968     pub fn is_signed(self) -> bool {
969         match self {
970             SignedInt(..) => true,
971             UnsignedInt(..) => false
972         }
973     }
974     fn is_ffi_safe(self) -> bool {
975         match self {
976             SignedInt(ast::IntTy::I8) | UnsignedInt(ast::UintTy::U8) |
977             SignedInt(ast::IntTy::I16) | UnsignedInt(ast::UintTy::U16) |
978             SignedInt(ast::IntTy::I32) | UnsignedInt(ast::UintTy::U32) |
979             SignedInt(ast::IntTy::I64) | UnsignedInt(ast::UintTy::U64) => true,
980             SignedInt(ast::IntTy::Is) | UnsignedInt(ast::UintTy::Us) => false
981         }
982     }
983 }
984
985 pub trait HasAttrs: Sized {
986     fn attrs(&self) -> &[ast::Attribute];
987     fn map_attrs<F: FnOnce(Vec<ast::Attribute>) -> Vec<ast::Attribute>>(self, f: F) -> Self;
988 }
989
990 impl HasAttrs for Vec<Attribute> {
991     fn attrs(&self) -> &[Attribute] {
992         &self
993     }
994     fn map_attrs<F: FnOnce(Vec<Attribute>) -> Vec<Attribute>>(self, f: F) -> Self {
995         f(self)
996     }
997 }
998
999 impl HasAttrs for ThinVec<Attribute> {
1000     fn attrs(&self) -> &[Attribute] {
1001         &self
1002     }
1003     fn map_attrs<F: FnOnce(Vec<Attribute>) -> Vec<Attribute>>(self, f: F) -> Self {
1004         f(self.into()).into()
1005     }
1006 }
1007
1008 impl<T: HasAttrs + 'static> HasAttrs for P<T> {
1009     fn attrs(&self) -> &[Attribute] {
1010         (**self).attrs()
1011     }
1012     fn map_attrs<F: FnOnce(Vec<Attribute>) -> Vec<Attribute>>(self, f: F) -> Self {
1013         self.map(|t| t.map_attrs(f))
1014     }
1015 }
1016
1017 impl HasAttrs for StmtKind {
1018     fn attrs(&self) -> &[Attribute] {
1019         match *self {
1020             StmtKind::Local(ref local) => local.attrs(),
1021             StmtKind::Item(..) => &[],
1022             StmtKind::Expr(ref expr) | StmtKind::Semi(ref expr) => expr.attrs(),
1023             StmtKind::Mac(ref mac) => {
1024                 let (_, _, ref attrs) = **mac;
1025                 attrs.attrs()
1026             }
1027         }
1028     }
1029
1030     fn map_attrs<F: FnOnce(Vec<Attribute>) -> Vec<Attribute>>(self, f: F) -> Self {
1031         match self {
1032             StmtKind::Local(local) => StmtKind::Local(local.map_attrs(f)),
1033             StmtKind::Item(..) => self,
1034             StmtKind::Expr(expr) => StmtKind::Expr(expr.map_attrs(f)),
1035             StmtKind::Semi(expr) => StmtKind::Semi(expr.map_attrs(f)),
1036             StmtKind::Mac(mac) => StmtKind::Mac(mac.map(|(mac, style, attrs)| {
1037                 (mac, style, attrs.map_attrs(f))
1038             })),
1039         }
1040     }
1041 }
1042
1043 macro_rules! derive_has_attrs_from_field {
1044     ($($ty:path),*) => { derive_has_attrs_from_field!($($ty: .attrs),*); };
1045     ($($ty:path : $(.$field:ident)*),*) => { $(
1046         impl HasAttrs for $ty {
1047             fn attrs(&self) -> &[Attribute] {
1048                 self $(.$field)* .attrs()
1049             }
1050
1051             fn map_attrs<F>(mut self, f: F) -> Self
1052                 where F: FnOnce(Vec<Attribute>) -> Vec<Attribute>,
1053             {
1054                 self $(.$field)* = self $(.$field)* .map_attrs(f);
1055                 self
1056             }
1057         }
1058     )* }
1059 }
1060
1061 derive_has_attrs_from_field! {
1062     Item, Expr, Local, ast::ForeignItem, ast::StructField, ast::ImplItem, ast::TraitItem, ast::Arm
1063 }
1064
1065 derive_has_attrs_from_field! { Stmt: .node, ast::Variant: .node.attrs }