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