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