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 INVALID_DOC_ATTRIBUTES, 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 {
Self::AllowList(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"AllowList", &__self_0),
Self::AllowListWarnRest(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"AllowListWarnRest", &__self_0),
Self::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::unreachable_default_msg()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::unreachable_default_msg()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 {
Self::Allow(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Allow",
&__self_0),
Self::AllowSilent(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"AllowSilent", &__self_0),
Self::Warn(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Warn",
&__self_0),
Self::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::marker::StructuralPartialEq for Policy {
}
#[automatically_derived]impl ::core::cmp::PartialEq for Policy {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other) &&
match (self, other) {
(Self::Allow(__self_0), Self::Allow(__arg1_0)) =>
__self_0 == __arg1_0,
(Self::AllowSilent(__self_0), Self::AllowSilent(__arg1_0)) =>
__self_0 == __arg1_0,
(Self::Warn(__self_0), Self::Warn(__arg1_0)) =>
__self_0 == __arg1_0,
(Self::Error(__self_0), Self::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 span = if attribute_args.is_empty() {
135 cx.attr_path.span
138 } else {
139 cx.inner_span
146 };
147 let target_span = if span.eq_ctxt(cx.target_span) && cx.target != Target::Crate {
148 cx.target_span.shrink_to_lo()
149 } else {
150 span
151 };
152
153 let diag = InvalidTarget {
154 span,
155 attr_span: cx.attr_span,
156 name: cx.attr_path.clone(),
157 target: cx.target.plural_name(),
158 target_span,
159 only: if only { "only " } else { "" },
160 applied: DiagArgValue::StrListSepByAnd(applied.into_iter().map(Cow::Owned).collect()),
161 attribute_args: attribute_args.to_string(),
162 help: Self::target_checking_help(attribute_args, cx),
163 previously_accepted: #[allow(non_exhaustive_omitted_patterns)] match result {
AllowedResult::Warn => true,
_ => false,
}matches!(result, AllowedResult::Warn) && !is_diagnostic_attr,
164 on_macro_call: #[allow(non_exhaustive_omitted_patterns)] match cx.target {
Target::MacroCall => true,
_ => false,
}matches!(cx.target, Target::MacroCall),
165 };
166
167 match result {
168 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"),
169 AllowedResult::Warn => {
170 let lint = if cx.attr_path.segments[0] == sym::deprecated
171 && ![
172 Target::Closure,
173 Target::Expression,
174 Target::Statement,
175 Target::Arm,
176 Target::MacroCall,
177 ]
178 .contains(&cx.target)
179 {
180 USELESS_DEPRECATED
181 } else if is_diagnostic_attr {
182 MISPLACED_DIAGNOSTIC_ATTRIBUTES
183 } else {
184 UNUSED_ATTRIBUTES
185 };
186
187 let attr_span = cx.attr_span;
188 cx.emit_lint(lint, diag, attr_span);
189 }
190 AllowedResult::Error => {
191 cx.dcx().emit_err(diag);
192 }
193 }
194 }
195
196 fn target_checking_help(
197 attribute_args: &str,
198 cx: &AcceptContext<'_, '_>,
199 ) -> Option<InvalidTargetHelp> {
200 match &*cx.attr_path.segments {
201 [sym::link_name] if cx.target == Target::Static => {
202 let needs_unsafe_wrapper = #[allow(non_exhaustive_omitted_patterns)] match cx.attr_safety {
Safety::Default => true,
_ => false,
}matches!(cx.attr_safety, Safety::Default);
203
204 Some(InvalidTargetHelp::UseExportName {
205 unsafe_open: needs_unsafe_wrapper.then(|| cx.inner_span.shrink_to_lo()),
206 name: cx.attr_path.span,
207 unsafe_close: needs_unsafe_wrapper.then(|| cx.inner_span.shrink_to_hi()),
208 })
209 }
210 [sym::repr] if attribute_args == "(align(...))" => match cx.target {
211 Target::Fn | Target::Method(..) if cx.features().fn_align() => {
212 Some(InvalidTargetHelp::UseRustcAlign)
213 }
214 Target::Static if cx.features().static_align() => {
215 Some(InvalidTargetHelp::UseRustcAlignStatic)
216 }
217 _ => None,
218 },
219 _ => None,
220 }
221 }
222
223 pub(crate) fn check_crate_level(cx: &mut AcceptContext<'_, 'sess>, warn: bool) {
224 if cx.target == Target::Crate {
225 return;
226 }
227
228 let name = cx.attr_path.to_string();
229 let is_used_as_inner = cx.attr_style == AttrStyle::Inner;
230 let target_span = cx.target_span;
231 let attr_span = cx.attr_span;
232
233 let (show_crate_root_help, crate_root_path) = is_used_as_inner
234 .then(|| cx.cx.sess.local_crate_source_file())
235 .flatten()
236 .filter(|src| {
237 !#[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!(
238 cx.cx.sess.source_map().span_to_filename(attr_span),
239 FileName::Real(ref name) if name == src
240 )
241 })
242 .map(|src| {
243 (true, src.path(RemapPathScopeComponents::DIAGNOSTICS).display().to_string())
244 })
245 .unwrap_or_default();
246
247 if name == "doc" {
248 let diag = crate::diagnostics::AttrCrateLevelOnly;
249 if warn {
250 cx.emit_lint(INVALID_DOC_ATTRIBUTES, diag, attr_span);
251 } else {
252 cx.emit_err(diag);
253 }
254 return;
255 }
256
257 let diag = crate::diagnostics::InvalidAttrStyle {
258 name,
259 is_used_as_inner,
260 target_span: (!is_used_as_inner).then_some(target_span),
261 target: cx.target.name(),
262 crate_root_path,
263 show_crate_root_help,
264 span: attr_span,
265 };
266 if warn {
267 cx.emit_lint(UNUSED_ATTRIBUTES, diag, attr_span);
268 } else {
269 cx.emit_err(diag);
270 }
271 }
272
273 pub(crate) fn check_invalid_crate_level_attr_item(&self, attr: &AttrItem, inner_span: Span) {
276 const ATTRS_TO_CHECK: &[Symbol] =
280 &[sym::derive, sym::test, sym::test_case, sym::global_allocator, sym::bench];
281
282 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)) {
284 let span = attr.span;
285 let name = *name;
286
287 let item = self.first_line_of_next_item(span).map(|span| ItemFollowingInnerAttr { span });
288
289 let err = self.dcx().create_err(InvalidAttrAtCrateLevel {
290 span,
291 pound_to_opening_bracket: span.until(inner_span),
292 name,
293 item,
294 });
295
296 self.dcx().try_steal_replace_and_emit_err(
297 attr.path.span,
298 StashKey::UndeterminedMacroResolution,
299 err,
300 );
301 }
302 }
303
304 fn first_line_of_next_item(&self, span: Span) -> Option<Span> {
305 self.sess()
310 .source_map()
311 .span_to_source(span, |content, _, span_end| {
312 let mut source = &content[span_end..];
313 let initial_source_len = source.len();
314 let span = try {
315 loop {
316 let first = source.chars().next()?;
317
318 if first.is_whitespace() {
319 let split_idx = source.find(|c: char| !c.is_whitespace())?;
320 source = &source[split_idx..];
321 } else if source.starts_with("//") {
322 let line_idx = source.find('\n')?;
323 source = &source[line_idx + '\n'.len_utf8()..];
324 } else if source.starts_with("/*") {
325 let close_idx = source.find("*/")?;
327 source = &source[close_idx + "*/".len()..];
328 } else if first == '#' {
329 let close_idx = source.find(']')?;
333 source = &source[close_idx + ']'.len_utf8()..];
334 } else {
335 let lo = span_end + initial_source_len - source.len();
336 let last_line = source.split('\n').next().map(|s| s.trim_end())?;
337
338 let hi = lo + last_line.len();
339 let lo = BytePos(lo as u32);
340 let hi = BytePos(hi as u32);
341 let next_item_span = Span::new(lo, hi, span.ctxt(), None);
342
343 break next_item_span;
344 }
345 }
346 };
347
348 Ok(span)
349 })
350 .ok()
351 .flatten()
352 }
353
354 pub(crate) fn check_invalid_where_predicate_attrs<'attr>(
355 &self,
356 attrs: impl IntoIterator<Item = &'attr Attribute>,
357 ) {
358 let spans = attrs
363 .into_iter()
364 .filter_map(|attr| {
365 match attr {
366 Attribute::Parsed(AttributeKind::DocComment { span, .. }) => Some(*span),
367 Attribute::Parsed(AttributeKind::Doc(attr)) => Some(attr.first_span),
369 Attribute::Parsed(_) => None,
371 Attribute::Unparsed(attr) => Some(attr.span),
372 }
373 })
374 .collect::<Vec<_>>();
375 if !spans.is_empty() {
376 self.dcx()
377 .emit_err(UnsupportedAttributesInWhere { span: MultiSpan::from_spans(spans) });
378 }
379 }
380}
381
382pub(crate) fn allowed_targets_applied(
385 mut allowed_targets: Vec<Target>,
386 target: Target,
387 features: Option<&Features>,
388) -> (Vec<String>, bool) {
389 if let Some(features) = features {
391 if !features.fn_delegation() {
392 allowed_targets.retain(|t| !#[allow(non_exhaustive_omitted_patterns)] match t {
Target::Delegation { .. } => true,
_ => false,
}matches!(t, Target::Delegation { .. }));
393 }
394 if !features.stmt_expr_attributes() {
395 allowed_targets.retain(|t| !#[allow(non_exhaustive_omitted_patterns)] match t {
Target::Expression | Target::Statement => true,
_ => false,
}matches!(t, Target::Expression | Target::Statement));
396 }
397 if !features.extern_types() {
398 allowed_targets.retain(|t| !#[allow(non_exhaustive_omitted_patterns)] match t {
Target::ForeignTy => true,
_ => false,
}matches!(t, Target::ForeignTy));
399 }
400 }
401
402 const FUNCTION_LIKE: &[Target] = &[
406 Target::Fn,
407 Target::Closure,
408 Target::ForeignFn,
409 Target::Method(MethodKind::Inherent),
410 Target::Method(MethodKind::Trait { body: false }),
411 Target::Method(MethodKind::Trait { body: true }),
412 Target::Method(MethodKind::TraitImpl),
413 ];
414 const FUNCTION_WITH_BODY_LIKE: &[Target] = &[
415 Target::Fn,
416 Target::Closure,
417 Target::Method(MethodKind::Inherent),
418 Target::Method(MethodKind::Trait { body: true }),
419 Target::Method(MethodKind::TraitImpl),
420 ];
421 const METHOD_LIKE: &[Target] = &[
422 Target::Method(MethodKind::Inherent),
423 Target::Method(MethodKind::Trait { body: false }),
424 Target::Method(MethodKind::Trait { body: true }),
425 Target::Method(MethodKind::TraitImpl),
426 ];
427 const IMPL_LIKE: &[Target] =
428 &[Target::Impl { of_trait: false }, Target::Impl { of_trait: true }];
429 const ADT_LIKE: &[Target] = &[Target::Struct, Target::Enum, Target::Union];
430
431 let mut added_fake_targets = Vec::new();
432 filter_targets(
433 &mut allowed_targets,
434 FUNCTION_LIKE,
435 "functions",
436 target,
437 &mut added_fake_targets,
438 );
439 filter_targets(
440 &mut allowed_targets,
441 FUNCTION_WITH_BODY_LIKE,
442 "functions with a body",
443 target,
444 &mut added_fake_targets,
445 );
446 filter_targets(&mut allowed_targets, METHOD_LIKE, "methods", target, &mut added_fake_targets);
447 filter_targets(&mut allowed_targets, IMPL_LIKE, "impl blocks", target, &mut added_fake_targets);
448 filter_targets(&mut allowed_targets, ADT_LIKE, "data types", target, &mut added_fake_targets);
449
450 let mut target_strings: Vec<_> = added_fake_targets
451 .iter()
452 .copied()
453 .chain(allowed_targets.iter().map(|t| t.plural_name()))
454 .map(|i| i.to_string())
455 .collect();
456
457 target_strings.sort();
459 target_strings.dedup();
460
461 let only_target = target_strings.len() == 1;
463
464 (target_strings, only_target)
465}
466
467fn filter_targets(
468 allowed_targets: &mut Vec<Target>,
469 target_group: &'static [Target],
470 target_group_name: &'static str,
471 target: Target,
472 added_fake_targets: &mut Vec<&'static str>,
473) {
474 if target_group.contains(&target) {
475 return;
476 }
477 if allowed_targets.iter().filter(|at| target_group.contains(at)).count() < 2 {
478 return;
479 }
480 allowed_targets.retain(|t| !target_group.contains(t));
481 added_fake_targets.push(target_group_name);
482}
483
484impl<'f, 'sess> AcceptContext<'f, 'sess> {
485 pub(crate) fn check_target(
486 &mut self,
487 attribute_args: &str,
488 allowed_targets: &AllowedTargets<'_>,
489 ) {
490 self.ignore_target_checks();
491 AttributeParser::check_target(allowed_targets, attribute_args, self);
492 }
493
494 pub(crate) fn ignore_target_checks(&mut self) {
495 #[cfg(debug_assertions)]
496 {
497 self.has_target_been_checked = true;
498 }
499 }
500}
501
502pub(crate) const ALL_TARGETS: &[Policy] = {
507 use Policy::Allow;
508 &[
509 Allow(Target::ExternCrate),
510 Allow(Target::Use),
511 Allow(Target::Static),
512 Allow(Target::Const),
513 Allow(Target::Fn),
514 Allow(Target::Closure),
515 Allow(Target::Mod),
516 Allow(Target::ForeignMod),
517 Allow(Target::GlobalAsm),
518 Allow(Target::TyAlias),
519 Allow(Target::Enum),
520 Allow(Target::Variant),
521 Allow(Target::Struct),
522 Allow(Target::Field),
523 Allow(Target::Union),
524 Allow(Target::Trait),
525 Allow(Target::TraitAlias),
526 Allow(Target::Impl { of_trait: false }),
527 Allow(Target::Impl { of_trait: true }),
528 Allow(Target::Expression),
529 Allow(Target::Statement),
530 Allow(Target::Arm),
531 Allow(Target::AssocConst(AssocCtxt::Impl { of_trait: false })),
532 Allow(Target::AssocConst(AssocCtxt::Trait)),
533 Allow(Target::AssocConst(AssocCtxt::Impl { of_trait: true })),
534 Allow(Target::Method(MethodKind::Inherent)),
535 Allow(Target::Method(MethodKind::Trait { body: false })),
536 Allow(Target::Method(MethodKind::Trait { body: true })),
537 Allow(Target::Method(MethodKind::TraitImpl)),
538 Allow(Target::AssocTy(AssocCtxt::Impl { of_trait: false })),
539 Allow(Target::AssocTy(AssocCtxt::Trait)),
540 Allow(Target::AssocTy(AssocCtxt::Impl { of_trait: true })),
541 Allow(Target::ForeignFn),
542 Allow(Target::ForeignStatic),
543 Allow(Target::ForeignTy),
544 Allow(Target::MacroDef),
545 Allow(Target::Param),
546 Allow(Target::PatField),
547 Allow(Target::ExprField),
548 Allow(Target::WherePredicate),
549 Allow(Target::MacroCall),
550 Allow(Target::Crate),
551 Allow(Target::Delegation { mac: false }),
552 Allow(Target::Delegation { mac: true }),
553 Allow(Target::ConstParam),
554 Allow(Target::LifetimeParam),
555 Allow(Target::TypeParam),
556 Allow(Target::Loop),
557 Allow(Target::ForLoop),
558 Allow(Target::While),
559 Allow(Target::Break),
560 ]
561};