1 //! Meta-syntax validation logic of attributes for post-expansion.
5 use rustc_ast::tokenstream::DelimSpan;
6 use rustc_ast::{self as ast, Attribute, MacArgs, MacArgsEq, MacDelimiter, MetaItem, MetaItemKind};
7 use rustc_ast_pretty::pprust;
8 use rustc_errors::{Applicability, FatalError, PResult};
9 use rustc_feature::{AttributeTemplate, BuiltinAttribute, BUILTIN_ATTRIBUTE_MAP};
10 use rustc_session::lint::builtin::ILL_FORMED_ATTRIBUTE_INPUT;
11 use rustc_session::parse::ParseSess;
12 use rustc_span::{sym, Symbol};
14 pub fn check_meta(sess: &ParseSess, attr: &Attribute) {
15 if attr.is_doc_comment() {
19 let attr_info = attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name));
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(BuiltinAttribute { 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::Delimited(dspan, delim, t) => {
47 check_meta_bad_delim(sess, *dspan, *delim, "wrong meta list delimiters");
48 let nmis = parse_in(sess, t.clone(), "meta list", |p| p.parse_meta_seq_top())?;
49 MetaItemKind::List(nmis)
51 MacArgs::Eq(_, MacArgsEq::Ast(expr)) => {
52 if let ast::ExprKind::Lit(token_lit) = expr.kind
53 && let Ok(lit) = ast::Lit::from_token_lit(token_lit, expr.span)
55 if token_lit.suffix.is_some() {
56 let mut err = sess.span_diagnostic.struct_span_err(
58 "suffixed literals are not allowed in attributes",
61 "instead of using a suffixed literal (`1u8`, `1.0f32`, etc.), \
62 use an unsuffixed version (`1`, `1.0`, etc.)",
66 MetaItemKind::NameValue(lit)
69 // The non-error case can happen with e.g. `#[foo = 1+1]`. The error case can
70 // happen with e.g. `#[foo = include_str!("non-existent-file.rs")]`; in that
71 // case we delay the error because an earlier error will have already been
73 let msg = format!("unexpected expression: `{}`", pprust::expr_to_string(expr));
74 let mut err = sess.span_diagnostic.struct_span_err(expr.span, msg);
75 if let ast::ExprKind::Err = expr.kind {
76 err.downgrade_to_delayed_bug();
81 MacArgs::Eq(_, MacArgsEq::Hir(lit)) => MetaItemKind::NameValue(lit.clone()),
86 pub fn check_meta_bad_delim(sess: &ParseSess, span: DelimSpan, delim: MacDelimiter, msg: &str) {
87 if let ast::MacDelimiter::Parenthesis = delim {
92 .struct_span_err(span.entire(), msg)
93 .multipart_suggestion(
94 "the delimiters should be `(` and `)`",
95 vec![(span.open, "(".to_string()), (span.close, ")".to_string())],
96 Applicability::MachineApplicable,
101 /// Checks that the given meta-item is compatible with this `AttributeTemplate`.
102 fn is_attr_template_compatible(template: &AttributeTemplate, meta: &ast::MetaItemKind) -> bool {
104 MetaItemKind::Word => template.word,
105 MetaItemKind::List(..) => template.list.is_some(),
106 MetaItemKind::NameValue(lit) if lit.kind.is_str() => template.name_value_str.is_some(),
107 MetaItemKind::NameValue(..) => false,
111 pub fn check_builtin_attribute(
115 template: AttributeTemplate,
117 // Some special attributes like `cfg` must be checked
118 // before the generic check, so we skip them here.
119 let should_skip = |name| name == sym::cfg;
121 match parse_meta(sess, attr) {
123 if !should_skip(name) && !is_attr_template_compatible(&template, &meta.kind) {
124 emit_malformed_attribute(sess, attr, name, template);
133 fn emit_malformed_attribute(
137 template: AttributeTemplate,
139 // Some of previously accepted forms were used in practice,
140 // report them as warnings for now.
141 let should_warn = |name| {
142 matches!(name, sym::doc | sym::ignore | sym::inline | sym::link | sym::test | sym::bench)
145 let error_msg = format!("malformed `{}` attribute input", name);
146 let mut msg = "attribute must be of the form ".to_owned();
147 let mut suggestions = vec![];
148 let mut first = true;
149 let inner = if attr.style == ast::AttrStyle::Inner { "!" } else { "" };
152 let code = format!("#{}[{}]", inner, name);
153 msg.push_str(&format!("`{}`", &code));
154 suggestions.push(code);
156 if let Some(descr) = template.list {
158 msg.push_str(" or ");
161 let code = format!("#{}[{}({})]", inner, name, descr);
162 msg.push_str(&format!("`{}`", &code));
163 suggestions.push(code);
165 if let Some(descr) = template.name_value_str {
167 msg.push_str(" or ");
169 let code = format!("#{}[{} = \"{}\"]", inner, name, descr);
170 msg.push_str(&format!("`{}`", &code));
171 suggestions.push(code);
173 if should_warn(name) {
174 sess.buffer_lint(&ILL_FORMED_ATTRIBUTE_INPUT, attr.span, ast::CRATE_NODE_ID, &msg);
177 .struct_span_err(attr.span, &error_msg)
180 if suggestions.len() == 1 {
181 "must be of the form"
183 "the following are the possible correct uses"
185 suggestions.into_iter(),
186 Applicability::HasPlaceholders,
192 pub fn emit_fatal_malformed_builtin_attribute(
197 let template = BUILTIN_ATTRIBUTE_MAP.get(&name).expect("builtin attr defined").template;
198 emit_malformed_attribute(sess, attr, name, template);
199 // This is fatal, otherwise it will likely cause a cascade of other errors
200 // (and an error here is expected to be very rare).