1 //! Meta-syntax validation logic of attributes for post-expansion.
5 use rustc_ast::tokenstream::DelimSpan;
6 use rustc_ast::MetaItemKind;
7 use rustc_ast::{self as ast, AttrArgs, AttrArgsEq, Attribute, DelimArgs, MacDelimiter, MetaItem};
8 use rustc_ast_pretty::pprust;
9 use rustc_errors::{Applicability, FatalError, PResult};
10 use rustc_feature::{AttributeTemplate, BuiltinAttribute, BUILTIN_ATTRIBUTE_MAP};
11 use rustc_session::lint::builtin::ILL_FORMED_ATTRIBUTE_INPUT;
12 use rustc_session::parse::ParseSess;
13 use rustc_span::{sym, Span, Symbol};
15 pub fn check_attr(sess: &ParseSess, attr: &Attribute) {
16 if attr.is_doc_comment() {
20 let attr_info = attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name));
22 // Check input tokens for built-in and key-value attributes.
24 // `rustc_dummy` doesn't have any restrictions specific to built-in attributes.
25 Some(BuiltinAttribute { name, template, .. }) if *name != sym::rustc_dummy => {
26 check_builtin_attribute(sess, attr, *name, *template)
28 _ if let AttrArgs::Eq(..) = attr.get_normal_item().args => {
29 // All key-value attributes are restricted to meta-item syntax.
30 parse_meta(sess, attr)
40 pub fn parse_meta<'a>(sess: &'a ParseSess, attr: &Attribute) -> PResult<'a, MetaItem> {
41 let item = attr.get_normal_item();
44 path: item.path.clone(),
45 kind: match &item.args {
46 AttrArgs::Empty => MetaItemKind::Word,
47 AttrArgs::Delimited(DelimArgs { dspan, delim, tokens }) => {
48 check_meta_bad_delim(sess, *dspan, *delim, "wrong meta list delimiters");
49 let nmis = parse_in(sess, tokens.clone(), "meta list", |p| p.parse_meta_seq_top())?;
50 MetaItemKind::List(nmis)
52 AttrArgs::Eq(_, AttrArgsEq::Ast(expr)) => {
53 if let ast::ExprKind::Lit(token_lit) = expr.kind
54 && let Ok(lit) = ast::MetaItemLit::from_token_lit(token_lit, expr.span)
56 if token_lit.suffix.is_some() {
57 let mut err = sess.span_diagnostic.struct_span_err(
59 "suffixed literals are not allowed in attributes",
62 "instead of using a suffixed literal (`1u8`, `1.0f32`, etc.), \
63 use an unsuffixed version (`1`, `1.0`, etc.)",
67 MetaItemKind::NameValue(lit)
70 // The non-error case can happen with e.g. `#[foo = 1+1]`. The error case can
71 // happen with e.g. `#[foo = include_str!("non-existent-file.rs")]`; in that
72 // case we delay the error because an earlier error will have already been
74 let msg = format!("unexpected expression: `{}`", pprust::expr_to_string(expr));
75 let mut err = sess.span_diagnostic.struct_span_err(expr.span, msg);
76 if let ast::ExprKind::Err = expr.kind {
77 err.downgrade_to_delayed_bug();
82 AttrArgs::Eq(_, AttrArgsEq::Hir(lit)) => MetaItemKind::NameValue(lit.clone()),
87 pub fn check_meta_bad_delim(sess: &ParseSess, span: DelimSpan, delim: MacDelimiter, msg: &str) {
88 if let ast::MacDelimiter::Parenthesis = delim {
93 .struct_span_err(span.entire(), msg)
94 .multipart_suggestion(
95 "the delimiters should be `(` and `)`",
96 vec![(span.open, "(".to_string()), (span.close, ")".to_string())],
97 Applicability::MachineApplicable,
102 /// Checks that the given meta-item is compatible with this `AttributeTemplate`.
103 fn is_attr_template_compatible(template: &AttributeTemplate, meta: &ast::MetaItemKind) -> bool {
105 MetaItemKind::Word => template.word,
106 MetaItemKind::List(..) => template.list.is_some(),
107 MetaItemKind::NameValue(lit) if lit.kind.is_str() => template.name_value_str.is_some(),
108 MetaItemKind::NameValue(..) => false,
112 pub fn check_builtin_attribute(
116 template: AttributeTemplate,
118 match parse_meta(sess, attr) {
119 Ok(meta) => check_builtin_meta_item(sess, &meta, attr.style, name, template),
126 pub fn check_builtin_meta_item(
129 style: ast::AttrStyle,
131 template: AttributeTemplate,
133 // Some special attributes like `cfg` must be checked
134 // before the generic check, so we skip them here.
135 let should_skip = |name| name == sym::cfg;
137 if !should_skip(name) && !is_attr_template_compatible(&template, &meta.kind) {
138 emit_malformed_attribute(sess, style, meta.span, name, template);
142 fn emit_malformed_attribute(
144 style: ast::AttrStyle,
147 template: AttributeTemplate,
149 // Some of previously accepted forms were used in practice,
150 // report them as warnings for now.
151 let should_warn = |name| {
152 matches!(name, sym::doc | sym::ignore | sym::inline | sym::link | sym::test | sym::bench)
155 let error_msg = format!("malformed `{}` attribute input", name);
156 let mut msg = "attribute must be of the form ".to_owned();
157 let mut suggestions = vec![];
158 let mut first = true;
159 let inner = if style == ast::AttrStyle::Inner { "!" } else { "" };
162 let code = format!("#{}[{}]", inner, name);
163 msg.push_str(&format!("`{}`", &code));
164 suggestions.push(code);
166 if let Some(descr) = template.list {
168 msg.push_str(" or ");
171 let code = format!("#{}[{}({})]", inner, name, descr);
172 msg.push_str(&format!("`{}`", &code));
173 suggestions.push(code);
175 if let Some(descr) = template.name_value_str {
177 msg.push_str(" or ");
179 let code = format!("#{}[{} = \"{}\"]", inner, name, descr);
180 msg.push_str(&format!("`{}`", &code));
181 suggestions.push(code);
183 if should_warn(name) {
184 sess.buffer_lint(&ILL_FORMED_ATTRIBUTE_INPUT, span, ast::CRATE_NODE_ID, &msg);
187 .struct_span_err(span, &error_msg)
190 if suggestions.len() == 1 {
191 "must be of the form"
193 "the following are the possible correct uses"
195 suggestions.into_iter(),
196 Applicability::HasPlaceholders,
202 pub fn emit_fatal_malformed_builtin_attribute(
207 let template = BUILTIN_ATTRIBUTE_MAP.get(&name).expect("builtin attr defined").template;
208 emit_malformed_attribute(sess, attr.style, attr.span, name, template);
209 // This is fatal, otherwise it will likely cause a cascade of other errors
210 // (and an error here is expected to be very rare).