]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_parse/src/validate_attr.rs
Rollup merge of #94113 - Mizobrook-kan:issue-94025, r=estebank
[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, FatalError, PResult};
8 use rustc_feature::{AttributeTemplate, BuiltinAttribute, 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 = attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name));
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(BuiltinAttribute { name, template, .. }) if *name != sym::rustc_dummy => {
24             check_builtin_attribute(sess, attr, *name, *template)
25         }
26         _ if let MacArgs::Eq(..) = attr.get_normal_item().args => {
27             // All key-value attributes are restricted to meta-item syntax.
28             parse_meta(sess, attr)
29                 .map_err(|mut err| {
30                     err.emit();
31                 })
32                 .ok();
33         }
34         _ => {}
35     }
36 }
37
38 pub fn parse_meta<'a>(sess: &'a ParseSess, attr: &Attribute) -> PResult<'a, MetaItem> {
39     let item = attr.get_normal_item();
40     Ok(MetaItem {
41         span: attr.span,
42         path: item.path.clone(),
43         kind: match &item.args {
44             MacArgs::Empty => MetaItemKind::Word,
45             MacArgs::Eq(_, t) => {
46                 let t = TokenTree::Token(t.clone()).into();
47                 let v = parse_in(sess, t, "name value", |p| p.parse_unsuffixed_lit())?;
48                 MetaItemKind::NameValue(v)
49             }
50             MacArgs::Delimited(dspan, delim, t) => {
51                 check_meta_bad_delim(sess, *dspan, *delim, "wrong meta list delimiters");
52                 let nmis = parse_in(sess, t.clone(), "meta list", |p| p.parse_meta_seq_top())?;
53                 MetaItemKind::List(nmis)
54             }
55         },
56     })
57 }
58
59 pub 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
94     match parse_meta(sess, attr) {
95         Ok(meta) => {
96             if !should_skip(name) && !is_attr_template_compatible(&template, &meta.kind) {
97                 emit_malformed_attribute(sess, attr, name, template);
98             }
99         }
100         Err(mut err) => {
101             err.emit();
102         }
103     }
104 }
105
106 fn emit_malformed_attribute(
107     sess: &ParseSess,
108     attr: &Attribute,
109     name: Symbol,
110     template: AttributeTemplate,
111 ) {
112     // Some of previously accepted forms were used in practice,
113     // report them as warnings for now.
114     let should_warn = |name| {
115         matches!(name, sym::doc | sym::ignore | sym::inline | sym::link | sym::test | sym::bench)
116     };
117
118     let error_msg = format!("malformed `{}` attribute input", name);
119     let mut msg = "attribute must be of the form ".to_owned();
120     let mut suggestions = vec![];
121     let mut first = true;
122     let inner = if attr.style == ast::AttrStyle::Inner { "!" } else { "" };
123     if template.word {
124         first = false;
125         let code = format!("#{}[{}]", inner, name);
126         msg.push_str(&format!("`{}`", &code));
127         suggestions.push(code);
128     }
129     if let Some(descr) = template.list {
130         if !first {
131             msg.push_str(" or ");
132         }
133         first = false;
134         let code = format!("#{}[{}({})]", inner, name, descr);
135         msg.push_str(&format!("`{}`", &code));
136         suggestions.push(code);
137     }
138     if let Some(descr) = template.name_value_str {
139         if !first {
140             msg.push_str(" or ");
141         }
142         let code = format!("#{}[{} = \"{}\"]", inner, name, descr);
143         msg.push_str(&format!("`{}`", &code));
144         suggestions.push(code);
145     }
146     if should_warn(name) {
147         sess.buffer_lint(&ILL_FORMED_ATTRIBUTE_INPUT, attr.span, ast::CRATE_NODE_ID, &msg);
148     } else {
149         sess.span_diagnostic
150             .struct_span_err(attr.span, &error_msg)
151             .span_suggestions(
152                 attr.span,
153                 if suggestions.len() == 1 {
154                     "must be of the form"
155                 } else {
156                     "the following are the possible correct uses"
157                 },
158                 suggestions.into_iter(),
159                 Applicability::HasPlaceholders,
160             )
161             .emit();
162     }
163 }
164
165 pub fn emit_fatal_malformed_builtin_attribute(
166     sess: &ParseSess,
167     attr: &Attribute,
168     name: Symbol,
169 ) -> ! {
170     let template = BUILTIN_ATTRIBUTE_MAP.get(&name).expect("builtin attr defined").template;
171     emit_malformed_attribute(sess, attr, name, template);
172     // This is fatal, otherwise it will likely cause a cascade of other errors
173     // (and an error here is expected to be very rare).
174     FatalError.raise()
175 }