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