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