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