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