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::msrvs;
5 use clippy_utils::source::{first_line_of_span, is_present_in_source, snippet_opt, without_block_comments};
6 use clippy_utils::{extract_msrv_attr, match_panic_def_id, meets_msrv};
7 use if_chain::if_chain;
8 use rustc_ast::{AttrKind, AttrStyle, Attribute, Lit, LitKind, MetaItemKind, 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, LintContext};
14 use rustc_middle::lint::in_external_macro;
16 use rustc_semver::RustcVersion;
17 use rustc_session::{declare_lint_pass, declare_tool_lint, impl_lint_pass};
18 use rustc_span::source_map::Span;
20 use rustc_span::symbol::{Symbol, SymbolStr};
23 static UNIX_SYSTEMS: &[&str] = &[
42 // NOTE: windows is excluded from the list because it's also a valid target family.
43 static NON_UNIX_SYSTEMS: &[&str] = &["hermit", "none", "wasi"];
45 declare_clippy_lint! {
47 /// Checks for items annotated with `#[inline(always)]`,
48 /// unless the annotated function is empty or simply panics.
50 /// ### Why is this bad?
51 /// While there are valid uses of this annotation (and once
52 /// you know when to use it, by all means `allow` this lint), it's a common
53 /// newbie-mistake to pepper one's code with it.
55 /// As a rule of thumb, before slapping `#[inline(always)]` on a function,
56 /// measure if that additional function call really affects your runtime profile
57 /// sufficiently to make up for the increase in compile time.
59 /// ### Known problems
60 /// False positives, big time. This lint is meant to be
61 /// deactivated by everyone doing serious performance work. This means having
62 /// done the measurement.
67 /// fn not_quite_hot_code(..) { ... }
69 #[clippy::version = "pre 1.29.0"]
72 "use of `#[inline(always)]`"
75 declare_clippy_lint! {
77 /// Checks for `extern crate` and `use` items annotated with
80 /// This lint permits `#[allow(unused_imports)]`, `#[allow(deprecated)]`,
81 /// `#[allow(unreachable_pub)]`, `#[allow(clippy::wildcard_imports)]` and
82 /// `#[allow(clippy::enum_glob_use)]` on `use` items and `#[allow(unused_imports)]` on
83 /// `extern crate` items with a `#[macro_use]` attribute.
85 /// ### Why is this bad?
86 /// Lint attributes have no effect on crate imports. Most
87 /// likely a `!` was forgotten.
92 /// #[deny(dead_code)]
94 /// #[forbid(dead_code)]
98 /// #[allow(unused_imports)]
100 /// #[allow(unused_imports)]
102 /// extern crate baz;
104 #[clippy::version = "pre 1.29.0"]
105 pub USELESS_ATTRIBUTE,
107 "use of lint attributes on `extern crate` items"
110 declare_clippy_lint! {
112 /// Checks for `#[deprecated]` annotations with a `since`
113 /// field that is not a valid semantic version.
115 /// ### Why is this bad?
116 /// For checking the version of the deprecation, it must be
117 /// a valid semver. Failing that, the contained information is useless.
121 /// #[deprecated(since = "forever")]
122 /// fn something_else() { /* ... */ }
124 #[clippy::version = "pre 1.29.0"]
125 pub DEPRECATED_SEMVER,
127 "use of `#[deprecated(since = \"x\")]` where x is not semver"
130 declare_clippy_lint! {
132 /// Checks for empty lines after outer attributes
134 /// ### Why is this bad?
135 /// Most likely the attribute was meant to be an inner attribute using a '!'.
136 /// If it was meant to be an outer attribute, then the following item
137 /// should not be separated by empty lines.
139 /// ### Known problems
140 /// Can cause false positives.
142 /// From the clippy side it's difficult to detect empty lines between an attributes and the
143 /// following item because empty lines and comments are not part of the AST. The parsing
144 /// currently works for basic cases but is not perfect.
148 /// // Good (as inner attribute)
149 /// #![allow(dead_code)]
151 /// fn this_is_fine() { }
154 /// #[allow(dead_code)]
156 /// fn not_quite_good_code() { }
158 /// // Good (as outer attribute)
159 /// #[allow(dead_code)]
160 /// fn this_is_fine_too() { }
162 #[clippy::version = "pre 1.29.0"]
163 pub EMPTY_LINE_AFTER_OUTER_ATTR,
165 "empty line after outer attribute"
168 declare_clippy_lint! {
170 /// Checks for `warn`/`deny`/`forbid` attributes targeting the whole clippy::restriction category.
172 /// ### Why is this bad?
173 /// Restriction lints sometimes are in contrast with other lints or even go against idiomatic rust.
174 /// These lints should only be enabled on a lint-by-lint basis and with careful consideration.
179 /// #![deny(clippy::restriction)]
184 /// #![deny(clippy::as_conversions)]
186 #[clippy::version = "1.47.0"]
187 pub BLANKET_CLIPPY_RESTRICTION_LINTS,
189 "enabling the complete restriction group"
192 declare_clippy_lint! {
194 /// Checks for `#[cfg_attr(rustfmt, rustfmt_skip)]` and suggests to replace it
195 /// with `#[rustfmt::skip]`.
197 /// ### Why is this bad?
198 /// Since tool_attributes ([rust-lang/rust#44690](https://github.com/rust-lang/rust/issues/44690))
199 /// are stable now, they should be used instead of the old `cfg_attr(rustfmt)` attributes.
201 /// ### Known problems
202 /// This lint doesn't detect crate level inner attributes, because they get
203 /// processed before the PreExpansionPass lints get executed. See
204 /// [#3123](https://github.com/rust-lang/rust-clippy/pull/3123#issuecomment-422321765)
209 /// #[cfg_attr(rustfmt, rustfmt_skip)]
218 #[clippy::version = "1.32.0"]
219 pub DEPRECATED_CFG_ATTR,
221 "usage of `cfg_attr(rustfmt)` instead of tool attributes"
224 declare_clippy_lint! {
226 /// Checks for cfg attributes having operating systems used in target family position.
228 /// ### Why is this bad?
229 /// The configuration option will not be recognised and the related item will not be included
230 /// by the conditional compilation engine.
236 /// fn conditional() { }
241 /// #[cfg(target_os = "linux")]
242 /// fn conditional() { }
248 /// fn conditional() { }
250 /// Check the [Rust Reference](https://doc.rust-lang.org/reference/conditional-compilation.html#target_os) for more details.
251 #[clippy::version = "1.45.0"]
252 pub MISMATCHED_TARGET_OS,
254 "usage of `cfg(operating_system)` instead of `cfg(target_os = \"operating_system\")`"
257 declare_lint_pass!(Attributes => [
261 BLANKET_CLIPPY_RESTRICTION_LINTS,
264 impl<'tcx> LateLintPass<'tcx> for Attributes {
265 fn check_attribute(&mut self, cx: &LateContext<'tcx>, attr: &'tcx Attribute) {
266 if let Some(items) = &attr.meta_item_list() {
267 if let Some(ident) = attr.ident() {
268 if is_lint_level(ident.name) {
269 check_clippy_lint_names(cx, ident.name, items);
271 if items.is_empty() || !attr.has_name(sym::deprecated) {
276 if let NestedMetaItem::MetaItem(mi) = &item;
277 if let MetaItemKind::NameValue(lit) = &mi.kind;
278 if mi.has_name(sym::since);
280 check_semver(cx, item.span(), lit);
288 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
289 let attrs = cx.tcx.hir().attrs(item.hir_id());
290 if is_relevant_item(cx, item) {
291 check_attrs(cx, item.span, item.ident.name, attrs);
294 ItemKind::ExternCrate(..) | ItemKind::Use(..) => {
295 let skip_unused_imports = attrs.iter().any(|attr| attr.has_name(sym::macro_use));
298 if in_external_macro(cx.sess(), attr.span) {
301 if let Some(lint_list) = &attr.meta_item_list() {
302 if attr.ident().map_or(false, |ident| is_lint_level(ident.name)) {
303 // permit `unused_imports`, `deprecated`, `unreachable_pub`,
304 // `clippy::wildcard_imports`, and `clippy::enum_glob_use` for `use` items
305 // and `unused_imports` for `extern crate` items with `macro_use`
306 for lint in lint_list {
308 ItemKind::Use(..) => {
309 if is_word(lint, sym!(unused_imports))
310 || is_word(lint, sym::deprecated)
311 || is_word(lint, sym!(unreachable_pub))
312 || is_word(lint, sym!(unused))
313 || extract_clippy_lint(lint).map_or(false, |s| s == "wildcard_imports")
314 || extract_clippy_lint(lint).map_or(false, |s| s == "enum_glob_use")
319 ItemKind::ExternCrate(..) => {
320 if is_word(lint, sym!(unused_imports)) && skip_unused_imports {
323 if is_word(lint, sym!(unused_extern_crates)) {
330 let line_span = first_line_of_span(cx, attr.span);
332 if let Some(mut sugg) = snippet_opt(cx, line_span) {
333 if sugg.contains("#[") {
338 "useless lint attribute",
340 sugg = sugg.replacen("#[", "#![", 1);
341 diag.span_suggestion(
343 "if you just forgot a `!`, use",
345 Applicability::MaybeIncorrect,
359 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx ImplItem<'_>) {
360 if is_relevant_impl(cx, item) {
361 check_attrs(cx, item.span, item.ident.name, cx.tcx.hir().attrs(item.hir_id()));
365 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
366 if is_relevant_trait(cx, item) {
367 check_attrs(cx, item.span, item.ident.name, cx.tcx.hir().attrs(item.hir_id()));
372 /// Returns the lint name if it is clippy lint.
373 fn extract_clippy_lint(lint: &NestedMetaItem) -> Option<SymbolStr> {
375 if let Some(meta_item) = lint.meta_item();
376 if meta_item.path.segments.len() > 1;
377 if let tool_name = meta_item.path.segments[0].ident;
378 if tool_name.name == sym::clippy;
380 let lint_name = meta_item.path.segments.last().unwrap().ident.name;
381 return Some(lint_name.as_str());
387 fn check_clippy_lint_names(cx: &LateContext<'_>, name: Symbol, items: &[NestedMetaItem]) {
389 if let Some(lint_name) = extract_clippy_lint(lint) {
390 if lint_name == "restriction" && name != sym::allow {
393 BLANKET_CLIPPY_RESTRICTION_LINTS,
395 "restriction lints are not meant to be all enabled",
397 "try enabling only the lints you really need",
404 fn is_relevant_item(cx: &LateContext<'_>, item: &Item<'_>) -> bool {
405 if let ItemKind::Fn(_, _, eid) = item.kind {
406 is_relevant_expr(cx, cx.tcx.typeck_body(eid), &cx.tcx.hir().body(eid).value)
412 fn is_relevant_impl(cx: &LateContext<'_>, item: &ImplItem<'_>) -> bool {
414 ImplItemKind::Fn(_, eid) => is_relevant_expr(cx, cx.tcx.typeck_body(eid), &cx.tcx.hir().body(eid).value),
419 fn is_relevant_trait(cx: &LateContext<'_>, item: &TraitItem<'_>) -> bool {
421 TraitItemKind::Fn(_, TraitFn::Required(_)) => true,
422 TraitItemKind::Fn(_, TraitFn::Provided(eid)) => {
423 is_relevant_expr(cx, cx.tcx.typeck_body(eid), &cx.tcx.hir().body(eid).value)
429 fn is_relevant_block(cx: &LateContext<'_>, typeck_results: &ty::TypeckResults<'_>, block: &Block<'_>) -> bool {
430 block.stmts.first().map_or(
434 .map_or(false, |e| is_relevant_expr(cx, typeck_results, e)),
435 |stmt| match &stmt.kind {
436 StmtKind::Local(_) => true,
437 StmtKind::Expr(expr) | StmtKind::Semi(expr) => is_relevant_expr(cx, typeck_results, expr),
438 StmtKind::Item(_) => false,
443 fn is_relevant_expr(cx: &LateContext<'_>, typeck_results: &ty::TypeckResults<'_>, expr: &Expr<'_>) -> bool {
445 ExprKind::Block(block, _) => is_relevant_block(cx, typeck_results, block),
446 ExprKind::Ret(Some(e)) => is_relevant_expr(cx, typeck_results, e),
447 ExprKind::Ret(None) | ExprKind::Break(_, None) => false,
448 ExprKind::Call(path_expr, _) => {
449 if let ExprKind::Path(qpath) = &path_expr.kind {
451 .qpath_res(qpath, path_expr.hir_id)
453 .map_or(true, |fun_id| !match_panic_def_id(cx, fun_id))
462 fn check_attrs(cx: &LateContext<'_>, span: Span, name: Symbol, attrs: &[Attribute]) {
463 if span.from_expansion() {
468 if let Some(values) = attr.meta_item_list() {
469 if values.len() != 1 || !attr.has_name(sym::inline) {
472 if is_word(&values[0], sym::always) {
478 "you have declared `#[inline(always)]` on `{}`. This is usually a bad idea",
487 fn check_semver(cx: &LateContext<'_>, span: Span, lit: &Lit) {
488 if let LitKind::Str(is, _) = lit.kind {
489 if Version::parse(&is.as_str()).is_ok() {
497 "the since field must contain a semver-compliant version",
501 fn is_word(nmi: &NestedMetaItem, expected: Symbol) -> bool {
502 if let NestedMetaItem::MetaItem(mi) = &nmi {
503 mi.is_word() && mi.has_name(expected)
509 pub struct EarlyAttributes {
510 pub msrv: Option<RustcVersion>,
513 impl_lint_pass!(EarlyAttributes => [
515 MISMATCHED_TARGET_OS,
516 EMPTY_LINE_AFTER_OUTER_ATTR,
519 impl EarlyLintPass for EarlyAttributes {
520 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &rustc_ast::Item) {
521 check_empty_line_after_outer_attr(cx, item);
524 fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &Attribute) {
525 check_deprecated_cfg_attr(cx, attr, self.msrv);
526 check_mismatched_target_os(cx, attr);
529 extract_msrv_attr!(EarlyContext);
532 fn check_empty_line_after_outer_attr(cx: &EarlyContext<'_>, item: &rustc_ast::Item) {
533 for attr in &item.attrs {
534 let attr_item = if let AttrKind::Normal(ref attr, _) = attr.kind {
540 if attr.style == AttrStyle::Outer {
541 if attr_item.args.inner_tokens().is_empty() || !is_present_in_source(cx, attr.span) {
545 let begin_of_attr_to_item = Span::new(attr.span.lo(), item.span.lo(), item.span.ctxt(), item.span.parent());
546 let end_of_attr_to_item = Span::new(attr.span.hi(), item.span.lo(), item.span.ctxt(), item.span.parent());
548 if let Some(snippet) = snippet_opt(cx, end_of_attr_to_item) {
549 let lines = snippet.split('\n').collect::<Vec<_>>();
550 let lines = without_block_comments(lines);
552 if lines.iter().filter(|l| l.trim().is_empty()).count() > 2 {
555 EMPTY_LINE_AFTER_OUTER_ATTR,
556 begin_of_attr_to_item,
557 "found an empty line after an outer attribute. \
558 Perhaps you forgot to add a `!` to make it an inner attribute?",
566 fn check_deprecated_cfg_attr(cx: &EarlyContext<'_>, attr: &Attribute, msrv: Option<RustcVersion>) {
568 if meets_msrv(msrv.as_ref(), &msrvs::TOOL_ATTRIBUTES);
570 if attr.has_name(sym::cfg_attr);
571 if let Some(items) = attr.meta_item_list();
573 // check for `rustfmt`
574 if let Some(feature_item) = items[0].meta_item();
575 if feature_item.has_name(sym::rustfmt);
576 // check for `rustfmt_skip` and `rustfmt::skip`
577 if let Some(skip_item) = &items[1].meta_item();
578 if skip_item.has_name(sym!(rustfmt_skip)) ||
579 skip_item.path.segments.last().expect("empty path in attribute").ident.name == sym::skip;
580 // Only lint outer attributes, because custom inner attributes are unstable
581 // Tracking issue: https://github.com/rust-lang/rust/issues/54726
582 if attr.style == AttrStyle::Outer;
588 "`cfg_attr` is deprecated for rustfmt and got replaced by tool attributes",
590 "#[rustfmt::skip]".to_string(),
591 Applicability::MachineApplicable,
597 fn check_mismatched_target_os(cx: &EarlyContext<'_>, attr: &Attribute) {
598 fn find_os(name: &str) -> Option<&'static str> {
601 .chain(NON_UNIX_SYSTEMS.iter())
602 .find(|&&os| os == name)
606 fn is_unix(name: &str) -> bool {
607 UNIX_SYSTEMS.iter().any(|&os| os == name)
610 fn find_mismatched_target_os(items: &[NestedMetaItem]) -> Vec<(&str, Span)> {
611 let mut mismatched = Vec::new();
614 if let NestedMetaItem::MetaItem(meta) = item {
616 MetaItemKind::List(list) => {
617 mismatched.extend(find_mismatched_target_os(list));
619 MetaItemKind::Word => {
621 if let Some(ident) = meta.ident();
622 if let Some(os) = find_os(&*ident.name.as_str());
624 mismatched.push((os, ident.span));
628 MetaItemKind::NameValue(..) => {},
637 if attr.has_name(sym::cfg);
638 if let Some(list) = attr.meta_item_list();
639 let mismatched = find_mismatched_target_os(&list);
640 if !mismatched.is_empty();
642 let mess = "operating system used in target family position";
644 span_lint_and_then(cx, MISMATCHED_TARGET_OS, attr.span, mess, |diag| {
645 // Avoid showing the unix suggestion multiple times in case
646 // we have more than one mismatch for unix-like systems
647 let mut unix_suggested = false;
649 for (os, span) in mismatched {
650 let sugg = format!("target_os = \"{}\"", os);
651 diag.span_suggestion(span, "try", sugg, Applicability::MaybeIncorrect);
653 if !unix_suggested && is_unix(os) {
654 diag.help("did you mean `unix`?");
655 unix_suggested = true;
663 fn is_lint_level(symbol: Symbol) -> bool {
664 matches!(symbol, sym::allow | sym::warn | sym::deny | sym::forbid)