]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/attr/builtin.rs
Rollup merge of #58365 - Zoxc:task-status, r=michaelwoerister
[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::feature_gate::{Features, GatedCfg};
5 use crate::parse::ParseSess;
6
7 use errors::{Applicability, Handler};
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 /// Checks 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 /// Finds 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 /// Finds 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.check_name("deprecated") {
600             continue;
601         }
602
603         if depr.is_some() {
604             span_err!(diagnostic, item_sp, E0550, "multiple deprecated attributes");
605             break
606         }
607
608         let meta = attr.meta().unwrap();
609         depr = match &meta.node {
610             MetaItemKind::Word => Some(Deprecation { since: None, note: None }),
611             MetaItemKind::NameValue(..) => {
612                 meta.value_str().map(|note| {
613                     Deprecation { since: None, note: Some(note) }
614                 })
615             }
616             MetaItemKind::List(list) => {
617                 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
618                     if item.is_some() {
619                         handle_errors(sess, meta.span, AttrError::MultipleItem(meta.name()));
620                         return false
621                     }
622                     if let Some(v) = meta.value_str() {
623                         *item = Some(v);
624                         true
625                     } else {
626                         if let Some(lit) = meta.name_value_literal() {
627                             handle_errors(
628                                 sess,
629                                 lit.span,
630                                 AttrError::UnsupportedLiteral(
631                                     "literal in `deprecated` \
632                                     value must be a string",
633                                     lit.node.is_bytestr()
634                                 ),
635                             );
636                         } else {
637                             span_err!(diagnostic, meta.span, E0551, "incorrect meta item");
638                         }
639
640                         false
641                     }
642                 };
643
644                 let mut since = None;
645                 let mut note = None;
646                 for meta in list {
647                     match &meta.node {
648                         NestedMetaItemKind::MetaItem(mi) => {
649                             match &*mi.name().as_str() {
650                                 "since" => if !get(mi, &mut since) { continue 'outer },
651                                 "note" => if !get(mi, &mut note) { continue 'outer },
652                                 _ => {
653                                     handle_errors(
654                                         sess,
655                                         meta.span,
656                                         AttrError::UnknownMetaItem(mi.name(), &["since", "note"]),
657                                     );
658                                     continue 'outer
659                                 }
660                             }
661                         }
662                         NestedMetaItemKind::Literal(lit) => {
663                             handle_errors(
664                                 sess,
665                                 lit.span,
666                                 AttrError::UnsupportedLiteral(
667                                     "item in `deprecated` must be a key/value pair",
668                                     false,
669                                 ),
670                             );
671                             continue 'outer
672                         }
673                     }
674                 }
675
676                 Some(Deprecation { since, note })
677             }
678         };
679     }
680
681     depr
682 }
683
684 #[derive(PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
685 pub enum ReprAttr {
686     ReprInt(IntType),
687     ReprC,
688     ReprPacked(u32),
689     ReprSimd,
690     ReprTransparent,
691     ReprAlign(u32),
692 }
693
694 #[derive(Eq, Hash, PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
695 pub enum IntType {
696     SignedInt(ast::IntTy),
697     UnsignedInt(ast::UintTy)
698 }
699
700 impl IntType {
701     #[inline]
702     pub fn is_signed(self) -> bool {
703         use IntType::*;
704
705         match self {
706             SignedInt(..) => true,
707             UnsignedInt(..) => false
708         }
709     }
710 }
711
712 /// Parse #[repr(...)] forms.
713 ///
714 /// Valid repr contents: any of the primitive integral type names (see
715 /// `int_type_of_word`, below) to specify enum discriminant type; `C`, to use
716 /// the same discriminant size that the corresponding C enum would or C
717 /// structure layout, `packed` to remove padding, and `transparent` to elegate representation
718 /// concerns to the only non-ZST field.
719 pub fn find_repr_attrs(sess: &ParseSess, attr: &Attribute) -> Vec<ReprAttr> {
720     use ReprAttr::*;
721
722     let mut acc = Vec::new();
723     let diagnostic = &sess.span_diagnostic;
724     if attr.path == "repr" {
725         if let Some(items) = attr.meta_item_list() {
726             mark_used(attr);
727             for item in items {
728                 if !item.is_meta_item() {
729                     handle_errors(
730                         sess,
731                         item.span,
732                         AttrError::UnsupportedLiteral(
733                             "meta item in `repr` must be an identifier",
734                             false,
735                         ),
736                     );
737                     continue
738                 }
739
740                 let mut recognised = false;
741                 if let Some(mi) = item.word() {
742                     let word = &*mi.name().as_str();
743                     let hint = match word {
744                         "C" => Some(ReprC),
745                         "packed" => Some(ReprPacked(1)),
746                         "simd" => Some(ReprSimd),
747                         "transparent" => Some(ReprTransparent),
748                         _ => match int_type_of_word(word) {
749                             Some(ity) => Some(ReprInt(ity)),
750                             None => {
751                                 None
752                             }
753                         }
754                     };
755
756                     if let Some(h) = hint {
757                         recognised = true;
758                         acc.push(h);
759                     }
760                 } else if let Some((name, value)) = item.name_value_literal() {
761                     let parse_alignment = |node: &ast::LitKind| -> Result<u32, &'static str> {
762                         if let ast::LitKind::Int(literal, ast::LitIntType::Unsuffixed) = node {
763                             if literal.is_power_of_two() {
764                                 // rustc::ty::layout::Align restricts align to <= 2^29
765                                 if *literal <= 1 << 29 {
766                                     Ok(*literal as u32)
767                                 } else {
768                                     Err("larger than 2^29")
769                                 }
770                             } else {
771                                 Err("not a power of two")
772                             }
773                         } else {
774                             Err("not an unsuffixed integer")
775                         }
776                     };
777
778                     let mut literal_error = None;
779                     if name == "align" {
780                         recognised = true;
781                         match parse_alignment(&value.node) {
782                             Ok(literal) => acc.push(ReprAlign(literal)),
783                             Err(message) => literal_error = Some(message)
784                         };
785                     }
786                     else if name == "packed" {
787                         recognised = true;
788                         match parse_alignment(&value.node) {
789                             Ok(literal) => acc.push(ReprPacked(literal)),
790                             Err(message) => literal_error = Some(message)
791                         };
792                     }
793                     if let Some(literal_error) = literal_error {
794                         span_err!(diagnostic, item.span, E0589,
795                                   "invalid `repr(align)` attribute: {}", literal_error);
796                     }
797                 } else {
798                     if let Some(meta_item) = item.meta_item() {
799                         if meta_item.name() == "align" {
800                             if let MetaItemKind::NameValue(ref value) = meta_item.node {
801                                 recognised = true;
802                                 let mut err = struct_span_err!(diagnostic, item.span, E0693,
803                                     "incorrect `repr(align)` attribute format");
804                                 match value.node {
805                                     ast::LitKind::Int(int, ast::LitIntType::Unsuffixed) => {
806                                         err.span_suggestion(
807                                             item.span,
808                                             "use parentheses instead",
809                                             format!("align({})", int),
810                                             Applicability::MachineApplicable
811                                         );
812                                     }
813                                     ast::LitKind::Str(s, _) => {
814                                         err.span_suggestion(
815                                             item.span,
816                                             "use parentheses instead",
817                                             format!("align({})", s),
818                                             Applicability::MachineApplicable
819                                         );
820                                     }
821                                     _ => {}
822                                 }
823                                 err.emit();
824                             }
825                         }
826                     }
827                 }
828                 if !recognised {
829                     // Not a word we recognize
830                     span_err!(diagnostic, item.span, E0552,
831                               "unrecognized representation hint");
832                 }
833             }
834         }
835     }
836     acc
837 }
838
839 fn int_type_of_word(s: &str) -> Option<IntType> {
840     use IntType::*;
841
842     match s {
843         "i8" => Some(SignedInt(ast::IntTy::I8)),
844         "u8" => Some(UnsignedInt(ast::UintTy::U8)),
845         "i16" => Some(SignedInt(ast::IntTy::I16)),
846         "u16" => Some(UnsignedInt(ast::UintTy::U16)),
847         "i32" => Some(SignedInt(ast::IntTy::I32)),
848         "u32" => Some(UnsignedInt(ast::UintTy::U32)),
849         "i64" => Some(SignedInt(ast::IntTy::I64)),
850         "u64" => Some(UnsignedInt(ast::UintTy::U64)),
851         "i128" => Some(SignedInt(ast::IntTy::I128)),
852         "u128" => Some(UnsignedInt(ast::UintTy::U128)),
853         "isize" => Some(SignedInt(ast::IntTy::Isize)),
854         "usize" => Some(UnsignedInt(ast::UintTy::Usize)),
855         _ => None
856     }
857 }