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