1use std::borrow::Cow;
2
3use rustc_ast::{AttrStyle, Safety};
4use rustc_attr_ir::target::{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,
10 UNUSED_DOC_COMMENTS, USELESS_DEPRECATED,
11};
12use rustc_span::{BytePos, FileName, RemapPathScopeComponents, Span, Symbol, sym};
13
14use crate::context::AcceptContext;
15use crate::diagnostics::{
16 InvalidAttrAtCrateLevel, InvalidTarget, InvalidTargetHelp, ItemFollowingInnerAttr,
17 UnsupportedAttributesInWhere,
18};
19use crate::target_checking::Policy::Allow;
20use crate::{AttributeParser, ShouldEmit};
21
22#[derive(#[automatically_derived]impl<'a> ::core::fmt::Debug for AllowedTargets<'a> {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::AllowList(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"AllowList", &__self_0),
Self::AllowListWarnRest(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"AllowListWarnRest", &__self_0),
Self::ManuallyChecked =>
::core::fmt::Formatter::write_str(f, "ManuallyChecked"),
}
}
}Debug)]
23pub(crate) enum AllowedTargets<'a> {
24 AllowList(&'a [Policy]),
25 AllowListWarnRest(&'a [Policy]),
26 ManuallyChecked,
30}
31
32#[derive(#[automatically_derived]impl ::core::cmp::Eq for AllowedResult { }Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
AllowedResult {
}
#[automatically_derived]impl ::core::cmp::PartialEq for AllowedResult {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]impl ::core::marker::Copy for AllowedResult { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for AllowedResult {
}
#[automatically_derived]impl ::core::clone::Clone for AllowedResult {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self { *self }
}Clone)]
33pub(crate) enum AllowedResult {
34 Allowed,
35 Warn,
36 Error,
37}
38
39impl AllowedTargets<'_> {
40 pub(crate) fn is_allowed(&self, target: Target) -> AllowedResult {
41 match self {
42 AllowedTargets::AllowList(list) => {
43 if list.contains(&Policy::Allow(target))
44 || list.contains(&Policy::AllowSilent(target))
45 {
46 AllowedResult::Allowed
47 } else if list.contains(&Policy::Warn(target)) {
48 AllowedResult::Warn
49 } else {
50 AllowedResult::Error
51 }
52 }
53 AllowedTargets::AllowListWarnRest(list) => {
54 if list.contains(&Policy::Allow(target))
55 || list.contains(&Policy::AllowSilent(target))
56 {
57 AllowedResult::Allowed
58 } else if list.contains(&Policy::Error(target)) {
59 AllowedResult::Error
60 } else {
61 AllowedResult::Warn
62 }
63 }
64 AllowedTargets::ManuallyChecked => ::core::panicking::unreachable_default_msg()unreachable!(),
65 }
66 }
67
68 pub(crate) fn allowed_targets(&self) -> Vec<Target> {
69 match self {
70 AllowedTargets::AllowList(list) | AllowedTargets::AllowListWarnRest(list) => list,
71 AllowedTargets::ManuallyChecked => ::core::panicking::unreachable_default_msg()unreachable!(),
72 }
73 .iter()
74 .filter_map(|target| match target {
75 Policy::Allow(target) => Some(*target),
76 Policy::AllowSilent(_) | Policy::Warn(_) | Policy::Error(_) => None,
77 })
78 .collect()
79 }
80}
81
82#[derive(#[automatically_derived]impl ::core::fmt::Debug for Policy {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::Allow(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f, "Allow",
&__self_0),
Self::AllowSilent(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"AllowSilent", &__self_0),
Self::Warn(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f, "Warn",
&__self_0),
Self::Error(__self_0) =>
::core::fmt::Formatter::debug_struct_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)]
84pub(crate) enum Policy {
85 Allow(Target),
87 AllowSilent(Target),
90 Warn(Target),
93 Error(Target),
95}
96
97impl<'sess> AttributeParser<'sess> {
98 pub(crate) fn check_target(
99 allowed_targets: &AllowedTargets<'_>,
100 attribute_args: &str,
101 cx: &mut AcceptContext<'_, 'sess>,
102 ) {
103 if #[allow(non_exhaustive_omitted_patterns)] match cx.should_emit {
ShouldEmit::Nothing => true,
_ => false,
}matches!(cx.should_emit, ShouldEmit::Nothing) {
104 return;
105 }
106
107 if let AllowedTargets::ManuallyChecked = allowed_targets {
108 #[cfg(debug_assertions)]
109 if !cx.has_target_been_checked {
110 cx.dcx().delayed_bug("Attribute target has not been checked");
111 }
112
113 return;
114 }
115
116 if let AllowedTargets::AllowList(policies) | AllowedTargets::AllowListWarnRest(policies) = allowed_targets
119 && policies.iter().filter(|p| #[allow(non_exhaustive_omitted_patterns)] match p {
Allow(_) => true,
_ => false,
}matches!(p, Allow(_))).all(|p| *p == Allow(Target::Crate))
121 {
122 Self::check_crate_level(cx, allowed_targets);
123 return;
124 }
125
126 let result = allowed_targets.is_allowed(cx.target);
127 if #[allow(non_exhaustive_omitted_patterns)] match result {
AllowedResult::Allowed => true,
_ => false,
}matches!(result, AllowedResult::Allowed) {
128 return;
129 }
130
131 let allowed_targets = allowed_targets.allowed_targets();
132 let (applied, only) = allowed_targets_applied(allowed_targets, cx.target, cx.features);
133 let is_diagnostic_attr = cx.attr_path.segments[0] == sym::diagnostic;
134 let is_lint_check_attr = [sym::allow, sym::expect, sym::deny, sym::warn, sym::forbid]
135 .contains(&cx.attr_path.segments[0]);
136
137 let span = if attribute_args.is_empty() {
138 cx.attr_path.span
141 } else {
142 cx.inner_span
149 };
150 let target_span = if span.ctxt() == cx.target_span.ctxt() && cx.target != Target::Crate {
151 cx.target_span.shrink_to_lo()
152 } else {
153 span
154 };
155
156 let diag = InvalidTarget {
157 span,
158 attr_span: cx.attr_span,
159 name: cx.attr_path.clone(),
160 target: cx.target.plural_name(),
161 target_span,
162 only: if only { "only " } else { "" },
163 applied: DiagArgValue::StrListSepByAnd(applied.into_iter().map(Cow::Owned).collect()),
164 attribute_args: attribute_args.to_string(),
165 help: Self::target_checking_help(attribute_args, cx),
166 previously_accepted: #[allow(non_exhaustive_omitted_patterns)] match result {
AllowedResult::Warn => true,
_ => false,
}matches!(result, AllowedResult::Warn)
167 && !is_diagnostic_attr
168 && !is_lint_check_attr,
169 on_macro_call: #[allow(non_exhaustive_omitted_patterns)] match cx.target {
Target::MacroCall => true,
_ => false,
}matches!(cx.target, Target::MacroCall),
170 };
171
172 match result {
173 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"),
174 AllowedResult::Warn => {
175 let lint = if cx.attr_path.segments[0] == sym::deprecated
176 && ![
177 Target::Closure,
178 Target::Expression,
179 Target::Statement,
180 Target::Arm,
181 Target::MacroCall,
182 ]
183 .contains(&cx.target)
184 {
185 USELESS_DEPRECATED
186 } else if cx.attr_path.segments[0] == sym::doc && attribute_args == "" {
187 UNUSED_DOC_COMMENTS } else if is_diagnostic_attr {
189 MISPLACED_DIAGNOSTIC_ATTRIBUTES
190 } else {
191 UNUSED_ATTRIBUTES
192 };
193
194 let attr_span = cx.attr_span;
195 cx.emit_lint(lint, diag, attr_span);
196 }
197 AllowedResult::Error => {
198 cx.dcx().emit_err(diag);
199 }
200 }
201 }
202
203 fn target_checking_help(
204 attribute_args: &str,
205 cx: &AcceptContext<'_, '_>,
206 ) -> Option<InvalidTargetHelp> {
207 match &*cx.attr_path.segments {
208 [sym::link_name] if cx.target == Target::Static => {
209 let needs_unsafe_wrapper = #[allow(non_exhaustive_omitted_patterns)] match cx.attr_safety {
Safety::Default => true,
_ => false,
}matches!(cx.attr_safety, Safety::Default);
210
211 Some(InvalidTargetHelp::UseExportName {
212 unsafe_open: needs_unsafe_wrapper.then(|| cx.inner_span.shrink_to_lo()),
213 name: cx.attr_path.span,
214 unsafe_close: needs_unsafe_wrapper.then(|| cx.inner_span.shrink_to_hi()),
215 })
216 }
217 [sym::repr] if attribute_args == "(align(...))" => match cx.target {
218 Target::Fn | Target::Method(..) if cx.features().fn_align() => {
219 Some(InvalidTargetHelp::UseRustcAlign)
220 }
221 Target::Static if cx.features().static_align() => {
222 Some(InvalidTargetHelp::UseRustcAlignStatic)
223 }
224 _ => None,
225 },
226 _ => None,
227 }
228 }
229
230 pub(crate) fn check_crate_level(
231 cx: &mut AcceptContext<'_, 'sess>,
232 allowed_targets: &AllowedTargets<'_>,
233 ) {
234 let warn = match allowed_targets.is_allowed(cx.target) {
235 AllowedResult::Allowed => return,
236 AllowedResult::Warn => true,
237 AllowedResult::Error => false,
238 };
239
240 let name = cx.attr_path.to_string();
241 let is_used_as_inner = cx.attr_style == AttrStyle::Inner;
242 let target_span = cx.target_span;
243 let attr_span = cx.attr_span;
244
245 let (show_crate_root_help, crate_root_path) = is_used_as_inner
246 .then(|| cx.cx.sess.local_crate_source_file())
247 .flatten()
248 .filter(|src| {
249 !#[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!(
250 cx.cx.sess.source_map().span_to_filename(attr_span),
251 FileName::Real(ref name) if name == src
252 )
253 })
254 .map(|src| {
255 (true, src.path(RemapPathScopeComponents::DIAGNOSTICS).display().to_string())
256 })
257 .unwrap_or_default();
258
259 if name == "doc" {
260 let diag = crate::diagnostics::AttrCrateLevelOnly { attr_span };
261 if warn {
262 cx.emit_lint(INVALID_DOC_ATTRIBUTES, diag, attr_span);
263 } else {
264 cx.emit_err(diag);
265 }
266 return;
267 }
268
269 let diag = crate::diagnostics::InvalidAttrStyle {
270 name,
271 is_used_as_inner,
272 target_span: (!is_used_as_inner).then_some(target_span),
273 target: cx.target.name(),
274 crate_root_path,
275 show_crate_root_help,
276 span: attr_span,
277 };
278 if warn {
279 cx.emit_lint(UNUSED_ATTRIBUTES, diag, attr_span);
280 } else {
281 cx.emit_err(diag);
282 }
283 }
284
285 pub(crate) fn check_invalid_crate_level_attr_item(&self, attr: &AttrItem, inner_span: Span) {
288 const ATTRS_TO_CHECK: &[Symbol] =
292 &[sym::derive, sym::test, sym::test_case, sym::global_allocator, sym::bench];
293
294 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)) {
296 let span = attr.span;
297 let name = *name;
298
299 let item = self.first_line_of_next_item(span).map(|span| ItemFollowingInnerAttr { span });
300
301 let err = self.dcx().create_err(InvalidAttrAtCrateLevel {
302 span,
303 pound_to_opening_bracket: span.until(inner_span),
304 name,
305 item,
306 });
307
308 self.dcx().try_steal_replace_and_emit_err(
309 attr.path.span,
310 StashKey::UndeterminedMacroResolution,
311 err,
312 );
313 }
314 }
315
316 fn first_line_of_next_item(&self, span: Span) -> Option<Span> {
317 self.sess()
322 .source_map()
323 .span_to_source(span, |content, _, span_end| {
324 let mut source = &content[span_end..];
325 let initial_source_len = source.len();
326 let span = try {
327 loop {
328 let first = source.chars().next()?;
329
330 if first.is_whitespace() {
331 let split_idx = source.find(|c: char| !c.is_whitespace())?;
332 source = &source[split_idx..];
333 } else if source.starts_with("//") {
334 let line_idx = source.find('\n')?;
335 source = &source[line_idx + '\n'.len_utf8()..];
336 } else if source.starts_with("/*") {
337 let close_idx = source.find("*/")?;
339 source = &source[close_idx + "*/".len()..];
340 } else if first == '#' {
341 let close_idx = source.find(']')?;
345 source = &source[close_idx + ']'.len_utf8()..];
346 } else {
347 let lo = span_end + initial_source_len - source.len();
348 let last_line = source.split('\n').next().map(|s| s.trim_end())?;
349
350 let hi = lo + last_line.len();
351 let lo = BytePos(lo as u32);
352 let hi = BytePos(hi as u32);
353 let next_item_span = Span::new(lo, hi, span.ctxt(), None);
354
355 break next_item_span;
356 }
357 }
358 };
359
360 Ok(span)
361 })
362 .ok()
363 .flatten()
364 }
365
366 pub(crate) fn check_invalid_where_predicate_attrs<'attr>(
367 &self,
368 attrs: impl IntoIterator<Item = &'attr Attribute>,
369 ) {
370 let spans = attrs
375 .into_iter()
376 .filter_map(|attr| {
377 match attr {
378 Attribute::Parsed(AttributeKind::DocComment { span, .. }) => Some(*span),
379 Attribute::Parsed(AttributeKind::Doc(attr)) => Some(attr.first_span),
381 Attribute::Parsed(_) => None,
383 Attribute::Tool { item: attr, .. } | Attribute::DeriveHelper(attr) => {
384 Some(attr.span)
385 }
386 }
387 })
388 .collect::<Vec<_>>();
389 if !spans.is_empty() {
390 self.dcx()
391 .emit_err(UnsupportedAttributesInWhere { span: MultiSpan::from_spans(spans) });
392 }
393 }
394}
395
396pub(crate) fn allowed_targets_applied(
399 mut allowed_targets: Vec<Target>,
400 target: Target,
401 features: Option<&Features>,
402) -> (Vec<String>, bool) {
403 if let Some(features) = features {
405 if !features.fn_delegation() {
406 allowed_targets.retain(|t| !#[allow(non_exhaustive_omitted_patterns)] match t {
Target::Delegation { .. } => true,
_ => false,
}matches!(t, Target::Delegation { .. }));
407 }
408 if !features.stmt_expr_attributes() {
409 allowed_targets.retain(|t| !#[allow(non_exhaustive_omitted_patterns)] match t {
Target::Expression | Target::Statement => true,
_ => false,
}matches!(t, Target::Expression | Target::Statement));
410 }
411 if !features.extern_types() {
412 allowed_targets.retain(|t| !#[allow(non_exhaustive_omitted_patterns)] match t {
Target::ForeignTy => true,
_ => false,
}matches!(t, Target::ForeignTy));
413 }
414 }
415
416 const FUNCTION_LIKE: &[Target] = &[
420 Target::Fn,
421 Target::Closure,
422 Target::ForeignFn,
423 Target::Method(MethodKind::Inherent),
424 Target::Method(MethodKind::Trait { body: false }),
425 Target::Method(MethodKind::Trait { body: true }),
426 Target::Method(MethodKind::TraitImpl),
427 ];
428 const FUNCTION_WITH_BODY_LIKE: &[Target] = &[
429 Target::Fn,
430 Target::Closure,
431 Target::Method(MethodKind::Inherent),
432 Target::Method(MethodKind::Trait { body: true }),
433 Target::Method(MethodKind::TraitImpl),
434 ];
435 const METHOD_LIKE: &[Target] = &[
436 Target::Method(MethodKind::Inherent),
437 Target::Method(MethodKind::Trait { body: false }),
438 Target::Method(MethodKind::Trait { body: true }),
439 Target::Method(MethodKind::TraitImpl),
440 ];
441 const IMPL_LIKE: &[Target] =
442 &[Target::Impl { of_trait: false }, Target::Impl { of_trait: true }];
443 const ADT_LIKE: &[Target] = &[Target::Struct, Target::Enum, Target::Union];
444
445 let mut added_fake_targets = Vec::new();
446 filter_targets(
447 &mut allowed_targets,
448 FUNCTION_LIKE,
449 "functions",
450 target,
451 &mut added_fake_targets,
452 );
453 filter_targets(
454 &mut allowed_targets,
455 FUNCTION_WITH_BODY_LIKE,
456 "functions with a body",
457 target,
458 &mut added_fake_targets,
459 );
460 filter_targets(&mut allowed_targets, METHOD_LIKE, "methods", target, &mut added_fake_targets);
461 filter_targets(&mut allowed_targets, IMPL_LIKE, "impl blocks", target, &mut added_fake_targets);
462 filter_targets(&mut allowed_targets, ADT_LIKE, "data types", target, &mut added_fake_targets);
463
464 let mut target_strings: Vec<_> = added_fake_targets
465 .iter()
466 .copied()
467 .chain(allowed_targets.iter().map(|t| t.plural_name()))
468 .map(|i| i.to_string())
469 .collect();
470
471 target_strings.sort();
473 target_strings.dedup();
474
475 let only_target = target_strings.len() == 1;
477
478 (target_strings, only_target)
479}
480
481fn filter_targets(
482 allowed_targets: &mut Vec<Target>,
483 target_group: &'static [Target],
484 target_group_name: &'static str,
485 target: Target,
486 added_fake_targets: &mut Vec<&'static str>,
487) {
488 if target_group.contains(&target) {
489 return;
490 }
491 if allowed_targets.iter().filter(|at| target_group.contains(at)).count() < 2 {
492 return;
493 }
494 allowed_targets.retain(|t| !target_group.contains(t));
495 added_fake_targets.push(target_group_name);
496}
497
498impl<'f, 'sess> AcceptContext<'f, 'sess> {
499 pub(crate) fn check_target(
500 &mut self,
501 attribute_args: &str,
502 allowed_targets: &AllowedTargets<'_>,
503 ) {
504 self.ignore_target_checks();
505 AttributeParser::check_target(allowed_targets, attribute_args, self);
506 }
507
508 pub(crate) fn ignore_target_checks(&mut self) {
509 #[cfg(debug_assertions)]
510 {
511 self.has_target_been_checked = true;
512 }
513 }
514}