]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/attr/builtin.rs
Rollup merge of #58247 - taiki-e:librustc_passes-2018, r=Centril
[rust.git] / src / libsyntax / attr / builtin.rs
1 //! Parsing and validation of builtin attributes
2
3 use crate::ast::{self, Attribute, MetaItem, Name, NestedMetaItemKind};
4 use crate::errors::{Applicability, Handler};
5 use crate::feature_gate::{Features, GatedCfg};
6 use crate::parse::ParseSess;
7
8 use syntax_pos::{symbol::Symbol, Span};
9
10 use super::{list_contains_name, mark_used, MetaItemKind};
11
12 enum AttrError {
13     MultipleItem(Name),
14     UnknownMetaItem(Name, &'static [&'static str]),
15     MissingSince,
16     MissingFeature,
17     MultipleStabilityLevels,
18     UnsupportedLiteral(&'static str, /* is_bytestr */ bool),
19 }
20
21 fn handle_errors(sess: &ParseSess, span: Span, error: AttrError) {
22     let diag = &sess.span_diagnostic;
23     match error {
24         AttrError::MultipleItem(item) => span_err!(diag, span, E0538,
25                                                    "multiple '{}' items", item),
26         AttrError::UnknownMetaItem(item, expected) => {
27             let expected = expected
28                 .iter()
29                 .map(|name| format!("`{}`", name))
30                 .collect::<Vec<_>>();
31             struct_span_err!(diag, span, E0541, "unknown meta item '{}'", item)
32                 .span_label(span, format!("expected one of {}", expected.join(", ")))
33                 .emit();
34         }
35         AttrError::MissingSince => span_err!(diag, span, E0542, "missing 'since'"),
36         AttrError::MissingFeature => span_err!(diag, span, E0546, "missing 'feature'"),
37         AttrError::MultipleStabilityLevels => span_err!(diag, span, E0544,
38                                                         "multiple stability levels"),
39         AttrError::UnsupportedLiteral(
40             msg,
41             is_bytestr,
42         ) => {
43             let mut err = struct_span_err!(diag, span, E0565, "{}", msg);
44             if is_bytestr {
45                 if let Ok(lint_str) = sess.source_map().span_to_snippet(span) {
46                     err.span_suggestion(
47                         span,
48                         "consider removing the prefix",
49                         format!("{}", &lint_str[1..]),
50                         Applicability::MaybeIncorrect,
51                     );
52                 }
53             }
54             err.emit();
55         }
56     }
57 }
58
59 #[derive(Copy, Clone, Hash, PartialEq, RustcEncodable, RustcDecodable)]
60 pub enum InlineAttr {
61     None,
62     Hint,
63     Always,
64     Never,
65 }
66
67 #[derive(Copy, Clone, Hash, PartialEq, RustcEncodable, RustcDecodable)]
68 pub enum OptimizeAttr {
69     None,
70     Speed,
71     Size,
72 }
73
74 #[derive(Copy, Clone, PartialEq)]
75 pub enum UnwindAttr {
76     Allowed,
77     Aborts,
78 }
79
80 /// Determine what `#[unwind]` attribute is present in `attrs`, if any.
81 pub fn find_unwind_attr(diagnostic: Option<&Handler>, attrs: &[Attribute]) -> Option<UnwindAttr> {
82     let syntax_error = |attr: &Attribute| {
83         mark_used(attr);
84         diagnostic.map(|d| {
85             span_err!(d, attr.span, E0633, "malformed `#[unwind]` attribute");
86         });
87         None
88     };
89
90     attrs.iter().fold(None, |ia, attr| {
91         if attr.path != "unwind" {
92             return ia;
93         }
94         let meta = match attr.meta() {
95             Some(meta) => meta.node,
96             None => return ia,
97         };
98         match meta {
99             MetaItemKind::Word => {
100                 syntax_error(attr)
101             }
102             MetaItemKind::List(ref items) => {
103                 mark_used(attr);
104                 if items.len() != 1 {
105                     syntax_error(attr)
106                 } else if list_contains_name(&items[..], "allowed") {
107                     Some(UnwindAttr::Allowed)
108                 } else if list_contains_name(&items[..], "aborts") {
109                     Some(UnwindAttr::Aborts)
110                 } else {
111                     syntax_error(attr)
112                 }
113             }
114             _ => ia,
115         }
116     })
117 }
118
119 /// Represents the #[stable], #[unstable], #[rustc_{deprecated,const_unstable}] attributes.
120 #[derive(RustcEncodable, RustcDecodable, Clone, Debug, PartialEq, Eq, Hash)]
121 pub struct Stability {
122     pub level: StabilityLevel,
123     pub feature: Symbol,
124     pub rustc_depr: Option<RustcDeprecation>,
125     /// `None` means the function is stable but needs to be a stable const fn, too
126     /// `Some` contains the feature gate required to be able to use the function
127     /// as const fn
128     pub const_stability: Option<Symbol>,
129     /// whether the function has a `#[rustc_promotable]` attribute
130     pub promotable: bool,
131 }
132
133 /// The available stability levels.
134 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Debug, Eq, Hash)]
135 pub enum StabilityLevel {
136     // Reason for the current stability level and the relevant rust-lang issue
137     Unstable { reason: Option<Symbol>, issue: u32 },
138     Stable { since: Symbol },
139 }
140
141 impl StabilityLevel {
142     pub fn is_unstable(&self) -> bool {
143         if let StabilityLevel::Unstable {..} = *self {
144             true
145         } else {
146             false
147         }
148     }
149     pub fn is_stable(&self) -> bool {
150         if let StabilityLevel::Stable {..} = *self {
151             true
152         } else {
153             false
154         }
155     }
156 }
157
158 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Debug, Eq, Hash)]
159 pub struct RustcDeprecation {
160     pub since: Symbol,
161     pub reason: Symbol,
162     /// A text snippet used to completely replace any use of the deprecated item in an expression.
163     pub suggestion: Option<Symbol>,
164 }
165
166 /// Check if `attrs` contains an attribute like `#![feature(feature_name)]`.
167 /// This will not perform any "sanity checks" on the form of the attributes.
168 pub fn contains_feature_attr(attrs: &[Attribute], feature_name: &str) -> bool {
169     attrs.iter().any(|item| {
170         item.check_name("feature") &&
171         item.meta_item_list().map(|list| {
172             list.iter().any(|mi| {
173                 mi.word().map(|w| w.name() == feature_name)
174                          .unwrap_or(false)
175             })
176         }).unwrap_or(false)
177     })
178 }
179
180 /// Find the first stability attribute. `None` if none exists.
181 pub fn find_stability(sess: &ParseSess, attrs: &[Attribute],
182                       item_sp: Span) -> Option<Stability> {
183     find_stability_generic(sess, attrs.iter(), item_sp)
184 }
185
186 fn find_stability_generic<'a, I>(sess: &ParseSess,
187                                  attrs_iter: I,
188                                  item_sp: Span)
189                                  -> Option<Stability>
190     where I: Iterator<Item = &'a Attribute>
191 {
192     use StabilityLevel::*;
193
194     let mut stab: Option<Stability> = None;
195     let mut rustc_depr: Option<RustcDeprecation> = None;
196     let mut rustc_const_unstable: Option<Symbol> = None;
197     let mut promotable = false;
198     let diagnostic = &sess.span_diagnostic;
199
200     'outer: for attr in attrs_iter {
201         if ![
202             "rustc_deprecated",
203             "rustc_const_unstable",
204             "unstable",
205             "stable",
206             "rustc_promotable",
207         ].iter().any(|&s| attr.path == s) {
208             continue // not a stability level
209         }
210
211         mark_used(attr);
212
213         let meta = attr.meta();
214
215         if attr.path == "rustc_promotable" {
216             promotable = true;
217         }
218         // attributes with data
219         else if let Some(MetaItem { node: MetaItemKind::List(ref metas), .. }) = meta {
220             let meta = meta.as_ref().unwrap();
221             let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
222                 if item.is_some() {
223                     handle_errors(sess, meta.span, AttrError::MultipleItem(meta.name()));
224                     return false
225                 }
226                 if let Some(v) = meta.value_str() {
227                     *item = Some(v);
228                     true
229                 } else {
230                     span_err!(diagnostic, meta.span, E0539, "incorrect meta item");
231                     false
232                 }
233             };
234
235             macro_rules! get_meta {
236                 ($($name:ident),+) => {
237                     $(
238                         let mut $name = None;
239                     )+
240                     for meta in metas {
241                         if let Some(mi) = meta.meta_item() {
242                             match &*mi.name().as_str() {
243                                 $(
244                                     stringify!($name)
245                                         => if !get(mi, &mut $name) { continue 'outer },
246                                 )+
247                                 _ => {
248                                     let expected = &[ $( stringify!($name) ),+ ];
249                                     handle_errors(
250                                         sess,
251                                         mi.span,
252                                         AttrError::UnknownMetaItem(mi.name(), expected),
253                                     );
254                                     continue 'outer
255                                 }
256                             }
257                         } else {
258                             handle_errors(
259                                 sess,
260                                 meta.span,
261                                 AttrError::UnsupportedLiteral(
262                                     "unsupported literal",
263                                     false,
264                                 ),
265                             );
266                             continue 'outer
267                         }
268                     }
269                 }
270             }
271
272             match &*meta.name().as_str() {
273                 "rustc_deprecated" => {
274                     if rustc_depr.is_some() {
275                         span_err!(diagnostic, item_sp, E0540,
276                                   "multiple rustc_deprecated attributes");
277                         continue 'outer
278                     }
279
280                     get_meta!(since, reason, suggestion);
281
282                     match (since, reason) {
283                         (Some(since), Some(reason)) => {
284                             rustc_depr = Some(RustcDeprecation {
285                                 since,
286                                 reason,
287                                 suggestion,
288                             })
289                         }
290                         (None, _) => {
291                             handle_errors(sess, attr.span(), AttrError::MissingSince);
292                             continue
293                         }
294                         _ => {
295                             span_err!(diagnostic, attr.span(), E0543, "missing 'reason'");
296                             continue
297                         }
298                     }
299                 }
300                 "rustc_const_unstable" => {
301                     if rustc_const_unstable.is_some() {
302                         span_err!(diagnostic, item_sp, E0553,
303                                   "multiple rustc_const_unstable attributes");
304                         continue 'outer
305                     }
306
307                     get_meta!(feature);
308                     if let Some(feature) = feature {
309                         rustc_const_unstable = Some(feature);
310                     } else {
311                         span_err!(diagnostic, attr.span(), E0629, "missing 'feature'");
312                         continue
313                     }
314                 }
315                 "unstable" => {
316                     if stab.is_some() {
317                         handle_errors(sess, attr.span(), AttrError::MultipleStabilityLevels);
318                         break
319                     }
320
321                     let mut feature = None;
322                     let mut reason = None;
323                     let mut issue = None;
324                     for meta in metas {
325                         if let Some(mi) = meta.meta_item() {
326                             match &*mi.name().as_str() {
327                                 "feature" => if !get(mi, &mut feature) { continue 'outer },
328                                 "reason" => if !get(mi, &mut reason) { continue 'outer },
329                                 "issue" => if !get(mi, &mut issue) { continue 'outer },
330                                 _ => {
331                                     handle_errors(
332                                         sess,
333                                         meta.span,
334                                         AttrError::UnknownMetaItem(
335                                             mi.name(),
336                                             &["feature", "reason", "issue"]
337                                         ),
338                                     );
339                                     continue 'outer
340                                 }
341                             }
342                         } else {
343                             handle_errors(
344                                 sess,
345                                 meta.span,
346                                 AttrError::UnsupportedLiteral(
347                                     "unsupported literal",
348                                     false,
349                                 ),
350                             );
351                             continue 'outer
352                         }
353                     }
354
355                     match (feature, reason, issue) {
356                         (Some(feature), reason, Some(issue)) => {
357                             stab = Some(Stability {
358                                 level: Unstable {
359                                     reason,
360                                     issue: {
361                                         if let Ok(issue) = issue.as_str().parse() {
362                                             issue
363                                         } else {
364                                             span_err!(diagnostic, attr.span(), E0545,
365                                                       "incorrect 'issue'");
366                                             continue
367                                         }
368                                     }
369                                 },
370                                 feature,
371                                 rustc_depr: None,
372                                 const_stability: None,
373                                 promotable: false,
374                             })
375                         }
376                         (None, _, _) => {
377                             handle_errors(sess, attr.span(), AttrError::MissingFeature);
378                             continue
379                         }
380                         _ => {
381                             span_err!(diagnostic, attr.span(), E0547, "missing 'issue'");
382                             continue
383                         }
384                     }
385                 }
386                 "stable" => {
387                     if stab.is_some() {
388                         handle_errors(sess, attr.span(), AttrError::MultipleStabilityLevels);
389                         break
390                     }
391
392                     let mut feature = None;
393                     let mut since = None;
394                     for meta in metas {
395                         match &meta.node {
396                             NestedMetaItemKind::MetaItem(mi) => {
397                                 match &*mi.name().as_str() {
398                                     "feature" => if !get(mi, &mut feature) { continue 'outer },
399                                     "since" => if !get(mi, &mut since) { continue 'outer },
400                                     _ => {
401                                         handle_errors(
402                                             sess,
403                                             meta.span,
404                                             AttrError::UnknownMetaItem(
405                                                 mi.name(), &["since", "note"],
406                                             ),
407                                         );
408                                         continue 'outer
409                                     }
410                                 }
411                             },
412                             NestedMetaItemKind::Literal(lit) => {
413                                 handle_errors(
414                                     sess,
415                                     lit.span,
416                                     AttrError::UnsupportedLiteral(
417                                         "unsupported literal",
418                                         false,
419                                     ),
420                                 );
421                                 continue 'outer
422                             }
423                         }
424                     }
425
426                     match (feature, since) {
427                         (Some(feature), Some(since)) => {
428                             stab = Some(Stability {
429                                 level: Stable {
430                                     since,
431                                 },
432                                 feature,
433                                 rustc_depr: None,
434                                 const_stability: None,
435                                 promotable: false,
436                             })
437                         }
438                         (None, _) => {
439                             handle_errors(sess, attr.span(), AttrError::MissingFeature);
440                             continue
441                         }
442                         _ => {
443                             handle_errors(sess, attr.span(), AttrError::MissingSince);
444                             continue
445                         }
446                     }
447                 }
448                 _ => unreachable!()
449             }
450         }
451     }
452
453     // Merge the deprecation info into the stability info
454     if let Some(rustc_depr) = rustc_depr {
455         if let Some(ref mut stab) = stab {
456             stab.rustc_depr = Some(rustc_depr);
457         } else {
458             span_err!(diagnostic, item_sp, E0549,
459                       "rustc_deprecated attribute must be paired with \
460                        either stable or unstable attribute");
461         }
462     }
463
464     // Merge the const-unstable info into the stability info
465     if let Some(feature) = rustc_const_unstable {
466         if let Some(ref mut stab) = stab {
467             stab.const_stability = Some(feature);
468         } else {
469             span_err!(diagnostic, item_sp, E0630,
470                       "rustc_const_unstable attribute must be paired with \
471                        either stable or unstable attribute");
472         }
473     }
474
475     // Merge the const-unstable info into the stability info
476     if promotable {
477         if let Some(ref mut stab) = stab {
478             stab.promotable = true;
479         } else {
480             span_err!(diagnostic, item_sp, E0717,
481                       "rustc_promotable attribute must be paired with \
482                        either stable or unstable attribute");
483         }
484     }
485
486     stab
487 }
488
489 pub fn find_crate_name(attrs: &[Attribute]) -> Option<Symbol> {
490     super::first_attr_value_str_by_name(attrs, "crate_name")
491 }
492
493 /// Tests if a cfg-pattern matches the cfg set
494 pub fn cfg_matches(cfg: &ast::MetaItem, sess: &ParseSess, features: Option<&Features>) -> bool {
495     eval_condition(cfg, sess, &mut |cfg| {
496         if let (Some(feats), Some(gated_cfg)) = (features, GatedCfg::gate(cfg)) {
497             gated_cfg.check_and_emit(sess, feats);
498         }
499         let error = |span, msg| { sess.span_diagnostic.span_err(span, msg); true };
500         if cfg.ident.segments.len() != 1 {
501             return error(cfg.ident.span, "`cfg` predicate key must be an identifier");
502         }
503         match &cfg.node {
504             MetaItemKind::List(..) => {
505                 error(cfg.span, "unexpected parentheses after `cfg` predicate key")
506             }
507             MetaItemKind::NameValue(lit) if !lit.node.is_str() => {
508                 handle_errors(
509                     sess,
510                     lit.span,
511                     AttrError::UnsupportedLiteral(
512                         "literal in `cfg` predicate value must be a string",
513                         lit.node.is_bytestr()
514                     ),
515                 );
516                 true
517             }
518             MetaItemKind::NameValue(..) | MetaItemKind::Word => {
519                 sess.config.contains(&(cfg.name(), cfg.value_str()))
520             }
521         }
522     })
523 }
524
525 /// Evaluate a cfg-like condition (with `any` and `all`), using `eval` to
526 /// evaluate individual items.
527 pub fn eval_condition<F>(cfg: &ast::MetaItem, sess: &ParseSess, eval: &mut F)
528                          -> bool
529     where F: FnMut(&ast::MetaItem) -> bool
530 {
531     match cfg.node {
532         ast::MetaItemKind::List(ref mis) => {
533             for mi in mis.iter() {
534                 if !mi.is_meta_item() {
535                     handle_errors(
536                         sess,
537                         mi.span,
538                         AttrError::UnsupportedLiteral(
539                             "unsupported literal",
540                             false
541                         ),
542                     );
543                     return false;
544                 }
545             }
546
547             // The unwraps below may look dangerous, but we've already asserted
548             // that they won't fail with the loop above.
549             match &*cfg.name().as_str() {
550                 "any" => mis.iter().any(|mi| {
551                     eval_condition(mi.meta_item().unwrap(), sess, eval)
552                 }),
553                 "all" => mis.iter().all(|mi| {
554                     eval_condition(mi.meta_item().unwrap(), sess, eval)
555                 }),
556                 "not" => {
557                     if mis.len() != 1 {
558                         span_err!(sess.span_diagnostic, cfg.span, E0536, "expected 1 cfg-pattern");
559                         return false;
560                     }
561
562                     !eval_condition(mis[0].meta_item().unwrap(), sess, eval)
563                 },
564                 p => {
565                     span_err!(sess.span_diagnostic, cfg.span, E0537, "invalid predicate `{}`", p);
566                     false
567                 }
568             }
569         },
570         ast::MetaItemKind::Word | ast::MetaItemKind::NameValue(..) => {
571             eval(cfg)
572         }
573     }
574 }
575
576
577 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Debug, Eq, Hash)]
578 pub struct Deprecation {
579     pub since: Option<Symbol>,
580     pub note: Option<Symbol>,
581 }
582
583 /// Find the deprecation attribute. `None` if none exists.
584 pub fn find_deprecation(sess: &ParseSess, attrs: &[Attribute],
585                         item_sp: Span) -> Option<Deprecation> {
586     find_deprecation_generic(sess, attrs.iter(), item_sp)
587 }
588
589 fn find_deprecation_generic<'a, I>(sess: &ParseSess,
590                                    attrs_iter: I,
591                                    item_sp: Span)
592                                    -> Option<Deprecation>
593     where I: Iterator<Item = &'a Attribute>
594 {
595     let mut depr: Option<Deprecation> = None;
596     let diagnostic = &sess.span_diagnostic;
597
598     'outer: for attr in attrs_iter {
599         if attr.path != "deprecated" {
600             continue
601         }
602
603         mark_used(attr);
604
605         if depr.is_some() {
606             span_err!(diagnostic, item_sp, E0550, "multiple deprecated attributes");
607             break
608         }
609
610         depr = if let Some(metas) = attr.meta_item_list() {
611             let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
612                 if item.is_some() {
613                     handle_errors(sess, meta.span, AttrError::MultipleItem(meta.name()));
614                     return false
615                 }
616                 if let Some(v) = meta.value_str() {
617                     *item = Some(v);
618                     true
619                 } else {
620                     if let Some(lit) = meta.name_value_literal() {
621                         handle_errors(
622                             sess,
623                             lit.span,
624                             AttrError::UnsupportedLiteral(
625                                 "literal in `deprecated` \
626                                 value must be a string",
627                                 lit.node.is_bytestr()
628                             ),
629                         );
630                     } else {
631                         span_err!(diagnostic, meta.span, E0551, "incorrect meta item");
632                     }
633
634                     false
635                 }
636             };
637
638             let mut since = None;
639             let mut note = None;
640             for meta in metas {
641                 match &meta.node {
642                     NestedMetaItemKind::MetaItem(mi) => {
643                         match &*mi.name().as_str() {
644                             "since" => if !get(mi, &mut since) { continue 'outer },
645                             "note" => if !get(mi, &mut note) { continue 'outer },
646                             _ => {
647                                 handle_errors(
648                                     sess,
649                                     meta.span,
650                                     AttrError::UnknownMetaItem(mi.name(), &["since", "note"]),
651                                 );
652                                 continue 'outer
653                             }
654                         }
655                     }
656                     NestedMetaItemKind::Literal(lit) => {
657                         handle_errors(
658                             sess,
659                             lit.span,
660                             AttrError::UnsupportedLiteral(
661                                 "item in `deprecated` must be a key/value pair",
662                                 false,
663                             ),
664                         );
665                         continue 'outer
666                     }
667                 }
668             }
669
670             Some(Deprecation {since: since, note: note})
671         } else {
672             Some(Deprecation{since: None, note: None})
673         }
674     }
675
676     depr
677 }
678
679 #[derive(PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
680 pub enum ReprAttr {
681     ReprInt(IntType),
682     ReprC,
683     ReprPacked(u32),
684     ReprSimd,
685     ReprTransparent,
686     ReprAlign(u32),
687 }
688
689 #[derive(Eq, Hash, PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
690 pub enum IntType {
691     SignedInt(ast::IntTy),
692     UnsignedInt(ast::UintTy)
693 }
694
695 impl IntType {
696     #[inline]
697     pub fn is_signed(self) -> bool {
698         use IntType::*;
699
700         match self {
701             SignedInt(..) => true,
702             UnsignedInt(..) => false
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, `packed` to remove padding, and `transparent` to elegate representation
713 /// concerns to the only non-ZST field.
714 pub fn find_repr_attrs(sess: &ParseSess, attr: &Attribute) -> Vec<ReprAttr> {
715     use ReprAttr::*;
716
717     let mut acc = Vec::new();
718     let diagnostic = &sess.span_diagnostic;
719     if attr.path == "repr" {
720         if let Some(items) = attr.meta_item_list() {
721             mark_used(attr);
722             for item in items {
723                 if !item.is_meta_item() {
724                     handle_errors(
725                         sess,
726                         item.span,
727                         AttrError::UnsupportedLiteral(
728                             "meta item in `repr` must be an identifier",
729                             false,
730                         ),
731                     );
732                     continue
733                 }
734
735                 let mut recognised = false;
736                 if let Some(mi) = item.word() {
737                     let word = &*mi.name().as_str();
738                     let hint = match word {
739                         "C" => Some(ReprC),
740                         "packed" => Some(ReprPacked(1)),
741                         "simd" => Some(ReprSimd),
742                         "transparent" => Some(ReprTransparent),
743                         _ => match int_type_of_word(word) {
744                             Some(ity) => Some(ReprInt(ity)),
745                             None => {
746                                 None
747                             }
748                         }
749                     };
750
751                     if let Some(h) = hint {
752                         recognised = true;
753                         acc.push(h);
754                     }
755                 } else if let Some((name, value)) = item.name_value_literal() {
756                     let parse_alignment = |node: &ast::LitKind| -> Result<u32, &'static str> {
757                         if let ast::LitKind::Int(literal, ast::LitIntType::Unsuffixed) = node {
758                             if literal.is_power_of_two() {
759                                 // rustc::ty::layout::Align restricts align to <= 2^29
760                                 if *literal <= 1 << 29 {
761                                     Ok(*literal as u32)
762                                 } else {
763                                     Err("larger than 2^29")
764                                 }
765                             } else {
766                                 Err("not a power of two")
767                             }
768                         } else {
769                             Err("not an unsuffixed integer")
770                         }
771                     };
772
773                     let mut literal_error = None;
774                     if name == "align" {
775                         recognised = true;
776                         match parse_alignment(&value.node) {
777                             Ok(literal) => acc.push(ReprAlign(literal)),
778                             Err(message) => literal_error = Some(message)
779                         };
780                     }
781                     else if name == "packed" {
782                         recognised = true;
783                         match parse_alignment(&value.node) {
784                             Ok(literal) => acc.push(ReprPacked(literal)),
785                             Err(message) => literal_error = Some(message)
786                         };
787                     }
788                     if let Some(literal_error) = literal_error {
789                         span_err!(diagnostic, item.span, E0589,
790                                   "invalid `repr(align)` attribute: {}", literal_error);
791                     }
792                 } else {
793                     if let Some(meta_item) = item.meta_item() {
794                         if meta_item.name() == "align" {
795                             if let MetaItemKind::NameValue(ref value) = meta_item.node {
796                                 recognised = true;
797                                 let mut err = struct_span_err!(diagnostic, item.span, E0693,
798                                     "incorrect `repr(align)` attribute format");
799                                 match value.node {
800                                     ast::LitKind::Int(int, ast::LitIntType::Unsuffixed) => {
801                                         err.span_suggestion(
802                                             item.span,
803                                             "use parentheses instead",
804                                             format!("align({})", int),
805                                             Applicability::MachineApplicable
806                                         );
807                                     }
808                                     ast::LitKind::Str(s, _) => {
809                                         err.span_suggestion(
810                                             item.span,
811                                             "use parentheses instead",
812                                             format!("align({})", s),
813                                             Applicability::MachineApplicable
814                                         );
815                                     }
816                                     _ => {}
817                                 }
818                                 err.emit();
819                             }
820                         }
821                     }
822                 }
823                 if !recognised {
824                     // Not a word we recognize
825                     span_err!(diagnostic, item.span, E0552,
826                               "unrecognized representation hint");
827                 }
828             }
829         }
830     }
831     acc
832 }
833
834 fn int_type_of_word(s: &str) -> Option<IntType> {
835     use IntType::*;
836
837     match s {
838         "i8" => Some(SignedInt(ast::IntTy::I8)),
839         "u8" => Some(UnsignedInt(ast::UintTy::U8)),
840         "i16" => Some(SignedInt(ast::IntTy::I16)),
841         "u16" => Some(UnsignedInt(ast::UintTy::U16)),
842         "i32" => Some(SignedInt(ast::IntTy::I32)),
843         "u32" => Some(UnsignedInt(ast::UintTy::U32)),
844         "i64" => Some(SignedInt(ast::IntTy::I64)),
845         "u64" => Some(UnsignedInt(ast::UintTy::U64)),
846         "i128" => Some(SignedInt(ast::IntTy::I128)),
847         "u128" => Some(UnsignedInt(ast::UintTy::U128)),
848         "isize" => Some(SignedInt(ast::IntTy::Isize)),
849         "usize" => Some(UnsignedInt(ast::UintTy::Usize)),
850         _ => None
851     }
852 }