Skip to main content

rustc_attr_parsing/
validate_attr.rs

1//! Meta-syntax validation logic of attributes for post-expansion.
2
3use std::convert::identity;
4
5use rustc_ast::SyntheticAttr::CfgAttrTrace;
6use rustc_ast::token::Delimiter;
7use rustc_ast::tokenstream::DelimSpan;
8use rustc_ast::{
9    self as ast, AttrArgs, AttrKind, Attribute, DelimArgs, MetaItem, MetaItemInner, MetaItemKind,
10    Safety,
11};
12use rustc_attr_ir::AttrPath;
13use rustc_errors::{Applicability, Diagnostic, PResult};
14use rustc_lint_defs::builtin::ILL_FORMED_ATTRIBUTE_INPUT;
15use rustc_parse::parse_in;
16use rustc_session::diagnostics::report_lit_error;
17use rustc_session::parse::ParseSess;
18use rustc_span::{Span, Symbol, sym};
19
20use crate::{AttributeTemplate, diagnostics as errors};
21
22pub fn parse_meta<'a>(psess: &'a ParseSess, attr: &Attribute) -> PResult<'a, MetaItem> {
23    let item = attr.get_normal_item();
24    Ok(MetaItem {
25        unsafety: item.unsafety,
26        span: attr.span,
27        path: item.path.clone(),
28        kind: match &item.args {
29            AttrArgs::Empty => MetaItemKind::Word,
30            AttrArgs::Delimited(DelimArgs { dspan, delim, tokens }) => {
31                check_meta_bad_delim(psess, *dspan, *delim);
32                let nmis =
33                    parse_in(psess, tokens.clone(), "meta list", |p| p.parse_meta_seq_top())?;
34                MetaItemKind::List(nmis)
35            }
36            AttrArgs::Eq { expr, .. } => {
37                check_attrs_on_rhs_expr(psess, expr)?;
38
39                if let ast::ExprKind::Lit(token_lit) = expr.kind {
40                    let res = ast::MetaItemLit::from_token_lit(token_lit, expr.span);
41
42                    match res {
43                        Ok(lit) => {
44                            if token_lit.suffix.is_some() {
45                                let mut err = psess.dcx().struct_span_err(
46                                    expr.span,
47                                    "suffixed literals are not allowed in attributes",
48                                );
49                                err.help(
50                                    "instead of using a suffixed literal (`1u8`, `1.0f32`, etc.), \
51                                    use an unsuffixed version (`1`, `1.0`, etc.)",
52                                );
53                                return Err(err);
54                            }
55                            MetaItemKind::NameValue(lit)
56                        }
57                        Err(err) => {
58                            let guar = report_lit_error(psess, err, token_lit, expr.span);
59                            let lit = ast::MetaItemLit {
60                                symbol: token_lit.symbol,
61                                suffix: token_lit.suffix,
62                                kind: ast::LitKind::Err(guar),
63                                span: expr.span,
64                            };
65                            MetaItemKind::NameValue(lit)
66                        }
67                    }
68                } else {
69                    // Example cases:
70                    // - `#[foo = 1+1]`: results in `ast::ExprKind::Binary`.
71                    // - `#[foo = include_str!("nonexistent-file.rs")]`:
72                    //   results in `ast::ExprKind::Err`. In that case we delay
73                    //   the error because an earlier error will have already
74                    //   been reported.
75                    let msg = "attribute value must be a literal";
76                    let mut err = psess.dcx().struct_span_err(expr.span, msg);
77                    if let ast::ExprKind::Err(_) = expr.kind {
78                        err.downgrade_to_delayed_bug();
79                    }
80                    return Err(err);
81                }
82            }
83        },
84    })
85}
86
87fn check_meta_bad_delim(psess: &ParseSess, span: DelimSpan, delim: Delimiter) {
88    if let Delimiter::Parenthesis = delim {
89        return;
90    }
91    psess.dcx().emit_err(errors::MetaBadDelim {
92        span: span.entire(),
93        sugg: errors::MetaBadDelimSugg { open: span.open, close: span.close },
94    });
95}
96
97pub(crate) fn check_attrs_on_rhs_expr<'sess>(
98    psess: &'sess ParseSess,
99    expr: &ast::Expr,
100) -> PResult<'sess, ()> {
101    // Cfg traces are not real attrs, they're just a marker that cfg expansion has occurred which is
102    // perfectly legal, so don't trigger on them. We only need to worry about `cfg_attr` traces and
103    // not about `cfg` ones because macro expansion would've already bailed out with an error if
104    // there was a `cfg` on an expr.
105    let attrs: Vec<_> = expr
106        .attrs
107        .iter()
108        .filter(|attr| !#[allow(non_exhaustive_omitted_patterns)] match attr.kind {
    AttrKind::Synthetic(CfgAttrTrace(_)) => true,
    _ => false,
}matches!(attr.kind, AttrKind::Synthetic(CfgAttrTrace(_))))
109        .map(|attr| attr.span)
110        .collect();
111
112    if !attrs.is_empty() {
113        return Err(psess
114            .dcx()
115            .create_err(errors::AttributeInInvalidContext { count: attrs.len(), attrs }));
116    }
117
118    Ok(())
119}
120
121/// Checks that the given meta-item is compatible with this `AttributeTemplate`.
122fn is_attr_template_compatible(template: &AttributeTemplate, meta: &ast::MetaItemKind) -> bool {
123    let is_one_allowed_subword = |items: &[MetaItemInner]| match items {
124        [item] => item.is_word() && template.one_of.iter().any(|&word| item.has_name(word)),
125        _ => false,
126    };
127    match meta {
128        MetaItemKind::Word => template.word,
129        MetaItemKind::List(items) => template.list.is_some() || is_one_allowed_subword(items),
130        MetaItemKind::NameValue(lit) if lit.kind.is_str() => template.name_value_str.is_some(),
131        MetaItemKind::NameValue(..) => false,
132    }
133}
134
135pub fn check_builtin_meta_item(
136    psess: &ParseSess,
137    meta: &MetaItem,
138    style: ast::AttrStyle,
139    name: Symbol,
140    template: AttributeTemplate,
141    deny_unsafety: bool,
142) {
143    if !is_attr_template_compatible(&template, &meta.kind) {
144        // attrs with new parsers are locally validated so excluded here
145        emit_malformed_attribute(psess, style, meta.span, name, template);
146    }
147
148    if deny_unsafety && let Safety::Unsafe(unsafe_span) = meta.unsafety {
149        psess.dcx().emit_err(errors::InvalidAttrUnsafe {
150            span: unsafe_span,
151            name: AttrPath::from_ast(&meta.path, identity),
152        });
153    }
154}
155
156pub fn emit_malformed_attribute(
157    psess: &ParseSess,
158    style: ast::AttrStyle,
159    span: Span,
160    name: Symbol,
161    template: AttributeTemplate,
162) {
163    // Some of previously accepted forms were used in practice,
164    // report them as warnings for now.
165    let should_warn = |name| #[allow(non_exhaustive_omitted_patterns)] match name {
    sym::doc | sym::link | sym::test | sym::bench => true,
    _ => false,
}matches!(name, sym::doc | sym::link | sym::test | sym::bench);
166
167    let error_msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("malformed `{0}` attribute input",
                name))
    })format!("malformed `{name}` attribute input");
