1 //! checks for attributes
3 use clippy_utils::diagnostics::{span_lint, span_lint_and_help, span_lint_and_sugg, span_lint_and_then};
4 use clippy_utils::macros::{is_panic, macro_backtrace};
5 use clippy_utils::msrvs;
6 use clippy_utils::source::{first_line_of_span, is_present_in_source, snippet_opt, without_block_comments};
7 use clippy_utils::{extract_msrv_attr, meets_msrv};
8 use if_chain::if_chain;
9 use rustc_ast::{AttrKind, AttrStyle, Attribute, Lit, LitKind, MetaItemKind, NestedMetaItem};
10 use rustc_errors::Applicability;
12 Block, Expr, ExprKind, ImplItem, ImplItemKind, Item, ItemKind, StmtKind, TraitFn, TraitItem, TraitItemKind,
14 use rustc_lint::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
15 use rustc_middle::lint::in_external_macro;
17 use rustc_semver::RustcVersion;
18 use rustc_session::{declare_lint_pass, declare_tool_lint, impl_lint_pass};
19 use rustc_span::source_map::Span;
21 use rustc_span::symbol::Symbol;
24 static UNIX_SYSTEMS: &[&str] = &[
43 // NOTE: windows is excluded from the list because it's also a valid target family.
44 static NON_UNIX_SYSTEMS: &[&str] = &["hermit", "none", "wasi"];
46 declare_clippy_lint! {
48 /// Checks for items annotated with `#[inline(always)]`,
49 /// unless the annotated function is empty or simply panics.
51 /// ### Why is this bad?
52 /// While there are valid uses of this annotation (and once
53 /// you know when to use it, by all means `allow` this lint), it's a common
54 /// newbie-mistake to pepper one's code with it.
56 /// As a rule of thumb, before slapping `#[inline(always)]` on a function,
57 /// measure if that additional function call really affects your runtime profile
58 /// sufficiently to make up for the increase in compile time.
60 /// ### Known problems
61 /// False positives, big time. This lint is meant to be
62 /// deactivated by everyone doing serious performance work. This means having
63 /// done the measurement.
68 /// fn not_quite_hot_code(..) { ... }
70 #[clippy::version = "pre 1.29.0"]
73 "use of `#[inline(always)]`"
76 declare_clippy_lint! {
78 /// Checks for `extern crate` and `use` items annotated with
81 /// This lint permits lint attributes for lints emitted on the items themself.
82 /// For `use` items these lints are:
86 /// * clippy::enum_glob_use
87 /// * clippy::macro_use_imports
88 /// * clippy::wildcard_imports
90 /// For `extern crate` items these lints are:
91 /// * `unused_imports` on items with `#[macro_use]`
93 /// ### Why is this bad?
94 /// Lint attributes have no effect on crate imports. Most
95 /// likely a `!` was forgotten.
99 /// #[deny(dead_code)]
100 /// extern crate foo;
101 /// #[forbid(dead_code)]
107 /// #[allow(unused_imports)]
109 /// #[allow(unused_imports)]
111 /// extern crate baz;
113 #[clippy::version = "pre 1.29.0"]
114 pub USELESS_ATTRIBUTE,
116 "use of lint attributes on `extern crate` items"
119 declare_clippy_lint! {
121 /// Checks for `#[deprecated]` annotations with a `since`
122 /// field that is not a valid semantic version.
124 /// ### Why is this bad?
125 /// For checking the version of the deprecation, it must be
126 /// a valid semver. Failing that, the contained information is useless.
130 /// #[deprecated(since = "forever")]
131 /// fn something_else() { /* ... */ }
133 #[clippy::version = "pre 1.29.0"]
134 pub DEPRECATED_SEMVER,
136 "use of `#[deprecated(since = \"x\")]` where x is not semver"
139 declare_clippy_lint! {
141 /// Checks for empty lines after outer attributes
143 /// ### Why is this bad?
144 /// Most likely the attribute was meant to be an inner attribute using a '!'.
145 /// If it was meant to be an outer attribute, then the following item
146 /// should not be separated by empty lines.
148 /// ### Known problems
149 /// Can cause false positives.
151 /// From the clippy side it's difficult to detect empty lines between an attributes and the
152 /// following item because empty lines and comments are not part of the AST. The parsing
153 /// currently works for basic cases but is not perfect.
157 /// #[allow(dead_code)]
159 /// fn not_quite_good_code() { }
164 /// // Good (as inner attribute)
165 /// #![allow(dead_code)]
167 /// fn this_is_fine() { }
171 /// // Good (as outer attribute)
172 /// #[allow(dead_code)]
173 /// fn this_is_fine_too() { }
175 #[clippy::version = "pre 1.29.0"]
176 pub EMPTY_LINE_AFTER_OUTER_ATTR,
178 "empty line after outer attribute"
181 declare_clippy_lint! {
183 /// Checks for `warn`/`deny`/`forbid` attributes targeting the whole clippy::restriction category.
185 /// ### Why is this bad?
186 /// Restriction lints sometimes are in contrast with other lints or even go against idiomatic rust.
187 /// These lints should only be enabled on a lint-by-lint basis and with careful consideration.
191 /// #![deny(clippy::restriction)]
196 /// #![deny(clippy::as_conversions)]
198 #[clippy::version = "1.47.0"]
199 pub BLANKET_CLIPPY_RESTRICTION_LINTS,
201 "enabling the complete restriction group"
204 declare_clippy_lint! {
206 /// Checks for `#[cfg_attr(rustfmt, rustfmt_skip)]` and suggests to replace it
207 /// with `#[rustfmt::skip]`.
209 /// ### Why is this bad?
210 /// Since tool_attributes ([rust-lang/rust#44690](https://github.com/rust-lang/rust/issues/44690))
211 /// are stable now, they should be used instead of the old `cfg_attr(rustfmt)` attributes.
213 /// ### Known problems
214 /// This lint doesn't detect crate level inner attributes, because they get
215 /// processed before the PreExpansionPass lints get executed. See
216 /// [#3123](https://github.com/rust-lang/rust-clippy/pull/3123#issuecomment-422321765)
220 /// #[cfg_attr(rustfmt, rustfmt_skip)]
229 #[clippy::version = "1.32.0"]
230 pub DEPRECATED_CFG_ATTR,
232 "usage of `cfg_attr(rustfmt)` instead of tool attributes"
235 declare_clippy_lint! {
237 /// Checks for cfg attributes having operating systems used in target family position.
239 /// ### Why is this bad?
240 /// The configuration option will not be recognised and the related item will not be included
241 /// by the conditional compilation engine.
246 /// fn conditional() { }
252 /// #[cfg(target_os = "linux")]
253 /// fn conditional() { }
259 /// fn conditional() { }
261 /// Check the [Rust Reference](https://doc.rust-lang.org/reference/conditional-compilation.html#target_os) for more details.
262 #[clippy::version = "1.45.0"]
263 pub MISMATCHED_TARGET_OS,
265 "usage of `cfg(operating_system)` instead of `cfg(target_os = \"operating_system\")`"
268 declare_clippy_lint! {
270 /// Checks for attributes that allow lints without a reason.
272 /// (This requires the `lint_reasons` feature)
274 /// ### Why is this bad?
275 /// Allowing a lint should always have a reason. This reason should be documented to
276 /// ensure that others understand the reasoning
280 /// #![feature(lint_reasons)]
282 /// #![allow(clippy::some_lint)]
287 /// #![feature(lint_reasons)]
289 /// #![allow(clippy::some_lint, reason = "False positive rust-lang/rust-clippy#1002020")]
291 #[clippy::version = "1.61.0"]
292 pub ALLOW_ATTRIBUTES_WITHOUT_REASON,
294 "ensures that all `allow` and `expect` attributes have a reason"
297 declare_lint_pass!(Attributes => [
298 ALLOW_ATTRIBUTES_WITHOUT_REASON,
302 BLANKET_CLIPPY_RESTRICTION_LINTS,
305 impl<'tcx> LateLintPass<'tcx> for Attributes {
306 fn check_attribute(&mut self, cx: &LateContext<'tcx>, attr: &'tcx Attribute) {
307 if let Some(items) = &attr.meta_item_list() {
308 if let Some(ident) = attr.ident() {
309 if is_lint_level(ident.name) {
310 check_clippy_lint_names(cx, ident.name, items);
312 if matches!(ident.name, sym::allow | sym::expect) {
313 check_lint_reason(cx, ident.name, items, attr);
315 if items.is_empty() || !attr.has_name(sym::deprecated) {
320 if let NestedMetaItem::MetaItem(mi) = &item;
321 if let MetaItemKind::NameValue(lit) = &mi.kind;
322 if mi.has_name(sym::since);
324 check_semver(cx, item.span(), lit);
332 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
333 let attrs = cx.tcx.hir().attrs(item.hir_id());
334 if is_relevant_item(cx, item) {
335 check_attrs(cx, item.span, item.ident.name, attrs);
338 ItemKind::ExternCrate(..) | ItemKind::Use(..) => {
339 let skip_unused_imports = attrs.iter().any(|attr| attr.has_name(sym::macro_use));
342 if in_external_macro(cx.sess(), attr.span) {
345 if let Some(lint_list) = &attr.meta_item_list() {
346 if attr.ident().map_or(false, |ident| is_lint_level(ident.name)) {
347 for lint in lint_list {
349 ItemKind::Use(..) => {
350 if is_word(lint, sym::unused_imports)
351 || is_word(lint, sym::deprecated)
352 || is_word(lint, sym!(unreachable_pub))
353 || is_word(lint, sym!(unused))
354 || extract_clippy_lint(lint).map_or(false, |s| {
359 | "redundant_pub_crate"
360 | "macro_use_imports",
367 ItemKind::ExternCrate(..) => {
368 if is_word(lint, sym::unused_imports) && skip_unused_imports {
371 if is_word(lint, sym!(unused_extern_crates)) {
378 let line_span = first_line_of_span(cx, attr.span);
380 if let Some(mut sugg) = snippet_opt(cx, line_span) {
381 if sugg.contains("#[") {
386 "useless lint attribute",
388 sugg = sugg.replacen("#[", "#![", 1);
389 diag.span_suggestion(
391 "if you just forgot a `!`, use",
393 Applicability::MaybeIncorrect,
407 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx ImplItem<'_>) {
408 if is_relevant_impl(cx, item) {
409 check_attrs(cx, item.span, item.ident.name, cx.tcx.hir().attrs(item.hir_id()));
413 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
414 if is_relevant_trait(cx, item) {
415 check_attrs(cx, item.span, item.ident.name, cx.tcx.hir().attrs(item.hir_id()));
420 /// Returns the lint name if it is clippy lint.
421 fn extract_clippy_lint(lint: &NestedMetaItem) -> Option<Symbol> {
423 if let Some(meta_item) = lint.meta_item();
424 if meta_item.path.segments.len() > 1;
425 if let tool_name = meta_item.path.segments[0].ident;
426 if tool_name.name == sym::clippy;
428 let lint_name = meta_item.path.segments.last().unwrap().ident.name;
429 return Some(lint_name);
435 fn check_clippy_lint_names(cx: &LateContext<'_>, name: Symbol, items: &[NestedMetaItem]) {
437 if let Some(lint_name) = extract_clippy_lint(lint) {
438 if lint_name.as_str() == "restriction" && name != sym::allow {
441 BLANKET_CLIPPY_RESTRICTION_LINTS,
443 "restriction lints are not meant to be all enabled",
445 "try enabling only the lints you really need",
452 fn check_lint_reason(cx: &LateContext<'_>, name: Symbol, items: &[NestedMetaItem], attr: &'_ Attribute) {
453 // Check for the feature
454 if !cx.tcx.sess.features_untracked().lint_reasons {
458 // Check if the reason is present
459 if let Some(item) = items.last().and_then(NestedMetaItem::meta_item)
460 && let MetaItemKind::NameValue(_) = &item.kind
461 && item.path == sym::reason
468 ALLOW_ATTRIBUTES_WITHOUT_REASON,
470 &format!("`{}` attribute without specifying a reason", name.as_str()),
472 "try adding a reason at the end with `, reason = \"..\"`",
476 fn is_relevant_item(cx: &LateContext<'_>, item: &Item<'_>) -> bool {
477 if let ItemKind::Fn(_, _, eid) = item.kind {
478 is_relevant_expr(cx, cx.tcx.typeck_body(eid), cx.tcx.hir().body(eid).value)
484 fn is_relevant_impl(cx: &LateContext<'_>, item: &ImplItem<'_>) -> bool {
486 ImplItemKind::Fn(_, eid) => is_relevant_expr(cx, cx.tcx.typeck_body(eid), cx.tcx.hir().body(eid).value),
491 fn is_relevant_trait(cx: &LateContext<'_>, item: &TraitItem<'_>) -> bool {
493 TraitItemKind::Fn(_, TraitFn::Required(_)) => true,
494 TraitItemKind::Fn(_, TraitFn::Provided(eid)) => {
495 is_relevant_expr(cx, cx.tcx.typeck_body(eid), cx.tcx.hir().body(eid).value)
501 fn is_relevant_block(cx: &LateContext<'_>, typeck_results: &ty::TypeckResults<'_>, block: &Block<'_>) -> bool {
502 block.stmts.first().map_or(
506 .map_or(false, |e| is_relevant_expr(cx, typeck_results, e)),
507 |stmt| match &stmt.kind {
508 StmtKind::Local(_) => true,
509 StmtKind::Expr(expr) | StmtKind::Semi(expr) => is_relevant_expr(cx, typeck_results, expr),
510 StmtKind::Item(_) => false,
515 fn is_relevant_expr(cx: &LateContext<'_>, typeck_results: &ty::TypeckResults<'_>, expr: &Expr<'_>) -> bool {
516 if macro_backtrace(expr.span).last().map_or(false, |macro_call| {
517 is_panic(cx, macro_call.def_id) || cx.tcx.item_name(macro_call.def_id) == sym::unreachable
522 ExprKind::Block(block, _) => is_relevant_block(cx, typeck_results, block),
523 ExprKind::Ret(Some(e)) => is_relevant_expr(cx, typeck_results, e),
524 ExprKind::Ret(None) | ExprKind::Break(_, None) => false,
529 fn check_attrs(cx: &LateContext<'_>, span: Span, name: Symbol, attrs: &[Attribute]) {
530 if span.from_expansion() {
535 if let Some(values) = attr.meta_item_list() {
536 if values.len() != 1 || !attr.has_name(sym::inline) {
539 if is_word(&values[0], sym::always) {
545 "you have declared `#[inline(always)]` on `{}`. This is usually a bad idea",
554 fn check_semver(cx: &LateContext<'_>, span: Span, lit: &Lit) {
555 if let LitKind::Str(is, _) = lit.kind {
556 if Version::parse(is.as_str()).is_ok() {
564 "the since field must contain a semver-compliant version",
568 fn is_word(nmi: &NestedMetaItem, expected: Symbol) -> bool {
569 if let NestedMetaItem::MetaItem(mi) = &nmi {
570 mi.is_word() && mi.has_name(expected)
576 pub struct EarlyAttributes {
577 pub msrv: Option<RustcVersion>,
580 impl_lint_pass!(EarlyAttributes => [
582 MISMATCHED_TARGET_OS,
583 EMPTY_LINE_AFTER_OUTER_ATTR,
586 impl EarlyLintPass for EarlyAttributes {
587 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &rustc_ast::Item) {
588 check_empty_line_after_outer_attr(cx, item);
591 fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &Attribute) {
592 check_deprecated_cfg_attr(cx, attr, self.msrv);
593 check_mismatched_target_os(cx, attr);
596 extract_msrv_attr!(EarlyContext);
599 fn check_empty_line_after_outer_attr(cx: &EarlyContext<'_>, item: &rustc_ast::Item) {
600 let mut iter = item.attrs.iter().peekable();
601 while let Some(attr) = iter.next() {
602 if matches!(attr.kind, AttrKind::Normal(..))
603 && attr.style == AttrStyle::Outer
604 && is_present_in_source(cx, attr.span)
606 let begin_of_attr_to_item = Span::new(attr.span.lo(), item.span.lo(), item.span.ctxt(), item.span.parent());
607 let end_of_attr_to_next_attr_or_item = Span::new(
609 iter.peek().map_or(item.span.lo(), |next_attr| next_attr.span.lo()),
614 if let Some(snippet) = snippet_opt(cx, end_of_attr_to_next_attr_or_item) {
615 let lines = snippet.split('\n').collect::<Vec<_>>();
616 let lines = without_block_comments(lines);
618 if lines.iter().filter(|l| l.trim().is_empty()).count() > 2 {
621 EMPTY_LINE_AFTER_OUTER_ATTR,
622 begin_of_attr_to_item,
623 "found an empty line after an outer attribute. \
624 Perhaps you forgot to add a `!` to make it an inner attribute?",
632 fn check_deprecated_cfg_attr(cx: &EarlyContext<'_>, attr: &Attribute, msrv: Option<RustcVersion>) {
634 if meets_msrv(msrv, msrvs::TOOL_ATTRIBUTES);
636 if attr.has_name(sym::cfg_attr);
637 if let Some(items) = attr.meta_item_list();
639 // check for `rustfmt`
640 if let Some(feature_item) = items[0].meta_item();
641 if feature_item.has_name(sym::rustfmt);
642 // check for `rustfmt_skip` and `rustfmt::skip`
643 if let Some(skip_item) = &items[1].meta_item();
644 if skip_item.has_name(sym!(rustfmt_skip))
649 .expect("empty path in attribute")
653 // Only lint outer attributes, because custom inner attributes are unstable
654 // Tracking issue: https://github.com/rust-lang/rust/issues/54726
655 if attr.style == AttrStyle::Outer;
661 "`cfg_attr` is deprecated for rustfmt and got replaced by tool attributes",
663 "#[rustfmt::skip]".to_string(),
664 Applicability::MachineApplicable,
670 fn check_mismatched_target_os(cx: &EarlyContext<'_>, attr: &Attribute) {
671 fn find_os(name: &str) -> Option<&'static str> {
674 .chain(NON_UNIX_SYSTEMS.iter())
675 .find(|&&os| os == name)
679 fn is_unix(name: &str) -> bool {
680 UNIX_SYSTEMS.iter().any(|&os| os == name)
683 fn find_mismatched_target_os(items: &[NestedMetaItem]) -> Vec<(&str, Span)> {
684 let mut mismatched = Vec::new();
687 if let NestedMetaItem::MetaItem(meta) = item {
689 MetaItemKind::List(list) => {
690 mismatched.extend(find_mismatched_target_os(list));
692 MetaItemKind::Word => {
694 if let Some(ident) = meta.ident();
695 if let Some(os) = find_os(ident.name.as_str());
697 mismatched.push((os, ident.span));
701 MetaItemKind::NameValue(..) => {},
710 if attr.has_name(sym::cfg);
711 if let Some(list) = attr.meta_item_list();
712 let mismatched = find_mismatched_target_os(&list);
713 if !mismatched.is_empty();
715 let mess = "operating system used in target family position";
717 span_lint_and_then(cx, MISMATCHED_TARGET_OS, attr.span, mess, |diag| {
718 // Avoid showing the unix suggestion multiple times in case
719 // we have more than one mismatch for unix-like systems
720 let mut unix_suggested = false;
722 for (os, span) in mismatched {
723 let sugg = format!("target_os = \"{}\"", os);
724 diag.span_suggestion(span, "try", sugg, Applicability::MaybeIncorrect);
726 if !unix_suggested && is_unix(os) {
727 diag.help("did you mean `unix`?");
728 unix_suggested = true;
736 fn is_lint_level(symbol: Symbol) -> bool {
737 matches!(symbol, sym::allow | sym::expect | sym::warn | sym::deny | sym::forbid)