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