1use std::borrow::Cow;
2
3use rustc_ast::AttrStyle;
4use rustc_errors::{DiagArgValue, Diagnostic, MultiSpan, StashKey};
5use rustc_feature::Features;
6use rustc_hir::attrs::AttributeKind;
7use rustc_hir::{AttrItem, Attribute, MethodKind, Target};
8use rustc_span::{BytePos, Span, Symbol, sym};
9
10use crate::AttributeParser;
11use crate::context::{AcceptContext, Stage};
12use crate::errors::{
13 InvalidAttrAtCrateLevel, InvalidTargetLint, ItemFollowingInnerAttr,
14 UnsupportedAttributesInWhere,
15};
16use crate::session_diagnostics::InvalidTarget;
17use crate::target_checking::Policy::Allow;
18
19#[derive(#[automatically_derived]
impl ::core::fmt::Debug for AllowedTargets {
#[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),
}
}
}Debug)]
20pub(crate) enum AllowedTargets {
21 AllowList(&'static [Policy]),
22 AllowListWarnRest(&'static [Policy]),
23}
24
25pub(crate) enum AllowedResult {
26 Allowed,
27 Warn,
28 Error,
29}
30
31impl AllowedTargets {
32 pub(crate) fn is_allowed(&self, target: Target) -> AllowedResult {
33 match self {
34 AllowedTargets::AllowList(list) => {
35 if list.contains(&Policy::Allow(target))
36 || list.contains(&Policy::AllowSilent(target))
37 {
38 AllowedResult::Allowed
39 } else if list.contains(&Policy::Warn(target)) {
40 AllowedResult::Warn
41 } else {
42 AllowedResult::Error
43 }
44 }
45 AllowedTargets::AllowListWarnRest(list) => {
46 if list.contains(&Policy::Allow(target))
47 || list.contains(&Policy::AllowSilent(target))
48 {
49 AllowedResult::Allowed
50 } else if list.contains(&Policy::Error(target)) {
51 AllowedResult::Error
52 } else {
53 AllowedResult::Warn
54 }
55 }
56 }
57 }
58
59 pub(crate) fn allowed_targets(&self) -> Vec<Target> {
60 match self {
61 AllowedTargets::AllowList(list) => list,
62 AllowedTargets::AllowListWarnRest(list) => list,
63 }
64 .iter()
65 .filter_map(|target| match target {
66 Policy::Allow(target) => Some(*target),
67 Policy::AllowSilent(_) => None, Policy::Warn(_) => None,
69 Policy::Error(_) => None,
70 })
71 .collect()
72 }
73}
74
75#[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)]
77pub(crate) enum Policy {
78 Allow(Target),
80 AllowSilent(Target),
83 Warn(Target),
86 Error(Target),
88}
89
90impl<'sess, S: Stage> AttributeParser<'sess, S> {
91 pub(crate) fn check_target(
92 allowed_targets: &AllowedTargets,
93 target: Target,
94 cx: &mut AcceptContext<'_, 'sess, S>,
95 ) {
96 if let &AllowedTargets::AllowList(&[Allow(Target::Crate)]) = allowed_targets {
99 Self::check_crate_level(target, cx);
100 return;
101 }
102
103 if #[allow(non_exhaustive_omitted_patterns)] match cx.attr_path.segments.as_ref()
{
[sym::repr] => true,
_ => false,
}matches!(cx.attr_path.segments.as_ref(), [sym::repr]) && target == Target::Crate {
104 let span = cx.attr_span;
107 let item =
108 cx.cx.first_line_of_next_item(span).map(|span| ItemFollowingInnerAttr { span });
109
110 let pound_to_opening_bracket = cx.attr_span.until(cx.inner_span);
111
112 cx.dcx()
113 .create_err(InvalidAttrAtCrateLevel {
114 span,
115 pound_to_opening_bracket,
116 name: sym::repr,
117 item,
118 })
119 .emit();
120 }
121
122 match allowed_targets.is_allowed(target) {
123 AllowedResult::Allowed => {}
124 AllowedResult::Warn => {
125 let allowed_targets = allowed_targets.allowed_targets();
126 let (applied, only) = allowed_targets_applied(allowed_targets, target, cx.features);
127 let name = cx.attr_path.clone();
128
129 let lint = if name.segments[0] == sym::deprecated
130 && ![
131 Target::Closure,
132 Target::Expression,
133 Target::Statement,
134 Target::Arm,
135 Target::MacroCall,
136 ]
137 .contains(&target)
138 {
139 rustc_session::lint::builtin::USELESS_DEPRECATED
140 } else {
141 rustc_session::lint::builtin::UNUSED_ATTRIBUTES
142 };
143
144 let attr_span = cx.attr_span;
145 cx.emit_dyn_lint(
146 lint,
147 move |dcx, level| {
148 InvalidTargetLint {
149 name: name.to_string(),
150 target: target.plural_name(),
151 only: if only { "only " } else { "" },
152 applied: DiagArgValue::StrListSepByAnd(
153 applied.iter().map(|i| Cow::Owned(i.to_string())).collect(),
154 ),
155 attr_span,
156 }
157 .into_diag(dcx, level)
158 },
159 attr_span,
160 );
161 }
162 AllowedResult::Error => {
163 let allowed_targets = allowed_targets.allowed_targets();
164 let (applied, only) = allowed_targets_applied(allowed_targets, target, cx.features);
165 let name = cx.attr_path.clone();
166 cx.dcx().emit_err(InvalidTarget {
167 span: cx.attr_span.clone(),
168 name,
169 target: target.plural_name(),
170 only: if only { "only " } else { "" },
171 applied: DiagArgValue::StrListSepByAnd(
172 applied.into_iter().map(Cow::Owned).collect(),
173 ),
174 });
175 }
176 }
177 }
178
179 pub(crate) fn check_crate_level(target: Target, cx: &mut AcceptContext<'_, 'sess, S>) {
180 if target == Target::Crate {
181 return;
182 }
183
184 let name = cx.attr_path.to_string();
185 let is_used_as_inner = cx.attr_style == AttrStyle::Inner;
186 let target_span = cx.target_span;
187 let attr_span = cx.attr_span;
188
189 cx.emit_dyn_lint(
190 rustc_session::lint::builtin::UNUSED_ATTRIBUTES,
191 move |dcx, level| {
192 crate::errors::InvalidAttrStyle {
193 name: &name,
194 is_used_as_inner,
195 target_span: (!is_used_as_inner).then_some(target_span),
196 target: target.name(),
197 }
198 .into_diag(dcx, level)
199 },
200 attr_span,
201 );
202 }
203
204 pub(crate) fn check_invalid_crate_level_attr_item(&self, attr: &AttrItem, inner_span: Span) {
207 const ATTRS_TO_CHECK: &[Symbol] =
211 &[sym::derive, sym::test, sym::test_case, sym::global_allocator, sym::bench];
212
213 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)) {
215 let span = attr.span;
216 let name = *name;
217
218 let item = self.first_line_of_next_item(span).map(|span| ItemFollowingInnerAttr { span });
219
220 let err = self.dcx().create_err(InvalidAttrAtCrateLevel {
221 span,
222 pound_to_opening_bracket: span.until(inner_span),
223 name,
224 item,
225 });
226
227 self.dcx().try_steal_replace_and_emit_err(
228 attr.path.span,
229 StashKey::UndeterminedMacroResolution,
230 err,
231 );
232 }
233 }
234
235 fn first_line_of_next_item(&self, span: Span) -> Option<Span> {
236 self.sess()
241 .source_map()
242 .span_to_source(span, |content, _, span_end| {
243 let mut source = &content[span_end..];
244 let initial_source_len = source.len();
245 let span = try {
246 loop {
247 let first = source.chars().next()?;
248
249 if first.is_whitespace() {
250 let split_idx = source.find(|c: char| !c.is_whitespace())?;
251 source = &source[split_idx..];
252 } else if source.starts_with("//") {
253 let line_idx = source.find('\n')?;
254 source = &source[line_idx + '\n'.len_utf8()..];
255 } else if source.starts_with("/*") {
256 let close_idx = source.find("*/")?;
258 source = &source[close_idx + "*/".len()..];
259 } else if first == '#' {
260 let close_idx = source.find(']')?;
264 source = &source[close_idx + ']'.len_utf8()..];
265 } else {
266 let lo = span_end + initial_source_len - source.len();
267 let last_line = source.split('\n').next().map(|s| s.trim_end())?;
268
269 let hi = lo + last_line.len();
270 let lo = BytePos(lo as u32);
271 let hi = BytePos(hi as u32);
272 let next_item_span = Span::new(lo, hi, span.ctxt(), None);
273
274 break next_item_span;
275 }
276 }
277 };
278
279 Ok(span)
280 })
281 .ok()
282 .flatten()
283 }
284
285 pub(crate) fn check_invalid_where_predicate_attrs<'attr>(
286 &self,
287 attrs: impl IntoIterator<Item = &'attr Attribute>,
288 ) {
289 let spans = attrs
294 .into_iter()
295 .filter(|attr| {
297 #[allow(non_exhaustive_omitted_patterns)] match attr {
Attribute::Parsed(AttributeKind::DocComment { .. } |
AttributeKind::Doc(_)) | Attribute::Unparsed(_) => true,
_ => false,
}matches!(
298 attr,
299 Attribute::Parsed(AttributeKind::DocComment { .. } | AttributeKind::Doc(_))
300 | Attribute::Unparsed(_)
301 )
302 })
303 .map(|attr| attr.span())
304 .collect::<Vec<_>>();
305 if !spans.is_empty() {
306 self.dcx()
307 .emit_err(UnsupportedAttributesInWhere { span: MultiSpan::from_spans(spans) });
308 }
309 }
310}
311
312pub(crate) fn allowed_targets_applied(
315 mut allowed_targets: Vec<Target>,
316 target: Target,
317 features: Option<&Features>,
318) -> (Vec<String>, bool) {
319 if let Some(features) = features {
321 if !features.fn_delegation() {
322 allowed_targets.retain(|t| !#[allow(non_exhaustive_omitted_patterns)] match t {
Target::Delegation { .. } => true,
_ => false,
}matches!(t, Target::Delegation { .. }));
323 }
324 if !features.stmt_expr_attributes() {
325 allowed_targets.retain(|t| !#[allow(non_exhaustive_omitted_patterns)] match t {
Target::Expression | Target::Statement => true,
_ => false,
}matches!(t, Target::Expression | Target::Statement));
326 }
327 if !features.extern_types() {
328 allowed_targets.retain(|t| !#[allow(non_exhaustive_omitted_patterns)] match t {
Target::ForeignTy => true,
_ => false,
}matches!(t, Target::ForeignTy));
329 }
330 }
331
332 const FUNCTION_LIKE: &[Target] = &[
336 Target::Fn,
337 Target::Closure,
338 Target::ForeignFn,
339 Target::Method(MethodKind::Inherent),
340 Target::Method(MethodKind::Trait { body: false }),
341 Target::Method(MethodKind::Trait { body: true }),
342 Target::Method(MethodKind::TraitImpl),
343 ];
344 const METHOD_LIKE: &[Target] = &[
345 Target::Method(MethodKind::Inherent),
346 Target::Method(MethodKind::Trait { body: false }),
347 Target::Method(MethodKind::Trait { body: true }),
348 Target::Method(MethodKind::TraitImpl),
349 ];
350 const IMPL_LIKE: &[Target] =
351 &[Target::Impl { of_trait: false }, Target::Impl { of_trait: true }];
352 const ADT_LIKE: &[Target] = &[Target::Struct, Target::Enum, Target::Union];
353
354 let mut added_fake_targets = Vec::new();
355 filter_targets(
356 &mut allowed_targets,
357 FUNCTION_LIKE,
358 "functions",
359 target,
360 &mut added_fake_targets,
361 );
362 filter_targets(&mut allowed_targets, METHOD_LIKE, "methods", target, &mut added_fake_targets);
363 filter_targets(&mut allowed_targets, IMPL_LIKE, "impl blocks", target, &mut added_fake_targets);
364 filter_targets(&mut allowed_targets, ADT_LIKE, "data types", target, &mut added_fake_targets);
365
366 let mut target_strings: Vec<_> = added_fake_targets
367 .iter()
368 .copied()
369 .chain(allowed_targets.iter().map(|t| t.plural_name()))
370 .map(|i| i.to_string())
371 .collect();
372
373 target_strings.sort();
375
376 let only_target = target_strings.len() == 1;
378
379 (target_strings, only_target)
380}
381
382fn filter_targets(
383 allowed_targets: &mut Vec<Target>,
384 target_group: &'static [Target],
385 target_group_name: &'static str,
386 target: Target,
387 added_fake_targets: &mut Vec<&'static str>,
388) {
389 if target_group.contains(&target) {
390 return;
391 }
392 if allowed_targets.iter().filter(|at| target_group.contains(at)).count() < 2 {
393 return;
394 }
395 allowed_targets.retain(|t| !target_group.contains(t));
396 added_fake_targets.push(target_group_name);
397}
398
399pub(crate) const ALL_TARGETS: &'static [Policy] = {
404 use Policy::Allow;
405 &[
406 Allow(Target::ExternCrate),
407 Allow(Target::Use),
408 Allow(Target::Static),
409 Allow(Target::Const),
410 Allow(Target::Fn),
411 Allow(Target::Closure),
412 Allow(Target::Mod),
413 Allow(Target::ForeignMod),
414 Allow(Target::GlobalAsm),
415 Allow(Target::TyAlias),
416 Allow(Target::Enum),
417 Allow(Target::Variant),
418 Allow(Target::Struct),
419 Allow(Target::Field),
420 Allow(Target::Union),
421 Allow(Target::Trait),
422 Allow(Target::TraitAlias),
423 Allow(Target::Impl { of_trait: false }),
424 Allow(Target::Impl { of_trait: true }),
425 Allow(Target::Expression),
426 Allow(Target::Statement),
427 Allow(Target::Arm),
428 Allow(Target::AssocConst),
429 Allow(Target::Method(MethodKind::Inherent)),
430 Allow(Target::Method(MethodKind::Trait { body: false })),
431 Allow(Target::Method(MethodKind::Trait { body: true })),
432 Allow(Target::Method(MethodKind::TraitImpl)),
433 Allow(Target::AssocTy),
434 Allow(Target::ForeignFn),
435 Allow(Target::ForeignStatic),
436 Allow(Target::ForeignTy),
437 Allow(Target::MacroDef),
438 Allow(Target::Param),
439 Allow(Target::PatField),
440 Allow(Target::ExprField),
441 Allow(Target::WherePredicate),
442 Allow(Target::MacroCall),
443 Allow(Target::Crate),
444 Allow(Target::Delegation { mac: false }),
445 Allow(Target::Delegation { mac: true }),
446 Allow(Target::GenericParam {
447 kind: rustc_hir::target::GenericParamKind::Const,
448 has_default: false,
449 }),
450 Allow(Target::GenericParam {
451 kind: rustc_hir::target::GenericParamKind::Const,
452 has_default: true,
453 }),
454 Allow(Target::GenericParam {
455 kind: rustc_hir::target::GenericParamKind::Lifetime,
456 has_default: false,
457 }),
458 Allow(Target::GenericParam {
459 kind: rustc_hir::target::GenericParamKind::Lifetime,
460 has_default: true,
461 }),
462 Allow(Target::GenericParam {
463 kind: rustc_hir::target::GenericParamKind::Type,
464 has_default: false,
465 }),
466 Allow(Target::GenericParam {
467 kind: rustc_hir::target::GenericParamKind::Type,
468 has_default: true,
469 }),
470 ]
471};