]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_parse/src/validate_attr.rs
Rollup merge of #104608 - Nilstrieb:fixmed, r=compiler-errors
[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;
6 use rustc_ast::{self as ast, Attribute, MacArgs, MacArgsEq, MacDelimiter, MetaItem, MetaItemKind};
7 use rustc_ast_pretty::pprust;
8 use rustc_errors::{Applicability, FatalError, PResult};
9 use rustc_feature::{AttributeTemplate, BuiltinAttribute, BUILTIN_ATTRIBUTE_MAP};
10 use rustc_session::lint::builtin::ILL_FORMED_ATTRIBUTE_INPUT;
11 use rustc_session::parse::ParseSess;
12 use rustc_span::{sym, Symbol};
13
14 pub fn check_meta(sess: &ParseSess, attr: &Attribute) {
15     if attr.is_doc_comment() {
16         return;
17     }
18
19     let attr_info = attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name));
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(BuiltinAttribute { name, template, .. }) if *name != sym::rustc_dummy => {
25             check_builtin_attribute(sess, attr, *name, *template)
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)
30                 .map_err(|mut err| {
31                     err.emit();
32                 })
33                 .ok();
34         }
35         _ => {}
36     }
37 }
38
39 pub fn parse_meta<'a>(sess: &'a ParseSess, attr: &Attribute) -> PResult<'a, MetaItem> {
40     let item = attr.get_normal_item();
41     Ok(MetaItem {
42         span: attr.span,
43         path: item.path.clone(),
44         kind: match &item.args {
45             MacArgs::Empty => MetaItemKind::Word,
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             MacArgs::Eq(_, MacArgsEq::Ast(expr)) => {
52                 if let ast::ExprKind::Lit(token_lit) = expr.kind
53                     && let Ok(lit) = ast::Lit::from_token_lit(token_lit, expr.span)
54                 {
55                     if token_lit.suffix.is_some() {
56                         let mut err = sess.span_diagnostic.struct_span_err(
57                             expr.span,
58                             "suffixed literals are not allowed in attributes",
59                         );
60                         err.help(
61                             "instead of using a suffixed literal (`1u8`, `1.0f32`, etc.), \
62                             use an unsuffixed version (`1`, `1.0`, etc.)",
63                         );
64                         return Err(err);
65                     } else {
66                         MetaItemKind::NameValue(lit)
67                     }
68                 } else {
69                     // The non-error case can happen with e.g. `#[foo = 1+1]`. The error case can
70                     // happen with e.g. `#[foo = include_str!("non-existent-file.rs")]`; in that
71                     // case we delay the error because an earlier error will have already been
72                     // reported.
73                     let msg = format!("unexpected expression: `{}`", pprust::expr_to_string(expr));
74                     let mut err = sess.span_diagnostic.struct_span_err(expr.span, msg);
75                     if let ast::ExprKind::Err = expr.kind {
76                         err.downgrade_to_delayed_bug();
77                     }
78                     return Err(err);
79                 }
80             }
81             MacArgs::Eq(_, MacArgsEq::Hir(lit)) => MetaItemKind::NameValue(lit.clone()),
82         },
83     })
84 }
85
86 pub fn check_meta_bad_delim(sess: &ParseSess, span: DelimSpan, delim: MacDelimiter, msg: &str) {
87     if let ast::MacDelimiter::Parenthesis = delim {
88         return;
89     }
90
91     sess.span_diagnostic
92         .struct_span_err(span.entire(), msg)
93         .multipart_suggestion(
94             "the delimiters should be `(` and `)`",
95             vec![(span.open, "(".to_string()), (span.close, ")".to_string())],
96             Applicability::MachineApplicable,
97         )
98         .emit();
99 }
100
101 /// Checks that the given meta-item is compatible with this `AttributeTemplate`.
102 fn is_attr_template_compatible(template: &AttributeTemplate, meta: &ast::MetaItemKind) -> bool {
103     match meta {
104         MetaItemKind::Word => template.word,
105         MetaItemKind::List(..) => template.list.is_some(),
106         MetaItemKind::NameValue(lit) if lit.kind.is_str() => template.name_value_str.is_some(),
107         MetaItemKind::NameValue(..) => false,
108     }
109 }
110
111 pub fn check_builtin_attribute(
112     sess: &ParseSess,
113     attr: &Attribute,
114     name: Symbol,
115     template: AttributeTemplate,
116 ) {
117     // Some special attributes like `cfg` must be checked
118     // before the generic check, so we skip them here.
119     let should_skip = |name| name == sym::cfg;
120
121     match parse_meta(sess, attr) {
122         Ok(meta) => {
123             if !should_skip(name) && !is_attr_template_compatible(&template, &meta.kind) {
124                 emit_malformed_attribute(sess, attr, name, template);
125             }
126         }
127         Err(mut err) => {
128             err.emit();
129         }
130     }
131 }
132
133 fn emit_malformed_attribute(
134     sess: &ParseSess,
135     attr: &Attribute,
136     name: Symbol,
137     template: AttributeTemplate,
138 ) {
139     // Some of previously accepted forms were used in practice,
140     // report them as warnings for now.
141     let should_warn = |name| {
142         matches!(name, sym::doc | sym::ignore | sym::inline | sym::link | sym::test | sym::bench)
143     };
144
145     let error_msg = format!("malformed `{}` attribute input", name);
146     let mut msg = "attribute must be of the form ".to_owned();
147     let mut suggestions = vec![];
148     let mut first = true;
149     let inner = if attr.style == ast::AttrStyle::Inner { "!" } else { "" };
150     if template.word {
151         first = false;
152         let code = format!("#{}[{}]", inner, name);
153         msg.push_str(&format!("`{}`", &code));
154         suggestions.push(code);
155     }
156     if let Some(descr) = template.list {
157         if !first {
158             msg.push_str(" or ");
159         }
160         first = false;
161         let code = format!("#{}[{}({})]", inner, name, descr);
162         msg.push_str(&format!("`{}`", &code));
163         suggestions.push(code);
164     }
165     if let Some(descr) = template.name_value_str {
166         if !first {
167             msg.push_str(" or ");
168         }
169         let code = format!("#{}[{} = \"{}\"]", inner, name, descr);
170         msg.push_str(&format!("`{}`", &code));
171         suggestions.push(code);
172     }
173     if should_warn(name) {
174         sess.buffer_lint(&ILL_FORMED_ATTRIBUTE_INPUT, attr.span, ast::CRATE_NODE_ID, &msg);
175     } else {
176         sess.span_diagnostic
177             .struct_span_err(attr.span, &error_msg)
178             .span_suggestions(
179                 attr.span,
180                 if suggestions.len() == 1 {
181                     "must be of the form"
182                 } else {
183                     "the following are the possible correct uses"
184                 },
185                 suggestions.into_iter(),
186                 Applicability::HasPlaceholders,
187             )
188             .emit();
189     }
190 }
191
192 pub fn emit_fatal_malformed_builtin_attribute(
193     sess: &ParseSess,
194     attr: &Attribute,
195     name: Symbol,
196 ) -> ! {
197     let template = BUILTIN_ATTRIBUTE_MAP.get(&name).expect("builtin attr defined").template;
198     emit_malformed_attribute(sess, attr, name, template);
199     // This is fatal, otherwise it will likely cause a cascade of other errors
200     // (and an error here is expected to be very rare).
201     FatalError.raise()
202 }