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