]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_parse/src/validate_attr.rs
Stabilize File::options()
[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, 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         _ 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::Eq(_, t) => {
47                 let t = TokenTree::Token(t.clone()).into();
48                 let v = parse_in(sess, t, "name value", |p| p.parse_unsuffixed_lit())?;
49                 MetaItemKind::NameValue(v)
50             }
51             MacArgs::Delimited(dspan, delim, t) => {
52                 check_meta_bad_delim(sess, *dspan, *delim, "wrong meta list delimiters");
53                 let nmis = parse_in(sess, t.clone(), "meta list", |p| p.parse_meta_seq_top())?;
54                 MetaItemKind::List(nmis)
55             }
56         },
57     })
58 }
59
60 pub fn check_meta_bad_delim(sess: &ParseSess, span: DelimSpan, delim: MacDelimiter, msg: &str) {
61     if let ast::MacDelimiter::Parenthesis = delim {
62         return;
63     }
64
65     sess.span_diagnostic
66         .struct_span_err(span.entire(), msg)
67         .multipart_suggestion(
68             "the delimiters should be `(` and `)`",
69             vec![(span.open, "(".to_string()), (span.close, ")".to_string())],
70             Applicability::MachineApplicable,
71         )
72         .emit();
73 }
74
75 /// Checks that the given meta-item is compatible with this `AttributeTemplate`.
76 fn is_attr_template_compatible(template: &AttributeTemplate, meta: &ast::MetaItemKind) -> bool {
77     match meta {
78         MetaItemKind::Word => template.word,
79         MetaItemKind::List(..) => template.list.is_some(),
80         MetaItemKind::NameValue(lit) if lit.kind.is_str() => template.name_value_str.is_some(),
81         MetaItemKind::NameValue(..) => false,
82     }
83 }
84
85 pub fn check_builtin_attribute(
86     sess: &ParseSess,
87     attr: &Attribute,
88     name: Symbol,
89     template: AttributeTemplate,
90 ) {
91     // Some special attributes like `cfg` must be checked
92     // before the generic check, so we skip them here.
93     let should_skip = |name| name == sym::cfg;
94
95     match parse_meta(sess, attr) {
96         Ok(meta) => {
97             if !should_skip(name) && !is_attr_template_compatible(&template, &meta.kind) {
98                 emit_malformed_attribute(sess, attr, name, template);
99             }
100         }
101         Err(mut err) => {
102             err.emit();
103         }
104     }
105 }
106
107 fn emit_malformed_attribute(
108     sess: &ParseSess,
109     attr: &Attribute,
110     name: Symbol,
111     template: AttributeTemplate,
112 ) {
113     // Some of previously accepted forms were used in practice,
114     // report them as warnings for now.
115     let should_warn = |name| {
116         matches!(name, sym::doc | sym::ignore | sym::inline | sym::link | sym::test | sym::bench)
117     };
118
119     let error_msg = format!("malformed `{}` attribute input", name);
120     let mut msg = "attribute must be of the form ".to_owned();
121     let mut suggestions = vec![];
122     let mut first = true;
123     let inner = if attr.style == ast::AttrStyle::Inner { "!" } else { "" };
124     if template.word {
125         first = false;
126         let code = format!("#{}[{}]", inner, name);
127         msg.push_str(&format!("`{}`", &code));
128         suggestions.push(code);
129     }
130     if let Some(descr) = template.list {
131         if !first {
132             msg.push_str(" or ");
133         }
134         first = false;
135         let code = format!("#{}[{}({})]", inner, name, descr);
136         msg.push_str(&format!("`{}`", &code));
137         suggestions.push(code);
138     }
139     if let Some(descr) = template.name_value_str {
140         if !first {
141             msg.push_str(" or ");
142         }
143         let code = format!("#{}[{} = \"{}\"]", inner, name, descr);
144         msg.push_str(&format!("`{}`", &code));
145         suggestions.push(code);
146     }
147     if should_warn(name) {
148         sess.buffer_lint(&ILL_FORMED_ATTRIBUTE_INPUT, attr.span, ast::CRATE_NODE_ID, &msg);
149     } else {
150         sess.span_diagnostic
151             .struct_span_err(attr.span, &error_msg)
152             .span_suggestions(
153                 attr.span,
154                 if suggestions.len() == 1 {
155                     "must be of the form"
156                 } else {
157                     "the following are the possible correct uses"
158                 },
159                 suggestions.into_iter(),
160                 Applicability::HasPlaceholders,
161             )
162             .emit();
163     }
164 }
165
166 pub fn emit_fatal_malformed_builtin_attribute(
167     sess: &ParseSess,
168     attr: &Attribute,
169     name: Symbol,
170 ) -> ! {
171     let template = BUILTIN_ATTRIBUTE_MAP.get(&name).expect("builtin attr defined").2;
172     emit_malformed_attribute(sess, attr, name, template);
173     // This is fatal, otherwise it will likely cause a cascade of other errors
174     // (and an error here is expected to be very rare).
175     FatalError.raise()
176 }