]> git.lizzy.rs Git - rust.git/blob - src/librustc_parse/validate_attr.rs
Rollup merge of #66771 - SimonSapin:panic-stability, r=KodrAus
[rust.git] / src / librustc_parse / validate_attr.rs
1 //! Meta-syntax validation logic of attributes for post-expansion.
2
3 use crate::parse_in;
4
5 use rustc_errors::{PResult, Applicability};
6 use rustc_feature::{AttributeTemplate, BUILTIN_ATTRIBUTE_MAP};
7 use syntax::ast::{self, Attribute, AttrKind, Ident, MacArgs, MacDelimiter, MetaItem, MetaItemKind};
8 use syntax::attr::mk_name_value_item_str;
9 use syntax::early_buffered_lints::ILL_FORMED_ATTRIBUTE_INPUT;
10 use syntax::tokenstream::DelimSpan;
11 use syntax::sess::ParseSess;
12 use syntax_pos::{Symbol, sym};
13
14 pub fn check_meta(sess: &ParseSess, attr: &Attribute) {
15     let attr_info =
16         attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name)).map(|a| **a);
17
18     // Check input tokens for built-in and key-value attributes.
19     match attr_info {
20         // `rustc_dummy` doesn't have any restrictions specific to built-in attributes.
21         Some((name, _, template, _)) if name != sym::rustc_dummy =>
22             check_builtin_attribute(sess, attr, name, template),
23         _ => if let MacArgs::Eq(..) = attr.get_normal_item().args {
24             // All key-value attributes are restricted to meta-item syntax.
25             parse_meta(sess, attr).map_err(|mut err| err.emit()).ok();
26         }
27     }
28 }
29
30 pub fn parse_meta<'a>(sess: &'a ParseSess, attr: &Attribute) -> PResult<'a, MetaItem> {
31     Ok(match attr.kind {
32         AttrKind::Normal(ref item) => MetaItem {
33             span: attr.span,
34             path: item.path.clone(),
35             kind: match &attr.get_normal_item().args {
36                 MacArgs::Empty => MetaItemKind::Word,
37                 MacArgs::Eq(_, t) => {
38                     let v = parse_in(sess, t.clone(), "name value", |p| p.parse_unsuffixed_lit())?;
39                     MetaItemKind::NameValue(v)
40                 }
41                 MacArgs::Delimited(dspan, delim, t) => {
42                     check_meta_bad_delim(sess, *dspan, *delim, "wrong meta list delimiters");
43                     let nmis = parse_in(sess, t.clone(), "meta list", |p| p.parse_meta_seq_top())?;
44                     MetaItemKind::List(nmis)
45                 }
46             }
47         },
48         AttrKind::DocComment(comment) => {
49             mk_name_value_item_str(Ident::new(sym::doc, attr.span), comment, attr.span)
50         }
51     })
52 }
53
54 crate fn check_meta_bad_delim(sess: &ParseSess, span: DelimSpan, delim: MacDelimiter, msg: &str) {
55     if let ast::MacDelimiter::Parenthesis = delim {
56         return;
57     }
58
59     sess.span_diagnostic
60         .struct_span_err(span.entire(), msg)
61         .multipart_suggestion(
62             "the delimiters should be `(` and `)`",
63             vec![
64                 (span.open, "(".to_string()),
65                 (span.close, ")".to_string()),
66             ],
67             Applicability::MachineApplicable,
68         )
69         .emit();
70 }
71
72 /// Checks that the given meta-item is compatible with this `AttributeTemplate`.
73 fn is_attr_template_compatible(template: &AttributeTemplate, meta: &ast::MetaItemKind) -> bool {
74     match meta {
75         MetaItemKind::Word => template.word,
76         MetaItemKind::List(..) => template.list.is_some(),
77         MetaItemKind::NameValue(lit) if lit.kind.is_str() => template.name_value_str.is_some(),
78         MetaItemKind::NameValue(..) => false,
79     }
80 }
81
82 pub fn check_builtin_attribute(
83     sess: &ParseSess,
84     attr: &Attribute,
85     name: Symbol,
86     template: AttributeTemplate,
87 ) {
88     // Some special attributes like `cfg` must be checked
89     // before the generic check, so we skip them here.
90     let should_skip = |name| name == sym::cfg;
91     // Some of previously accepted forms were used in practice,
92     // report them as warnings for now.
93     let should_warn = |name| name == sym::doc || name == sym::ignore ||
94                              name == sym::inline || name == sym::link ||
95                              name == sym::test || name == sym::bench;
96
97     match parse_meta(sess, attr) {
98         Ok(meta) => if !should_skip(name) && !is_attr_template_compatible(&template, &meta.kind) {
99             let error_msg = format!("malformed `{}` attribute input", name);
100             let mut msg = "attribute must be of the form ".to_owned();
101             let mut suggestions = vec![];
102             let mut first = true;
103             if template.word {
104                 first = false;
105                 let code = format!("#[{}]", name);
106                 msg.push_str(&format!("`{}`", &code));
107                 suggestions.push(code);
108             }
109             if let Some(descr) = template.list {
110                 if !first {
111                     msg.push_str(" or ");
112                 }
113                 first = false;
114                 let code = format!("#[{}({})]", name, descr);
115                 msg.push_str(&format!("`{}`", &code));
116                 suggestions.push(code);
117             }
118             if let Some(descr) = template.name_value_str {
119                 if !first {
120                     msg.push_str(" or ");
121                 }
122                 let code = format!("#[{} = \"{}\"]", name, descr);
123                 msg.push_str(&format!("`{}`", &code));
124                 suggestions.push(code);
125             }
126             if should_warn(name) {
127                 sess.buffer_lint(
128                     &ILL_FORMED_ATTRIBUTE_INPUT,
129                     meta.span,
130                     ast::CRATE_NODE_ID,
131                     &msg,
132                 );
133             } else {
134                 sess.span_diagnostic.struct_span_err(meta.span, &error_msg)
135                     .span_suggestions(
136                         meta.span,
137                         if suggestions.len() == 1 {
138                             "must be of the form"
139                         } else {
140                             "the following are the possible correct uses"
141                         },
142                         suggestions.into_iter(),
143                         Applicability::HasPlaceholders,
144                     ).emit();
145             }
146         }
147         Err(mut err) => err.emit(),
148     }
149 }