1use std::borrow::Cow;
2
3use rustc_ast::{AttrStyle, Safety};
4use rustc_attr_ir::target::{AssocCtxt, MethodKind, Target};
5use rustc_attr_ir::{AttrItem, Attribute, AttributeKind};
6use rustc_errors::{DiagArgValue, MultiSpan, StashKey};
7use rustc_feature::Features;
8use rustc_lint_defs::builtin::{
9 MISPLACED_DIAGNOSTIC_ATTRIBUTES, UNUSED_ATTRIBUTES, USELESS_DEPRECATED,
10};
11use rustc_span::{BytePos, FileName, RemapPathScopeComponents, Span, Symbol, sym};
12
13use crate::context::AcceptContext;
14use crate::diagnostics::{
15 InvalidAttrAtCrateLevel, InvalidTarget, InvalidTargetHelp, ItemFollowingInnerAttr,
16 UnsupportedAttributesInWhere,
17};
18use crate::target_checking::Policy::Allow;
19use crate::{AttributeParser, ShouldEmit};
20
21#[derive(#[automatically_derived]
impl<'a> ::core::fmt::Debug for AllowedTargets<'a> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
AllowedTargets::AllowList(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"AllowList", &__self_0),
AllowedTargets::AllowListWarnRest(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"AllowListWarnRest", &__self_0),
AllowedTargets::ManuallyChecked =>
::core::fmt::Formatter::write_str(f, "ManuallyChecked"),
}
}
}Debug)]
22pub(crate) enum AllowedTargets<'a> {
23 AllowList(&'a [Policy]),
24 AllowListWarnRest(&'a [Policy]),
25 ManuallyChecked,
29}
30
31pub(crate) enum AllowedResult {
32 Allowed,
33 Warn,
34 Error,
35}
36
37impl AllowedTargets<'_> {
38 pub(crate) fn is_allowed(&self, target: Target) -> AllowedResult {
39 match self {
40 AllowedTargets::AllowList(list) => {
41 if list.contains(&Policy::Allow(target))
42 || list.contains(&Policy::AllowSilent(target))
43 {
44 AllowedResult::Allowed
45 } else if list.contains(&Policy::Warn(target)) {
46 AllowedResult::Warn
47 } else {
48 AllowedResult::Error
49 }
50 }
51 AllowedTargets::AllowListWarnRest(list) => {
52 if list.contains(&Policy::Allow(target))
53 || list.contains(&Policy::AllowSilent(target))
54 {
55 AllowedResult::Allowed
56 } else if list.contains(&Policy::Error(target)) {
57 AllowedResult::Error
58 } else {
59 AllowedResult::Warn
60 }
61 }
62 AllowedTargets::ManuallyChecked => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
63 }
64 }
65
66 pub(crate) fn allowed_targets(&self) -> Vec<Target> {
67 match self {
68 AllowedTargets::AllowList(list) | AllowedTargets::AllowListWarnRest(list) => list,
69 AllowedTargets::ManuallyChecked => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
70 }
71 .iter()
72 .filter_map(|target| match target {
73 Policy::Allow(target) => Some(*target),
74 Policy::AllowSilent(_) | Policy::Warn(_) | Policy::Error(_) => None,
75 })
76 .collect()
77 }
78}
79
80#[derive(#[automatically_derived]
impl ::core::fmt::Debug for Policy {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Policy::Allow(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Allow",
&__self_0),
Policy::AllowSilent(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"AllowSilent", &__self_0),
Policy::Warn(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Warn",
&__self_0),
Policy::Error(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Error",
&__self_0),
}
}
}Debug, #[automatically_derived]
impl ::core::cmp::Eq for Policy {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Target>;
}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for Policy {
#[inline]
fn eq(&self, other: &Policy) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(Policy::Allow(__self_0), Policy::Allow(__arg1_0)) =>
__self_0 == __arg1_0,
(Policy::AllowSilent(__self_0), Policy::AllowSilent(__arg1_0))
=> __self_0 == __arg1_0,
(Policy::Warn(__self_0), Policy::Warn(__arg1_0)) =>
__self_0 == __arg1_0,
(Policy::Error(__self_0), Policy::Error(__arg1_0)) =>
__self_0 == __arg1_0,
_ => unsafe { ::core::intrinsics::unreachable() }
}
}
}PartialEq)]
82pub(crate) enum Policy {
83 Allow(Target),
85 AllowSilent(Target),
88 Warn(Target),
91 Error(Target),
93}
94
95impl<'sess> AttributeParser<'sess> {
96 pub(crate) fn check_target(
97 allowed_targets: &AllowedTargets<'_>,
98 attribute_args: &str,
99 cx: &mut AcceptContext<'_, 'sess>,
100 ) {
101 if #[allow(non_exhaustive_omitted_patterns)] match cx.should_emit {
ShouldEmit::Nothing => true,
_ => false,
}matches!(cx.should_emit, ShouldEmit::Nothing) {
102 return;
103 }
104
105 if let AllowedTargets::ManuallyChecked = allowed_targets {
106 #[cfg(debug_assertions)]
107 if !cx.has_target_been_checked {
108 cx.dcx().delayed_bug("Attribute target has not been checked");
109 }
110
111 return;
112 }
113
114 if let &AllowedTargets::AllowList(&[Allow(Target::Crate)]) = allowed_targets {
117 Self::check_crate_level(cx, false);
118 return;
119 }
120 if let &AllowedTargets::AllowListWarnRest(&[Allow(Target::Crate)]) = allowed_targets {
121 Self::check_crate_level(cx, true);
122 return;
123 }
124
125 let result = allowed_targets.is_allowed(cx.target);
126 if #[allow(non_exhaustive_omitted_patterns)] match result {
AllowedResult::Allowed => true,
_ => false,
}matches!(result, AllowedResult::Allowed) {
127 return;
128 }
129
130 let allowed_targets = allowed_targets.allowed_targets();
131 let (applied, only) = allowed_targets_applied(allowed_targets, cx.target, cx.features);
132 let is_diagnostic_attr = cx.attr_path.segments[0] == sym::diagnostic;
133
134 let diag = InvalidTarget {
135 span: if attribute_args.is_empty() {
136 cx.attr_path.span
139 } else {
140 cx.inner_span
147 },
148 attr_span: cx.attr_span,
149 name: cx.attr_path.clone(),
150 target: cx.target.plural_name(),
151 only: if only { "only " } else { "" },
152 applied: DiagArgValue::StrListSepByAnd(applied.into_iter().map(Cow::Owned).collect()),
153 attribute_args: attribute_args.to_string(),
154 help: Self::target_checking_help(attribute_args, cx),
155 previously_accepted: #[allow(non_exhaustive_omitted_patterns)] match result {
AllowedResult::Warn => true,
_ => false,
}matches!(result, AllowedResult::Warn) && !is_diagnostic_attr,
156 on_macro_call: #[allow(non_exhaustive_omitted_patterns)] match cx.target {
Target::MacroCall => true,
_ => false,
}matches!(cx.target, Target::MacroCall),
157 };
158
159 match result {
160 AllowedResult::Allowed => {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("Should have early returned above")));
}unreachable!("Should have early returned above"),
161 AllowedResult::Warn => {
162 let lint = if cx.attr_path.segments[0] == sym::deprecated
163 && ![
164 Target::Closure,
165 Target::Expression,
166 Target::Statement,
167 Target::Arm,
168 Target::MacroCall,
169 ]
170 .contains(&cx.target)
171 {
172 USELESS_DEPRECATED
173 } else if is_diagnostic_attr {
174 MISPLACED_DIAGNOSTIC_ATTRIBUTES
175 } else {
176 UNUSED_ATTRIBUTES
177 };
178
179 let attr_span = cx.attr_span;
180 cx.emit_lint(lint, diag, attr_span);
181 }
182 AllowedResult::Error => {
183 cx.dcx().emit_err(diag);
184 }
185 }
186 }
187
188 fn target_checking_help(
189 attribute_args: &str,
190 cx: &AcceptContext<'_, '_>,
191 ) -> Option<InvalidTargetHelp> {
192 match &*cx.attr_path.segments {
193 [sym::link_name] if cx.target == Target::Static => {
194 let needs_unsafe_wrapper = #[allow(non_exhaustive_omitted_patterns)] match cx.attr_safety {
Safety::Default => true,
_ => false,
}matches!(cx.attr_safety, Safety::Default);
195
196 Some(InvalidTargetHelp::UseExportName {
197 unsafe_open: needs_unsafe_wrapper.then(|| cx.inner_span.shrink_to_lo()),
198 name: cx.attr_path.span,
199 unsafe_close: needs_unsafe_wrapper.then(|| cx.inner_span.shrink_to_hi()),
200 })
201 }
202 [sym::repr] if attribute_args == "(align(...))" => match cx.target {
203 Target::Fn | Target::Method(..) if cx.features().fn_align() => {
204 Some(InvalidTargetHelp::UseRustcAlign)
205 }
206 Target::Static if cx.features().static_align() => {
207 Some(InvalidTargetHelp::UseRustcAlignStatic)
208 }
209 _ => None,
210 },
211 _ => None,
212 }
213 }
214
215 pub(crate) fn check_crate_level(cx: &mut AcceptContext<'_, 'sess>, warn: bool) {
216 if cx.target == Target::Crate {
217 return;
218 }
219
220 let name = cx.attr_path.to_string();
221 let is_used_as_inner = cx.attr_style == AttrStyle::Inner;
222 let target_span = cx.target_span;
223 let attr_span = cx.attr_span;
224
225 let (show_crate_root_help, crate_root_path) = is_used_as_inner
226 .then(|| cx.cx.sess.local_crate_source_file())
227 .flatten()
228 .filter(|src| {
229 !#[allow(non_exhaustive_omitted_patterns)] match cx.cx.sess.source_map().span_to_filename(attr_span)
{
FileName::Real(ref name) if name == src => true,
_ => false,
}matches!(
230 cx.cx.sess.source_map().span_to_filename(attr_span),
231 FileName::Real(ref name) if name == src
232 )
233 })
234 .map(|src| {
235 (true, src.path(RemapPathScopeComponents::DIAGNOSTICS).display().to_string())
236 })
237 .unwrap_or_default();
238
239 let diag = crate::diagnostics::InvalidAttrStyle {
240 name,
241 is_used_as_inner,
242 target_span: (!is_used_as_inner).then_some(target_span),
243 target: cx.target.name(),
244 crate_root_path,
245 show_crate_root_help,
246 span: attr_span,
247 };
248 if warn {
249 cx.emit_lint(UNUSED_ATTRIBUTES, diag, attr_span);
250 } else {
251 cx.emit_err(diag);
252 }
253 }
254
255 pub(crate) fn check_invalid_crate_level_attr_item(&self, attr: &AttrItem, inner_span: Span) {
258 const ATTRS_TO_CHECK: &[Symbol] =
262 &[sym::derive, sym::test, sym::test_case, sym::global_allocator, sym::bench];
263
264 if let Some(name) = ATTRS_TO_CHECK.iter().find(|attr_to_check| #[allow(non_exhaustive_omitted_patterns)] match attr.path.segments.as_ref() {
[segment] if segment == *attr_to_check => true,
_ => false,
}matches!(attr.path.segments.as_ref(), [segment] if segment == *attr_to_check)) {
266 let span = attr.span;
267 let name = *name;
268
269 let item = self.first_line_of_next_item(span).map(|span| ItemFollowingInnerAttr { span });
270
271 let err = self.dcx().create_err(InvalidAttrAtCrateLevel {
272 span,
273 pound_to_opening_bracket: span.until(inner_span),
274 name,
275 item,
276 });
277
278 self.dcx().try_steal_replace_and_emit_err(
279 attr.path.span,
280 StashKey::UndeterminedMacroResolution,
281 err,
282 );
283 }
284 }
285
286 fn first_line_of_next_item(&self, span: Span) -> Option<Span> {
287 self.sess()
292 .source_map()
293 .span_to_source(span, |content, _, span_end| {
294 let mut source = &content[span_end..];
295 let initial_source_len = source.len();
296 let span = try {
297 loop {
298 let first = source.chars().next()?;
299
300 if first.is_whitespace() {
301 let split_idx = source.find(|c: char| !c.is_whitespace())?;
302 source = &source[split_idx..];
303 } else if source.starts_with("//") {
304 let line_idx = source.find('\n')?;
305 source = &source[line_idx + '\n'.len_utf8()..];
306 } else if source.starts_with("/*") {
307 let close_idx = source.find("*/")?;
309 source = &source[close_idx + "*/".len()..];
310 } else if first == '#' {
311 let close_idx = source.find(']')?;
315 source = &source[close_idx + ']'.len_utf8()..];
316 } else {
317 let lo = span_end + initial_source_len - source.len();
318 let last_line = source.split('\n').next().map(|s| s.trim_end())?;
319
320 let hi = lo + last_line.len();
321 let lo = BytePos(lo as u32);
322 let hi = BytePos(hi as u32);
323 let next_item_span = Span::new(lo, hi, span.ctxt(), None);
324
325 break next_item_span;
326 }
327 }
328 };
329
330 Ok(span)
331 })
332 .ok()
333 .flatten()
334 }
335
336 pub(crate) fn check_invalid_where_predicate_attrs<'attr>(
337 &self,
338 attrs: impl IntoIterator<Item = &'attr Attribute>,
339 ) {
340 let spans = attrs
345 .into_iter()
346 .filter_map(|attr| {
347 match attr {
348 Attribute::Parsed(AttributeKind::DocComment { span, .. }) => Some(*span),
349 Attribute::Parsed(AttributeKind::Doc(attr)) => Some(attr.first_span),
351 Attribute::Parsed(_) => None,
353 Attribute::Unparsed(attr) => Some(attr.span),
354 }
355 })
356 .collect::<Vec<_>>();
357 if !spans.is_empty() {
358 self.dcx()
359 .emit_err(UnsupportedAttributesInWhere { span: MultiSpan::from_spans(spans) });
360 }
361 }
362}
363
364pub(crate) fn allowed_targets_applied(
367 mut allowed_targets: Vec<Target>,
368 target: Target,
369 features: Option<&Features>,
370) -> (Vec<String>, bool) {
371 if let Some(features) = features {
373 if !features.fn_delegation() {
374 allowed_targets.retain(|t| !#[allow(non_exhaustive_omitted_patterns)] match t {
Target::Delegation { .. } => true,
_ => false,
}matches!(t, Target::Delegation { .. }));
375 }
376 if !features.stmt_expr_attributes() {
377 allowed_targets.retain(|t| !#[allow(non_exhaustive_omitted_patterns)] match t {
Target::Expression | Target::Statement => true,
_ => false,
}matches!(t, Target::Expression | Target::Statement));
378 }
379 if !features.extern_types() {
380 allowed_targets.retain(|t| !#[allow(non_exhaustive_omitted_patterns)] match t {
Target::ForeignTy => true,
_ => false,
}matches!(t, Target::ForeignTy));
381 }
382 }
383
384 const FUNCTION_LIKE: &[Target] = &[
388 Target::Fn,
389 Target::Closure,
390 Target::ForeignFn,
391 Target::Method(MethodKind::Inherent),
392 Target::Method(MethodKind::Trait { body: false }),
393 Target::Method(MethodKind::Trait { body: true }),
394 Target::Method(MethodKind::TraitImpl),
395 ];
396 const FUNCTION_WITH_BODY_LIKE: &[Target] = &[
397 Target::Fn,
398 Target::Closure,
399 Target::Method(MethodKind::Inherent),
400 Target::Method(MethodKind::Trait { body: true }),
401 Target::Method(MethodKind::TraitImpl),
402 ];
403 const METHOD_LIKE: &[Target] = &[
404 Target::Method(MethodKind::Inherent),
405 Target::Method(MethodKind::Trait { body: false }),
406 Target::Method(MethodKind::Trait { body: true }),
407 Target::Method(MethodKind::TraitImpl),
408 ];
409 const IMPL_LIKE: &[Target] =
410 &[Target::Impl { of_trait: false }, Target::Impl { of_trait: true }];
411 const ADT_LIKE: &[Target] = &[Target::Struct, Target::Enum, Target::Union];
412
413 let mut added_fake_targets = Vec::new();
414 filter_targets(
415 &mut allowed_targets,
416 FUNCTION_LIKE,
417 "functions",
418 target,
419 &mut added_fake_targets,
420 );
421 filter_targets(
422 &mut allowed_targets,
423 FUNCTION_WITH_BODY_LIKE,
424 "functions with a body",
425 target,
426 &mut added_fake_targets,
427 );
428 filter_targets(&mut allowed_targets, METHOD_LIKE, "methods", target, &mut added_fake_targets);
429 filter_targets(&mut allowed_targets, IMPL_LIKE, "impl blocks", target, &mut added_fake_targets);
430 filter_targets(&mut allowed_targets, ADT_LIKE, "data types", target, &mut added_fake_targets);
431
432 let mut target_strings: Vec<_> = added_fake_targets
433 .iter()
434 .copied()
435 .chain(allowed_targets.iter().map(|t| t.plural_name()))
436 .map(|i| i.to_string())
437 .collect();
438
439 target_strings.sort();
441 target_strings.dedup();
442
443 let only_target = target_strings.len() == 1;
445
446 (target_strings, only_target)
447}
448
449fn filter_targets(
450 allowed_targets: &mut Vec<Target>,
451 target_group: &'static [Target],
452 target_group_name: &'static str,
453 target: Target,
454 added_fake_targets: &mut Vec<&'static str>,
455) {
456 if target_group.contains(&target) {
457 return;
458 }
459 if allowed_targets.iter().filter(|at| target_group.contains(at)).count() < 2 {
460 return;
461 }
462 allowed_targets.retain(|t| !target_group.contains(t));
463 added_fake_targets.push(target_group_name);
464}
465
466impl<'f, 'sess> AcceptContext<'f, 'sess> {
467 pub(crate) fn check_target(
468 &mut self,
469 attribute_args: &str,
470 allowed_targets: &AllowedTargets<'_>,
471 ) {
472 self.ignore_target_checks();
473 AttributeParser::check_target(allowed_targets, attribute_args, self);
474 }
475
476 pub(crate) fn ignore_target_checks(&mut self) {
477 #[cfg(debug_assertions)]
478 {
479 self.has_target_been_checked = true;
480 }
481 }
482}
483
484pub(crate) const ALL_TARGETS: &[Policy] = {
489 use Policy::Allow;
490 &[
491 Allow(Target::ExternCrate),
492 Allow(Target::Use),
493 Allow(Target::Static),
494 Allow(Target::Const),
495 Allow(Target::Fn),
496 Allow(Target::Closure),
497 Allow(Target::Mod),
498 Allow(Target::ForeignMod),
499 Allow(Target::GlobalAsm),
500 Allow(Target::TyAlias),
501 Allow(Target::Enum),
502 Allow(Target::Variant),
503 Allow(Target::Struct),
504 Allow(Target::Field),
505 Allow(Target::Union),
506 Allow(Target::Trait),
507 Allow(Target::TraitAlias),
508 Allow(Target::Impl { of_trait: false }),
509 Allow(Target::Impl { of_trait: true }),
510 Allow(Target::Expression),
511 Allow(Target::Statement),
512 Allow(Target::Arm),
513 Allow(Target::AssocConst(AssocCtxt::Impl { of_trait: false })),
514 Allow(Target::AssocConst(AssocCtxt::Trait)),
515 Allow(Target::AssocConst(AssocCtxt::Impl { of_trait: true })),
516 Allow(Target::Method(MethodKind::Inherent)),
517 Allow(Target::Method(MethodKind::Trait { body: false })),
518 Allow(Target::Method(MethodKind::Trait { body: true })),
519 Allow(Target::Method(MethodKind::TraitImpl)),
520 Allow(Target::AssocTy(AssocCtxt::Impl { of_trait: false })),
521 Allow(Target::AssocTy(AssocCtxt::Trait)),
522 Allow(Target::AssocTy(AssocCtxt::Impl { of_trait: true })),
523 Allow(Target::ForeignFn),
524 Allow(Target::ForeignStatic),
525 Allow(Target::ForeignTy),
526 Allow(Target::MacroDef),
527 Allow(Target::Param),
528 Allow(Target::PatField),
529 Allow(Target::ExprField),
530 Allow(Target::WherePredicate),
531 Allow(Target::MacroCall),
532 Allow(Target::Crate),
533 Allow(Target::Delegation { mac: false }),
534 Allow(Target::Delegation { mac: true }),
535 Allow(Target::GenericParam {
536 kind: rustc_attr_ir::target::GenericParamKind::Const,
537 has_default: false,
538 }),
539 Allow(Target::GenericParam {
540 kind: rustc_attr_ir::target::GenericParamKind::Const,
541 has_default: true,
542 }),
543 Allow(Target::GenericParam {
544 kind: rustc_attr_ir::target::GenericParamKind::Lifetime,
545 has_default: false,
546 }),
547 Allow(Target::GenericParam {
548 kind: rustc_attr_ir::target::GenericParamKind::Lifetime,
549 has_default: true,
550 }),
551 Allow(Target::GenericParam {
552 kind: rustc_attr_ir::target::GenericParamKind::Type,
553 has_default: false,
554 }),
555 Allow(Target::GenericParam {
556 kind: rustc_attr_ir::target::GenericParamKind::Type,
557 has_default: true,
558 }),
559 Allow(Target::Loop),
560 Allow(Target::ForLoop),
561 Allow(Target::While),
562 Allow(Target::Break),
563 ]
564};