]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/attr.rs
Rollup merge of #30404 - Shiney:ImprovedStackHeap, r=steveklabnik
[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, MetaWord, MetaNameValue, MetaList};
19 use ast::{Stmt, StmtDecl, StmtExpr, StmtMac, StmtSemi, DeclItem, DeclLocal};
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 diagnostic::SpanHandler;
25 use feature_gate::{GatedCfg, GatedCfgAttr};
26 use parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
27 use parse::token::{InternedString, intern_and_get_ident};
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 MetaNameValue 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             MetaWord(ref n) => (*n).clone(),
100             MetaNameValue(ref n, _) => (*n).clone(),
101             MetaList(ref n, _) => (*n).clone(),
102         }
103     }
104
105     fn value_str(&self) -> Option<InternedString> {
106         match self.node {
107             MetaNameValue(_, ref v) => {
108                 match v.node {
109                     ast::LitStr(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             MetaList(_, 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::LitStr(value, ast::CookedStr));
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(MetaNameValue(name, value)))
183 }
184
185 pub fn mk_list_item(name: InternedString, items: Vec<P<MetaItem>>) -> P<MetaItem> {
186     P(dummy_spanned(MetaList(name, items)))
187 }
188
189 pub fn mk_word_item(name: InternedString) -> P<MetaItem> {
190     P(dummy_spanned(MetaWord(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::LitStr(text, ast::CookedStr));
229     let attr = Attribute_ {
230         id: id,
231         style: style,
232         value: P(spanned(lo, hi, MetaNameValue(InternedString::new("doc"),
233                                                lit))),
234         is_sugared_doc: true
235     };
236     spanned(lo, hi, attr)
237 }
238
239 /* Searching */
240 /// Check if `needle` occurs in `haystack` by a structural
241 /// comparison. This is slightly subtle, and relies on ignoring the
242 /// span included in the `==` comparison a plain MetaItem.
243 pub fn contains(haystack: &[P<MetaItem>], needle: &MetaItem) -> bool {
244     debug!("attr::contains (name={})", needle.name());
245     haystack.iter().any(|item| {
246         debug!("  testing: {}", item.name());
247         item.node == needle.node
248     })
249 }
250
251 pub fn contains_name<AM: AttrMetaMethods>(metas: &[AM], name: &str) -> bool {
252     debug!("attr::contains_name (name={})", name);
253     metas.iter().any(|item| {
254         debug!("  testing: {}", item.name());
255         item.check_name(name)
256     })
257 }
258
259 pub fn first_attr_value_str_by_name(attrs: &[Attribute], name: &str)
260                                  -> Option<InternedString> {
261     attrs.iter()
262         .find(|at| at.check_name(name))
263         .and_then(|at| at.value_str())
264 }
265
266 pub fn last_meta_item_value_str_by_name(items: &[P<MetaItem>], name: &str)
267                                      -> Option<InternedString> {
268     items.iter()
269          .rev()
270          .find(|mi| mi.check_name(name))
271          .and_then(|i| i.value_str())
272 }
273
274 /* Higher-level applications */
275
276 pub fn sort_meta_items(items: Vec<P<MetaItem>>) -> Vec<P<MetaItem>> {
277     // This is sort of stupid here, but we need to sort by
278     // human-readable strings.
279     let mut v = items.into_iter()
280         .map(|mi| (mi.name(), mi))
281         .collect::<Vec<(InternedString, P<MetaItem>)>>();
282
283     v.sort_by(|&(ref a, _), &(ref b, _)| a.cmp(b));
284
285     // There doesn't seem to be a more optimal way to do this
286     v.into_iter().map(|(_, m)| m.map(|Spanned {node, span}| {
287         Spanned {
288             node: match node {
289                 MetaList(n, mis) => MetaList(n, sort_meta_items(mis)),
290                 _ => node
291             },
292             span: span
293         }
294     })).collect()
295 }
296
297 pub fn find_crate_name(attrs: &[Attribute]) -> Option<InternedString> {
298     first_attr_value_str_by_name(attrs, "crate_name")
299 }
300
301 /// Find the value of #[export_name=*] attribute and check its validity.
302 pub fn find_export_name_attr(diag: &SpanHandler, attrs: &[Attribute]) -> Option<InternedString> {
303     attrs.iter().fold(None, |ia,attr| {
304         if attr.check_name("export_name") {
305             if let s@Some(_) = attr.value_str() {
306                 s
307             } else {
308                 diag.span_err(attr.span, "export_name attribute has invalid format");
309                 diag.handler.help("use #[export_name=\"*\"]");
310                 None
311             }
312         } else {
313             ia
314         }
315     })
316 }
317
318 #[derive(Copy, Clone, PartialEq)]
319 pub enum InlineAttr {
320     None,
321     Hint,
322     Always,
323     Never,
324 }
325
326 /// Determine what `#[inline]` attribute is present in `attrs`, if any.
327 pub fn find_inline_attr(diagnostic: Option<&SpanHandler>, attrs: &[Attribute]) -> InlineAttr {
328     attrs.iter().fold(InlineAttr::None, |ia,attr| {
329         match attr.node.value.node {
330             MetaWord(ref n) if *n == "inline" => {
331                 mark_used(attr);
332                 InlineAttr::Hint
333             }
334             MetaList(ref n, ref items) if *n == "inline" => {
335                 mark_used(attr);
336                 if items.len() != 1 {
337                     diagnostic.map(|d|{ d.span_err(attr.span, "expected one argument"); });
338                     InlineAttr::None
339                 } else if contains_name(&items[..], "always") {
340                     InlineAttr::Always
341                 } else if contains_name(&items[..], "never") {
342                     InlineAttr::Never
343                 } else {
344                     diagnostic.map(|d|{ d.span_err((*items[0]).span, "invalid argument"); });
345                     InlineAttr::None
346                 }
347             }
348             _ => ia
349         }
350     })
351 }
352
353 /// True if `#[inline]` or `#[inline(always)]` is present in `attrs`.
354 pub fn requests_inline(attrs: &[Attribute]) -> bool {
355     match find_inline_attr(None, attrs) {
356         InlineAttr::Hint | InlineAttr::Always => true,
357         InlineAttr::None | InlineAttr::Never => false,
358     }
359 }
360
361 /// Tests if a cfg-pattern matches the cfg set
362 pub fn cfg_matches<T: CfgDiag>(cfgs: &[P<MetaItem>],
363                            cfg: &ast::MetaItem,
364                            diag: &mut T) -> bool {
365     match cfg.node {
366         ast::MetaList(ref pred, ref mis) if &pred[..] == "any" =>
367             mis.iter().any(|mi| cfg_matches(cfgs, &**mi, diag)),
368         ast::MetaList(ref pred, ref mis) if &pred[..] == "all" =>
369             mis.iter().all(|mi| cfg_matches(cfgs, &**mi, diag)),
370         ast::MetaList(ref pred, ref mis) if &pred[..] == "not" => {
371             if mis.len() != 1 {
372                 diag.emit_error(|diagnostic| {
373                     diagnostic.span_err(cfg.span, "expected 1 cfg-pattern");
374                 });
375                 return false;
376             }
377             !cfg_matches(cfgs, &*mis[0], diag)
378         }
379         ast::MetaList(ref pred, _) => {
380             diag.emit_error(|diagnostic| {
381                 diagnostic.span_err(cfg.span,
382                     &format!("invalid predicate `{}`", pred));
383             });
384             false
385         },
386         ast::MetaWord(_) | ast::MetaNameValue(..) => {
387             diag.flag_gated(|feature_gated_cfgs| {
388                 feature_gated_cfgs.extend(
389                     GatedCfg::gate(cfg).map(GatedCfgAttr::GatedCfg));
390             });
391             contains(cfgs, cfg)
392         }
393     }
394 }
395
396 /// Represents the #[stable], #[unstable] and #[rustc_deprecated] attributes.
397 #[derive(RustcEncodable, RustcDecodable, Clone, Debug, PartialEq, Eq, Hash)]
398 pub struct Stability {
399     pub level: StabilityLevel,
400     pub feature: InternedString,
401     pub rustc_depr: Option<RustcDeprecation>,
402 }
403
404 /// The available stability levels.
405 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Debug, Eq, Hash)]
406 pub enum StabilityLevel {
407     // Reason for the current stability level and the relevant rust-lang issue
408     Unstable { reason: Option<InternedString>, issue: u32 },
409     Stable { since: InternedString },
410 }
411
412 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Debug, Eq, Hash)]
413 pub struct RustcDeprecation {
414     pub since: InternedString,
415     pub reason: InternedString,
416 }
417
418 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Debug, Eq, Hash)]
419 pub struct Deprecation {
420     pub since: Option<InternedString>,
421     pub note: Option<InternedString>,
422 }
423
424 impl StabilityLevel {
425     pub fn is_unstable(&self) -> bool { if let Unstable {..} = *self { true } else { false }}
426     pub fn is_stable(&self) -> bool { if let Stable {..} = *self { true } else { false }}
427 }
428
429 fn find_stability_generic<'a, I>(diagnostic: &SpanHandler,
430                                  attrs_iter: I,
431                                  item_sp: Span)
432                                  -> Option<Stability>
433     where I: Iterator<Item = &'a Attribute>
434 {
435     let mut stab: Option<Stability> = None;
436     let mut rustc_depr: Option<RustcDeprecation> = None;
437
438     'outer: for attr in attrs_iter {
439         let tag = attr.name();
440         let tag = &*tag;
441         if tag != "rustc_deprecated" && tag != "unstable" && tag != "stable" {
442             continue // not a stability level
443         }
444
445         mark_used(attr);
446
447         if let Some(metas) = attr.meta_item_list() {
448             let get = |meta: &MetaItem, item: &mut Option<InternedString>| {
449                 if item.is_some() {
450                     diagnostic.span_err(meta.span, &format!("multiple '{}' items",
451                                                              meta.name()));
452                     return false
453                 }
454                 if let Some(v) = meta.value_str() {
455                     *item = Some(v);
456                     true
457                 } else {
458                     diagnostic.span_err(meta.span, "incorrect meta item");
459                     false
460                 }
461             };
462
463             match tag {
464                 "rustc_deprecated" => {
465                     if rustc_depr.is_some() {
466                         diagnostic.span_err(item_sp, "multiple rustc_deprecated attributes");
467                         break
468                     }
469
470                     let mut since = None;
471                     let mut reason = None;
472                     for meta in metas {
473                         match &*meta.name() {
474                             "since" => if !get(meta, &mut since) { continue 'outer },
475                             "reason" => if !get(meta, &mut reason) { continue 'outer },
476                             _ => {
477                                 diagnostic.span_err(meta.span, &format!("unknown meta item '{}'",
478                                                                         meta.name()));
479                                 continue 'outer
480                             }
481                         }
482                     }
483
484                     match (since, reason) {
485                         (Some(since), Some(reason)) => {
486                             rustc_depr = Some(RustcDeprecation {
487                                 since: since,
488                                 reason: reason,
489                             })
490                         }
491                         (None, _) => {
492                             diagnostic.span_err(attr.span(), "missing 'since'");
493                             continue
494                         }
495                         _ => {
496                             diagnostic.span_err(attr.span(), "missing 'reason'");
497                             continue
498                         }
499                     }
500                 }
501                 "unstable" => {
502                     if stab.is_some() {
503                         diagnostic.span_err(item_sp, "multiple stability levels");
504                         break
505                     }
506
507                     let mut feature = None;
508                     let mut reason = None;
509                     let mut issue = None;
510                     for meta in metas {
511                         match &*meta.name() {
512                             "feature" => if !get(meta, &mut feature) { continue 'outer },
513                             "reason" => if !get(meta, &mut reason) { continue 'outer },
514                             "issue" => if !get(meta, &mut issue) { continue 'outer },
515                             _ => {
516                                 diagnostic.span_err(meta.span, &format!("unknown meta item '{}'",
517                                                                         meta.name()));
518                                 continue 'outer
519                             }
520                         }
521                     }
522
523                     match (feature, reason, issue) {
524                         (Some(feature), reason, Some(issue)) => {
525                             stab = Some(Stability {
526                                 level: Unstable {
527                                     reason: reason,
528                                     issue: {
529                                         if let Ok(issue) = issue.parse() {
530                                             issue
531                                         } else {
532                                             diagnostic.span_err(attr.span(), "incorrect 'issue'");
533                                             continue
534                                         }
535                                     }
536                                 },
537                                 feature: feature,
538                                 rustc_depr: None,
539                             })
540                         }
541                         (None, _, _) => {
542                             diagnostic.span_err(attr.span(), "missing 'feature'");
543                             continue
544                         }
545                         _ => {
546                             diagnostic.span_err(attr.span(), "missing 'issue'");
547                             continue
548                         }
549                     }
550                 }
551                 "stable" => {
552                     if stab.is_some() {
553                         diagnostic.span_err(item_sp, "multiple stability levels");
554                         break
555                     }
556
557                     let mut feature = None;
558                     let mut since = None;
559                     for meta in metas {
560                         match &*meta.name() {
561                             "feature" => if !get(meta, &mut feature) { continue 'outer },
562                             "since" => if !get(meta, &mut since) { continue 'outer },
563                             _ => {
564                                 diagnostic.span_err(meta.span, &format!("unknown meta item '{}'",
565                                                                         meta.name()));
566                                 continue 'outer
567                             }
568                         }
569                     }
570
571                     match (feature, since) {
572                         (Some(feature), Some(since)) => {
573                             stab = Some(Stability {
574                                 level: Stable {
575                                     since: since,
576                                 },
577                                 feature: feature,
578                                 rustc_depr: None,
579                             })
580                         }
581                         (None, _) => {
582                             diagnostic.span_err(attr.span(), "missing 'feature'");
583                             continue
584                         }
585                         _ => {
586                             diagnostic.span_err(attr.span(), "missing 'since'");
587                             continue
588                         }
589                     }
590                 }
591                 _ => unreachable!()
592             }
593         } else {
594             diagnostic.span_err(attr.span(), "incorrect stability attribute type");
595             continue
596         }
597     }
598
599     // Merge the deprecation info into the stability info
600     if let Some(rustc_depr) = rustc_depr {
601         if let Some(ref mut stab) = stab {
602             if let Unstable {reason: ref mut reason @ None, ..} = stab.level {
603                 *reason = Some(rustc_depr.reason.clone())
604             }
605             stab.rustc_depr = Some(rustc_depr);
606         } else {
607             diagnostic.span_err(item_sp, "rustc_deprecated attribute must be paired with \
608                                           either stable or unstable attribute");
609         }
610     }
611
612     stab
613 }
614
615 fn find_deprecation_generic<'a, I>(diagnostic: &SpanHandler,
616                                  attrs_iter: I,
617                                  item_sp: Span)
618                                  -> Option<Deprecation>
619     where I: Iterator<Item = &'a Attribute>
620 {
621     let mut depr: Option<Deprecation> = None;
622
623     'outer: for attr in attrs_iter {
624         if attr.name() != "deprecated" {
625             continue
626         }
627
628         mark_used(attr);
629
630         if depr.is_some() {
631             diagnostic.span_err(item_sp, "multiple deprecated attributes");
632             break
633         }
634
635         depr = if let Some(metas) = attr.meta_item_list() {
636             let get = |meta: &MetaItem, item: &mut Option<InternedString>| {
637                 if item.is_some() {
638                     diagnostic.span_err(meta.span, &format!("multiple '{}' items",
639                                                              meta.name()));
640                     return false
641                 }
642                 if let Some(v) = meta.value_str() {
643                     *item = Some(v);
644                     true
645                 } else {
646                     diagnostic.span_err(meta.span, "incorrect meta item");
647                     false
648                 }
649             };
650
651             let mut since = None;
652             let mut note = None;
653             for meta in metas {
654                 match &*meta.name() {
655                     "since" => if !get(meta, &mut since) { continue 'outer },
656                     "note" => if !get(meta, &mut note) { continue 'outer },
657                     _ => {
658                         diagnostic.span_err(meta.span, &format!("unknown meta item '{}'",
659                                                                 meta.name()));
660                         continue 'outer
661                     }
662                 }
663             }
664
665             Some(Deprecation {since: since, note: note})
666         } else {
667             Some(Deprecation{since: None, note: None})
668         }
669     }
670
671     depr
672 }
673
674 /// Find the first stability attribute. `None` if none exists.
675 pub fn find_stability(diagnostic: &SpanHandler, attrs: &[Attribute],
676                       item_sp: Span) -> Option<Stability> {
677     find_stability_generic(diagnostic, attrs.iter(), item_sp)
678 }
679
680 /// Find the deprecation attribute. `None` if none exists.
681 pub fn find_deprecation(diagnostic: &SpanHandler, attrs: &[Attribute],
682                       item_sp: Span) -> Option<Deprecation> {
683     find_deprecation_generic(diagnostic, attrs.iter(), item_sp)
684 }
685
686 pub fn require_unique_names(diagnostic: &SpanHandler, metas: &[P<MetaItem>]) {
687     let mut set = HashSet::new();
688     for meta in metas {
689         let name = meta.name();
690
691         if !set.insert(name.clone()) {
692             panic!(diagnostic.span_fatal(meta.span,
693                                   &format!("duplicate meta item `{}`", name)));
694         }
695     }
696 }
697
698
699 /// Parse #[repr(...)] forms.
700 ///
701 /// Valid repr contents: any of the primitive integral type names (see
702 /// `int_type_of_word`, below) to specify enum discriminant type; `C`, to use
703 /// the same discriminant size that the corresponding C enum would or C
704 /// structure layout, and `packed` to remove padding.
705 pub fn find_repr_attrs(diagnostic: &SpanHandler, attr: &Attribute) -> Vec<ReprAttr> {
706     let mut acc = Vec::new();
707     match attr.node.value.node {
708         ast::MetaList(ref s, ref items) if *s == "repr" => {
709             mark_used(attr);
710             for item in items {
711                 match item.node {
712                     ast::MetaWord(ref word) => {
713                         let hint = match &word[..] {
714                             // Can't use "extern" because it's not a lexical identifier.
715                             "C" => Some(ReprExtern),
716                             "packed" => Some(ReprPacked),
717                             "simd" => Some(ReprSimd),
718                             _ => match int_type_of_word(&word) {
719                                 Some(ity) => Some(ReprInt(item.span, ity)),
720                                 None => {
721                                     // Not a word we recognize
722                                     diagnostic.span_err(item.span,
723                                                         "unrecognized representation hint");
724                                     None
725                                 }
726                             }
727                         };
728
729                         match hint {
730                             Some(h) => acc.push(h),
731                             None => { }
732                         }
733                     }
734                     // Not a word:
735                     _ => diagnostic.span_err(item.span, "unrecognized enum representation hint")
736                 }
737             }
738         }
739         // Not a "repr" hint: ignore.
740         _ => { }
741     }
742     acc
743 }
744
745 fn int_type_of_word(s: &str) -> Option<IntType> {
746     match s {
747         "i8" => Some(SignedInt(ast::TyI8)),
748         "u8" => Some(UnsignedInt(ast::TyU8)),
749         "i16" => Some(SignedInt(ast::TyI16)),
750         "u16" => Some(UnsignedInt(ast::TyU16)),
751         "i32" => Some(SignedInt(ast::TyI32)),
752         "u32" => Some(UnsignedInt(ast::TyU32)),
753         "i64" => Some(SignedInt(ast::TyI64)),
754         "u64" => Some(UnsignedInt(ast::TyU64)),
755         "isize" => Some(SignedInt(ast::TyIs)),
756         "usize" => Some(UnsignedInt(ast::TyUs)),
757         _ => None
758     }
759 }
760
761 #[derive(PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
762 pub enum ReprAttr {
763     ReprAny,
764     ReprInt(Span, IntType),
765     ReprExtern,
766     ReprPacked,
767     ReprSimd,
768 }
769
770 impl ReprAttr {
771     pub fn is_ffi_safe(&self) -> bool {
772         match *self {
773             ReprAny => false,
774             ReprInt(_sp, ity) => ity.is_ffi_safe(),
775             ReprExtern => true,
776             ReprPacked => false,
777             ReprSimd => true,
778         }
779     }
780 }
781
782 #[derive(Eq, Hash, PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
783 pub enum IntType {
784     SignedInt(ast::IntTy),
785     UnsignedInt(ast::UintTy)
786 }
787
788 impl IntType {
789     #[inline]
790     pub fn is_signed(self) -> bool {
791         match self {
792             SignedInt(..) => true,
793             UnsignedInt(..) => false
794         }
795     }
796     fn is_ffi_safe(self) -> bool {
797         match self {
798             SignedInt(ast::TyI8) | UnsignedInt(ast::TyU8) |
799             SignedInt(ast::TyI16) | UnsignedInt(ast::TyU16) |
800             SignedInt(ast::TyI32) | UnsignedInt(ast::TyU32) |
801             SignedInt(ast::TyI64) | UnsignedInt(ast::TyU64) => true,
802             SignedInt(ast::TyIs) | UnsignedInt(ast::TyUs) => false
803         }
804     }
805 }
806
807 /// A list of attributes, behind a optional box as
808 /// a space optimization.
809 pub type ThinAttributes = Option<Box<Vec<Attribute>>>;
810
811 pub trait ThinAttributesExt {
812     fn map_thin_attrs<F>(self, f: F) -> Self
813         where F: FnOnce(Vec<Attribute>) -> Vec<Attribute>;
814     fn prepend(mut self, attrs: Self) -> Self;
815     fn append(mut self, attrs: Self) -> Self;
816     fn update<F>(&mut self, f: F)
817         where Self: Sized,
818               F: FnOnce(Self) -> Self;
819     fn as_attr_slice(&self) -> &[Attribute];
820     fn into_attr_vec(self) -> Vec<Attribute>;
821 }
822
823 impl ThinAttributesExt for ThinAttributes {
824     fn map_thin_attrs<F>(self, f: F) -> Self
825         where F: FnOnce(Vec<Attribute>) -> Vec<Attribute>
826     {
827         f(self.map(|b| *b).unwrap_or(Vec::new())).into_thin_attrs()
828     }
829
830     fn prepend(self, attrs: ThinAttributes) -> Self {
831         attrs.map_thin_attrs(|mut attrs| {
832             attrs.extend(self.into_attr_vec());
833             attrs
834         })
835     }
836
837     fn append(self, attrs: ThinAttributes) -> Self {
838         self.map_thin_attrs(|mut self_| {
839             self_.extend(attrs.into_attr_vec());
840             self_
841         })
842     }
843
844     fn update<F>(&mut self, f: F)
845         where Self: Sized,
846               F: FnOnce(ThinAttributes) -> ThinAttributes
847     {
848         let self_ = f(self.take());
849         *self = self_;
850     }
851
852     fn as_attr_slice(&self) -> &[Attribute] {
853         match *self {
854             Some(ref b) => b,
855             None => &[],
856         }
857     }
858
859     fn into_attr_vec(self) -> Vec<Attribute> {
860         match self {
861             Some(b) => *b,
862             None => Vec::new(),
863         }
864     }
865 }
866
867 pub trait AttributesExt {
868     fn into_thin_attrs(self) -> ThinAttributes;
869 }
870
871 impl AttributesExt for Vec<Attribute> {
872     fn into_thin_attrs(self) -> ThinAttributes {
873         if self.len() == 0 {
874             None
875         } else {
876             Some(Box::new(self))
877         }
878     }
879 }
880
881 /// A cheap way to add Attributes to an AST node.
882 pub trait WithAttrs {
883     // FIXME: Could be extended to anything IntoIter<Item=Attribute>
884     fn with_attrs(self, attrs: ThinAttributes) -> Self;
885 }
886
887 impl WithAttrs for P<Expr> {
888     fn with_attrs(self, attrs: ThinAttributes) -> Self {
889         self.map(|mut e| {
890             e.attrs.update(|a| a.append(attrs));
891             e
892         })
893     }
894 }
895
896 impl WithAttrs for P<Item> {
897     fn with_attrs(self, attrs: ThinAttributes) -> Self {
898         self.map(|Item { ident, attrs: mut ats, id, node, vis, span }| {
899             ats.extend(attrs.into_attr_vec());
900             Item {
901                 ident: ident,
902                 attrs: ats,
903                 id: id,
904                 node: node,
905                 vis: vis,
906                 span: span,
907             }
908         })
909     }
910 }
911
912 impl WithAttrs for P<Local> {
913     fn with_attrs(self, attrs: ThinAttributes) -> Self {
914         self.map(|Local { pat, ty, init, id, span, attrs: mut ats }| {
915             ats.update(|a| a.append(attrs));
916             Local {
917                 pat: pat,
918                 ty: ty,
919                 init: init,
920                 id: id,
921                 span: span,
922                 attrs: ats,
923             }
924         })
925     }
926 }
927
928 impl WithAttrs for P<Decl> {
929     fn with_attrs(self, attrs: ThinAttributes) -> Self {
930         self.map(|Spanned { span, node }| {
931             Spanned {
932                 span: span,
933                 node: match node {
934                     DeclLocal(local) => DeclLocal(local.with_attrs(attrs)),
935                     DeclItem(item) => DeclItem(item.with_attrs(attrs)),
936                 }
937             }
938         })
939     }
940 }
941
942 impl WithAttrs for P<Stmt> {
943     fn with_attrs(self, attrs: ThinAttributes) -> Self {
944         self.map(|Spanned { span, node }| {
945             Spanned {
946                 span: span,
947                 node: match node {
948                     StmtDecl(decl, id) => StmtDecl(decl.with_attrs(attrs), id),
949                     StmtExpr(expr, id) => StmtExpr(expr.with_attrs(attrs), id),
950                     StmtSemi(expr, id) => StmtSemi(expr.with_attrs(attrs), id),
951                     StmtMac(mac, style, mut ats) => {
952                         ats.update(|a| a.append(attrs));
953                         StmtMac(mac, style, ats)
954                     }
955                 },
956             }
957         })
958     }
959 }