]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_parse/src/validate_attr.rs
Rollup merge of #104692 - chbaker0:libtest-cfg-if, r=thomcc
[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, Symbol};
14
15 pub fn check_meta(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::Lit::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     // Some special attributes like `cfg` must be checked
119     // before the generic check, so we skip them here.
120     let should_skip = |name| name == sym::cfg;
121
122     match parse_meta(sess, attr) {
123         Ok(meta) => {
124             if !should_skip(name) && !is_attr_template_compatible(&template, &meta.kind) {
125                 emit_malformed_attribute(sess, attr, name, template);
126             }
127         }
128         Err(mut err) => {
129             err.emit();
130         }
131     }
132 }
133
134 fn emit_malformed_attribute(
135     sess: &ParseSess,
136     attr: &Attribute,
137     name: Symbol,
138     template: AttributeTemplate,
139 ) {
140     // Some of previously accepted forms were used in practice,
141     // report them as warnings for now.
142     let should_warn = |name| {
143         matches!(name, sym::doc | sym::ignore | sym::inline | sym::link | sym::test | sym::bench)
144     };
145
146     let error_msg = format!("malformed `{}` attribute input", name);
147     let mut msg = "attribute must be of the form ".to_owned();
148     let mut suggestions = vec![];
149     let mut first = true;
150     let inner = if attr.style == ast::AttrStyle::Inner { "!" } else { "" };
151     if template.word {
152         first = false;
153         let code = format!("#{}[{}]", inner, name);
154         msg.push_str(&format!("`{}`", &code));
155         suggestions.push(code);
156     }
157     if let Some(descr) = template.list {
158         if !first {
159             msg.push_str(" or ");
160         }
161         first = false;
162         let code = format!("#{}[{}({})]", inner, name, descr);
163         msg.push_str(&format!("`{}`", &code));
164         suggestions.push(code);
165     }
166     if let Some(descr) = template.name_value_str {
167         if !first {
168             msg.push_str(" or ");
169         }
170         let code = format!("#{}[{} = \"{}\"]", inner, name, descr);
171         msg.push_str(&format!("`{}`", &code));
172         suggestions.push(code);
173     }
174     if should_warn(name) {
175         sess.buffer_lint(&ILL_FORMED_ATTRIBUTE_INPUT, attr.span, ast::CRATE_NODE_ID, &msg);
176     } else {
177         sess.span_diagnostic
178             .struct_span_err(attr.span, &error_msg)
179             .span_suggestions(
180                 attr.span,
181                 if suggestions.len() == 1 {
182                     "must be of the form"
183                 } else {
184                     "the following are the possible correct uses"
185                 },
186                 suggestions.into_iter(),
187                 Applicability::HasPlaceholders,
188             )
189             .emit();
190     }
191 }
192
193 pub fn emit_fatal_malformed_builtin_attribute(
194     sess: &ParseSess,
195     attr: &Attribute,
196     name: Symbol,
197 ) -> ! {
198     let template = BUILTIN_ATTRIBUTE_MAP.get(&name).expect("builtin attr defined").template;
199     emit_malformed_attribute(sess, attr, name, template);
200     // This is fatal, otherwise it will likely cause a cascade of other errors
201     // (and an error here is expected to be very rare).
202     FatalError.raise()
203 }