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, BuiltinAttribute, 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() {
18 let attr_info = attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name));
20 // Check input tokens for built-in and key-value attributes.
22 // `rustc_dummy` doesn't have any restrictions specific to built-in attributes.
23 Some(BuiltinAttribute { name, template, .. }) if *name != sym::rustc_dummy => {
24 check_builtin_attribute(sess, attr, *name, *template)
26 _ if let MacArgs::Eq(..) = attr.get_normal_item().args => {
27 // All key-value attributes are restricted to meta-item syntax.
28 parse_meta(sess, attr)
38 pub fn parse_meta<'a>(sess: &'a ParseSess, attr: &Attribute) -> PResult<'a, MetaItem> {
39 let item = attr.get_normal_item();
42 path: item.path.clone(),
43 kind: match &item.args {
44 MacArgs::Empty => MetaItemKind::Word,
45 MacArgs::Eq(_, t) => {
46 let t = TokenTree::Token(t.clone()).into();
47 let v = parse_in(sess, t, "name value", |p| p.parse_unsuffixed_lit())?;
48 MetaItemKind::NameValue(v)
50 MacArgs::Delimited(dspan, delim, t) => {
51 check_meta_bad_delim(sess, *dspan, *delim, "wrong meta list delimiters");
52 let nmis = parse_in(sess, t.clone(), "meta list", |p| p.parse_meta_seq_top())?;
53 MetaItemKind::List(nmis)
59 pub fn check_meta_bad_delim(sess: &ParseSess, span: DelimSpan, delim: MacDelimiter, msg: &str) {
60 if let ast::MacDelimiter::Parenthesis = delim {
65 .struct_span_err(span.entire(), msg)
66 .multipart_suggestion(
67 "the delimiters should be `(` and `)`",
68 vec![(span.open, "(".to_string()), (span.close, ")".to_string())],
69 Applicability::MachineApplicable,
74 /// Checks that the given meta-item is compatible with this `AttributeTemplate`.
75 fn is_attr_template_compatible(template: &AttributeTemplate, meta: &ast::MetaItemKind) -> bool {
77 MetaItemKind::Word => template.word,
78 MetaItemKind::List(..) => template.list.is_some(),
79 MetaItemKind::NameValue(lit) if lit.kind.is_str() => template.name_value_str.is_some(),
80 MetaItemKind::NameValue(..) => false,
84 pub fn check_builtin_attribute(
88 template: AttributeTemplate,
90 // Some special attributes like `cfg` must be checked
91 // before the generic check, so we skip them here.
92 let should_skip = |name| name == sym::cfg;
94 match parse_meta(sess, attr) {
96 if !should_skip(name) && !is_attr_template_compatible(&template, &meta.kind) {
97 emit_malformed_attribute(sess, attr, name, template);
106 fn emit_malformed_attribute(
110 template: AttributeTemplate,
112 // Some of previously accepted forms were used in practice,
113 // report them as warnings for now.
114 let should_warn = |name| {
115 matches!(name, sym::doc | sym::ignore | sym::inline | sym::link | sym::test | sym::bench)
118 let error_msg = format!("malformed `{}` attribute input", name);
119 let mut msg = "attribute must be of the form ".to_owned();
120 let mut suggestions = vec![];
121 let mut first = true;
122 let inner = if attr.style == ast::AttrStyle::Inner { "!" } else { "" };
125 let code = format!("#{}[{}]", inner, name);
126 msg.push_str(&format!("`{}`", &code));
127 suggestions.push(code);
129 if let Some(descr) = template.list {
131 msg.push_str(" or ");
134 let code = format!("#{}[{}({})]", inner, name, descr);
135 msg.push_str(&format!("`{}`", &code));
136 suggestions.push(code);
138 if let Some(descr) = template.name_value_str {
140 msg.push_str(" or ");
142 let code = format!("#{}[{} = \"{}\"]", inner, name, descr);
143 msg.push_str(&format!("`{}`", &code));
144 suggestions.push(code);
146 if should_warn(name) {
147 sess.buffer_lint(&ILL_FORMED_ATTRIBUTE_INPUT, attr.span, ast::CRATE_NODE_ID, &msg);
150 .struct_span_err(attr.span, &error_msg)
153 if suggestions.len() == 1 {
154 "must be of the form"
156 "the following are the possible correct uses"
158 suggestions.into_iter(),
159 Applicability::HasPlaceholders,
165 pub fn emit_fatal_malformed_builtin_attribute(
170 let template = BUILTIN_ATTRIBUTE_MAP.get(&name).expect("builtin attr defined").template;
171 emit_malformed_attribute(sess, attr, name, template);
172 // This is fatal, otherwise it will likely cause a cascade of other errors
173 // (and an error here is expected to be very rare).