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::match_panic_def_id;
5 use clippy_utils::source::{first_line_of_span, is_present_in_source, snippet_opt, without_block_comments};
6 use if_chain::if_chain;
7 use rustc_ast::{AttrKind, AttrStyle, Attribute, Lit, LitKind, MetaItemKind, NestedMetaItem};
8 use rustc_errors::Applicability;
10 Block, Expr, ExprKind, ImplItem, ImplItemKind, Item, ItemKind, StmtKind, TraitFn, TraitItem, TraitItemKind,
12 use rustc_lint::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
13 use rustc_middle::lint::in_external_macro;
15 use rustc_session::{declare_lint_pass, declare_tool_lint};
16 use rustc_span::source_map::Span;
18 use rustc_span::symbol::{Symbol, SymbolStr};
21 static UNIX_SYSTEMS: &[&str] = &[
40 // NOTE: windows is excluded from the list because it's also a valid target family.
41 static NON_UNIX_SYSTEMS: &[&str] = &["hermit", "none", "wasi"];
43 declare_clippy_lint! {
44 /// **What it does:** Checks for items annotated with `#[inline(always)]`,
45 /// unless the annotated function is empty or simply panics.
47 /// **Why is this bad?** While there are valid uses of this annotation (and once
48 /// you know when to use it, by all means `allow` this lint), it's a common
49 /// newbie-mistake to pepper one's code with it.
51 /// As a rule of thumb, before slapping `#[inline(always)]` on a function,
52 /// measure if that additional function call really affects your runtime profile
53 /// sufficiently to make up for the increase in compile time.
55 /// **Known problems:** False positives, big time. This lint is meant to be
56 /// deactivated by everyone doing serious performance work. This means having
57 /// done the measurement.
62 /// fn not_quite_hot_code(..) { ... }
66 "use of `#[inline(always)]`"
69 declare_clippy_lint! {
70 /// **What it does:** Checks for `extern crate` and `use` items annotated with
73 /// This lint permits `#[allow(unused_imports)]`, `#[allow(deprecated)]`,
74 /// `#[allow(unreachable_pub)]`, `#[allow(clippy::wildcard_imports)]` and
75 /// `#[allow(clippy::enum_glob_use)]` on `use` items and `#[allow(unused_imports)]` on
76 /// `extern crate` items with a `#[macro_use]` attribute.
78 /// **Why is this bad?** Lint attributes have no effect on crate imports. Most
79 /// likely a `!` was forgotten.
81 /// **Known problems:** None.
86 /// #[deny(dead_code)]
88 /// #[forbid(dead_code)]
92 /// #[allow(unused_imports)]
94 /// #[allow(unused_imports)]
98 pub USELESS_ATTRIBUTE,
100 "use of lint attributes on `extern crate` items"
103 declare_clippy_lint! {
104 /// **What it does:** Checks for `#[deprecated]` annotations with a `since`
105 /// field that is not a valid semantic version.
107 /// **Why is this bad?** For checking the version of the deprecation, it must be
108 /// a valid semver. Failing that, the contained information is useless.
110 /// **Known problems:** None.
114 /// #[deprecated(since = "forever")]
115 /// fn something_else() { /* ... */ }
117 pub DEPRECATED_SEMVER,
119 "use of `#[deprecated(since = \"x\")]` where x is not semver"
122 declare_clippy_lint! {
123 /// **What it does:** Checks for empty lines after outer attributes
125 /// **Why is this bad?**
126 /// Most likely the attribute was meant to be an inner attribute using a '!'.
127 /// If it was meant to be an outer attribute, then the following item
128 /// should not be separated by empty lines.
130 /// **Known problems:** Can cause false positives.
132 /// From the clippy side it's difficult to detect empty lines between an attributes and the
133 /// following item because empty lines and comments are not part of the AST. The parsing
134 /// currently works for basic cases but is not perfect.
138 /// // Good (as inner attribute)
139 /// #![allow(dead_code)]
141 /// fn this_is_fine() { }
144 /// #[allow(dead_code)]
146 /// fn not_quite_good_code() { }
148 /// // Good (as outer attribute)
149 /// #[allow(dead_code)]
150 /// fn this_is_fine_too() { }
152 pub EMPTY_LINE_AFTER_OUTER_ATTR,
154 "empty line after outer attribute"
157 declare_clippy_lint! {
158 /// **What it does:** Checks for `warn`/`deny`/`forbid` attributes targeting the whole clippy::restriction category.
160 /// **Why is this bad?** Restriction lints sometimes are in contrast with other lints or even go against idiomatic rust.
161 /// These lints should only be enabled on a lint-by-lint basis and with careful consideration.
163 /// **Known problems:** None.
168 /// #![deny(clippy::restriction)]
173 /// #![deny(clippy::as_conversions)]
175 pub BLANKET_CLIPPY_RESTRICTION_LINTS,
177 "enabling the complete restriction group"
180 declare_clippy_lint! {
181 /// **What it does:** Checks for `#[cfg_attr(rustfmt, rustfmt_skip)]` and suggests to replace it
182 /// with `#[rustfmt::skip]`.
184 /// **Why is this bad?** Since tool_attributes ([rust-lang/rust#44690](https://github.com/rust-lang/rust/issues/44690))
185 /// are stable now, they should be used instead of the old `cfg_attr(rustfmt)` attributes.
187 /// **Known problems:** This lint doesn't detect crate level inner attributes, because they get
188 /// processed before the PreExpansionPass lints get executed. See
189 /// [#3123](https://github.com/rust-lang/rust-clippy/pull/3123#issuecomment-422321765)
195 /// #[cfg_attr(rustfmt, rustfmt_skip)]
204 pub DEPRECATED_CFG_ATTR,
206 "usage of `cfg_attr(rustfmt)` instead of tool attributes"
209 declare_clippy_lint! {
210 /// **What it does:** Checks for cfg attributes having operating systems used in target family position.
212 /// **Why is this bad?** The configuration option will not be recognised and the related item will not be included
213 /// by the conditional compilation engine.
215 /// **Known problems:** None.
222 /// fn conditional() { }
227 /// #[cfg(target_os = "linux")]
228 /// fn conditional() { }
234 /// fn conditional() { }
236 /// Check the [Rust Reference](https://doc.rust-lang.org/reference/conditional-compilation.html#target_os) for more details.
237 pub MISMATCHED_TARGET_OS,
239 "usage of `cfg(operating_system)` instead of `cfg(target_os = \"operating_system\")`"
242 declare_lint_pass!(Attributes => [
246 BLANKET_CLIPPY_RESTRICTION_LINTS,
249 impl<'tcx> LateLintPass<'tcx> for Attributes {
250 fn check_attribute(&mut self, cx: &LateContext<'tcx>, attr: &'tcx Attribute) {
251 if let Some(items) = &attr.meta_item_list() {
252 if let Some(ident) = attr.ident() {
253 let ident = &*ident.as_str();
255 "allow" | "warn" | "deny" | "forbid" => {
256 check_clippy_lint_names(cx, ident, items);
260 if items.is_empty() || !attr.has_name(sym::deprecated) {
265 if let NestedMetaItem::MetaItem(mi) = &item;
266 if let MetaItemKind::NameValue(lit) = &mi.kind;
267 if mi.has_name(sym::since);
269 check_semver(cx, item.span(), lit);
277 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
278 let attrs = cx.tcx.hir().attrs(item.hir_id());
279 if is_relevant_item(cx, item) {
280 check_attrs(cx, item.span, item.ident.name, attrs)
283 ItemKind::ExternCrate(..) | ItemKind::Use(..) => {
284 let skip_unused_imports = attrs.iter().any(|attr| attr.has_name(sym::macro_use));
287 if in_external_macro(cx.sess(), attr.span) {
290 if let Some(lint_list) = &attr.meta_item_list() {
291 if let Some(ident) = attr.ident() {
292 match &*ident.as_str() {
293 "allow" | "warn" | "deny" | "forbid" => {
294 // permit `unused_imports`, `deprecated`, `unreachable_pub`,
295 // `clippy::wildcard_imports`, and `clippy::enum_glob_use` for `use` items
296 // and `unused_imports` for `extern crate` items with `macro_use`
297 for lint in lint_list {
299 ItemKind::Use(..) => {
300 if is_word(lint, sym!(unused_imports))
301 || is_word(lint, sym::deprecated)
302 || is_word(lint, sym!(unreachable_pub))
303 || is_word(lint, sym!(unused))
304 || extract_clippy_lint(lint)
305 .map_or(false, |s| s == "wildcard_imports")
306 || extract_clippy_lint(lint).map_or(false, |s| s == "enum_glob_use")
311 ItemKind::ExternCrate(..) => {
312 if is_word(lint, sym!(unused_imports)) && skip_unused_imports {
315 if is_word(lint, sym!(unused_extern_crates)) {
322 let line_span = first_line_of_span(cx, attr.span);
324 if let Some(mut sugg) = snippet_opt(cx, line_span) {
325 if sugg.contains("#[") {
330 "useless lint attribute",
332 sugg = sugg.replacen("#[", "#![", 1);
333 diag.span_suggestion(
335 "if you just forgot a `!`, use",
337 Applicability::MaybeIncorrect,
354 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx ImplItem<'_>) {
355 if is_relevant_impl(cx, item) {
356 check_attrs(cx, item.span, item.ident.name, cx.tcx.hir().attrs(item.hir_id()))
360 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
361 if is_relevant_trait(cx, item) {
362 check_attrs(cx, item.span, item.ident.name, cx.tcx.hir().attrs(item.hir_id()))
367 /// Returns the lint name if it is clippy lint.
368 fn extract_clippy_lint(lint: &NestedMetaItem) -> Option<SymbolStr> {
370 if let Some(meta_item) = lint.meta_item();
371 if meta_item.path.segments.len() > 1;
372 if let tool_name = meta_item.path.segments[0].ident;
373 if tool_name.name == sym::clippy;
374 let lint_name = meta_item.path.segments.last().unwrap().ident.name;
376 return Some(lint_name.as_str());
382 fn check_clippy_lint_names(cx: &LateContext<'_>, ident: &str, items: &[NestedMetaItem]) {
384 if let Some(lint_name) = extract_clippy_lint(lint) {
385 if lint_name == "restriction" && ident != "allow" {
388 BLANKET_CLIPPY_RESTRICTION_LINTS,
390 "restriction lints are not meant to be all enabled",
392 "try enabling only the lints you really need",
399 fn is_relevant_item(cx: &LateContext<'_>, item: &Item<'_>) -> bool {
400 if let ItemKind::Fn(_, _, eid) = item.kind {
401 is_relevant_expr(cx, cx.tcx.typeck_body(eid), &cx.tcx.hir().body(eid).value)
407 fn is_relevant_impl(cx: &LateContext<'_>, item: &ImplItem<'_>) -> bool {
409 ImplItemKind::Fn(_, eid) => is_relevant_expr(cx, cx.tcx.typeck_body(eid), &cx.tcx.hir().body(eid).value),
414 fn is_relevant_trait(cx: &LateContext<'_>, item: &TraitItem<'_>) -> bool {
416 TraitItemKind::Fn(_, TraitFn::Required(_)) => true,
417 TraitItemKind::Fn(_, TraitFn::Provided(eid)) => {
418 is_relevant_expr(cx, cx.tcx.typeck_body(eid), &cx.tcx.hir().body(eid).value)
424 fn is_relevant_block(cx: &LateContext<'_>, typeck_results: &ty::TypeckResults<'_>, block: &Block<'_>) -> bool {
425 block.stmts.first().map_or(
429 .map_or(false, |e| is_relevant_expr(cx, typeck_results, e)),
430 |stmt| match &stmt.kind {
431 StmtKind::Local(_) => true,
432 StmtKind::Expr(expr) | StmtKind::Semi(expr) => is_relevant_expr(cx, typeck_results, expr),
433 StmtKind::Item(_) => false,
438 fn is_relevant_expr(cx: &LateContext<'_>, typeck_results: &ty::TypeckResults<'_>, expr: &Expr<'_>) -> bool {
440 ExprKind::Block(block, _) => is_relevant_block(cx, typeck_results, block),
441 ExprKind::Ret(Some(e)) => is_relevant_expr(cx, typeck_results, e),
442 ExprKind::Ret(None) | ExprKind::Break(_, None) => false,
443 ExprKind::Call(path_expr, _) => {
444 if let ExprKind::Path(qpath) = &path_expr.kind {
446 .qpath_res(qpath, path_expr.hir_id)
448 .map_or(true, |fun_id| !match_panic_def_id(cx, fun_id))
457 fn check_attrs(cx: &LateContext<'_>, span: Span, name: Symbol, attrs: &[Attribute]) {
458 if span.from_expansion() {
463 if let Some(values) = attr.meta_item_list() {
464 if values.len() != 1 || !attr.has_name(sym::inline) {
467 if is_word(&values[0], sym::always) {
473 "you have declared `#[inline(always)]` on `{}`. This is usually a bad idea",
482 fn check_semver(cx: &LateContext<'_>, span: Span, lit: &Lit) {
483 if let LitKind::Str(is, _) = lit.kind {
484 if Version::parse(&is.as_str()).is_ok() {
492 "the since field must contain a semver-compliant version",
496 fn is_word(nmi: &NestedMetaItem, expected: Symbol) -> bool {
497 if let NestedMetaItem::MetaItem(mi) = &nmi {
498 mi.is_word() && mi.has_name(expected)
504 declare_lint_pass!(EarlyAttributes => [
506 MISMATCHED_TARGET_OS,
507 EMPTY_LINE_AFTER_OUTER_ATTR,
510 impl EarlyLintPass for EarlyAttributes {
511 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &rustc_ast::Item) {
512 check_empty_line_after_outer_attr(cx, item);
515 fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &Attribute) {
516 check_deprecated_cfg_attr(cx, attr);
517 check_mismatched_target_os(cx, attr);
521 fn check_empty_line_after_outer_attr(cx: &EarlyContext<'_>, item: &rustc_ast::Item) {
522 for attr in &item.attrs {
523 let attr_item = if let AttrKind::Normal(ref attr, _) = attr.kind {
529 if attr.style == AttrStyle::Outer {
530 if attr_item.args.inner_tokens().is_empty() || !is_present_in_source(cx, attr.span) {
534 let begin_of_attr_to_item = Span::new(attr.span.lo(), item.span.lo(), item.span.ctxt());
535 let end_of_attr_to_item = Span::new(attr.span.hi(), item.span.lo(), item.span.ctxt());
537 if let Some(snippet) = snippet_opt(cx, end_of_attr_to_item) {
538 let lines = snippet.split('\n').collect::<Vec<_>>();
539 let lines = without_block_comments(lines);
541 if lines.iter().filter(|l| l.trim().is_empty()).count() > 2 {
544 EMPTY_LINE_AFTER_OUTER_ATTR,
545 begin_of_attr_to_item,
546 "found an empty line after an outer attribute. \
547 Perhaps you forgot to add a `!` to make it an inner attribute?",
555 fn check_deprecated_cfg_attr(cx: &EarlyContext<'_>, attr: &Attribute) {
558 if attr.has_name(sym::cfg_attr);
559 if let Some(items) = attr.meta_item_list();
561 // check for `rustfmt`
562 if let Some(feature_item) = items[0].meta_item();
563 if feature_item.has_name(sym::rustfmt);
564 // check for `rustfmt_skip` and `rustfmt::skip`
565 if let Some(skip_item) = &items[1].meta_item();
566 if skip_item.has_name(sym!(rustfmt_skip)) ||
567 skip_item.path.segments.last().expect("empty path in attribute").ident.name == sym!(skip);
568 // Only lint outer attributes, because custom inner attributes are unstable
569 // Tracking issue: https://github.com/rust-lang/rust/issues/54726
570 if let AttrStyle::Outer = attr.style;
576 "`cfg_attr` is deprecated for rustfmt and got replaced by tool attributes",
578 "#[rustfmt::skip]".to_string(),
579 Applicability::MachineApplicable,
585 fn check_mismatched_target_os(cx: &EarlyContext<'_>, attr: &Attribute) {
586 fn find_os(name: &str) -> Option<&'static str> {
589 .chain(NON_UNIX_SYSTEMS.iter())
590 .find(|&&os| os == name)
594 fn is_unix(name: &str) -> bool {
595 UNIX_SYSTEMS.iter().any(|&os| os == name)
598 fn find_mismatched_target_os(items: &[NestedMetaItem]) -> Vec<(&str, Span)> {
599 let mut mismatched = Vec::new();
602 if let NestedMetaItem::MetaItem(meta) = item {
604 MetaItemKind::List(list) => {
605 mismatched.extend(find_mismatched_target_os(&list));
607 MetaItemKind::Word => {
609 if let Some(ident) = meta.ident();
610 if let Some(os) = find_os(&*ident.name.as_str());
612 mismatched.push((os, ident.span));
616 MetaItemKind::NameValue(..) => {},
625 if attr.has_name(sym::cfg);
626 if let Some(list) = attr.meta_item_list();
627 let mismatched = find_mismatched_target_os(&list);
628 if !mismatched.is_empty();
630 let mess = "operating system used in target family position";
632 span_lint_and_then(cx, MISMATCHED_TARGET_OS, attr.span, &mess, |diag| {
633 // Avoid showing the unix suggestion multiple times in case
634 // we have more than one mismatch for unix-like systems
635 let mut unix_suggested = false;
637 for (os, span) in mismatched {
638 let sugg = format!("target_os = \"{}\"", os);
639 diag.span_suggestion(span, "try", sugg, Applicability::MaybeIncorrect);
641 if !unix_suggested && is_unix(os) {
642 diag.help("did you mean `unix`?");
643 unix_suggested = true;