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, Level, 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;
20 use rustc_span::symbol::Symbol;
21 use rustc_span::{sym, DUMMY_SP};
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_crate(&mut self, cx: &LateContext<'tcx>) {
307 for (name, level) in &cx.sess().opts.lint_opts {
308 if name == "clippy::restriction" && *level > Level::Allow {
311 BLANKET_CLIPPY_RESTRICTION_LINTS,
313 "`clippy::restriction` is not meant to be enabled as a group",
316 "because of the command line `--{} clippy::restriction`",
319 diag.help("enable the restriction lints you need individually");
326 fn check_attribute(&mut self, cx: &LateContext<'tcx>, attr: &'tcx Attribute) {
327 if let Some(items) = &attr.meta_item_list() {
328 if let Some(ident) = attr.ident() {
329 if is_lint_level(ident.name) {
330 check_clippy_lint_names(cx, ident.name, items);
332 if matches!(ident.name, sym::allow | sym::expect) {
333 check_lint_reason(cx, ident.name, items, attr);
335 if items.is_empty() || !attr.has_name(sym::deprecated) {
340 if let NestedMetaItem::MetaItem(mi) = &item;
341 if let MetaItemKind::NameValue(lit) = &mi.kind;
342 if mi.has_name(sym::since);
344 check_semver(cx, item.span(), lit);
352 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
353 let attrs = cx.tcx.hir().attrs(item.hir_id());
354 if is_relevant_item(cx, item) {
355 check_attrs(cx, item.span, item.ident.name, attrs);
358 ItemKind::ExternCrate(..) | ItemKind::Use(..) => {
359 let skip_unused_imports = attrs.iter().any(|attr| attr.has_name(sym::macro_use));
362 if in_external_macro(cx.sess(), attr.span) {
365 if let Some(lint_list) = &attr.meta_item_list() {
366 if attr.ident().map_or(false, |ident| is_lint_level(ident.name)) {
367 for lint in lint_list {
369 ItemKind::Use(..) => {
370 if is_word(lint, sym::unused_imports)
371 || is_word(lint, sym::deprecated)
372 || is_word(lint, sym!(unreachable_pub))
373 || is_word(lint, sym!(unused))
374 || extract_clippy_lint(lint).map_or(false, |s| {
379 | "redundant_pub_crate"
380 | "macro_use_imports"
381 | "unsafe_removed_from_name"
382 | "module_name_repetitions"
383 | "single_component_path_imports"
390 ItemKind::ExternCrate(..) => {
391 if is_word(lint, sym::unused_imports) && skip_unused_imports {
394 if is_word(lint, sym!(unused_extern_crates)) {
401 let line_span = first_line_of_span(cx, attr.span);
403 if let Some(mut sugg) = snippet_opt(cx, line_span) {
404 if sugg.contains("#[") {
409 "useless lint attribute",
411 sugg = sugg.replacen("#[", "#![", 1);
412 diag.span_suggestion(
414 "if you just forgot a `!`, use",
416 Applicability::MaybeIncorrect,
430 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx ImplItem<'_>) {
431 if is_relevant_impl(cx, item) {
432 check_attrs(cx, item.span, item.ident.name, cx.tcx.hir().attrs(item.hir_id()));
436 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
437 if is_relevant_trait(cx, item) {
438 check_attrs(cx, item.span, item.ident.name, cx.tcx.hir().attrs(item.hir_id()));
443 /// Returns the lint name if it is clippy lint.
444 fn extract_clippy_lint(lint: &NestedMetaItem) -> Option<Symbol> {
446 if let Some(meta_item) = lint.meta_item();
447 if meta_item.path.segments.len() > 1;
448 if let tool_name = meta_item.path.segments[0].ident;
449 if tool_name.name == sym::clippy;
451 let lint_name = meta_item.path.segments.last().unwrap().ident.name;
452 return Some(lint_name);
458 fn check_clippy_lint_names(cx: &LateContext<'_>, name: Symbol, items: &[NestedMetaItem]) {
460 if let Some(lint_name) = extract_clippy_lint(lint) {
461 if lint_name.as_str() == "restriction" && name != sym::allow {
464 BLANKET_CLIPPY_RESTRICTION_LINTS,
466 "`clippy::restriction` is not meant to be enabled as a group",
468 "enable the restriction lints you need individually",
475 fn check_lint_reason(cx: &LateContext<'_>, name: Symbol, items: &[NestedMetaItem], attr: &'_ Attribute) {
476 // Check for the feature
477 if !cx.tcx.sess.features_untracked().lint_reasons {
481 // Check if the reason is present
482 if let Some(item) = items.last().and_then(NestedMetaItem::meta_item)
483 && let MetaItemKind::NameValue(_) = &item.kind
484 && item.path == sym::reason
489 // Check if the attribute is in an external macro and therefore out of the developer's control
490 if in_external_macro(cx.sess(), attr.span) {
496 ALLOW_ATTRIBUTES_WITHOUT_REASON,
498 &format!("`{}` attribute without specifying a reason", name.as_str()),
500 "try adding a reason at the end with `, reason = \"..\"`",
504 fn is_relevant_item(cx: &LateContext<'_>, item: &Item<'_>) -> bool {
505 if let ItemKind::Fn(_, _, eid) = item.kind {
506 is_relevant_expr(cx, cx.tcx.typeck_body(eid), cx.tcx.hir().body(eid).value)
512 fn is_relevant_impl(cx: &LateContext<'_>, item: &ImplItem<'_>) -> bool {
514 ImplItemKind::Fn(_, eid) => is_relevant_expr(cx, cx.tcx.typeck_body(eid), cx.tcx.hir().body(eid).value),
519 fn is_relevant_trait(cx: &LateContext<'_>, item: &TraitItem<'_>) -> bool {
521 TraitItemKind::Fn(_, TraitFn::Required(_)) => true,
522 TraitItemKind::Fn(_, TraitFn::Provided(eid)) => {
523 is_relevant_expr(cx, cx.tcx.typeck_body(eid), cx.tcx.hir().body(eid).value)
529 fn is_relevant_block(cx: &LateContext<'_>, typeck_results: &ty::TypeckResults<'_>, block: &Block<'_>) -> bool {
530 block.stmts.first().map_or(
534 .map_or(false, |e| is_relevant_expr(cx, typeck_results, e)),
535 |stmt| match &stmt.kind {
536 StmtKind::Local(_) => true,
537 StmtKind::Expr(expr) | StmtKind::Semi(expr) => is_relevant_expr(cx, typeck_results, expr),
538 StmtKind::Item(_) => false,
543 fn is_relevant_expr(cx: &LateContext<'_>, typeck_results: &ty::TypeckResults<'_>, expr: &Expr<'_>) -> bool {
544 if macro_backtrace(expr.span).last().map_or(false, |macro_call| {
545 is_panic(cx, macro_call.def_id) || cx.tcx.item_name(macro_call.def_id) == sym::unreachable
550 ExprKind::Block(block, _) => is_relevant_block(cx, typeck_results, block),
551 ExprKind::Ret(Some(e)) => is_relevant_expr(cx, typeck_results, e),
552 ExprKind::Ret(None) | ExprKind::Break(_, None) => false,
557 fn check_attrs(cx: &LateContext<'_>, span: Span, name: Symbol, attrs: &[Attribute]) {
558 if span.from_expansion() {
563 if let Some(values) = attr.meta_item_list() {
564 if values.len() != 1 || !attr.has_name(sym::inline) {
567 if is_word(&values[0], sym::always) {
572 &format!("you have declared `#[inline(always)]` on `{name}`. This is usually a bad idea"),
579 fn check_semver(cx: &LateContext<'_>, span: Span, lit: &Lit) {
580 if let LitKind::Str(is, _) = lit.kind {
581 if Version::parse(is.as_str()).is_ok() {
589 "the since field must contain a semver-compliant version",
593 fn is_word(nmi: &NestedMetaItem, expected: Symbol) -> bool {
594 if let NestedMetaItem::MetaItem(mi) = &nmi {
595 mi.is_word() && mi.has_name(expected)
601 pub struct EarlyAttributes {
602 pub msrv: Option<RustcVersion>,
605 impl_lint_pass!(EarlyAttributes => [
607 MISMATCHED_TARGET_OS,
608 EMPTY_LINE_AFTER_OUTER_ATTR,
611 impl EarlyLintPass for EarlyAttributes {
612 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &rustc_ast::Item) {
613 check_empty_line_after_outer_attr(cx, item);
616 fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &Attribute) {
617 check_deprecated_cfg_attr(cx, attr, self.msrv);
618 check_mismatched_target_os(cx, attr);
621 extract_msrv_attr!(EarlyContext);
624 fn check_empty_line_after_outer_attr(cx: &EarlyContext<'_>, item: &rustc_ast::Item) {
625 let mut iter = item.attrs.iter().peekable();
626 while let Some(attr) = iter.next() {
627 if matches!(attr.kind, AttrKind::Normal(..))
628 && attr.style == AttrStyle::Outer
629 && is_present_in_source(cx, attr.span)
631 let begin_of_attr_to_item = Span::new(attr.span.lo(), item.span.lo(), item.span.ctxt(), item.span.parent());
632 let end_of_attr_to_next_attr_or_item = Span::new(
634 iter.peek().map_or(item.span.lo(), |next_attr| next_attr.span.lo()),
639 if let Some(snippet) = snippet_opt(cx, end_of_attr_to_next_attr_or_item) {
640 let lines = snippet.split('\n').collect::<Vec<_>>();
641 let lines = without_block_comments(lines);
643 if lines.iter().filter(|l| l.trim().is_empty()).count() > 2 {
646 EMPTY_LINE_AFTER_OUTER_ATTR,
647 begin_of_attr_to_item,
648 "found an empty line after an outer attribute. \
649 Perhaps you forgot to add a `!` to make it an inner attribute?",
657 fn check_deprecated_cfg_attr(cx: &EarlyContext<'_>, attr: &Attribute, msrv: Option<RustcVersion>) {
659 if meets_msrv(msrv, msrvs::TOOL_ATTRIBUTES);
661 if attr.has_name(sym::cfg_attr);
662 if let Some(items) = attr.meta_item_list();
664 // check for `rustfmt`
665 if let Some(feature_item) = items[0].meta_item();
666 if feature_item.has_name(sym::rustfmt);
667 // check for `rustfmt_skip` and `rustfmt::skip`
668 if let Some(skip_item) = &items[1].meta_item();
669 if skip_item.has_name(sym!(rustfmt_skip))
674 .expect("empty path in attribute")
678 // Only lint outer attributes, because custom inner attributes are unstable
679 // Tracking issue: https://github.com/rust-lang/rust/issues/54726
680 if attr.style == AttrStyle::Outer;
686 "`cfg_attr` is deprecated for rustfmt and got replaced by tool attributes",
688 "#[rustfmt::skip]".to_string(),
689 Applicability::MachineApplicable,
695 fn check_mismatched_target_os(cx: &EarlyContext<'_>, attr: &Attribute) {
696 fn find_os(name: &str) -> Option<&'static str> {
699 .chain(NON_UNIX_SYSTEMS.iter())
700 .find(|&&os| os == name)
704 fn is_unix(name: &str) -> bool {
705 UNIX_SYSTEMS.iter().any(|&os| os == name)
708 fn find_mismatched_target_os(items: &[NestedMetaItem]) -> Vec<(&str, Span)> {
709 let mut mismatched = Vec::new();
712 if let NestedMetaItem::MetaItem(meta) = item {
714 MetaItemKind::List(list) => {
715 mismatched.extend(find_mismatched_target_os(list));
717 MetaItemKind::Word => {
719 if let Some(ident) = meta.ident();
720 if let Some(os) = find_os(ident.name.as_str());
722 mismatched.push((os, ident.span));
726 MetaItemKind::NameValue(..) => {},
735 if attr.has_name(sym::cfg);
736 if let Some(list) = attr.meta_item_list();
737 let mismatched = find_mismatched_target_os(&list);
738 if !mismatched.is_empty();
740 let mess = "operating system used in target family position";
742 span_lint_and_then(cx, MISMATCHED_TARGET_OS, attr.span, mess, |diag| {
743 // Avoid showing the unix suggestion multiple times in case
744 // we have more than one mismatch for unix-like systems
745 let mut unix_suggested = false;
747 for (os, span) in mismatched {
748 let sugg = format!("target_os = \"{os}\"");
749 diag.span_suggestion(span, "try", sugg, Applicability::MaybeIncorrect);
751 if !unix_suggested && is_unix(os) {
752 diag.help("did you mean `unix`?");
753 unix_suggested = true;
761 fn is_lint_level(symbol: Symbol) -> bool {
762 matches!(symbol, sym::allow | sym::expect | sym::warn | sym::deny | sym::forbid)