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 `#[allow(unused_imports)]`, `#[allow(deprecated)]`,
82 /// `#[allow(unreachable_pub)]`, `#[allow(clippy::wildcard_imports)]` and
83 /// `#[allow(clippy::enum_glob_use)]` on `use` items and `#[allow(unused_imports)]` on
84 /// `extern crate` items with a `#[macro_use]` attribute.
86 /// ### Why is this bad?
87 /// Lint attributes have no effect on crate imports. Most
88 /// likely a `!` was forgotten.
93 /// #[deny(dead_code)]
95 /// #[forbid(dead_code)]
99 /// #[allow(unused_imports)]
101 /// #[allow(unused_imports)]
103 /// extern crate baz;
105 #[clippy::version = "pre 1.29.0"]
106 pub USELESS_ATTRIBUTE,
108 "use of lint attributes on `extern crate` items"
111 declare_clippy_lint! {
113 /// Checks for `#[deprecated]` annotations with a `since`
114 /// field that is not a valid semantic version.
116 /// ### Why is this bad?
117 /// For checking the version of the deprecation, it must be
118 /// a valid semver. Failing that, the contained information is useless.
122 /// #[deprecated(since = "forever")]
123 /// fn something_else() { /* ... */ }
125 #[clippy::version = "pre 1.29.0"]
126 pub DEPRECATED_SEMVER,
128 "use of `#[deprecated(since = \"x\")]` where x is not semver"
131 declare_clippy_lint! {
133 /// Checks for empty lines after outer attributes
135 /// ### Why is this bad?
136 /// Most likely the attribute was meant to be an inner attribute using a '!'.
137 /// If it was meant to be an outer attribute, then the following item
138 /// should not be separated by empty lines.
140 /// ### Known problems
141 /// Can cause false positives.
143 /// From the clippy side it's difficult to detect empty lines between an attributes and the
144 /// following item because empty lines and comments are not part of the AST. The parsing
145 /// currently works for basic cases but is not perfect.
149 /// // Good (as inner attribute)
150 /// #![allow(dead_code)]
152 /// fn this_is_fine() { }
155 /// #[allow(dead_code)]
157 /// fn not_quite_good_code() { }
159 /// // Good (as outer attribute)
160 /// #[allow(dead_code)]
161 /// fn this_is_fine_too() { }
163 #[clippy::version = "pre 1.29.0"]
164 pub EMPTY_LINE_AFTER_OUTER_ATTR,
166 "empty line after outer attribute"
169 declare_clippy_lint! {
171 /// Checks for `warn`/`deny`/`forbid` attributes targeting the whole clippy::restriction category.
173 /// ### Why is this bad?
174 /// Restriction lints sometimes are in contrast with other lints or even go against idiomatic rust.
175 /// These lints should only be enabled on a lint-by-lint basis and with careful consideration.
180 /// #![deny(clippy::restriction)]
185 /// #![deny(clippy::as_conversions)]
187 #[clippy::version = "1.47.0"]
188 pub BLANKET_CLIPPY_RESTRICTION_LINTS,
190 "enabling the complete restriction group"
193 declare_clippy_lint! {
195 /// Checks for `#[cfg_attr(rustfmt, rustfmt_skip)]` and suggests to replace it
196 /// with `#[rustfmt::skip]`.
198 /// ### Why is this bad?
199 /// Since tool_attributes ([rust-lang/rust#44690](https://github.com/rust-lang/rust/issues/44690))
200 /// are stable now, they should be used instead of the old `cfg_attr(rustfmt)` attributes.
202 /// ### Known problems
203 /// This lint doesn't detect crate level inner attributes, because they get
204 /// processed before the PreExpansionPass lints get executed. See
205 /// [#3123](https://github.com/rust-lang/rust-clippy/pull/3123#issuecomment-422321765)
210 /// #[cfg_attr(rustfmt, rustfmt_skip)]
219 #[clippy::version = "1.32.0"]
220 pub DEPRECATED_CFG_ATTR,
222 "usage of `cfg_attr(rustfmt)` instead of tool attributes"
225 declare_clippy_lint! {
227 /// Checks for cfg attributes having operating systems used in target family position.
229 /// ### Why is this bad?
230 /// The configuration option will not be recognised and the related item will not be included
231 /// by the conditional compilation engine.
237 /// fn conditional() { }
242 /// #[cfg(target_os = "linux")]
243 /// fn conditional() { }
249 /// fn conditional() { }
251 /// Check the [Rust Reference](https://doc.rust-lang.org/reference/conditional-compilation.html#target_os) for more details.
252 #[clippy::version = "1.45.0"]
253 pub MISMATCHED_TARGET_OS,
255 "usage of `cfg(operating_system)` instead of `cfg(target_os = \"operating_system\")`"
258 declare_clippy_lint! {
260 /// Checks for attributes that allow lints without a reason.
262 /// (This requires the `lint_reasons` feature)
264 /// ### Why is this bad?
265 /// Allowing a lint should always have a reason. This reason should be documented to
266 /// ensure that others understand the reasoning
271 /// #![feature(lint_reasons)]
273 /// #![allow(clippy::some_lint)]
278 /// #![feature(lint_reasons)]
280 /// #![allow(clippy::some_lint, reason = "False positive rust-lang/rust-clippy#1002020")]
282 #[clippy::version = "1.61.0"]
283 pub ALLOW_ATTRIBUTES_WITHOUT_REASON,
285 "ensures that all `allow` and `expect` attributes have a reason"
288 declare_lint_pass!(Attributes => [
289 ALLOW_ATTRIBUTES_WITHOUT_REASON,
293 BLANKET_CLIPPY_RESTRICTION_LINTS,
296 impl<'tcx> LateLintPass<'tcx> for Attributes {
297 fn check_attribute(&mut self, cx: &LateContext<'tcx>, attr: &'tcx Attribute) {
298 if let Some(items) = &attr.meta_item_list() {
299 if let Some(ident) = attr.ident() {
300 if is_lint_level(ident.name) {
301 check_clippy_lint_names(cx, ident.name, items);
303 if matches!(ident.name, sym::allow | sym::expect) {
304 check_lint_reason(cx, ident.name, items, attr);
306 if items.is_empty() || !attr.has_name(sym::deprecated) {
311 if let NestedMetaItem::MetaItem(mi) = &item;
312 if let MetaItemKind::NameValue(lit) = &mi.kind;
313 if mi.has_name(sym::since);
315 check_semver(cx, item.span(), lit);
323 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
324 let attrs = cx.tcx.hir().attrs(item.hir_id());
325 if is_relevant_item(cx, item) {
326 check_attrs(cx, item.span, item.ident.name, attrs);
329 ItemKind::ExternCrate(..) | ItemKind::Use(..) => {
330 let skip_unused_imports = attrs.iter().any(|attr| attr.has_name(sym::macro_use));
333 if in_external_macro(cx.sess(), attr.span) {
336 if let Some(lint_list) = &attr.meta_item_list() {
337 if attr.ident().map_or(false, |ident| is_lint_level(ident.name)) {
338 // permit `unused_imports`, `deprecated`, `unreachable_pub`,
339 // `clippy::wildcard_imports`, and `clippy::enum_glob_use` for `use` items
340 // and `unused_imports` for `extern crate` items with `macro_use`
341 for lint in lint_list {
343 ItemKind::Use(..) => {
344 if is_word(lint, sym!(unused_imports))
345 || is_word(lint, sym::deprecated)
346 || is_word(lint, sym!(unreachable_pub))
347 || is_word(lint, sym!(unused))
348 || extract_clippy_lint(lint)
349 .map_or(false, |s| s.as_str() == "wildcard_imports")
350 || extract_clippy_lint(lint)
351 .map_or(false, |s| s.as_str() == "enum_glob_use")
356 ItemKind::ExternCrate(..) => {
357 if is_word(lint, sym!(unused_imports)) && skip_unused_imports {
360 if is_word(lint, sym!(unused_extern_crates)) {
367 let line_span = first_line_of_span(cx, attr.span);
369 if let Some(mut sugg) = snippet_opt(cx, line_span) {
370 if sugg.contains("#[") {
375 "useless lint attribute",
377 sugg = sugg.replacen("#[", "#![", 1);
378 diag.span_suggestion(
380 "if you just forgot a `!`, use",
382 Applicability::MaybeIncorrect,
396 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx ImplItem<'_>) {
397 if is_relevant_impl(cx, item) {
398 check_attrs(cx, item.span, item.ident.name, cx.tcx.hir().attrs(item.hir_id()));
402 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
403 if is_relevant_trait(cx, item) {
404 check_attrs(cx, item.span, item.ident.name, cx.tcx.hir().attrs(item.hir_id()));
409 /// Returns the lint name if it is clippy lint.
410 fn extract_clippy_lint(lint: &NestedMetaItem) -> Option<Symbol> {
412 if let Some(meta_item) = lint.meta_item();
413 if meta_item.path.segments.len() > 1;
414 if let tool_name = meta_item.path.segments[0].ident;
415 if tool_name.name == sym::clippy;
417 let lint_name = meta_item.path.segments.last().unwrap().ident.name;
418 return Some(lint_name);
424 fn check_clippy_lint_names(cx: &LateContext<'_>, name: Symbol, items: &[NestedMetaItem]) {
426 if let Some(lint_name) = extract_clippy_lint(lint) {
427 if lint_name.as_str() == "restriction" && name != sym::allow {
430 BLANKET_CLIPPY_RESTRICTION_LINTS,
432 "restriction lints are not meant to be all enabled",
434 "try enabling only the lints you really need",
441 fn check_lint_reason(cx: &LateContext<'_>, name: Symbol, items: &[NestedMetaItem], attr: &'_ Attribute) {
442 // Check for the feature
443 if !cx.tcx.sess.features_untracked().lint_reasons {
447 // Check if the reason is present
448 if let Some(item) = items.last().and_then(NestedMetaItem::meta_item)
449 && let MetaItemKind::NameValue(_) = &item.kind
450 && item.path == sym::reason
457 ALLOW_ATTRIBUTES_WITHOUT_REASON,
459 &format!("`{}` attribute without specifying a reason", name.as_str()),
461 "try adding a reason at the end with `, reason = \"..\"`",
465 fn is_relevant_item(cx: &LateContext<'_>, item: &Item<'_>) -> bool {
466 if let ItemKind::Fn(_, _, eid) = item.kind {
467 is_relevant_expr(cx, cx.tcx.typeck_body(eid), &cx.tcx.hir().body(eid).value)
473 fn is_relevant_impl(cx: &LateContext<'_>, item: &ImplItem<'_>) -> bool {
475 ImplItemKind::Fn(_, eid) => is_relevant_expr(cx, cx.tcx.typeck_body(eid), &cx.tcx.hir().body(eid).value),
480 fn is_relevant_trait(cx: &LateContext<'_>, item: &TraitItem<'_>) -> bool {
482 TraitItemKind::Fn(_, TraitFn::Required(_)) => true,
483 TraitItemKind::Fn(_, TraitFn::Provided(eid)) => {
484 is_relevant_expr(cx, cx.tcx.typeck_body(eid), &cx.tcx.hir().body(eid).value)
490 fn is_relevant_block(cx: &LateContext<'_>, typeck_results: &ty::TypeckResults<'_>, block: &Block<'_>) -> bool {
491 block.stmts.first().map_or(
495 .map_or(false, |e| is_relevant_expr(cx, typeck_results, e)),
496 |stmt| match &stmt.kind {
497 StmtKind::Local(_) => true,
498 StmtKind::Expr(expr) | StmtKind::Semi(expr) => is_relevant_expr(cx, typeck_results, expr),
499 StmtKind::Item(_) => false,
504 fn is_relevant_expr(cx: &LateContext<'_>, typeck_results: &ty::TypeckResults<'_>, expr: &Expr<'_>) -> bool {
505 if macro_backtrace(expr.span).last().map_or(false, |macro_call| {
506 is_panic(cx, macro_call.def_id) || cx.tcx.item_name(macro_call.def_id) == sym::unreachable
511 ExprKind::Block(block, _) => is_relevant_block(cx, typeck_results, block),
512 ExprKind::Ret(Some(e)) => is_relevant_expr(cx, typeck_results, e),
513 ExprKind::Ret(None) | ExprKind::Break(_, None) => false,
518 fn check_attrs(cx: &LateContext<'_>, span: Span, name: Symbol, attrs: &[Attribute]) {
519 if span.from_expansion() {
524 if let Some(values) = attr.meta_item_list() {
525 if values.len() != 1 || !attr.has_name(sym::inline) {
528 if is_word(&values[0], sym::always) {
534 "you have declared `#[inline(always)]` on `{}`. This is usually a bad idea",
543 fn check_semver(cx: &LateContext<'_>, span: Span, lit: &Lit) {
544 if let LitKind::Str(is, _) = lit.kind {
545 if Version::parse(is.as_str()).is_ok() {
553 "the since field must contain a semver-compliant version",
557 fn is_word(nmi: &NestedMetaItem, expected: Symbol) -> bool {
558 if let NestedMetaItem::MetaItem(mi) = &nmi {
559 mi.is_word() && mi.has_name(expected)
565 pub struct EarlyAttributes {
566 pub msrv: Option<RustcVersion>,
569 impl_lint_pass!(EarlyAttributes => [
571 MISMATCHED_TARGET_OS,
572 EMPTY_LINE_AFTER_OUTER_ATTR,
575 impl EarlyLintPass for EarlyAttributes {
576 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &rustc_ast::Item) {
577 check_empty_line_after_outer_attr(cx, item);
580 fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &Attribute) {
581 check_deprecated_cfg_attr(cx, attr, self.msrv);
582 check_mismatched_target_os(cx, attr);
585 extract_msrv_attr!(EarlyContext);
588 fn check_empty_line_after_outer_attr(cx: &EarlyContext<'_>, item: &rustc_ast::Item) {
589 for attr in &item.attrs {
590 let attr_item = if let AttrKind::Normal(ref attr, _) = attr.kind {
596 if attr.style == AttrStyle::Outer {
597 if attr_item.args.inner_tokens().is_empty() || !is_present_in_source(cx, attr.span) {
601 let begin_of_attr_to_item = Span::new(attr.span.lo(), item.span.lo(), item.span.ctxt(), item.span.parent());
602 let end_of_attr_to_item = Span::new(attr.span.hi(), item.span.lo(), item.span.ctxt(), item.span.parent());
604 if let Some(snippet) = snippet_opt(cx, end_of_attr_to_item) {
605 let lines = snippet.split('\n').collect::<Vec<_>>();
606 let lines = without_block_comments(lines);
608 if lines.iter().filter(|l| l.trim().is_empty()).count() > 2 {
611 EMPTY_LINE_AFTER_OUTER_ATTR,
612 begin_of_attr_to_item,
613 "found an empty line after an outer attribute. \
614 Perhaps you forgot to add a `!` to make it an inner attribute?",
622 fn check_deprecated_cfg_attr(cx: &EarlyContext<'_>, attr: &Attribute, msrv: Option<RustcVersion>) {
624 if meets_msrv(msrv.as_ref(), &msrvs::TOOL_ATTRIBUTES);
626 if attr.has_name(sym::cfg_attr);
627 if let Some(items) = attr.meta_item_list();
629 // check for `rustfmt`
630 if let Some(feature_item) = items[0].meta_item();
631 if feature_item.has_name(sym::rustfmt);
632 // check for `rustfmt_skip` and `rustfmt::skip`
633 if let Some(skip_item) = &items[1].meta_item();
634 if skip_item.has_name(sym!(rustfmt_skip)) ||
635 skip_item.path.segments.last().expect("empty path in attribute").ident.name == sym::skip;
636 // Only lint outer attributes, because custom inner attributes are unstable
637 // Tracking issue: https://github.com/rust-lang/rust/issues/54726
638 if attr.style == AttrStyle::Outer;
644 "`cfg_attr` is deprecated for rustfmt and got replaced by tool attributes",
646 "#[rustfmt::skip]".to_string(),
647 Applicability::MachineApplicable,
653 fn check_mismatched_target_os(cx: &EarlyContext<'_>, attr: &Attribute) {
654 fn find_os(name: &str) -> Option<&'static str> {
657 .chain(NON_UNIX_SYSTEMS.iter())
658 .find(|&&os| os == name)
662 fn is_unix(name: &str) -> bool {
663 UNIX_SYSTEMS.iter().any(|&os| os == name)
666 fn find_mismatched_target_os(items: &[NestedMetaItem]) -> Vec<(&str, Span)> {
667 let mut mismatched = Vec::new();
670 if let NestedMetaItem::MetaItem(meta) = item {
672 MetaItemKind::List(list) => {
673 mismatched.extend(find_mismatched_target_os(list));
675 MetaItemKind::Word => {
677 if let Some(ident) = meta.ident();
678 if let Some(os) = find_os(ident.name.as_str());
680 mismatched.push((os, ident.span));
684 MetaItemKind::NameValue(..) => {},
693 if attr.has_name(sym::cfg);
694 if let Some(list) = attr.meta_item_list();
695 let mismatched = find_mismatched_target_os(&list);
696 if !mismatched.is_empty();
698 let mess = "operating system used in target family position";
700 span_lint_and_then(cx, MISMATCHED_TARGET_OS, attr.span, mess, |diag| {
701 // Avoid showing the unix suggestion multiple times in case
702 // we have more than one mismatch for unix-like systems
703 let mut unix_suggested = false;
705 for (os, span) in mismatched {
706 let sugg = format!("target_os = \"{}\"", os);
707 diag.span_suggestion(span, "try", sugg, Applicability::MaybeIncorrect);
709 if !unix_suggested && is_unix(os) {
710 diag.help("did you mean `unix`?");
711 unix_suggested = true;
719 fn is_lint_level(symbol: Symbol) -> bool {
720 matches!(symbol, sym::allow | sym::expect | sym::warn | sym::deny | sym::forbid)