rustc_parse/
validate_attr.rs

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