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