]> git.lizzy.rs Git - rust.git/blob - src/librustc_parse/validate_attr.rs
Added minor clarification to specification of realloc.
[rust.git] / src / librustc_parse / validate_attr.rs
1 //! Meta-syntax validation logic of attributes for post-expansion.
2
3 use crate::parse_in;
4
5 use rustc_errors::{Applicability, PResult};
6 use rustc_feature::{AttributeTemplate, BUILTIN_ATTRIBUTE_MAP};
7 use rustc_session::lint::builtin::ILL_FORMED_ATTRIBUTE_INPUT;
8 use rustc_session::parse::ParseSess;
9 use rustc_span::{sym, Symbol};
10 use syntax::ast::{self, Attribute, MacArgs, MacDelimiter, MetaItem, MetaItemKind};
11 use syntax::tokenstream::DelimSpan;
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         _ => {
28             if let MacArgs::Eq(..) = attr.get_normal_item().args {
29                 // All key-value attributes are restricted to meta-item syntax.
30                 parse_meta(sess, attr).map_err(|mut err| err.emit()).ok();
31             }
32         }
33     }
34 }
35
36 pub fn parse_meta<'a>(sess: &'a ParseSess, attr: &Attribute) -> PResult<'a, MetaItem> {
37     let item = attr.get_normal_item();
38     Ok(MetaItem {
39         span: attr.span,
40         path: item.path.clone(),
41         kind: match &item.args {
42             MacArgs::Empty => MetaItemKind::Word,
43             MacArgs::Eq(_, t) => {
44                 let v = parse_in(sess, t.clone(), "name value", |p| p.parse_unsuffixed_lit())?;
45                 MetaItemKind::NameValue(v)
46             }
47             MacArgs::Delimited(dspan, delim, t) => {
48                 check_meta_bad_delim(sess, *dspan, *delim, "wrong meta list delimiters");
49                 let nmis = parse_in(sess, t.clone(), "meta list", |p| p.parse_meta_seq_top())?;
50                 MetaItemKind::List(nmis)
51             }
52         },
53     })
54 }
55
56 crate fn check_meta_bad_delim(sess: &ParseSess, span: DelimSpan, delim: MacDelimiter, msg: &str) {
57     if let ast::MacDelimiter::Parenthesis = delim {
58         return;
59     }
60
61     sess.span_diagnostic
62         .struct_span_err(span.entire(), msg)
63         .multipart_suggestion(
64             "the delimiters should be `(` and `)`",
65             vec![(span.open, "(".to_string()), (span.close, ")".to_string())],
66             Applicability::MachineApplicable,
67         )
68         .emit();
69 }
70
71 /// Checks that the given meta-item is compatible with this `AttributeTemplate`.
72 fn is_attr_template_compatible(template: &AttributeTemplate, meta: &ast::MetaItemKind) -> bool {
73     match meta {
74         MetaItemKind::Word => template.word,
75         MetaItemKind::List(..) => template.list.is_some(),
76         MetaItemKind::NameValue(lit) if lit.kind.is_str() => template.name_value_str.is_some(),
77         MetaItemKind::NameValue(..) => false,
78     }
79 }
80
81 pub fn check_builtin_attribute(
82     sess: &ParseSess,
83     attr: &Attribute,
84     name: Symbol,
85     template: AttributeTemplate,
86 ) {
87     // Some special attributes like `cfg` must be checked
88     // before the generic check, so we skip them here.
89     let should_skip = |name| name == sym::cfg;
90     // Some of previously accepted forms were used in practice,
91     // report them as warnings for now.
92     let should_warn = |name| {
93         name == sym::doc
94             || name == sym::ignore
95             || name == sym::inline
96             || name == sym::link
97             || name == sym::test
98             || name == sym::bench
99     };
100
101     match parse_meta(sess, attr) {
102         Ok(meta) => {
103             if !should_skip(name) && !is_attr_template_compatible(&template, &meta.kind) {
104                 let error_msg = format!("malformed `{}` attribute input", name);
105                 let mut msg = "attribute must be of the form ".to_owned();
106                 let mut suggestions = vec![];
107                 let mut first = true;
108                 if template.word {
109                     first = false;
110                     let code = format!("#[{}]", name);
111                     msg.push_str(&format!("`{}`", &code));
112                     suggestions.push(code);
113                 }
114                 if let Some(descr) = template.list {
115                     if !first {
116                         msg.push_str(" or ");
117                     }
118                     first = false;
119                     let code = format!("#[{}({})]", name, descr);
120                     msg.push_str(&format!("`{}`", &code));
121                     suggestions.push(code);
122                 }
123                 if let Some(descr) = template.name_value_str {
124                     if !first {
125                         msg.push_str(" or ");
126                     }
127                     let code = format!("#[{} = \"{}\"]", name, descr);
128                     msg.push_str(&format!("`{}`", &code));
129                     suggestions.push(code);
130                 }
131                 if should_warn(name) {
132                     sess.buffer_lint(
133                         &ILL_FORMED_ATTRIBUTE_INPUT,
134                         meta.span,
135                         ast::CRATE_NODE_ID,
136                         &msg,
137                     );
138                 } else {
139                     sess.span_diagnostic
140                         .struct_span_err(meta.span, &error_msg)
141                         .span_suggestions(
142                             meta.span,
143                             if suggestions.len() == 1 {
144                                 "must be of the form"
145                             } else {
146                                 "the following are the possible correct uses"
147                             },
148                             suggestions.into_iter(),
149                             Applicability::HasPlaceholders,
150                         )
151                         .emit();
152                 }
153             }
154         }
155         Err(mut err) => err.emit(),
156     }
157 }