168    let mut suggestions = ::alloc::vec::Vec::new()vec![];
169    let inner = if style == ast::AttrStyle::Inner { "!" } else { "" };
170    if template.word {
171        suggestions.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#{0}[{1}]", inner, name))
    })format!("#{inner}[{name}]"));
172    }
173    if let Some(descr) = template.list {
174        for descr in descr {
175            suggestions.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#{0}[{1}({2})]", inner, name,
                descr))
    })format!("#{inner}[{name}({descr})]"));
176        }
177    }
178    suggestions.extend(template.one_of.iter().map(|&word| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#{0}[{1}({2})]", inner, name,
                word))
    })format!("#{inner}[{name}({word})]")));
179    if let Some(descr) = template.name_value_str {
180        for descr in descr {
181            suggestions.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#{0}[{1} = \"{2}\"]", inner, name,
                descr))
    })format!("#{inner}[{name} = \"{descr}\"]"));
182        }
183    }
184    // If there are too many suggestions, better remove all of them as it's just noise at this
185    // point.
186    if suggestions.len() > 3 {
187        suggestions.clear();
188    }
189    if should_warn(name) {
190        let suggestions = suggestions.clone();
191        psess.dyn_buffer_lint(
192            ILL_FORMED_ATTRIBUTE_INPUT,
193            span,
194            ast::CRATE_NODE_ID,
195            move |dcx, level| {
196                crate::diagnostics::IllFormedAttributeInput::new(&suggestions, template.docs, None)
197                    .into_diag(dcx, level)
198            },
199        );
200    } else {
201        suggestions.sort();
202        let mut err = psess.dcx().struct_span_err(span, error_msg).with_span_suggestions(
203            span,
204            if suggestions.len() == 1 {
205                "must be of the form"
206            } else {
207                "the following are the possible correct uses"
208            },
209            suggestions,
210            Applicability::HasPlaceholders,
211        );
212        if let Some(link) = template.docs {
213            err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("for more information, visit <{0}>",
                link))
    })format!("for more information, visit <{link}>"));
214        }
215        err.emit();
216    }
217}