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::{self, Msrv};
6 use clippy_utils::source::{first_line_of_span, is_present_in_source, snippet_opt, without_block_comments};
7 use if_chain::if_chain;
8 use rustc_ast::{AttrKind, AttrStyle, Attribute, LitKind, MetaItemKind, MetaItemLit, NestedMetaItem};
9 use rustc_errors::Applicability;
11 Block, Expr, ExprKind, ImplItem, ImplItemKind, Item, ItemKind, StmtKind, TraitFn, TraitItem, TraitItemKind,
13 use rustc_lint::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, Level, LintContext};
14 use rustc_middle::lint::in_external_macro;
16 use rustc_session::{declare_lint_pass, declare_tool_lint, impl_lint_pass};
17 use rustc_span::source_map::Span;
18 use rustc_span::symbol::Symbol;
19 use rustc_span::{sym, DUMMY_SP};
22 static UNIX_SYSTEMS: &[&str] = &[
41 // NOTE: windows is excluded from the list because it's also a valid target family.
42 static NON_UNIX_SYSTEMS: &[&str] = &["hermit", "none", "wasi"];
44 declare_clippy_lint! {
46 /// Checks for items annotated with `#[inline(always)]`,
47 /// unless the annotated function is empty or simply panics.
49 /// ### Why is this bad?
50 /// While there are valid uses of this annotation (and once
51 /// you know when to use it, by all means `allow` this lint), it's a common
52 /// newbie-mistake to pepper one's code with it.
54 /// As a rule of thumb, before slapping `#[inline(always)]` on a function,
55 /// measure if that additional function call really affects your runtime profile
56 /// sufficiently to make up for the increase in compile time.
58 /// ### Known problems
59 /// False positives, big time. This lint is meant to be
60 /// deactivated by everyone doing serious performance work. This means having
61 /// done the measurement.
66 /// fn not_quite_hot_code(..) { ... }
68 #[clippy::version = "pre 1.29.0"]
71 "use of `#[inline(always)]`"
74 declare_clippy_lint! {
76 /// Checks for `extern crate` and `use` items annotated with
79 /// This lint permits lint attributes for lints emitted on the items themself.
80 /// For `use` items these lints are:
84 /// * clippy::enum_glob_use
85 /// * clippy::macro_use_imports
86 /// * clippy::wildcard_imports
88 /// For `extern crate` items these lints are:
89 /// * `unused_imports` on items with `#[macro_use]`
91 /// ### Why is this bad?
92 /// Lint attributes have no effect on crate imports. Most
93 /// likely a `!` was forgotten.
97 /// #[deny(dead_code)]
99 /// #[forbid(dead_code)]
105 /// #[allow(unused_imports)]
107 /// #[allow(unused_imports)]
109 /// extern crate baz;
111 #[clippy::version = "pre 1.29.0"]
112 pub USELESS_ATTRIBUTE,
114 "use of lint attributes on `extern crate` items"
117 declare_clippy_lint! {
119 /// Checks for `#[deprecated]` annotations with a `since`
120 /// field that is not a valid semantic version.
122 /// ### Why is this bad?
123 /// For checking the version of the deprecation, it must be
124 /// a valid semver. Failing that, the contained information is useless.
128 /// #[deprecated(since = "forever")]
129 /// fn something_else() { /* ... */ }
131 #[clippy::version = "pre 1.29.0"]
132 pub DEPRECATED_SEMVER,
134 "use of `#[deprecated(since = \"x\")]` where x is not semver"
137 declare_clippy_lint! {
139 /// Checks for empty lines after outer attributes
141 /// ### Why is this bad?
142 /// Most likely the attribute was meant to be an inner attribute using a '!'.
143 /// If it was meant to be an outer attribute, then the following item
144 /// should not be separated by empty lines.
146 /// ### Known problems
147 /// Can cause false positives.
149 /// From the clippy side it's difficult to detect empty lines between an attributes and the
150 /// following item because empty lines and comments are not part of the AST. The parsing
151 /// currently works for basic cases but is not perfect.
155 /// #[allow(dead_code)]
157 /// fn not_quite_good_code() { }
162 /// // Good (as inner attribute)
163 /// #![allow(dead_code)]
165 /// fn this_is_fine() { }
169 /// // Good (as outer attribute)
170 /// #[allow(dead_code)]
171 /// fn this_is_fine_too() { }
173 #[clippy::version = "pre 1.29.0"]
174 pub EMPTY_LINE_AFTER_OUTER_ATTR,
176 "empty line after outer attribute"
179 declare_clippy_lint! {
181 /// Checks for `warn`/`deny`/`forbid` attributes targeting the whole clippy::restriction category.
183 /// ### Why is this bad?
184 /// Restriction lints sometimes are in contrast with other lints or even go against idiomatic rust.
185 /// These lints should only be enabled on a lint-by-lint basis and with careful consideration.
189 /// #![deny(clippy::restriction)]
194 /// #![deny(clippy::as_conversions)]
196 #[clippy::version = "1.47.0"]
197 pub BLANKET_CLIPPY_RESTRICTION_LINTS,
199 "enabling the complete restriction group"
202 declare_clippy_lint! {
204 /// Checks for `#[cfg_attr(rustfmt, rustfmt_skip)]` and suggests to replace it
205 /// with `#[rustfmt::skip]`.
207 /// ### Why is this bad?
208 /// Since tool_attributes ([rust-lang/rust#44690](https://github.com/rust-lang/rust/issues/44690))
209 /// are stable now, they should be used instead of the old `cfg_attr(rustfmt)` attributes.
211 /// ### Known problems
212 /// This lint doesn't detect crate level inner attributes, because they get
213 /// processed before the PreExpansionPass lints get executed. See
214 /// [#3123](https://github.com/rust-lang/rust-clippy/pull/3123#issuecomment-422321765)
218 /// #[cfg_attr(rustfmt, rustfmt_skip)]
227 #[clippy::version = "1.32.0"]
228 pub DEPRECATED_CFG_ATTR,
230 "usage of `cfg_attr(rustfmt)` instead of tool attributes"
233 declare_clippy_lint! {
235 /// Checks for cfg attributes having operating systems used in target family position.
237 /// ### Why is this bad?
238 /// The configuration option will not be recognised and the related item will not be included
239 /// by the conditional compilation engine.
244 /// fn conditional() { }
250 /// #[cfg(target_os = "linux")]
251 /// fn conditional() { }
257 /// fn conditional() { }
259 /// Check the [Rust Reference](https://doc.rust-lang.org/reference/conditional-compilation.html#target_os) for more details.
260 #[clippy::version = "1.45.0"]
261 pub MISMATCHED_TARGET_OS,
263 "usage of `cfg(operating_system)` instead of `cfg(target_os = \"operating_system\")`"
266 declare_clippy_lint! {
268 /// Checks for attributes that allow lints without a reason.
270 /// (This requires the `lint_reasons` feature)
272 /// ### Why is this bad?
273 /// Allowing a lint should always have a reason. This reason should be documented to
274 /// ensure that others understand the reasoning
278 /// #![feature(lint_reasons)]
280 /// #![allow(clippy::some_lint)]
285 /// #![feature(lint_reasons)]
287 /// #![allow(clippy::some_lint, reason = "False positive rust-lang/rust-clippy#1002020")]
289 #[clippy::version = "1.61.0"]
290 pub ALLOW_ATTRIBUTES_WITHOUT_REASON,
292 "ensures that all `allow` and `expect` attributes have a reason"
295 declare_lint_pass!(Attributes => [
296 ALLOW_ATTRIBUTES_WITHOUT_REASON,
300 BLANKET_CLIPPY_RESTRICTION_LINTS,
303 impl<'tcx> LateLintPass<'tcx> for Attributes {
304 fn check_crate(&mut self, cx: &LateContext<'tcx>) {
305 for (name, level) in &cx.sess().opts.lint_opts {
306 if name == "clippy::restriction" && *level > Level::Allow {
309 BLANKET_CLIPPY_RESTRICTION_LINTS,
311 "`clippy::restriction` is not meant to be enabled as a group",
314 "because of the command line `--{} clippy::restriction`",
317 diag.help("enable the restriction lints you need individually");
324 fn check_attribute(&mut self, cx: &LateContext<'tcx>, attr: &'tcx Attribute) {
325 if let Some(items) = &attr.meta_item_list() {
326 if let Some(ident) = attr.ident() {
327 if is_lint_level(ident.name) {
328 check_clippy_lint_names(cx, ident.name, items);
330 if matches!(ident.name, sym::allow | sym::expect) {
331 check_lint_reason(cx, ident.name, items, attr);
333 if items.is_empty() || !attr.has_name(sym::deprecated) {
338 if let NestedMetaItem::MetaItem(mi) = &item;
339 if let MetaItemKind::NameValue(lit) = &mi.kind;
340 if mi.has_name(sym::since);
342 check_semver(cx, item.span(), lit);
350 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
351 let attrs = cx.tcx.hir().attrs(item.hir_id());
352 if is_relevant_item(cx, item) {
353 check_attrs(cx, item.span, item.ident.name, attrs);
356 ItemKind::ExternCrate(..) | ItemKind::Use(..) => {
357 let skip_unused_imports = attrs.iter().any(|attr| attr.has_name(sym::macro_use));
360 if in_external_macro(cx.sess(), attr.span) {
363 if let Some(lint_list) = &attr.meta_item_list() {
364 if attr.ident().map_or(false, |ident| is_lint_level(ident.name)) {
365 for lint in lint_list {
367 ItemKind::Use(..) => {
368 if is_word(lint, sym::unused_imports)
369 || is_word(lint, sym::deprecated)
370 || is_word(lint, sym!(unreachable_pub))
371 || is_word(lint, sym!(unused))
372 || extract_clippy_lint(lint).map_or(false, |s| {
377 | "redundant_pub_crate"
378 | "macro_use_imports"
379 | "unsafe_removed_from_name"
380 | "module_name_repetitions"
381 | "single_component_path_imports"
388 ItemKind::ExternCrate(..) => {
389 if is_word(lint, sym::unused_imports) && skip_unused_imports {
392 if is_word(lint, sym!(unused_extern_crates)) {
399 let line_span = first_line_of_span(cx, attr.span);
401 if let Some(mut sugg) = snippet_opt(cx, line_span) {
402 if sugg.contains("#[") {
407 "useless lint attribute",
409 sugg = sugg.replacen("#[", "#![", 1);
410 diag.span_suggestion(
412 "if you just forgot a `!`, use",
414 Applicability::MaybeIncorrect,
428 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx ImplItem<'_>) {
429 if is_relevant_impl(cx, item) {
430 check_attrs(cx, item.span, item.ident.name, cx.tcx.hir().attrs(item.hir_id()));
434 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
435 if is_relevant_trait(cx, item) {
436 check_attrs(cx, item.span, item.ident.name, cx.tcx.hir().attrs(item.hir_id()));
441 /// Returns the lint name if it is clippy lint.
442 fn extract_clippy_lint(lint: &NestedMetaItem) -> Option<Symbol> {
444 if let Some(meta_item) = lint.meta_item();
445 if meta_item.path.segments.len() > 1;
446 if let tool_name = meta_item.path.segments[0].ident;
447 if tool_name.name == sym::clippy;
449 let lint_name = meta_item.path.segments.last().unwrap().ident.name;
450 return Some(lint_name);
456 fn check_clippy_lint_names(cx: &LateContext<'_>, name: Symbol, items: &[NestedMetaItem]) {
458 if let Some(lint_name) = extract_clippy_lint(lint) {
459 if lint_name.as_str() == "restriction" && name != sym::allow {
462 BLANKET_CLIPPY_RESTRICTION_LINTS,
464 "`clippy::restriction` is not meant to be enabled as a group",
466 "enable the restriction lints you need individually",
473 fn check_lint_reason(cx: &LateContext<'_>, name: Symbol, items: &[NestedMetaItem], attr: &'_ Attribute) {
474 // Check for the feature
475 if !cx.tcx.sess.features_untracked().lint_reasons {
479 // Check if the reason is present
480 if let Some(item) = items.last().and_then(NestedMetaItem::meta_item)
481 && let MetaItemKind::NameValue(_) = &item.kind
482 && item.path == sym::reason
487 // Check if the attribute is in an external macro and therefore out of the developer's control
488 if in_external_macro(cx.sess(), attr.span) {
494 ALLOW_ATTRIBUTES_WITHOUT_REASON,
496 &format!("`{}` attribute without specifying a reason", name.as_str()),
498 "try adding a reason at the end with `, reason = \"..\"`",
502 fn is_relevant_item(cx: &LateContext<'_>, item: &Item<'_>) -> bool {
503 if let ItemKind::Fn(_, _, eid) = item.kind {
504 is_relevant_expr(cx, cx.tcx.typeck_body(eid), cx.tcx.hir().body(eid).value)
510 fn is_relevant_impl(cx: &LateContext<'_>, item: &ImplItem<'_>) -> bool {
512 ImplItemKind::Fn(_, eid) => is_relevant_expr(cx, cx.tcx.typeck_body(eid), cx.tcx.hir().body(eid).value),
517 fn is_relevant_trait(cx: &LateContext<'_>, item: &TraitItem<'_>) -> bool {
519 TraitItemKind::Fn(_, TraitFn::Required(_)) => true,
520 TraitItemKind::Fn(_, TraitFn::Provided(eid)) => {
521 is_relevant_expr(cx, cx.tcx.typeck_body(eid), cx.tcx.hir().body(eid).value)
527 fn is_relevant_block(cx: &LateContext<'_>, typeck_results: &ty::TypeckResults<'_>, block: &Block<'_>) -> bool {
528 block.stmts.first().map_or(
532 .map_or(false, |e| is_relevant_expr(cx, typeck_results, e)),
533 |stmt| match &stmt.kind {
534 StmtKind::Local(_) => true,
535 StmtKind::Expr(expr) | StmtKind::Semi(expr) => is_relevant_expr(cx, typeck_results, expr),
536 StmtKind::Item(_) => false,
541 fn is_relevant_expr(cx: &LateContext<'_>, typeck_results: &ty::TypeckResults<'_>, expr: &Expr<'_>) -> bool {
542 if macro_backtrace(expr.span).last().map_or(false, |macro_call| {
543 is_panic(cx, macro_call.def_id) || cx.tcx.item_name(macro_call.def_id) == sym::unreachable
548 ExprKind::Block(block, _) => is_relevant_block(cx, typeck_results, block),
549 ExprKind::Ret(Some(e)) => is_relevant_expr(cx, typeck_results, e),
550 ExprKind::Ret(None) | ExprKind::Break(_, None) => false,
555 fn check_attrs(cx: &LateContext<'_>, span: Span, name: Symbol, attrs: &[Attribute]) {
556 if span.from_expansion() {
561 if let Some(values) = attr.meta_item_list() {
562 if values.len() != 1 || !attr.has_name(sym::inline) {
565 if is_word(&values[0], sym::always) {
570 &format!("you have declared `#[inline(always)]` on `{name}`. This is usually a bad idea"),
577 fn check_semver(cx: &LateContext<'_>, span: Span, lit: &MetaItemLit) {
578 if let LitKind::Str(is, _) = lit.kind {
579 if Version::parse(is.as_str()).is_ok() {
587 "the since field must contain a semver-compliant version",
591 fn is_word(nmi: &NestedMetaItem, expected: Symbol) -> bool {
592 if let NestedMetaItem::MetaItem(mi) = &nmi {
593 mi.is_word() && mi.has_name(expected)
599 pub struct EarlyAttributes {
603 impl_lint_pass!(EarlyAttributes => [
605 MISMATCHED_TARGET_OS,
606 EMPTY_LINE_AFTER_OUTER_ATTR,
609 impl EarlyLintPass for EarlyAttributes {
610 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &rustc_ast::Item) {
611 check_empty_line_after_outer_attr(cx, item);
614 fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &Attribute) {
615 check_deprecated_cfg_attr(cx, attr, &self.msrv);
616 check_mismatched_target_os(cx, attr);
619 extract_msrv_attr!(EarlyContext);
622 fn check_empty_line_after_outer_attr(cx: &EarlyContext<'_>, item: &rustc_ast::Item) {
623 let mut iter = item.attrs.iter().peekable();
624 while let Some(attr) = iter.next() {
625 if matches!(attr.kind, AttrKind::Normal(..))
626 && attr.style == AttrStyle::Outer
627 && is_present_in_source(cx, attr.span)
629 let begin_of_attr_to_item = Span::new(attr.span.lo(), item.span.lo(), item.span.ctxt(), item.span.parent());
630 let end_of_attr_to_next_attr_or_item = Span::new(
632 iter.peek().map_or(item.span.lo(), |next_attr| next_attr.span.lo()),
637 if let Some(snippet) = snippet_opt(cx, end_of_attr_to_next_attr_or_item) {
638 let lines = snippet.split('\n').collect::<Vec<_>>();
639 let lines = without_block_comments(lines);
641 if lines.iter().filter(|l| l.trim().is_empty()).count() > 2 {
644 EMPTY_LINE_AFTER_OUTER_ATTR,
645 begin_of_attr_to_item,
646 "found an empty line after an outer attribute. \
647 Perhaps you forgot to add a `!` to make it an inner attribute?",
655 fn check_deprecated_cfg_attr(cx: &EarlyContext<'_>, attr: &Attribute, msrv: &Msrv) {
657 if msrv.meets(msrvs::TOOL_ATTRIBUTES);
659 if attr.has_name(sym::cfg_attr);
660 if let Some(items) = attr.meta_item_list();
662 // check for `rustfmt`
663 if let Some(feature_item) = items[0].meta_item();
664 if feature_item.has_name(sym::rustfmt);
665 // check for `rustfmt_skip` and `rustfmt::skip`
666 if let Some(skip_item) = &items[1].meta_item();
667 if skip_item.has_name(sym!(rustfmt_skip))
672 .expect("empty path in attribute")
676 // Only lint outer attributes, because custom inner attributes are unstable
677 // Tracking issue: https://github.com/rust-lang/rust/issues/54726
678 if attr.style == AttrStyle::Outer;
684 "`cfg_attr` is deprecated for rustfmt and got replaced by tool attributes",
686 "#[rustfmt::skip]".to_string(),
687 Applicability::MachineApplicable,
693 fn check_mismatched_target_os(cx: &EarlyContext<'_>, attr: &Attribute) {
694 fn find_os(name: &str) -> Option<&'static str> {
697 .chain(NON_UNIX_SYSTEMS.iter())
698 .find(|&&os| os == name)
702 fn is_unix(name: &str) -> bool {
703 UNIX_SYSTEMS.iter().any(|&os| os == name)
706 fn find_mismatched_target_os(items: &[NestedMetaItem]) -> Vec<(&str, Span)> {
707 let mut mismatched = Vec::new();
710 if let NestedMetaItem::MetaItem(meta) = item {
712 MetaItemKind::List(list) => {
713 mismatched.extend(find_mismatched_target_os(list));
715 MetaItemKind::Word => {
717 if let Some(ident) = meta.ident();
718 if let Some(os) = find_os(ident.name.as_str());
720 mismatched.push((os, ident.span));
724 MetaItemKind::NameValue(..) => {},
733 if attr.has_name(sym::cfg);
734 if let Some(list) = attr.meta_item_list();
735 let mismatched = find_mismatched_target_os(&list);
736 if !mismatched.is_empty();
738 let mess = "operating system used in target family position";
740 span_lint_and_then(cx, MISMATCHED_TARGET_OS, attr.span, mess, |diag| {
741 // Avoid showing the unix suggestion multiple times in case
742 // we have more than one mismatch for unix-like systems
743 let mut unix_suggested = false;
745 for (os, span) in mismatched {
746 let sugg = format!("target_os = \"{os}\"");
747 diag.span_suggestion(span, "try", sugg, Applicability::MaybeIncorrect);
749 if !unix_suggested && is_unix(os) {
750 diag.help("did you mean `unix`?");
751 unix_suggested = true;
759 fn is_lint_level(symbol: Symbol) -> bool {
760 matches!(symbol, sym::allow | sym::expect | sym::warn | sym::deny | sym::forbid)