rustc_attr_parsing/
validate_attr.rs

1//! Meta-syntax validation logic of attributes for post-expansion.
2
3use std::slice;
4
5use rustc_ast::token::Delimiter;
6use rustc_ast::tokenstream::DelimSpan;
7use rustc_ast::{
8    self as ast, AttrArgs, Attribute, DelimArgs, MetaItem, MetaItemInner, MetaItemKind, NodeId,
9    Path, Safety,
10};
11use rustc_errors::{Applicability, DiagCtxtHandle, FatalError, PResult};
12use rustc_feature::{AttributeSafety, AttributeTemplate, BUILTIN_ATTRIBUTE_MAP, BuiltinAttribute};
13use rustc_parse::parse_in;
14use rustc_session::errors::report_lit_error;
15use rustc_session::lint::BuiltinLintDiag;
16use rustc_session::lint::builtin::{ILL_FORMED_ATTRIBUTE_INPUT, UNSAFE_ATTR_OUTSIDE_UNSAFE};
17use rustc_session::parse::ParseSess;
18use rustc_span::{Span, Symbol, sym};
19
20use crate::{AttributeParser, Late, session_diagnostics as errors};
21
22pub fn check_attr(psess: &ParseSess, attr: &Attribute, id: NodeId) {
23    if attr.is_doc_comment() || attr.has_name(sym::cfg_trace) || attr.has_name(sym::cfg_attr_trace)
24    {
25        return;
26    }
27
28    let builtin_attr_info = attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name));
29
30    let builtin_attr_safety = builtin_attr_info.map(|x| x.safety);
31    check_attribute_safety(psess, builtin_attr_safety, attr, id);
32
33    // Check input tokens for built-in and key-value attributes.
34    match builtin_attr_info {
35        // `rustc_dummy` doesn't have any restrictions specific to built-in attributes.
36        Some(BuiltinAttribute { name, template, .. }) => {
37            if AttributeParser::<Late>::is_parsed_attribute(slice::from_ref(&name)) {
38                return;
39            }
40            match parse_meta(psess, attr) {
41                // Don't check safety again, we just did that
42                Ok(meta) => {
43                    check_builtin_meta_item(psess, &meta, attr.style, *name, *template, false)
44                }
45                Err(err) => {
46                    err.emit();
47                }
48            }
49        }
50        _ => {
51            let attr_item = attr.get_normal_item();
52            if let AttrArgs::Eq { .. } = attr_item.args {
53                // All key-value attributes are restricted to meta-item syntax.
54                match parse_meta(psess, attr) {
55                    Ok(_) => {}
56                    Err(err) => {
57                        err.emit();
58                    }
59                }
60            }
61        }
62    }
63}
64
65pub fn parse_meta<'a>(psess: &'a ParseSess, attr: &Attribute) -> PResult<'a, MetaItem> {
66    let item = attr.get_normal_item();
67    Ok(MetaItem {
68        unsafety: item.unsafety,
69        span: attr.span,
70        path: item.path.clone(),
71        kind: match &item.args {
72            AttrArgs::Empty => MetaItemKind::Word,
73            AttrArgs::Delimited(DelimArgs { dspan, delim, tokens }) => {
74                check_meta_bad_delim(psess, *dspan, *delim);
75                let nmis =
76                    parse_in(psess, tokens.clone(), "meta list", |p| p.parse_meta_seq_top())?;
77                MetaItemKind::List(nmis)
78            }
79            AttrArgs::Eq { expr, .. } => {
80                if let ast::ExprKind::Lit(token_lit) = expr.kind {
81                    let res = ast::MetaItemLit::from_token_lit(token_lit, expr.span);
82                    let res = match res {
83                        Ok(lit) => {
84                            if token_lit.suffix.is_some() {
85                                let mut err = psess.dcx().struct_span_err(
86                                    expr.span,
87                                    "suffixed literals are not allowed in attributes",
88                                );
89                                err.help(
90                                    "instead of using a suffixed literal (`1u8`, `1.0f32`, etc.), \
91                                    use an unsuffixed version (`1`, `1.0`, etc.)",
92                                );
93                                return Err(err);
94                            } else {
95                                MetaItemKind::NameValue(lit)
96                            }
97                        }
98                        Err(err) => {
99                            let guar = report_lit_error(psess, err, token_lit, expr.span);
100                            let lit = ast::MetaItemLit {
101                                symbol: token_lit.symbol,
102                                suffix: token_lit.suffix,
103                                kind: ast::LitKind::Err(guar),
104                                span: expr.span,
105                            };
106                            MetaItemKind::NameValue(lit)
107                        }
108                    };
109                    res
110                } else {
111                    // Example cases:
112                    // - `#[foo = 1+1]`: results in `ast::ExprKind::Binary`.
113                    // - `#[foo = include_str!("nonexistent-file.rs")]`:
114                    //   results in `ast::ExprKind::Err`. In that case we delay
115                    //   the error because an earlier error will have already
116                    //   been reported.
117                    let msg = "attribute value must be a literal";
118                    let mut err = psess.dcx().struct_span_err(expr.span, msg);
119                    if let ast::ExprKind::Err(_) = expr.kind {
120                        err.downgrade_to_delayed_bug();
121                    }
122                    return Err(err);
123                }
124            }
125        },
126    })
127}
128
129fn check_meta_bad_delim(psess: &ParseSess, span: DelimSpan, delim: Delimiter) {
130    if let Delimiter::Parenthesis = delim {
131        return;
132    }
133    psess.dcx().emit_err(errors::MetaBadDelim {
134        span: span.entire(),
135        sugg: errors::MetaBadDelimSugg { open: span.open, close: span.close },
136    });
137}
138
139/// Checks that the given meta-item is compatible with this `AttributeTemplate`.
140fn is_attr_template_compatible(template: &AttributeTemplate, meta: &ast::MetaItemKind) -> bool {
141    let is_one_allowed_subword = |items: &[MetaItemInner]| match items {
142        [item] => item.is_word() && template.one_of.iter().any(|&word| item.has_name(word)),
143        _ => false,
144    };
145    match meta {
146        MetaItemKind::Word => template.word,
147        MetaItemKind::List(items) => template.list.is_some() || is_one_allowed_subword(items),
148        MetaItemKind::NameValue(lit) if lit.kind.is_str() => template.name_value_str.is_some(),
149        MetaItemKind::NameValue(..) => false,
150    }
151}
152
153pub fn check_attribute_safety(
154    psess: &ParseSess,
155    builtin_attr_safety: Option<AttributeSafety>,
156    attr: &Attribute,
157    id: NodeId,
158) {
159    let attr_item = attr.get_normal_item();
160    match (builtin_attr_safety, attr_item.unsafety) {
161        // - Unsafe builtin attribute
162        // - User wrote `#[unsafe(..)]`, which is permitted on any edition
163        (Some(AttributeSafety::Unsafe { .. }), Safety::Unsafe(..)) => {
164            // OK
165        }
166
167        // - Unsafe builtin attribute
168        // - User did not write `#[unsafe(..)]`
169        (Some(AttributeSafety::Unsafe { unsafe_since }), Safety::Default) => {
170            let path_span = attr_item.path.span;
171
172            // If the `attr_item`'s span is not from a macro, then just suggest
173            // wrapping it in `unsafe(...)`. Otherwise, we suggest putting the
174            // `unsafe(`, `)` right after and right before the opening and closing
175            // square bracket respectively.
176            let diag_span = attr_item.span();
177
178            // Attributes can be safe in earlier editions, and become unsafe in later ones.
179            //
180            // Use the span of the attribute's name to determine the edition: the span of the
181            // attribute as a whole may be inaccurate if it was emitted by a macro.
182            //
183            // See https://github.com/rust-lang/rust/issues/142182.
184            let emit_error = match unsafe_since {
185                None => true,
186                Some(unsafe_since) => path_span.edition() >= unsafe_since,
187            };
188
189            if emit_error {
190                psess.dcx().emit_err(errors::UnsafeAttrOutsideUnsafe {
191                    span: path_span,
192                    suggestion: errors::UnsafeAttrOutsideUnsafeSuggestion {
193                        left: diag_span.shrink_to_lo(),
194                        right: diag_span.shrink_to_hi(),
195                    },
196                });
197            } else {
198                psess.buffer_lint(
199                    UNSAFE_ATTR_OUTSIDE_UNSAFE,
200                    path_span,
201                    id,
202                    BuiltinLintDiag::UnsafeAttrOutsideUnsafe {
203                        attribute_name_span: path_span,
204                        sugg_spans: (diag_span.shrink_to_lo(), diag_span.shrink_to_hi()),
205                    },
206                );
207            }
208        }
209
210        // - Normal builtin attribute
211        // - Writing `#[unsafe(..)]` is not permitted on normal builtin attributes
212        (Some(AttributeSafety::Normal), Safety::Unsafe(unsafe_span)) => {
213            psess.dcx().emit_err(errors::InvalidAttrUnsafe {
214                span: unsafe_span,
215                name: attr_item.path.clone(),
216            });
217        }
218
219        // - Normal builtin attribute
220        // - No explicit `#[unsafe(..)]` written.
221        (Some(AttributeSafety::Normal), Safety::Default) => {
222            // OK
223        }
224
225        // - Non-builtin attribute
226        (None, Safety::Unsafe(_) | Safety::Default) => {
227            // OK (not checked here)
228        }
229
230        (
231            Some(AttributeSafety::Unsafe { .. } | AttributeSafety::Normal) | None,
232            Safety::Safe(..),
233        ) => {
234            psess.dcx().span_delayed_bug(
235                attr_item.span(),
236                "`check_attribute_safety` does not expect `Safety::Safe` on attributes",
237            );
238        }
239    }
240}
241
242// Called by `check_builtin_meta_item` and code that manually denies
243// `unsafe(...)` in `cfg`
244pub fn deny_builtin_meta_unsafety(diag: DiagCtxtHandle<'_>, unsafety: Safety, name: &Path) {
245    // This only supports denying unsafety right now - making builtin attributes
246    // support unsafety will requite us to thread the actual `Attribute` through
247    // for the nice diagnostics.
248    if let Safety::Unsafe(unsafe_span) = unsafety {
249        diag.emit_err(errors::InvalidAttrUnsafe { span: unsafe_span, name: name.clone() });
250    }
251}
252
253pub fn check_builtin_meta_item(
254    psess: &ParseSess,
255    meta: &MetaItem,
256    style: ast::AttrStyle,
257    name: Symbol,
258    template: AttributeTemplate,
259    deny_unsafety: bool,
260) {
261    if !is_attr_template_compatible(&template, &meta.kind) {
262        // attrs with new parsers are locally validated so excluded here
263        emit_malformed_attribute(psess, style, meta.span, name, template);
264    }
265
266    if deny_unsafety {
267        deny_builtin_meta_unsafety(psess.dcx(), meta.unsafety, &meta.path);
268    }
269}
270
271fn emit_malformed_attribute(
272    psess: &ParseSess,
273    style: ast::AttrStyle,
274    span: Span,
275    name: Symbol,
276    template: AttributeTemplate,
277) {
278    // Some of previously accepted forms were used in practice,
279    // report them as warnings for now.
280    let should_warn = |name| matches!(name, sym::doc | sym::link | sym::test | sym::bench);
281
282    let error_msg = format!("malformed `{name}` attribute input");
283    let mut suggestions = vec![];
284    let inner = if style == ast::AttrStyle::Inner { "!" } else { "" };
285    if template.word {
286        suggestions.push(format!("#{inner}[{name}]"));
287    }
288    if let Some(descr) = template.list {
289        for descr in descr {
290            suggestions.push(format!("#{inner}[{name}({descr})]"));
291        }
292    }
293    suggestions.extend(template.one_of.iter().map(|&word| format!("#{inner}[{name}({word})]")));
294    if let Some(descr) = template.name_value_str {
295        for descr in descr {
296            suggestions.push(format!("#{inner}[{name} = \"{descr}\"]"));
297        }
298    }
299    if should_warn(name) {
300        psess.buffer_lint(
301            ILL_FORMED_ATTRIBUTE_INPUT,
302            span,
303            ast::CRATE_NODE_ID,
304            BuiltinLintDiag::IllFormedAttributeInput {
305                suggestions: suggestions.clone(),
306                docs: template.docs,
307            },
308        );
309    } else {
310        suggestions.sort();
311        let mut err = psess.dcx().struct_span_err(span, error_msg).with_span_suggestions(
312            span,
313            if suggestions.len() == 1 {
314                "must be of the form"
315            } else {
316                "the following are the possible correct uses"
317            },
318            suggestions,
319            Applicability::HasPlaceholders,
320        );
321        if let Some(link) = template.docs {
322            err.note(format!("for more information, visit <{link}>"));
323        }
324        err.emit();
325    }
326}
327
328pub fn emit_fatal_malformed_builtin_attribute(
329    psess: &ParseSess,
330    attr: &Attribute,
331    name: Symbol,
332) -> ! {
333    let template = BUILTIN_ATTRIBUTE_MAP.get(&name).expect("builtin attr defined").template;
334    emit_malformed_attribute(psess, attr.style, attr.span, name, template);
335    // This is fatal, otherwise it will likely cause a cascade of other errors
336    // (and an error here is expected to be very rare).
337    FatalError.raise()
338}