1use 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 match builtin_attr_info {
35 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 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 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 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
139fn 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 (Some(AttributeSafety::Unsafe { .. }), Safety::Unsafe(..)) => {
164 }
166
167 (Some(AttributeSafety::Unsafe { unsafe_since }), Safety::Default) => {
170 let path_span = attr_item.path.span;
171
172 let diag_span = attr_item.span();
177
178 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 (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 (Some(AttributeSafety::Normal), Safety::Default) => {
223 }
225
226 (None, Safety::Default) => {
229 }
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
244pub fn deny_builtin_meta_unsafety(diag: DiagCtxtHandle<'_>, unsafety: Safety, name: &Path) {
247 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 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 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 FatalError.raise()
340}