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