1 //! Meta-syntax validation logic of attributes for post-expansion.
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};
13 pub fn check_meta(sess: &ParseSess, attr: &Attribute) {
14 if attr.is_doc_comment() {
19 attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name)).map(|a| **a);
21 // Check input tokens for built-in and key-value attributes.
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)
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)
39 pub fn parse_meta<'a>(sess: &'a ParseSess, attr: &Attribute) -> PResult<'a, MetaItem> {
40 let item = attr.get_normal_item();
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)
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)
60 pub fn check_meta_bad_delim(sess: &ParseSess, span: DelimSpan, delim: MacDelimiter, msg: &str) {
61 if let ast::MacDelimiter::Parenthesis = delim {
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,
75 /// Checks that the given meta-item is compatible with this `AttributeTemplate`.
76 fn is_attr_template_compatible(template: &AttributeTemplate, meta: &ast::MetaItemKind) -> bool {
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,
85 pub fn check_builtin_attribute(
89 template: AttributeTemplate,
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;
95 match parse_meta(sess, attr) {
97 if !should_skip(name) && !is_attr_template_compatible(&template, &meta.kind) {
98 emit_malformed_attribute(sess, attr, name, template);
107 fn emit_malformed_attribute(
111 template: AttributeTemplate,
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)
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 { "" };
126 let code = format!("#{}[{}]", inner, name);
127 msg.push_str(&format!("`{}`", &code));
128 suggestions.push(code);
130 if let Some(descr) = template.list {
132 msg.push_str(" or ");
135 let code = format!("#{}[{}({})]", inner, name, descr);
136 msg.push_str(&format!("`{}`", &code));
137 suggestions.push(code);
139 if let Some(descr) = template.name_value_str {
141 msg.push_str(" or ");
143 let code = format!("#{}[{} = \"{}\"]", inner, name, descr);
144 msg.push_str(&format!("`{}`", &code));
145 suggestions.push(code);
147 if should_warn(name) {
148 sess.buffer_lint(&ILL_FORMED_ATTRIBUTE_INPUT, attr.span, ast::CRATE_NODE_ID, &msg);
151 .struct_span_err(attr.span, &error_msg)
154 if suggestions.len() == 1 {
155 "must be of the form"
157 "the following are the possible correct uses"
159 suggestions.into_iter(),
160 Applicability::HasPlaceholders,
166 pub fn emit_fatal_malformed_builtin_attribute(
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).