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        (None | 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        (None | Some(AttributeSafety::Normal), Safety::Default) => {
222            // OK
223        }
224
225        (
226            Some(AttributeSafety::Unsafe { .. } | AttributeSafety::Normal) | None,
227            Safety::Safe(..),
228        ) => {
229            psess.dcx().span_delayed_bug(
230                attr_item.span(),
231                "`check_attribute_safety` does not expect `Safety::Safe` on attributes",
232            );
233        }
234    }
235}
236
237// Called by `check_builtin_meta_item` and code that manually denies
238// `unsafe(...)` in `cfg`
239pub fn deny_builtin_meta_unsafety(diag: DiagCtxtHandle<'_>, unsafety: Safety, name: &Path) {
240    // This only supports denying unsafety right now - making builtin attributes
241    // support unsafety will requite us to thread the actual `Attribute` through
242    // for the nice diagnostics.
243    if let Safety::Unsafe(unsafe_span) = unsafety {
244        diag.emit_err(errors::InvalidAttrUnsafe { span: unsafe_span, name: name.clone() });
245    }
246}
247
248pub fn check_builtin_meta_item(
249    psess: &ParseSess,
250    meta: &MetaItem,
251    style: ast::AttrStyle,
252    name: Symbol,
253    template: AttributeTemplate,
254    deny_unsafety: bool,
255) {
256    if !is_attr_template_compatible(&template, &meta.kind) {
257        // attrs with new parsers are locally validated so excluded here
258        emit_malformed_attribute(psess, style, meta.span, name, template);
259    }
260
261    if deny_unsafety {
262        deny_builtin_meta_unsafety(psess.dcx(), meta.unsafety, &meta.path);
263    }
264}
265
266fn emit_malformed_attribute(
267    psess: &ParseSess,
268    style: ast::AttrStyle,
269    span: Span,
270    name: Symbol,
271    template: AttributeTemplate,
272) {
273    // Some of previously accepted forms were used in practice,
274    // report them as warnings for now.
275    let should_warn = |name| matches!(name, sym::doc | sym::link | sym::test | sym::bench);
276
277    let error_msg = format!("malformed `{name}` attribute input");
278    let mut suggestions = vec![];
279    let inner = if style == ast::AttrStyle::Inner { "!" } else { "" };
280    if template.word {
281        suggestions.push(format!("#{inner}[{name}]"));
282    }
283    if let Some(descr) = template.list {
284        for descr in descr {
285            suggestions.push(format!("#{inner}[{name}({descr})]"));
286        }
287    }
288    suggestions.extend(template.one_of.iter().map(|&word| format!("#{inner}[{name}({word})]")));
289    if let Some(descr) = template.name_value_str {
290        for descr in descr {
291            suggestions.push(format!("#{inner}[{name} = \"{descr}\"]"));
292        }
293    }
294    if should_warn(name) {
295        psess.buffer_lint(
296            ILL_FORMED_ATTRIBUTE_INPUT,
297            span,
298            ast::CRATE_NODE_ID,
299            BuiltinLintDiag::IllFormedAttributeInput {
300                suggestions: suggestions.clone(),
301                docs: template.docs,
302            },
303        );
304    } else {
305        suggestions.sort();
306        let mut err = psess.dcx().struct_span_err(span, error_msg).with_span_suggestions(
307            span,
308            if suggestions.len() == 1 {
309                "must be of the form"
310            } else {
311                "the following are the possible correct uses"
312            },
313            suggestions,
314            Applicability::HasPlaceholders,
315        );
316        if let Some(link) = template.docs {
317            err.note(format!("for more information, visit <{link}>"));
318        }
319        err.emit();
320    }
321}
322
323pub fn emit_fatal_malformed_builtin_attribute(
324    psess: &ParseSess,
325    attr: &Attribute,
326    name: Symbol,
327) -> ! {
328    let template = BUILTIN_ATTRIBUTE_MAP.get(&name).expect("builtin attr defined").template;
329    emit_malformed_attribute(psess, attr.style, attr.span, name, template);
330    // This is fatal, otherwise it will likely cause a cascade of other errors
331    // (and an error here is expected to be very rare).
332    FatalError.raise()
333}