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), 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 (Some(AttributeSafety::Normal), Safety::Default) => {
222 }
224
225 (None, Safety::Unsafe(_) | Safety::Default) => {
227 }
229
230 (
231 Some(AttributeSafety::Unsafe { .. } | AttributeSafety::Normal) | None,
232 Safety::Safe(..),
233 ) => {
234 psess.dcx().span_delayed_bug(
235 attr_item.span(),
236 "`check_attribute_safety` does not expect `Safety::Safe` on attributes",
237 );
238 }
239 }
240}
241
242pub fn deny_builtin_meta_unsafety(diag: DiagCtxtHandle<'_>, unsafety: Safety, name: &Path) {
245 if let Safety::Unsafe(unsafe_span) = unsafety {
249 diag.emit_err(errors::InvalidAttrUnsafe { span: unsafe_span, name: name.clone() });
250 }
251}
252
253pub fn check_builtin_meta_item(
254 psess: &ParseSess,
255 meta: &MetaItem,
256 style: ast::AttrStyle,
257 name: Symbol,
258 template: AttributeTemplate,
259 deny_unsafety: bool,
260) {
261 if !is_attr_template_compatible(&template, &meta.kind) {
262 emit_malformed_attribute(psess, style, meta.span, name, template);
264 }
265
266 if deny_unsafety {
267 deny_builtin_meta_unsafety(psess.dcx(), meta.unsafety, &meta.path);
268 }
269}
270
271fn emit_malformed_attribute(
272 psess: &ParseSess,
273 style: ast::AttrStyle,
274 span: Span,
275 name: Symbol,
276 template: AttributeTemplate,
277) {
278 let should_warn = |name| matches!(name, sym::doc | sym::link | sym::test | sym::bench);
281
282 let error_msg = format!("malformed `{name}` attribute input");
283 let mut suggestions = vec![];
284 let inner = if style == ast::AttrStyle::Inner { "!" } else { "" };
285 if template.word {
286 suggestions.push(format!("#{inner}[{name}]"));
287 }
288 if let Some(descr) = template.list {
289 for descr in descr {
290 suggestions.push(format!("#{inner}[{name}({descr})]"));
291 }
292 }
293 suggestions.extend(template.one_of.iter().map(|&word| format!("#{inner}[{name}({word})]")));
294 if let Some(descr) = template.name_value_str {
295 for descr in descr {
296 suggestions.push(format!("#{inner}[{name} = \"{descr}\"]"));
297 }
298 }
299 if should_warn(name) {
300 psess.buffer_lint(
301 ILL_FORMED_ATTRIBUTE_INPUT,
302 span,
303 ast::CRATE_NODE_ID,
304 BuiltinLintDiag::IllFormedAttributeInput {
305 suggestions: suggestions.clone(),
306 docs: template.docs,
307 },
308 );
309 } else {
310 suggestions.sort();
311 let mut err = psess.dcx().struct_span_err(span, error_msg).with_span_suggestions(
312 span,
313 if suggestions.len() == 1 {
314 "must be of the form"
315 } else {
316 "the following are the possible correct uses"
317 },
318 suggestions,
319 Applicability::HasPlaceholders,
320 );
321 if let Some(link) = template.docs {
322 err.note(format!("for more information, visit <{link}>"));
323 }
324 err.emit();
325 }
326}
327
328pub fn emit_fatal_malformed_builtin_attribute(
329 psess: &ParseSess,
330 attr: &Attribute,
331 name: Symbol,
332) -> ! {
333 let template = BUILTIN_ATTRIBUTE_MAP.get(&name).expect("builtin attr defined").template;
334 emit_malformed_attribute(psess, attr.style, attr.span, name, template);
335 FatalError.raise()
338}