From 637751ff62662247480ae1641042a019d8e6609a Mon Sep 17 00:00:00 2001 From: xFrednet Date: Sun, 31 Jan 2021 14:46:09 +0100 Subject: [PATCH 01/15] Metadata collection lint: Basic lint collection WIP-2021-02-01 WIP-2021-02-01 WIP-2021-02-13 --- .gitignore | 1 + Cargo.toml | 1 + clippy_lints/Cargo.toml | 2 + clippy_lints/src/lib.rs | 3 + clippy_lints/src/utils/internal_lints.rs | 3 + .../internal_lints/metadata_collector.rs | 206 ++++++++++++++++++ clippy_lints/src/utils/mod.rs | 2 +- tests/dogfood.rs | 9 + 8 files changed, 226 insertions(+), 1 deletion(-) create mode 100644 clippy_lints/src/utils/internal_lints/metadata_collector.rs diff --git a/.gitignore b/.gitignore index 376528e3085..523bab18828 100644 --- a/.gitignore +++ b/.gitignore @@ -29,6 +29,7 @@ out # gh pages docs util/gh-pages/lints.json +**/metadata_collection.json # rustfmt backups *.rs.bk diff --git a/Cargo.toml b/Cargo.toml index cade44a0a9a..bdee8e40821 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -52,6 +52,7 @@ rustc_tools_util = { version = "0.2.0", path = "rustc_tools_util" } deny-warnings = [] integration = ["tempfile"] internal-lints = ["clippy_lints/internal-lints"] +metadata-collector-lint = ["clippy_lints/metadata-collector-lint"] [package.metadata.rust-analyzer] # This package uses #[feature(rustc_private)] diff --git a/clippy_lints/Cargo.toml b/clippy_lints/Cargo.toml index 05cdd9d064a..d1d56fc84f9 100644 --- a/clippy_lints/Cargo.toml +++ b/clippy_lints/Cargo.toml @@ -20,6 +20,7 @@ pulldown-cmark = { version = "0.8", default-features = false } quine-mc_cluskey = "0.2.2" regex-syntax = "0.6" serde = { version = "1.0", features = ["derive"] } +serde_json = { version = "1.0", optional = true } toml = "0.5.3" unicode-normalization = "0.1" semver = "0.11" @@ -32,6 +33,7 @@ url = { version = "2.1.0", features = ["serde"] } deny-warnings = [] # build clippy with internal lints enabled, off by default internal-lints = ["clippy_utils/internal-lints"] +metadata-collector-lint = ["serde_json"] [package.metadata.rust-analyzer] # This crate uses #[feature(rustc_private)] diff --git a/clippy_lints/src/lib.rs b/clippy_lints/src/lib.rs index 40a793e48cf..7668d4dd0b1 100644 --- a/clippy_lints/src/lib.rs +++ b/clippy_lints/src/lib.rs @@ -1004,6 +1004,9 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: store.register_late_pass(|| box utils::internal_lints::MatchTypeOnDiagItem); store.register_late_pass(|| box utils::internal_lints::OuterExpnDataPass); } + #[cfg(feature = "metadata-collector-lint")] + store.register_late_pass(|| box utils::internal_lints::metadata_collector::MetadataCollector::default()); + store.register_late_pass(|| box utils::author::Author); store.register_late_pass(|| box await_holding_invalid::AwaitHolding); store.register_late_pass(|| box serde_api::SerdeApi); diff --git a/clippy_lints/src/utils/internal_lints.rs b/clippy_lints/src/utils/internal_lints.rs index 3d3d0e19d26..ee7be24eae8 100644 --- a/clippy_lints/src/utils/internal_lints.rs +++ b/clippy_lints/src/utils/internal_lints.rs @@ -32,6 +32,9 @@ use std::borrow::{Borrow, Cow}; +#[cfg(feature = "metadata-collector-lint")] +pub mod metadata_collector; + declare_clippy_lint! { /// **What it does:** Checks for various things we like to keep tidy in clippy. /// diff --git a/clippy_lints/src/utils/internal_lints/metadata_collector.rs b/clippy_lints/src/utils/internal_lints/metadata_collector.rs new file mode 100644 index 00000000000..dc4267697cb --- /dev/null +++ b/clippy_lints/src/utils/internal_lints/metadata_collector.rs @@ -0,0 +1,206 @@ +//! This lint is used to collect metadata about clippy lints. This metadata is exported as a json +//! file and then used to generate the [clippy lint list](https://rust-lang.github.io/rust-clippy/master/index.html) +//! +//! This module and therefor the entire lint is guarded by a feature flag called +//! `internal_metadata_lint` +//! +//! The metadata currently contains: +//! - [ ] TODO The lint declaration line for [#1303](https://github.com/rust-lang/rust-clippy/issues/1303) +//! and [#6492](https://github.com/rust-lang/rust-clippy/issues/6492) +//! - [ ] TODO The Applicability for each lint for [#4310](https://github.com/rust-lang/rust-clippy/issues/4310) + +// # Applicability +// - TODO xFrednet 2021-01-17: Find all methods that take and modify applicability or predefine +// them? +// - TODO xFrednet 2021-01-17: Find lint emit and collect applicability +// # NITs +// - TODO xFrednet 2021-02-13: Collect depreciations and maybe renames + +use if_chain::if_chain; +use rustc_hir::{ExprKind, Item, ItemKind, Mutability}; +use rustc_lint::{CheckLintNameResult, LateContext, LateLintPass, LintContext, LintId}; +use rustc_session::{declare_tool_lint, impl_lint_pass}; +use rustc_span::{sym, Loc, Span}; +use serde::Serialize; +use std::fs::OpenOptions; +use std::io::prelude::*; + +use crate::utils::internal_lints::is_lint_ref_type; +use crate::utils::span_lint; + +const OUTPUT_FILE: &str = "metadata_collection.json"; +const BLACK_LISTED_LINTS: [&str; 2] = ["lint_author", "deep_code_inspection"]; + +declare_clippy_lint! { + /// **What it does:** Collects metadata about clippy lints for the website. + /// + /// This lint will be used to report problems of syntax parsing. You should hopefully never + /// see this but never say never I guess ^^ + /// + /// **Why is this bad?** This is not a bad thing but definitely a hacky way to do it. See + /// issue [#4310](https://github.com/rust-lang/rust-clippy/issues/4310) for a discussion + /// about the implementation. + /// + /// **Known problems:** Hopefully none. It would be pretty uncool to have a problem here :) + /// + /// **Example output:** + /// ```json,ignore + /// { + /// "id": "internal_metadata_collector", + /// "id_span": { + /// "path": "clippy_lints/src/utils/internal_lints/metadata_collector.rs", + /// "line": 1 + /// }, + /// "group": "clippy::internal", + /// "docs": " **What it does:** Collects metadata about clippy lints for the website. [...] " + /// } + /// ``` + pub INTERNAL_METADATA_COLLECTOR, + internal, + "A busy bee collection metadata about lints" +} + +impl_lint_pass!(MetadataCollector => [INTERNAL_METADATA_COLLECTOR]); + +#[allow(clippy::module_name_repetitions)] +#[derive(Debug, Clone, Default)] +pub struct MetadataCollector { + lints: Vec, +} + +impl Drop for MetadataCollector { + fn drop(&mut self) { + // You might ask: How hacky is this? + // My answer: YES + let mut file = OpenOptions::new().write(true).create(true).open(OUTPUT_FILE).unwrap(); + writeln!(file, "{}", serde_json::to_string_pretty(&self.lints).unwrap()).unwrap(); + } +} + +#[derive(Debug, Clone, Serialize)] +struct LintMetadata { + id: String, + id_span: SerializableSpan, + group: String, + docs: String, +} + +#[derive(Debug, Clone, Serialize)] +struct SerializableSpan { + path: String, + line: usize, +} + +impl SerializableSpan { + fn from_item(cx: &LateContext<'_>, item: &Item<'_>) -> Self { + Self::from_span(cx, item.ident.span) + } + + fn from_span(cx: &LateContext<'_>, span: Span) -> Self { + let loc: Loc = cx.sess().source_map().lookup_char_pos(span.lo()); + + Self { + path: format!("{}", loc.file.name), + line: 1, + } + } +} + +impl<'tcx> LateLintPass<'tcx> for MetadataCollector { + fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) { + if_chain! { + if let ItemKind::Static(ref ty, Mutability::Not, body_id) = item.kind; + if is_lint_ref_type(cx, ty); + let expr = &cx.tcx.hir().body(body_id).value; + if let ExprKind::AddrOf(_, _, ref inner_exp) = expr.kind; + if let ExprKind::Struct(_, _, _) = inner_exp.kind; + then { + let lint_name = item.ident.name.as_str().to_string().to_ascii_lowercase(); + if BLACK_LISTED_LINTS.contains(&lint_name.as_str()) { + return; + } + + let group: String; + let result = cx.lint_store.check_lint_name(lint_name.as_str(), Some(sym::clippy)); + if let CheckLintNameResult::Tool(Ok(lint_lst)) = result { + if let Some(group_some) = get_lint_group(cx, lint_lst[0]) { + group = group_some; + } else { + lint_collection_error(cx, item, "Unable to determine lint group"); + return; + } + } else { + lint_collection_error(cx, item, "Unable to find lint in lint_store"); + return; + } + + let docs: String; + if let Some(docs_some) = extract_attr_docs(item) { + docs = docs_some; + } else { + lint_collection_error(cx, item, "could not collect the lint documentation"); + return; + }; + + self.lints.push(LintMetadata { + id: lint_name, + id_span: SerializableSpan::from_item(cx, item), + group, + docs, + }); + } + } + } +} + +/// This function collects all documentation that has been added to an item using +/// `#[doc = r""]` attributes. Several attributes are aggravated using line breaks +/// +/// ```ignore +/// #[doc = r"Hello world!"] +/// #[doc = r"=^.^="] +/// struct SomeItem {} +/// ``` +/// +/// Would result in `Hello world!\n=^.^=\n` +fn extract_attr_docs(item: &Item<'_>) -> Option { + item.attrs + .iter() + .filter_map(|ref x| x.doc_str()) + .fold(None, |acc, sym| { + let mut doc_str = sym.as_str().to_string(); + doc_str.push('\n'); + + #[allow(clippy::option_if_let_else)] // See clippy#6737 + if let Some(mut x) = acc { + x.push_str(&doc_str); + Some(x) + } else { + Some(doc_str) + } + + // acc.map_or(Some(doc_str), |mut x| { + // x.push_str(&doc_str); + // Some(x) + // }) + }) +} + +fn get_lint_group(cx: &LateContext<'_>, lint_id: LintId) -> Option { + for (group_name, lints, _) in &cx.lint_store.get_lint_groups() { + if lints.iter().any(|x| *x == lint_id) { + return Some((*group_name).to_string()); + } + } + + None +} + +fn lint_collection_error(cx: &LateContext<'_>, item: &Item<'_>, message: &str) { + span_lint( + cx, + INTERNAL_METADATA_COLLECTOR, + item.ident.span, + &format!("Metadata collection error for `{}`: {}", item.ident.name, message), + ); +} diff --git a/clippy_lints/src/utils/mod.rs b/clippy_lints/src/utils/mod.rs index d8b31344e6d..b67448e3a57 100644 --- a/clippy_lints/src/utils/mod.rs +++ b/clippy_lints/src/utils/mod.rs @@ -1,5 +1,5 @@ pub mod author; pub mod conf; pub mod inspector; -#[cfg(feature = "internal-lints")] +#[cfg(any(feature = "internal-lints", feature = "metadata-collector-lint"))] pub mod internal_lints; diff --git a/tests/dogfood.rs b/tests/dogfood.rs index d92530f073f..b0da0bfcc35 100644 --- a/tests/dogfood.rs +++ b/tests/dogfood.rs @@ -1,3 +1,8 @@ +//! This test is a part of quality control and makes clippy eat what it produces. Awesome lints and +//! long error messages +//! +//! See [Eating your own dog food](https://en.wikipedia.org/wiki/Eating_your_own_dog_food) for context + // Dogfood cannot run on Windows #![cfg(not(windows))] #![feature(once_cell)] @@ -36,6 +41,10 @@ fn dogfood_clippy() { command.args(&["-D", "clippy::internal"]); } + if cfg!(feature = "metadata-collector-lint") { + command.args(&["-D", "clippy::internal"]); + } + let output = command.output().unwrap(); println!("status: {}", output.status); From 060e0e9f9382cb7975165cede8d04b7bbe26bcb2 Mon Sep 17 00:00:00 2001 From: xFrednet Date: Sun, 14 Feb 2021 16:17:07 +0100 Subject: [PATCH 02/15] Metadata collection lint: Basic applicability collection --- .../internal_lints/metadata_collector.rs | 180 ++++++++++++++---- clippy_utils/src/paths.rs | 2 + 2 files changed, 148 insertions(+), 34 deletions(-) diff --git a/clippy_lints/src/utils/internal_lints/metadata_collector.rs b/clippy_lints/src/utils/internal_lints/metadata_collector.rs index dc4267697cb..677f9fcc83f 100644 --- a/clippy_lints/src/utils/internal_lints/metadata_collector.rs +++ b/clippy_lints/src/utils/internal_lints/metadata_collector.rs @@ -2,10 +2,14 @@ //! file and then used to generate the [clippy lint list](https://rust-lang.github.io/rust-clippy/master/index.html) //! //! This module and therefor the entire lint is guarded by a feature flag called -//! `internal_metadata_lint` +//! `metadata-collector-lint` +//! +//! The module transforms all lint names to ascii lowercase to ensure that we don't have mismatches +//! during any comparison or mapping. (Please take care of this, it's not fun to spend time on such +//! a simple mistake) //! //! The metadata currently contains: -//! - [ ] TODO The lint declaration line for [#1303](https://github.com/rust-lang/rust-clippy/issues/1303) +//! - [x] TODO The lint declaration line for [#1303](https://github.com/rust-lang/rust-clippy/issues/1303) //! and [#6492](https://github.com/rust-lang/rust-clippy/issues/6492) //! - [ ] TODO The Applicability for each lint for [#4310](https://github.com/rust-lang/rust-clippy/issues/4310) @@ -17,20 +21,34 @@ // - TODO xFrednet 2021-02-13: Collect depreciations and maybe renames use if_chain::if_chain; -use rustc_hir::{ExprKind, Item, ItemKind, Mutability}; +use rustc_data_structures::fx::{FxHashMap, FxHashSet}; +use rustc_hir::{self as hir, ExprKind, Item, ItemKind, Mutability}; use rustc_lint::{CheckLintNameResult, LateContext, LateLintPass, LintContext, LintId}; use rustc_session::{declare_tool_lint, impl_lint_pass}; -use rustc_span::{sym, Loc, Span}; +use rustc_span::{sym, Loc, Span, Symbol}; use serde::Serialize; use std::fs::OpenOptions; use std::io::prelude::*; use crate::utils::internal_lints::is_lint_ref_type; -use crate::utils::span_lint; +use crate::utils::{last_path_segment, match_function_call, match_type, paths, span_lint, walk_ptrs_ty_depth}; +/// This is the output file of the lint collector. const OUTPUT_FILE: &str = "metadata_collection.json"; +/// These lints are excluded from the export. const BLACK_LISTED_LINTS: [&str; 2] = ["lint_author", "deep_code_inspection"]; +// TODO xFrednet 2021-02-15: `span_lint_and_then` & `span_lint_hir_and_then` requires special +// handling +#[rustfmt::skip] +const LINT_EMISSION_FUNCTIONS: [&[&str]; 5] = [ + &["clippy_lints", "utils", "diagnostics", "span_lint"], + &["clippy_lints", "utils", "diagnostics", "span_lint_and_help"], + &["clippy_lints", "utils", "diagnostics", "span_lint_and_note"], + &["clippy_lints", "utils", "diagnostics", "span_lint_hir"], + &["clippy_lints", "utils", "diagnostics", "span_lint_and_sugg"], +]; + declare_clippy_lint! { /// **What it does:** Collects metadata about clippy lints for the website. /// @@ -66,12 +84,21 @@ #[derive(Debug, Clone, Default)] pub struct MetadataCollector { lints: Vec, + applicability_into: FxHashMap, } impl Drop for MetadataCollector { + /// You might ask: How hacky is this? + /// My answer: YES fn drop(&mut self) { - // You might ask: How hacky is this? - // My answer: YES + let mut applicability_info = std::mem::take(&mut self.applicability_into); + + // Mapping the final data + self.lints + .iter_mut() + .for_each(|x| x.applicability = applicability_info.remove(&x.id)); + + // Outputting let mut file = OpenOptions::new().write(true).create(true).open(OUTPUT_FILE).unwrap(); writeln!(file, "{}", serde_json::to_string_pretty(&self.lints).unwrap()).unwrap(); } @@ -83,6 +110,21 @@ struct LintMetadata { id_span: SerializableSpan, group: String, docs: String, + /// This field is only used in the output and will only be + /// mapped shortly before the actual output. + applicability: Option, +} + +impl LintMetadata { + fn new(id: String, id_span: SerializableSpan, group: String, docs: String) -> Self { + Self { + id, + id_span, + group, + docs, + applicability: None, + } + } } #[derive(Debug, Clone, Serialize)] @@ -101,12 +143,31 @@ fn from_span(cx: &LateContext<'_>, span: Span) -> Self { Self { path: format!("{}", loc.file.name), - line: 1, + line: loc.line, } } } +#[derive(Debug, Clone, Default, Serialize)] +struct ApplicabilityInfo { + /// Indicates if any of the lint emissions uses multiple spans. This is related to + /// [rustfix#141](https://github.com/rust-lang/rustfix/issues/141) as such suggestions can + /// currently not be applied automatically. + has_multi_suggestion: bool, + /// These are all the available applicability values for the lint suggestions + applicabilities: FxHashSet, +} + impl<'tcx> LateLintPass<'tcx> for MetadataCollector { + /// Collecting lint declarations like: + /// ```rust, ignore + /// declare_clippy_lint! { + /// /// **What it does:** Something IDK. + /// pub SOME_LINT, + /// internal, + /// "Who am I?" + /// } + /// ``` fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) { if_chain! { if let ItemKind::Static(ref ty, Mutability::Not, body_id) = item.kind; @@ -115,7 +176,7 @@ fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) { if let ExprKind::AddrOf(_, _, ref inner_exp) = expr.kind; if let ExprKind::Struct(_, _, _) = inner_exp.kind; then { - let lint_name = item.ident.name.as_str().to_string().to_ascii_lowercase(); + let lint_name = sym_to_string(item.ident.name).to_ascii_lowercase(); if BLACK_LISTED_LINTS.contains(&lint_name.as_str()) { return; } @@ -126,11 +187,11 @@ fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) { if let Some(group_some) = get_lint_group(cx, lint_lst[0]) { group = group_some; } else { - lint_collection_error(cx, item, "Unable to determine lint group"); + lint_collection_error_item(cx, item, "Unable to determine lint group"); return; } } else { - lint_collection_error(cx, item, "Unable to find lint in lint_store"); + lint_collection_error_item(cx, item, "Unable to find lint in lint_store"); return; } @@ -138,19 +199,36 @@ fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) { if let Some(docs_some) = extract_attr_docs(item) { docs = docs_some; } else { - lint_collection_error(cx, item, "could not collect the lint documentation"); + lint_collection_error_item(cx, item, "could not collect the lint documentation"); return; }; - self.lints.push(LintMetadata { - id: lint_name, - id_span: SerializableSpan::from_item(cx, item), + self.lints.push(LintMetadata::new( + lint_name, + SerializableSpan::from_item(cx, item), group, docs, - }); + )); } } } + + fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) { + if let Some(args) = match_simple_lint_emission(cx, expr) { + if let Some((lint_name, mut applicability)) = extract_emission_info(cx, args) { + let app_info = self.applicability_into.entry(lint_name).or_default(); + applicability.drain(..).for_each(|x| { + app_info.applicabilities.insert(x); + }); + } else { + lint_collection_error_span(cx, expr.span, "I found this but I can't get the lint or applicability"); + } + } + } +} + +fn sym_to_string(sym: Symbol) -> String { + sym.as_str().to_string() } /// This function collects all documentation that has been added to an item using @@ -166,23 +244,11 @@ fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) { fn extract_attr_docs(item: &Item<'_>) -> Option { item.attrs .iter() - .filter_map(|ref x| x.doc_str()) - .fold(None, |acc, sym| { - let mut doc_str = sym.as_str().to_string(); - doc_str.push('\n'); - - #[allow(clippy::option_if_let_else)] // See clippy#6737 - if let Some(mut x) = acc { - x.push_str(&doc_str); - Some(x) - } else { - Some(doc_str) - } - - // acc.map_or(Some(doc_str), |mut x| { - // x.push_str(&doc_str); - // Some(x) - // }) + .filter_map(|ref x| x.doc_str().map(|sym| sym.as_str().to_string())) + .reduce(|mut acc, sym| { + acc.push_str(&sym); + acc.push('\n'); + acc }) } @@ -196,7 +262,7 @@ fn get_lint_group(cx: &LateContext<'_>, lint_id: LintId) -> Option { None } -fn lint_collection_error(cx: &LateContext<'_>, item: &Item<'_>, message: &str) { +fn lint_collection_error_item(cx: &LateContext<'_>, item: &Item<'_>, message: &str) { span_lint( cx, INTERNAL_METADATA_COLLECTOR, @@ -204,3 +270,49 @@ fn lint_collection_error(cx: &LateContext<'_>, item: &Item<'_>, message: &str) { &format!("Metadata collection error for `{}`: {}", item.ident.name, message), ); } + +fn lint_collection_error_span(cx: &LateContext<'_>, span: Span, message: &str) { + span_lint( + cx, + INTERNAL_METADATA_COLLECTOR, + span, + &format!("Metadata collection error: {}", message), + ); +} + +fn match_simple_lint_emission<'tcx>( + cx: &LateContext<'tcx>, + expr: &'tcx hir::Expr<'_>, +) -> Option<&'tcx [hir::Expr<'tcx>]> { + LINT_EMISSION_FUNCTIONS + .iter() + .find_map(|emission_fn| match_function_call(cx, expr, emission_fn).map(|args| args)) +} + +/// This returns the lint name and the possible applicability of this emission +fn extract_emission_info<'tcx>(cx: &LateContext<'tcx>, args: &[hir::Expr<'_>]) -> Option<(String, Vec)> { + let mut lint_name = None; + let mut applicability = None; + + for arg in args { + let (arg_ty, _) = walk_ptrs_ty_depth(cx.typeck_results().expr_ty(&arg)); + + if match_type(cx, arg_ty, &paths::LINT) { + // If we found the lint arg, extract the lint name + if let ExprKind::Path(ref lint_path) = arg.kind { + lint_name = Some(last_path_segment(lint_path).ident.name) + } + } else if match_type(cx, arg_ty, &paths::APPLICABILITY) { + if let ExprKind::Path(ref path) = arg.kind { + applicability = Some(last_path_segment(path).ident.name) + } + } + } + + lint_name.map(|lint_name| { + ( + sym_to_string(lint_name).to_ascii_lowercase(), + applicability.map(sym_to_string).map_or_else(Vec::new, |x| vec![x]), + ) + }) +} diff --git a/clippy_utils/src/paths.rs b/clippy_utils/src/paths.rs index 5e6733a300f..91e5cd6c046 100644 --- a/clippy_utils/src/paths.rs +++ b/clippy_utils/src/paths.rs @@ -5,6 +5,8 @@ //! See for more information. pub const ANY_TRAIT: [&str; 3] = ["core", "any", "Any"]; +#[cfg(feature = "metadata-collector-lint")] +pub const APPLICABILITY: [&str; 2] = ["rustc_lint_defs", "Applicability"]; pub const ARC_PTR_EQ: [&str; 4] = ["alloc", "sync", "Arc", "ptr_eq"]; pub const ASMUT_TRAIT: [&str; 3] = ["core", "convert", "AsMut"]; pub const ASREF_TRAIT: [&str; 3] = ["core", "convert", "AsRef"]; From 68d702f88ded863b9cde999f1850b32c6531fe11 Mon Sep 17 00:00:00 2001 From: xFrednet Date: Thu, 18 Feb 2021 00:20:19 +0100 Subject: [PATCH 03/15] Metadata collection lint: Start Applicability value tracking --- .../internal_lints/metadata_collector.rs | 158 +++++++++++++++++- 1 file changed, 155 insertions(+), 3 deletions(-) diff --git a/clippy_lints/src/utils/internal_lints/metadata_collector.rs b/clippy_lints/src/utils/internal_lints/metadata_collector.rs index 677f9fcc83f..2bdb92376ca 100644 --- a/clippy_lints/src/utils/internal_lints/metadata_collector.rs +++ b/clippy_lints/src/utils/internal_lints/metadata_collector.rs @@ -24,14 +24,21 @@ use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_hir::{self as hir, ExprKind, Item, ItemKind, Mutability}; use rustc_lint::{CheckLintNameResult, LateContext, LateLintPass, LintContext, LintId}; +use rustc_middle::ty::BorrowKind; use rustc_session::{declare_tool_lint, impl_lint_pass}; use rustc_span::{sym, Loc, Span, Symbol}; +use rustc_trait_selection::infer::TyCtxtInferExt; +use rustc_typeck::expr_use_visitor::{ConsumeMode, Delegate, ExprUseVisitor, PlaceWithHirId}; +use rustc_typeck::hir_ty_to_ty; use serde::Serialize; -use std::fs::OpenOptions; +use std::fs::{self, OpenOptions}; use std::io::prelude::*; +use std::path::Path; use crate::utils::internal_lints::is_lint_ref_type; -use crate::utils::{last_path_segment, match_function_call, match_type, paths, span_lint, walk_ptrs_ty_depth}; +use crate::utils::{ + last_path_segment, match_function_call, match_type, path_to_local_id, paths, span_lint, walk_ptrs_ty_depth, +}; /// This is the output file of the lint collector. const OUTPUT_FILE: &str = "metadata_collection.json"; @@ -91,6 +98,10 @@ impl Drop for MetadataCollector { /// You might ask: How hacky is this? /// My answer: YES fn drop(&mut self) { + if self.lints.is_empty() { + return; + } + let mut applicability_info = std::mem::take(&mut self.applicability_into); // Mapping the final data @@ -99,6 +110,9 @@ fn drop(&mut self) { .for_each(|x| x.applicability = applicability_info.remove(&x.id)); // Outputting + if Path::new(OUTPUT_FILE).exists() { + fs::remove_file(OUTPUT_FILE).unwrap(); + } let mut file = OpenOptions::new().write(true).create(true).open(OUTPUT_FILE).unwrap(); writeln!(file, "{}", serde_json::to_string_pretty(&self.lints).unwrap()).unwrap(); } @@ -158,6 +172,17 @@ struct ApplicabilityInfo { applicabilities: FxHashSet, } +fn log_to_file(msg: &str) { + let mut file = OpenOptions::new() + .write(true) + .append(true) + .create(true) + .open("metadata-lint.log") + .unwrap(); + + write!(file, "{}", msg).unwrap(); +} + impl<'tcx> LateLintPass<'tcx> for MetadataCollector { /// Collecting lint declarations like: /// ```rust, ignore @@ -213,6 +238,20 @@ fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) { } } + /// Collecting constant applicability from the actual lint emissions + /// + /// Example: + /// ```rust, ignore + /// span_lint_and_sugg( + /// cx, + /// SOME_LINT, + /// item.span, + /// "Le lint message", + /// "Here comes help:", + /// "#![allow(clippy::all)]", + /// Applicability::MachineApplicable, // <-- Extracts this constant value + /// ); + /// ``` fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) { if let Some(args) = match_simple_lint_emission(cx, expr) { if let Some((lint_name, mut applicability)) = extract_emission_info(cx, args) { @@ -225,6 +264,73 @@ fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) { } } } + + /// Tracking and hopefully collecting dynamic applicability values + /// + /// Example: + /// ```rust, ignore + /// // vvv Applicability value to track + /// let mut applicability = Applicability::MachineApplicable; + /// // vvv Value Mutation + /// let suggestion = snippet_with_applicability(cx, expr.span, "_", &mut applicability); + /// // vvv Emission to link the value to the lint + /// span_lint_and_sugg( + /// cx, + /// SOME_LINT, + /// expr.span, + /// "This can be improved", + /// "try", + /// suggestion, + /// applicability, + /// ); + /// ``` + fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx hir::Local<'tcx>) { + if let Some(tc) = cx.maybe_typeck_results() { + // TODO xFrednet 2021-02-14: support nested applicability (only in tuples) + let local_ty = if let Some(ty) = local.ty { + hir_ty_to_ty(cx.tcx, ty) + } else if let Some(init) = local.init { + tc.expr_ty(init) + } else { + return; + }; + + if_chain! { + if match_type(cx, local_ty, &paths::APPLICABILITY); + if let Some(body) = get_parent_body(cx, local.hir_id); + then { + let span = SerializableSpan::from_span(cx, local.span); + let local_str = crate::utils::snippet(cx, local.span, "_"); + let value_life = format!("{} -- {}:{}\n", local_str, span.path.rsplit('/').next().unwrap_or_default(), span.line); + let value_hir_id = local.pat.hir_id; + let mut tracker = ValueTracker {cx, value_hir_id, value_life}; + + cx.tcx.infer_ctxt().enter(|infcx| { + let body_owner_id = cx.tcx.hir().body_owner_def_id(body.id()); + ExprUseVisitor::new( + &mut tracker, + &infcx, + body_owner_id, + cx.param_env, + cx.typeck_results() + ) + .consume_body(body); + }); + + log_to_file(&tracker.value_life); + lint_collection_error_span(cx, local.span, "Applicability value found"); + } + } + } + } +} + +fn get_parent_body<'a, 'tcx>(cx: &'a LateContext<'tcx>, id: hir::HirId) -> Option<&'tcx hir::Body<'tcx>> { + let map = cx.tcx.hir(); + + map.parent_iter(id) + .find_map(|(parent, _)| map.maybe_body_owned_by(parent)) + .map(|body| map.body(body)) } fn sym_to_string(sym: Symbol) -> String { @@ -262,6 +368,9 @@ fn get_lint_group(cx: &LateContext<'_>, lint_id: LintId) -> Option { None } +// ================================================================== +// Lint emission +// ================================================================== fn lint_collection_error_item(cx: &LateContext<'_>, item: &Item<'_>, message: &str) { span_lint( cx, @@ -280,13 +389,16 @@ fn lint_collection_error_span(cx: &LateContext<'_>, span: Span, message: &str) { ); } +// ================================================================== +// Applicability +// ================================================================== fn match_simple_lint_emission<'tcx>( cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, ) -> Option<&'tcx [hir::Expr<'tcx>]> { LINT_EMISSION_FUNCTIONS .iter() - .find_map(|emission_fn| match_function_call(cx, expr, emission_fn).map(|args| args)) + .find_map(|emission_fn| match_function_call(cx, expr, emission_fn)) } /// This returns the lint name and the possible applicability of this emission @@ -316,3 +428,43 @@ fn extract_emission_info<'tcx>(cx: &LateContext<'tcx>, args: &[hir::Expr<'_>]) - ) }) } + +struct ValueTracker<'a, 'tcx> { + cx: &'a LateContext<'tcx>, + value_hir_id: hir::HirId, + value_life: String, +} + +impl<'a, 'tcx> ValueTracker<'a, 'tcx> { + fn is_value_expr(&self, expr_id: hir::HirId) -> bool { + match self.cx.tcx.hir().find(expr_id) { + Some(hir::Node::Expr(expr)) => path_to_local_id(expr, self.value_hir_id), + _ => false, + } + } +} + +impl<'a, 'tcx> Delegate<'tcx> for ValueTracker<'a, 'tcx> { + fn consume(&mut self, _place_with_id: &PlaceWithHirId<'tcx>, expr_id: hir::HirId, _: ConsumeMode) { + if self.is_value_expr(expr_id) { + // TODO xFrednet 2021-02-17: Check if lint emission and extract lint ID + todo!(); + } + } + + fn borrow(&mut self, _place_with_id: &PlaceWithHirId<'tcx>, expr_id: hir::HirId, bk: BorrowKind) { + if self.is_value_expr(expr_id) { + if let BorrowKind::MutBorrow = bk { + // TODO xFrednet 2021-02-17: Save the function + todo!(); + } + } + } + + fn mutate(&mut self, _assignee_place: &PlaceWithHirId<'tcx>, expr_id: hir::HirId) { + if self.is_value_expr(expr_id) { + // TODO xFrednet 2021-02-17: Save the new value as a mutation + todo!(); + } + } +} From 8dca1b8f618fdec3f1b354d9bafa01b32ecc8ab6 Mon Sep 17 00:00:00 2001 From: xFrednet Date: Thu, 18 Feb 2021 23:40:33 +0100 Subject: [PATCH 04/15] Metadata collection: Collecting Applicability assign values --- .../internal_lints/metadata_collector.rs | 257 ++++++++++++++---- clippy_utils/src/paths.rs | 7 + .../track_applicability_value.rs | 46 ++++ 3 files changed, 252 insertions(+), 58 deletions(-) create mode 100644 tests/ui-internal/metadata-collector/track_applicability_value.rs diff --git a/clippy_lints/src/utils/internal_lints/metadata_collector.rs b/clippy_lints/src/utils/internal_lints/metadata_collector.rs index 2bdb92376ca..e22aa285f17 100644 --- a/clippy_lints/src/utils/internal_lints/metadata_collector.rs +++ b/clippy_lints/src/utils/internal_lints/metadata_collector.rs @@ -24,7 +24,7 @@ use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_hir::{self as hir, ExprKind, Item, ItemKind, Mutability}; use rustc_lint::{CheckLintNameResult, LateContext, LateLintPass, LintContext, LintId}; -use rustc_middle::ty::BorrowKind; +use rustc_middle::ty::{BorrowKind, Ty}; use rustc_session::{declare_tool_lint, impl_lint_pass}; use rustc_span::{sym, Loc, Span, Symbol}; use rustc_trait_selection::infer::TyCtxtInferExt; @@ -37,7 +37,8 @@ use crate::utils::internal_lints::is_lint_ref_type; use crate::utils::{ - last_path_segment, match_function_call, match_type, path_to_local_id, paths, span_lint, walk_ptrs_ty_depth, + get_enclosing_body, get_parent_expr_for_hir, last_path_segment, match_function_call, match_qpath, match_type, + path_to_local_id, paths, span_lint, walk_ptrs_ty_depth, }; /// This is the output file of the lint collector. @@ -147,6 +148,12 @@ struct SerializableSpan { line: usize, } +impl std::fmt::Display for SerializableSpan { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}:{}", self.path.rsplit('/').next().unwrap_or_default(), self.line) + } +} + impl SerializableSpan { fn from_item(cx: &LateContext<'_>, item: &Item<'_>) -> Self { Self::from_span(cx, item.ident.span) @@ -285,52 +292,54 @@ fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) { /// ); /// ``` fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx hir::Local<'tcx>) { - if let Some(tc) = cx.maybe_typeck_results() { - // TODO xFrednet 2021-02-14: support nested applicability (only in tuples) - let local_ty = if let Some(ty) = local.ty { - hir_ty_to_ty(cx.tcx, ty) - } else if let Some(init) = local.init { - tc.expr_ty(init) - } else { - return; - }; - - if_chain! { - if match_type(cx, local_ty, &paths::APPLICABILITY); - if let Some(body) = get_parent_body(cx, local.hir_id); - then { - let span = SerializableSpan::from_span(cx, local.span); - let local_str = crate::utils::snippet(cx, local.span, "_"); - let value_life = format!("{} -- {}:{}\n", local_str, span.path.rsplit('/').next().unwrap_or_default(), span.line); - let value_hir_id = local.pat.hir_id; - let mut tracker = ValueTracker {cx, value_hir_id, value_life}; - - cx.tcx.infer_ctxt().enter(|infcx| { - let body_owner_id = cx.tcx.hir().body_owner_def_id(body.id()); - ExprUseVisitor::new( - &mut tracker, - &infcx, - body_owner_id, - cx.param_env, - cx.typeck_results() - ) - .consume_body(body); - }); - - log_to_file(&tracker.value_life); - lint_collection_error_span(cx, local.span, "Applicability value found"); + if_chain! { + if let Some(local_ty) = get_local_type(cx, local); + if match_type(cx, local_ty, &paths::APPLICABILITY); + if let Some(body) = get_enclosing_body(cx, local.hir_id); + then { + // TODO xFrednet: 2021-02-19: Remove debug code + let span = SerializableSpan::from_span(cx, local.span); + let local_str = crate::utils::snippet(cx, local.span, "_"); + log_to_file(&format!("{} -- {}\n", local_str, span)); + + let value_hir_id = local.pat.hir_id; + let mut tracker = ValueTracker::new(cx, value_hir_id); + if let Some(init_expr) = local.init { + tracker.process_assign_expr(init_expr) } + + // TODO xFrednet 2021-02-18: Support nested bodies + // Note: The `ExprUseVisitor` only searches though one body, this means that values + // references in nested bodies like closures are not found by this simple visitor. + cx.tcx.infer_ctxt().enter(|infcx| { + let body_owner_id = cx.tcx.hir().body_owner_def_id(body.id()); + ExprUseVisitor::new( + &mut tracker, + &infcx, + body_owner_id, + cx.param_env, + cx.typeck_results() + ) + .consume_body(body); + }); + + log_to_file(&format!("{:?}\n", tracker.value_mutations)); } } } } -fn get_parent_body<'a, 'tcx>(cx: &'a LateContext<'tcx>, id: hir::HirId) -> Option<&'tcx hir::Body<'tcx>> { - let map = cx.tcx.hir(); +fn get_local_type<'a>(cx: &'a LateContext<'_>, local: &'a hir::Local<'_>) -> Option> { + // TODO xFrednet 2021-02-14: support nested applicability (only in tuples) + if let Some(tc) = cx.maybe_typeck_results() { + if let Some(ty) = local.ty { + return Some(hir_ty_to_ty(cx.tcx, ty)); + } else if let Some(init) = local.init { + return Some(tc.expr_ty(init)); + } + } - map.parent_iter(id) - .find_map(|(parent, _)| map.maybe_body_owned_by(parent)) - .map(|body| map.body(body)) + None } fn sym_to_string(sym: Symbol) -> String { @@ -429,42 +438,174 @@ fn extract_emission_info<'tcx>(cx: &LateContext<'tcx>, args: &[hir::Expr<'_>]) - }) } -struct ValueTracker<'a, 'tcx> { - cx: &'a LateContext<'tcx>, +#[allow(dead_code)] +struct ValueTracker<'a, 'hir> { + cx: &'a LateContext<'hir>, value_hir_id: hir::HirId, - value_life: String, + value_mutations: Vec>, } -impl<'a, 'tcx> ValueTracker<'a, 'tcx> { +impl<'a, 'hir> ValueTracker<'a, 'hir> { + fn new(cx: &'a LateContext<'hir>, value_hir_id: hir::HirId) -> Self { + Self { + cx, + value_hir_id, + value_mutations: Vec::new(), + } + } + fn is_value_expr(&self, expr_id: hir::HirId) -> bool { match self.cx.tcx.hir().find(expr_id) { Some(hir::Node::Expr(expr)) => path_to_local_id(expr, self.value_hir_id), _ => false, } } -} -impl<'a, 'tcx> Delegate<'tcx> for ValueTracker<'a, 'tcx> { - fn consume(&mut self, _place_with_id: &PlaceWithHirId<'tcx>, expr_id: hir::HirId, _: ConsumeMode) { - if self.is_value_expr(expr_id) { - // TODO xFrednet 2021-02-17: Check if lint emission and extract lint ID - todo!(); + /// This function extracts possible `ApplicabilityModifier` from an assign statement like this: + /// + /// ```rust, ignore + /// // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv The expression to process + /// let value = Applicability::MachineApplicable; + /// ``` + fn process_assign_expr(&mut self, expr: &'hir hir::Expr<'hir>) { + // This is a bit more complicated. I'll therefor settle on the simple solution of + // simplifying the cases we support. + match &expr.kind { + hir::ExprKind::Call(func_expr, ..) => { + // We only deal with resolved paths as this is the usual case. Other expression kinds like closures + // etc. are hard to track but might be a worthy improvement in the future + if let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = func_expr.kind { + self.value_mutations.push(ApplicabilityModifier::Producer(path)); + } else { + let msg = format!( + "Unsupported Call expression at: {}", + SerializableSpan::from_span(self.cx, func_expr.span) + ); + self.value_mutations.push(ApplicabilityModifier::Unknown(msg)); + } + }, + hir::ExprKind::MethodCall(..) => { + let msg = format!( + "Unsupported MethodCall expression at: {}", + SerializableSpan::from_span(self.cx, expr.span) + ); + self.value_mutations.push(ApplicabilityModifier::Unknown(msg)); + }, + // We can ignore ifs without an else block because those can't be used as an assignment + hir::ExprKind::If(_con, if_block, Some(else_block)) => { + self.process_assign_expr(if_block); + self.process_assign_expr(else_block); + }, + hir::ExprKind::Match(_expr, arms, _) => { + for arm in *arms { + self.process_assign_expr(arm.body); + } + }, + hir::ExprKind::Loop(block, ..) | hir::ExprKind::Block(block, ..) => { + if let Some(block_expr) = block.expr { + self.process_assign_expr(block_expr); + } + }, + hir::ExprKind::Path(path) => { + for enum_value in &paths::APPLICABILITY_VALUES { + if match_qpath(path, enum_value) { + self.value_mutations + .push(ApplicabilityModifier::ConstValue(enum_value[2].to_string())); + } + } + }, + // hir::ExprKind::Field(expr, ident) => not supported + // hir::ExprKind::Index(expr, expr) => not supported + _ => { + let msg = format!( + "Unexpected expression at: {}", + SerializableSpan::from_span(self.cx, expr.span) + ); + self.value_mutations.push(ApplicabilityModifier::Unknown(msg)); + }, } } +} - fn borrow(&mut self, _place_with_id: &PlaceWithHirId<'tcx>, expr_id: hir::HirId, bk: BorrowKind) { +impl<'a, 'hir> Delegate<'hir> for ValueTracker<'a, 'hir> { + fn consume(&mut self, _place_with_id: &PlaceWithHirId<'hir>, expr_id: hir::HirId, _: ConsumeMode) { if self.is_value_expr(expr_id) { - if let BorrowKind::MutBorrow = bk { - // TODO xFrednet 2021-02-17: Save the function - todo!(); + // TODO xFrednet 2021-02-17: Check if lint emission and extract lint ID + if let Some(hir::Node::Expr(expr)) = self.cx.tcx.hir().find(expr_id) { + let span = SerializableSpan::from_span(self.cx, expr.span); + log_to_file(&format!("- consume {}\n", span)); } } } - fn mutate(&mut self, _assignee_place: &PlaceWithHirId<'tcx>, expr_id: hir::HirId) { + fn borrow(&mut self, _place_with_id: &PlaceWithHirId<'hir>, expr_id: hir::HirId, bk: BorrowKind) { if self.is_value_expr(expr_id) { - // TODO xFrednet 2021-02-17: Save the new value as a mutation - todo!(); + if let BorrowKind::MutBorrow = bk { + // TODO xFrednet 2021-02-17: Save the function + if let Some(hir::Node::Expr(expr)) = self.cx.tcx.hir().find(expr_id) { + let span = SerializableSpan::from_span(self.cx, expr.span); + log_to_file(&format!("- &mut {}\n", span)); + } + } + } + } + + fn mutate(&mut self, _assignee_place: &PlaceWithHirId<'hir>, expr_id: hir::HirId) { + if_chain! { + if self.is_value_expr(expr_id); + if let Some(expr) = get_parent_expr_for_hir(self.cx, expr_id); + if let hir::ExprKind::Assign(_value_expr, assign_expr, ..) = expr.kind; + then { + self.process_assign_expr(assign_expr); + } } } } + +/// The life of a value in Rust is a true adventure. These are the corner stones of such a +/// fairy tale. Let me introduce you to the possible stepping stones a value might have in +/// in our crazy word: +#[derive(Debug)] +#[allow(dead_code)] +enum ApplicabilityModifier<'hir> { + Unknown(String), + /// A simple constant value. + /// + /// This is the actual character of a value. It's baseline. This only defines where the value + /// started. As in real life it can still change and fully decide who it wants to be. + ConstValue(String), + /// A producer is a function that returns an applicability value. + /// + /// This is the heritage of this value. This value comes from a long family tree and is not + /// just a black piece of paper. The evaluation of this stepping stone needs additional + /// context. We therefore only add a reference. This reference will later be used to ask + /// the librarian about the possible initial character that this value might have. + Producer(&'hir hir::Path<'hir>), + /// A modifier that takes the given applicability and might modify it + /// + /// What would an RPG be without it's NPCs. The special thing about modifiers is that they can + /// be actively interested in the story of the value and might make decisions based on the + /// character of this hero. This means that a modifier doesn't just force its way into the life + /// of our hero but it actually asks him how he's been. The possible modification is a result + /// of the situation. + /// + /// Take this part of our heroes life very seriously! + Modifier(&'hir hir::Path<'hir>), + /// The actual emission of a lint + /// + /// All good things must come to an end. Even the life of your awesome applicability hero. He + /// was the bravest soul that has ever wondered this earth. Songs will be written about his + /// heroic deeds. Castles will be named after him and the world how we know it will never be + /// the same! + /// + /// Is this a happy ending? Did he archive what he wanted in his life? Yes, YES, he has lived a + /// life and he will continue to live in all the lint suggestions that can be applied or just + /// displayed by Clippy. He might be no more, but his legacy will serve generations to come. + LintEmit(LintEmission), +} + +#[derive(Debug)] +struct LintEmission { + lint: String, + is_multi_line_sugg: bool, +} diff --git a/clippy_utils/src/paths.rs b/clippy_utils/src/paths.rs index 91e5cd6c046..46f58b788e6 100644 --- a/clippy_utils/src/paths.rs +++ b/clippy_utils/src/paths.rs @@ -7,6 +7,13 @@ pub const ANY_TRAIT: [&str; 3] = ["core", "any", "Any"]; #[cfg(feature = "metadata-collector-lint")] pub const APPLICABILITY: [&str; 2] = ["rustc_lint_defs", "Applicability"]; +#[cfg(feature = "metadata-collector-lint")] +pub const APPLICABILITY_VALUES: [[&str; 3]; 4] = [ + ["rustc_lint_defs", "Applicability", "MachineApplicable"], + ["rustc_lint_defs", "Applicability", "MaybeIncorrect"], + ["rustc_lint_defs", "Applicability", "HasPlaceholders"], + ["rustc_lint_defs", "Applicability", "Unspecified"], +]; pub const ARC_PTR_EQ: [&str; 4] = ["alloc", "sync", "Arc", "ptr_eq"]; pub const ASMUT_TRAIT: [&str; 3] = ["core", "convert", "AsMut"]; pub const ASREF_TRAIT: [&str; 3] = ["core", "convert", "AsRef"]; diff --git a/tests/ui-internal/metadata-collector/track_applicability_value.rs b/tests/ui-internal/metadata-collector/track_applicability_value.rs new file mode 100644 index 00000000000..75fae623e61 --- /dev/null +++ b/tests/ui-internal/metadata-collector/track_applicability_value.rs @@ -0,0 +1,46 @@ +#![deny(clippy::internal)] +#![feature(rustc_private)] + +extern crate rustc_ast; +extern crate rustc_errors; +extern crate rustc_lint; +extern crate rustc_session; +extern crate rustc_span; + +use rustc_ast::ast::Expr; +use rustc_errors::{Applicability, DiagnosticBuilder}; +use rustc_lint::{EarlyContext, EarlyLintPass, Lint, LintContext}; +use rustc_session::{declare_lint_pass, declare_tool_lint}; +use rustc_span::source_map::Span; + +fn producer_fn() -> Applicability { + Applicability::MachineApplicable +} + +fn modifier_fn(applicability: &mut Applicability) { + if let Applicability::MaybeIncorrect = applicability { + *applicability = Applicability::HasPlaceholders; + } +} + +struct Muh; + +impl Muh { + fn producer_method() -> Applicability { + Applicability::MachineApplicable + } +} + +fn main() { + let mut applicability = producer_fn(); + applicability = Applicability::MachineApplicable; + applicability = Muh::producer_method(); + + applicability = if true { + Applicability::HasPlaceholders + } else { + Applicability::MaybeIncorrect + }; + + modifier_fn(&mut applicability); +} From ee130d066d362118cd0bf756de42ee08a2bfc301 Mon Sep 17 00:00:00 2001 From: xFrednet Date: Sat, 20 Feb 2021 00:35:28 +0100 Subject: [PATCH 05/15] Metadata collection: Tracking Applicability mut borrows --- .../internal_lints/metadata_collector.rs | 57 ++++++++++++++++--- 1 file changed, 48 insertions(+), 9 deletions(-) diff --git a/clippy_lints/src/utils/internal_lints/metadata_collector.rs b/clippy_lints/src/utils/internal_lints/metadata_collector.rs index e22aa285f17..c8637531d94 100644 --- a/clippy_lints/src/utils/internal_lints/metadata_collector.rs +++ b/clippy_lints/src/utils/internal_lints/metadata_collector.rs @@ -38,7 +38,7 @@ use crate::utils::internal_lints::is_lint_ref_type; use crate::utils::{ get_enclosing_body, get_parent_expr_for_hir, last_path_segment, match_function_call, match_qpath, match_type, - path_to_local_id, paths, span_lint, walk_ptrs_ty_depth, + path_to_local_id, paths, span_lint, walk_ptrs_ty_depth, get_parent_expr }; /// This is the output file of the lint collector. @@ -478,7 +478,7 @@ fn process_assign_expr(&mut self, expr: &'hir hir::Expr<'hir>) { self.value_mutations.push(ApplicabilityModifier::Producer(path)); } else { let msg = format!( - "Unsupported Call expression at: {}", + "Unsupported assign Call expression at: {}", SerializableSpan::from_span(self.cx, func_expr.span) ); self.value_mutations.push(ApplicabilityModifier::Unknown(msg)); @@ -486,7 +486,7 @@ fn process_assign_expr(&mut self, expr: &'hir hir::Expr<'hir>) { }, hir::ExprKind::MethodCall(..) => { let msg = format!( - "Unsupported MethodCall expression at: {}", + "Unsupported assign MethodCall expression at: {}", SerializableSpan::from_span(self.cx, expr.span) ); self.value_mutations.push(ApplicabilityModifier::Unknown(msg)); @@ -518,13 +518,56 @@ fn process_assign_expr(&mut self, expr: &'hir hir::Expr<'hir>) { // hir::ExprKind::Index(expr, expr) => not supported _ => { let msg = format!( - "Unexpected expression at: {}", + "Unexpected assign expression at: {}", SerializableSpan::from_span(self.cx, expr.span) ); self.value_mutations.push(ApplicabilityModifier::Unknown(msg)); }, } } + + fn process_borrow_expr(&mut self, access_hir_id: hir::HirId) { + let borrower: &rustc_hir::Expr<'_>; + if let Some(addr_of_expr) = get_parent_expr_for_hir(self.cx, access_hir_id) { + if let Some(borrower_expr) = get_parent_expr(self.cx, addr_of_expr) { + borrower = borrower_expr + } else { + return; + } + } else { + return; + } + + match &borrower.kind { + hir::ExprKind::Call(func_expr, ..) => { + // We only deal with resolved paths as this is the usual case. Other expression kinds like closures + // etc. are hard to track but might be a worthy improvement in the future + if let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = func_expr.kind { + self.value_mutations.push(ApplicabilityModifier::Modifier(path)); + } else { + let msg = format!( + "Unsupported borrow in Call at: {}", + SerializableSpan::from_span(self.cx, func_expr.span) + ); + self.value_mutations.push(ApplicabilityModifier::Unknown(msg)); + } + }, + hir::ExprKind::MethodCall(..) => { + let msg = format!( + "Unsupported borrow in MethodCall at: {}", + SerializableSpan::from_span(self.cx, borrower.span) + ); + self.value_mutations.push(ApplicabilityModifier::Unknown(msg)); + }, + _ => { + let msg = format!( + "Unexpected borrow at: {}", + SerializableSpan::from_span(self.cx, borrower.span) + ); + self.value_mutations.push(ApplicabilityModifier::Unknown(msg)); + }, + } + } } impl<'a, 'hir> Delegate<'hir> for ValueTracker<'a, 'hir> { @@ -541,11 +584,7 @@ fn consume(&mut self, _place_with_id: &PlaceWithHirId<'hir>, expr_id: hir::HirId fn borrow(&mut self, _place_with_id: &PlaceWithHirId<'hir>, expr_id: hir::HirId, bk: BorrowKind) { if self.is_value_expr(expr_id) { if let BorrowKind::MutBorrow = bk { - // TODO xFrednet 2021-02-17: Save the function - if let Some(hir::Node::Expr(expr)) = self.cx.tcx.hir().find(expr_id) { - let span = SerializableSpan::from_span(self.cx, expr.span); - log_to_file(&format!("- &mut {}\n", span)); - } + self.process_borrow_expr(expr_id); } } } From a39912cfbbd682270b5f3d534bc69eedfaa73a7b Mon Sep 17 00:00:00 2001 From: xFrednet Date: Sat, 20 Feb 2021 13:12:30 +0100 Subject: [PATCH 06/15] Metadata collection: Some refactoring for readability --- .../internal_lints/metadata_collector.rs | 104 +++++++++--------- .../track_applicability_value.rs | 4 + 2 files changed, 57 insertions(+), 51 deletions(-) diff --git a/clippy_lints/src/utils/internal_lints/metadata_collector.rs b/clippy_lints/src/utils/internal_lints/metadata_collector.rs index c8637531d94..de94e47047b 100644 --- a/clippy_lints/src/utils/internal_lints/metadata_collector.rs +++ b/clippy_lints/src/utils/internal_lints/metadata_collector.rs @@ -37,8 +37,8 @@ use crate::utils::internal_lints::is_lint_ref_type; use crate::utils::{ - get_enclosing_body, get_parent_expr_for_hir, last_path_segment, match_function_call, match_qpath, match_type, - path_to_local_id, paths, span_lint, walk_ptrs_ty_depth, get_parent_expr + get_enclosing_body, get_parent_expr, get_parent_expr_for_hir, last_path_segment, match_function_call, match_qpath, + match_type, path_to_local_id, paths, span_lint, walk_ptrs_ty_depth, }; /// This is the output file of the lint collector. @@ -202,39 +202,19 @@ impl<'tcx> LateLintPass<'tcx> for MetadataCollector { /// ``` fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) { if_chain! { + // item validation if let ItemKind::Static(ref ty, Mutability::Not, body_id) = item.kind; if is_lint_ref_type(cx, ty); let expr = &cx.tcx.hir().body(body_id).value; if let ExprKind::AddrOf(_, _, ref inner_exp) = expr.kind; if let ExprKind::Struct(_, _, _) = inner_exp.kind; + // blacklist check + let lint_name = sym_to_string(item.ident.name).to_ascii_lowercase(); + if !BLACK_LISTED_LINTS.contains(&lint_name.as_str()); + // metadata extraction + if let Some(group) = get_lint_group_or_lint(cx, &lint_name, item); + if let Some(docs) = extract_attr_docs_or_lint(cx, item); then { - let lint_name = sym_to_string(item.ident.name).to_ascii_lowercase(); - if BLACK_LISTED_LINTS.contains(&lint_name.as_str()) { - return; - } - - let group: String; - let result = cx.lint_store.check_lint_name(lint_name.as_str(), Some(sym::clippy)); - if let CheckLintNameResult::Tool(Ok(lint_lst)) = result { - if let Some(group_some) = get_lint_group(cx, lint_lst[0]) { - group = group_some; - } else { - lint_collection_error_item(cx, item, "Unable to determine lint group"); - return; - } - } else { - lint_collection_error_item(cx, item, "Unable to find lint in lint_store"); - return; - } - - let docs: String; - if let Some(docs_some) = extract_attr_docs(item) { - docs = docs_some; - } else { - lint_collection_error_item(cx, item, "could not collect the lint documentation"); - return; - }; - self.lints.push(LintMetadata::new( lint_name, SerializableSpan::from_item(cx, item), @@ -301,7 +281,7 @@ fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx hir::Local<'tcx>) let span = SerializableSpan::from_span(cx, local.span); let local_str = crate::utils::snippet(cx, local.span, "_"); log_to_file(&format!("{} -- {}\n", local_str, span)); - + let value_hir_id = local.pat.hir_id; let mut tracker = ValueTracker::new(cx, value_hir_id); if let Some(init_expr) = local.init { @@ -342,10 +322,21 @@ fn get_local_type<'a>(cx: &'a LateContext<'_>, local: &'a hir::Local<'_>) -> Opt None } +// ================================================================== +// Lint definition extraction +// ================================================================== + fn sym_to_string(sym: Symbol) -> String { sym.as_str().to_string() } +fn extract_attr_docs_or_lint(cx: &LateContext<'_>, item: &Item<'_>) -> Option { + extract_attr_docs(item).or_else(|| { + lint_collection_error_item(cx, item, "could not collect the lint documentation"); + None + }) +} + /// This function collects all documentation that has been added to an item using /// `#[doc = r""]` attributes. Several attributes are aggravated using line breaks /// @@ -367,6 +358,19 @@ fn extract_attr_docs(item: &Item<'_>) -> Option { }) } +fn get_lint_group_or_lint(cx: &LateContext<'_>, lint_name: &str, item: &'tcx Item<'_>) -> Option { + let result = cx.lint_store.check_lint_name(lint_name, Some(sym::clippy)); + if let CheckLintNameResult::Tool(Ok(lint_lst)) = result { + get_lint_group(cx, lint_lst[0]).or_else(|| { + lint_collection_error_item(cx, item, "Unable to determine lint group"); + None + }) + } else { + lint_collection_error_item(cx, item, "Unable to find lint in lint_store"); + None + } +} + fn get_lint_group(cx: &LateContext<'_>, lint_id: LintId) -> Option { for (group_name, lints, _) in &cx.lint_store.get_lint_groups() { if lints.iter().any(|x| *x == lint_id) { @@ -526,19 +530,8 @@ fn process_assign_expr(&mut self, expr: &'hir hir::Expr<'hir>) { } } - fn process_borrow_expr(&mut self, access_hir_id: hir::HirId) { - let borrower: &rustc_hir::Expr<'_>; - if let Some(addr_of_expr) = get_parent_expr_for_hir(self.cx, access_hir_id) { - if let Some(borrower_expr) = get_parent_expr(self.cx, addr_of_expr) { - borrower = borrower_expr - } else { - return; - } - } else { - return; - } - - match &borrower.kind { + fn process_borrow_expr(&mut self, borrower_expr: &'hir rustc_hir::Expr<'hir>) { + match &borrower_expr.kind { hir::ExprKind::Call(func_expr, ..) => { // We only deal with resolved paths as this is the usual case. Other expression kinds like closures // etc. are hard to track but might be a worthy improvement in the future @@ -555,36 +548,45 @@ fn process_borrow_expr(&mut self, access_hir_id: hir::HirId) { hir::ExprKind::MethodCall(..) => { let msg = format!( "Unsupported borrow in MethodCall at: {}", - SerializableSpan::from_span(self.cx, borrower.span) + SerializableSpan::from_span(self.cx, borrower_expr.span) ); self.value_mutations.push(ApplicabilityModifier::Unknown(msg)); }, _ => { let msg = format!( "Unexpected borrow at: {}", - SerializableSpan::from_span(self.cx, borrower.span) + SerializableSpan::from_span(self.cx, borrower_expr.span) ); self.value_mutations.push(ApplicabilityModifier::Unknown(msg)); }, } } + + fn process_consume_expr(&mut self, consume_expr: &'hir rustc_hir::Expr<'hir>) { + // We are only interested in lint emissions. Other types like assignments might be + // interesting for further use or improvement but are to complex for now. + if let hir::ExprKind::Call(func_expr, ..) = &consume_expr.kind {} + } } impl<'a, 'hir> Delegate<'hir> for ValueTracker<'a, 'hir> { fn consume(&mut self, _place_with_id: &PlaceWithHirId<'hir>, expr_id: hir::HirId, _: ConsumeMode) { if self.is_value_expr(expr_id) { // TODO xFrednet 2021-02-17: Check if lint emission and extract lint ID - if let Some(hir::Node::Expr(expr)) = self.cx.tcx.hir().find(expr_id) { - let span = SerializableSpan::from_span(self.cx, expr.span); - log_to_file(&format!("- consume {}\n", span)); + if let Some(expr) = get_parent_expr_for_hir(self.cx, expr_id) { + log_to_file(&format!("- consume {:?}\n", expr)); } } } fn borrow(&mut self, _place_with_id: &PlaceWithHirId<'hir>, expr_id: hir::HirId, bk: BorrowKind) { - if self.is_value_expr(expr_id) { - if let BorrowKind::MutBorrow = bk { - self.process_borrow_expr(expr_id); + if_chain! { + if self.is_value_expr(expr_id); + if let BorrowKind::MutBorrow = bk; + if let Some(addr_of_expr) = get_parent_expr_for_hir(self.cx, expr_id); + if let Some(borrower_expr) = get_parent_expr(self.cx, addr_of_expr); + then { + self.process_borrow_expr(borrower_expr); } } } diff --git a/tests/ui-internal/metadata-collector/track_applicability_value.rs b/tests/ui-internal/metadata-collector/track_applicability_value.rs index 75fae623e61..b0f59e5cf8a 100644 --- a/tests/ui-internal/metadata-collector/track_applicability_value.rs +++ b/tests/ui-internal/metadata-collector/track_applicability_value.rs @@ -23,6 +23,8 @@ fn modifier_fn(applicability: &mut Applicability) { } } +fn consumer_fn(_applicability: Applicability) {} + struct Muh; impl Muh { @@ -43,4 +45,6 @@ fn main() { }; modifier_fn(&mut applicability); + + consumer_fn(applicability); } From ee8a99a1140880e10677fa0b03167cd364fece3f Mon Sep 17 00:00:00 2001 From: xFrednet Date: Sat, 20 Feb 2021 13:50:09 +0100 Subject: [PATCH 07/15] Metadata collection: Collecting Applicability assign values --- clippy_lints/Cargo.toml | 2 +- .../internal_lints/metadata_collector.rs | 365 ++++-------------- clippy_utils/Cargo.toml | 1 + clippy_utils/src/lib.rs | 8 +- 4 files changed, 75 insertions(+), 301 deletions(-) diff --git a/clippy_lints/Cargo.toml b/clippy_lints/Cargo.toml index d1d56fc84f9..42218c2c00a 100644 --- a/clippy_lints/Cargo.toml +++ b/clippy_lints/Cargo.toml @@ -33,7 +33,7 @@ url = { version = "2.1.0", features = ["serde"] } deny-warnings = [] # build clippy with internal lints enabled, off by default internal-lints = ["clippy_utils/internal-lints"] -metadata-collector-lint = ["serde_json"] +metadata-collector-lint = ["serde_json", "clippy_utils/metadata-collector-lint"] [package.metadata.rust-analyzer] # This crate uses #[feature(rustc_private)] diff --git a/clippy_lints/src/utils/internal_lints/metadata_collector.rs b/clippy_lints/src/utils/internal_lints/metadata_collector.rs index de94e47047b..a16f7c2ea5e 100644 --- a/clippy_lints/src/utils/internal_lints/metadata_collector.rs +++ b/clippy_lints/src/utils/internal_lints/metadata_collector.rs @@ -21,15 +21,11 @@ // - TODO xFrednet 2021-02-13: Collect depreciations and maybe renames use if_chain::if_chain; -use rustc_data_structures::fx::{FxHashMap, FxHashSet}; +use rustc_data_structures::fx::FxHashMap; use rustc_hir::{self as hir, ExprKind, Item, ItemKind, Mutability}; use rustc_lint::{CheckLintNameResult, LateContext, LateLintPass, LintContext, LintId}; -use rustc_middle::ty::{BorrowKind, Ty}; use rustc_session::{declare_tool_lint, impl_lint_pass}; use rustc_span::{sym, Loc, Span, Symbol}; -use rustc_trait_selection::infer::TyCtxtInferExt; -use rustc_typeck::expr_use_visitor::{ConsumeMode, Delegate, ExprUseVisitor, PlaceWithHirId}; -use rustc_typeck::hir_ty_to_ty; use serde::Serialize; use std::fs::{self, OpenOptions}; use std::io::prelude::*; @@ -37,8 +33,7 @@ use crate::utils::internal_lints::is_lint_ref_type; use crate::utils::{ - get_enclosing_body, get_parent_expr, get_parent_expr_for_hir, last_path_segment, match_function_call, match_qpath, - match_type, path_to_local_id, paths, span_lint, walk_ptrs_ty_depth, + last_path_segment, match_function_call, match_type, paths, span_lint, walk_ptrs_ty_depth, match_path, }; /// This is the output file of the lint collector. @@ -50,11 +45,11 @@ // handling #[rustfmt::skip] const LINT_EMISSION_FUNCTIONS: [&[&str]; 5] = [ - &["clippy_lints", "utils", "diagnostics", "span_lint"], - &["clippy_lints", "utils", "diagnostics", "span_lint_and_help"], - &["clippy_lints", "utils", "diagnostics", "span_lint_and_note"], - &["clippy_lints", "utils", "diagnostics", "span_lint_hir"], - &["clippy_lints", "utils", "diagnostics", "span_lint_and_sugg"], + &["clippy_utils", "diagnostics", "span_lint"], + &["clippy_utils", "diagnostics", "span_lint_and_help"], + &["clippy_utils", "diagnostics", "span_lint_and_note"], + &["clippy_utils", "diagnostics", "span_lint_hir"], + &["clippy_utils", "diagnostics", "span_lint_and_sugg"], ]; declare_clippy_lint! { @@ -175,10 +170,10 @@ struct ApplicabilityInfo { /// [rustfix#141](https://github.com/rust-lang/rustfix/issues/141) as such suggestions can /// currently not be applied automatically. has_multi_suggestion: bool, - /// These are all the available applicability values for the lint suggestions - applicabilities: FxHashSet, + applicability: Option, } +#[allow(dead_code)] fn log_to_file(msg: &str) { let mut file = OpenOptions::new() .write(true) @@ -190,7 +185,7 @@ fn log_to_file(msg: &str) { write!(file, "{}", msg).unwrap(); } -impl<'tcx> LateLintPass<'tcx> for MetadataCollector { +impl<'hir> LateLintPass<'hir> for MetadataCollector { /// Collecting lint declarations like: /// ```rust, ignore /// declare_clippy_lint! { @@ -200,7 +195,7 @@ impl<'tcx> LateLintPass<'tcx> for MetadataCollector { /// "Who am I?" /// } /// ``` - fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) { + fn check_item(&mut self, cx: &LateContext<'hir>, item: &'hir Item<'_>) { if_chain! { // item validation if let ItemKind::Static(ref ty, Mutability::Not, body_id) = item.kind; @@ -239,87 +234,16 @@ fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) { /// Applicability::MachineApplicable, // <-- Extracts this constant value /// ); /// ``` - fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) { + fn check_expr(&mut self, cx: &LateContext<'hir>, expr: &'hir hir::Expr<'_>) { if let Some(args) = match_simple_lint_emission(cx, expr) { - if let Some((lint_name, mut applicability)) = extract_emission_info(cx, args) { + if let Some((lint_name, applicability)) = extract_emission_info(cx, args) { let app_info = self.applicability_into.entry(lint_name).or_default(); - applicability.drain(..).for_each(|x| { - app_info.applicabilities.insert(x); - }); + app_info.applicability = applicability; } else { lint_collection_error_span(cx, expr.span, "I found this but I can't get the lint or applicability"); } } } - - /// Tracking and hopefully collecting dynamic applicability values - /// - /// Example: - /// ```rust, ignore - /// // vvv Applicability value to track - /// let mut applicability = Applicability::MachineApplicable; - /// // vvv Value Mutation - /// let suggestion = snippet_with_applicability(cx, expr.span, "_", &mut applicability); - /// // vvv Emission to link the value to the lint - /// span_lint_and_sugg( - /// cx, - /// SOME_LINT, - /// expr.span, - /// "This can be improved", - /// "try", - /// suggestion, - /// applicability, - /// ); - /// ``` - fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx hir::Local<'tcx>) { - if_chain! { - if let Some(local_ty) = get_local_type(cx, local); - if match_type(cx, local_ty, &paths::APPLICABILITY); - if let Some(body) = get_enclosing_body(cx, local.hir_id); - then { - // TODO xFrednet: 2021-02-19: Remove debug code - let span = SerializableSpan::from_span(cx, local.span); - let local_str = crate::utils::snippet(cx, local.span, "_"); - log_to_file(&format!("{} -- {}\n", local_str, span)); - - let value_hir_id = local.pat.hir_id; - let mut tracker = ValueTracker::new(cx, value_hir_id); - if let Some(init_expr) = local.init { - tracker.process_assign_expr(init_expr) - } - - // TODO xFrednet 2021-02-18: Support nested bodies - // Note: The `ExprUseVisitor` only searches though one body, this means that values - // references in nested bodies like closures are not found by this simple visitor. - cx.tcx.infer_ctxt().enter(|infcx| { - let body_owner_id = cx.tcx.hir().body_owner_def_id(body.id()); - ExprUseVisitor::new( - &mut tracker, - &infcx, - body_owner_id, - cx.param_env, - cx.typeck_results() - ) - .consume_body(body); - }); - - log_to_file(&format!("{:?}\n", tracker.value_mutations)); - } - } - } -} - -fn get_local_type<'a>(cx: &'a LateContext<'_>, local: &'a hir::Local<'_>) -> Option> { - // TODO xFrednet 2021-02-14: support nested applicability (only in tuples) - if let Some(tc) = cx.maybe_typeck_results() { - if let Some(ty) = local.ty { - return Some(hir_ty_to_ty(cx.tcx, ty)); - } else if let Some(init) = local.init { - return Some(tc.expr_ty(init)); - } - } - - None } // ================================================================== @@ -358,7 +282,7 @@ fn extract_attr_docs(item: &Item<'_>) -> Option { }) } -fn get_lint_group_or_lint(cx: &LateContext<'_>, lint_name: &str, item: &'tcx Item<'_>) -> Option { +fn get_lint_group_or_lint(cx: &LateContext<'_>, lint_name: &str, item: &'hir Item<'_>) -> Option { let result = cx.lint_store.check_lint_name(lint_name, Some(sym::clippy)); if let CheckLintNameResult::Tool(Ok(lint_lst)) = result { get_lint_group(cx, lint_lst[0]).or_else(|| { @@ -405,17 +329,19 @@ fn lint_collection_error_span(cx: &LateContext<'_>, span: Span, message: &str) { // ================================================================== // Applicability // ================================================================== -fn match_simple_lint_emission<'tcx>( - cx: &LateContext<'tcx>, - expr: &'tcx hir::Expr<'_>, -) -> Option<&'tcx [hir::Expr<'tcx>]> { +/// This function checks if a given expression is equal to a simple lint emission function call. +/// It will return the function arguments if the emission matched any function. +fn match_simple_lint_emission<'hir>( + cx: &LateContext<'hir>, + expr: &'hir hir::Expr<'_>, +) -> Option<&'hir [hir::Expr<'hir>]> { LINT_EMISSION_FUNCTIONS .iter() .find_map(|emission_fn| match_function_call(cx, expr, emission_fn)) } /// This returns the lint name and the possible applicability of this emission -fn extract_emission_info<'tcx>(cx: &LateContext<'tcx>, args: &[hir::Expr<'_>]) -> Option<(String, Vec)> { +fn extract_emission_info<'hir>(cx: &LateContext<'hir>, args: &[hir::Expr<'_>]) -> Option<(String, Option)> { let mut lint_name = None; let mut applicability = None; @@ -425,228 +351,69 @@ fn extract_emission_info<'tcx>(cx: &LateContext<'tcx>, args: &[hir::Expr<'_>]) - if match_type(cx, arg_ty, &paths::LINT) { // If we found the lint arg, extract the lint name if let ExprKind::Path(ref lint_path) = arg.kind { - lint_name = Some(last_path_segment(lint_path).ident.name) + lint_name = Some(last_path_segment(lint_path).ident.name); } } else if match_type(cx, arg_ty, &paths::APPLICABILITY) { - if let ExprKind::Path(ref path) = arg.kind { - applicability = Some(last_path_segment(path).ident.name) - } + applicability = resolve_applicability(cx, arg); } } lint_name.map(|lint_name| { ( sym_to_string(lint_name).to_ascii_lowercase(), - applicability.map(sym_to_string).map_or_else(Vec::new, |x| vec![x]), + applicability, ) }) } -#[allow(dead_code)] -struct ValueTracker<'a, 'hir> { - cx: &'a LateContext<'hir>, - value_hir_id: hir::HirId, - value_mutations: Vec>, -} - -impl<'a, 'hir> ValueTracker<'a, 'hir> { - fn new(cx: &'a LateContext<'hir>, value_hir_id: hir::HirId) -> Self { - Self { - cx, - value_hir_id, - value_mutations: Vec::new(), - } - } - - fn is_value_expr(&self, expr_id: hir::HirId) -> bool { - match self.cx.tcx.hir().find(expr_id) { - Some(hir::Node::Expr(expr)) => path_to_local_id(expr, self.value_hir_id), - _ => false, - } - } - - /// This function extracts possible `ApplicabilityModifier` from an assign statement like this: - /// - /// ```rust, ignore - /// // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv The expression to process - /// let value = Applicability::MachineApplicable; - /// ``` - fn process_assign_expr(&mut self, expr: &'hir hir::Expr<'hir>) { - // This is a bit more complicated. I'll therefor settle on the simple solution of - // simplifying the cases we support. - match &expr.kind { - hir::ExprKind::Call(func_expr, ..) => { - // We only deal with resolved paths as this is the usual case. Other expression kinds like closures - // etc. are hard to track but might be a worthy improvement in the future - if let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = func_expr.kind { - self.value_mutations.push(ApplicabilityModifier::Producer(path)); - } else { - let msg = format!( - "Unsupported assign Call expression at: {}", - SerializableSpan::from_span(self.cx, func_expr.span) - ); - self.value_mutations.push(ApplicabilityModifier::Unknown(msg)); +fn resolve_applicability(cx: &LateContext<'hir>, expr: &hir::Expr<'_>) -> Option { + match expr.kind { + // We can ignore ifs without an else block because those can't be used as an assignment + hir::ExprKind::If(_con, _if_block, Some(_else_block)) => { + // self.process_assign_expr(if_block); + // self.process_assign_expr(else_block); + return Some("TODO IF EXPR".to_string()); + }, + hir::ExprKind::Match(_expr, _arms, _) => { + // for arm in *arms { + // self.process_assign_expr(arm.body); + // } + return Some("TODO MATCH EXPR".to_string()); + }, + hir::ExprKind::Loop(block, ..) | hir::ExprKind::Block(block, ..) => { + if let Some(block_expr) = block.expr { + return resolve_applicability(cx, block_expr); + } + }, + ExprKind::Path(hir::QPath::Resolved(_, path)) => { + // direct applicabilities are simple: + for enum_value in &paths::APPLICABILITY_VALUES { + if match_path(path, enum_value) { + return Some(enum_value[2].to_string()); } - }, - hir::ExprKind::MethodCall(..) => { - let msg = format!( - "Unsupported assign MethodCall expression at: {}", - SerializableSpan::from_span(self.cx, expr.span) - ); - self.value_mutations.push(ApplicabilityModifier::Unknown(msg)); - }, - // We can ignore ifs without an else block because those can't be used as an assignment - hir::ExprKind::If(_con, if_block, Some(else_block)) => { - self.process_assign_expr(if_block); - self.process_assign_expr(else_block); - }, - hir::ExprKind::Match(_expr, arms, _) => { - for arm in *arms { - self.process_assign_expr(arm.body); - } - }, - hir::ExprKind::Loop(block, ..) | hir::ExprKind::Block(block, ..) => { - if let Some(block_expr) = block.expr { - self.process_assign_expr(block_expr); - } - }, - hir::ExprKind::Path(path) => { - for enum_value in &paths::APPLICABILITY_VALUES { - if match_qpath(path, enum_value) { - self.value_mutations - .push(ApplicabilityModifier::ConstValue(enum_value[2].to_string())); + } + + // Values yay + if let hir::def::Res::Local(local_hir) = path.res { + if let Some(local) = get_parent_local(cx, local_hir) { + if let Some(local_init) = local.init { + return resolve_applicability(cx, local_init); } } - }, - // hir::ExprKind::Field(expr, ident) => not supported - // hir::ExprKind::Index(expr, expr) => not supported - _ => { - let msg = format!( - "Unexpected assign expression at: {}", - SerializableSpan::from_span(self.cx, expr.span) - ); - self.value_mutations.push(ApplicabilityModifier::Unknown(msg)); - }, - } - } - - fn process_borrow_expr(&mut self, borrower_expr: &'hir rustc_hir::Expr<'hir>) { - match &borrower_expr.kind { - hir::ExprKind::Call(func_expr, ..) => { - // We only deal with resolved paths as this is the usual case. Other expression kinds like closures - // etc. are hard to track but might be a worthy improvement in the future - if let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = func_expr.kind { - self.value_mutations.push(ApplicabilityModifier::Modifier(path)); - } else { - let msg = format!( - "Unsupported borrow in Call at: {}", - SerializableSpan::from_span(self.cx, func_expr.span) - ); - self.value_mutations.push(ApplicabilityModifier::Unknown(msg)); - } - }, - hir::ExprKind::MethodCall(..) => { - let msg = format!( - "Unsupported borrow in MethodCall at: {}", - SerializableSpan::from_span(self.cx, borrower_expr.span) - ); - self.value_mutations.push(ApplicabilityModifier::Unknown(msg)); - }, - _ => { - let msg = format!( - "Unexpected borrow at: {}", - SerializableSpan::from_span(self.cx, borrower_expr.span) - ); - self.value_mutations.push(ApplicabilityModifier::Unknown(msg)); - }, - } - } - - fn process_consume_expr(&mut self, consume_expr: &'hir rustc_hir::Expr<'hir>) { - // We are only interested in lint emissions. Other types like assignments might be - // interesting for further use or improvement but are to complex for now. - if let hir::ExprKind::Call(func_expr, ..) = &consume_expr.kind {} - } -} - -impl<'a, 'hir> Delegate<'hir> for ValueTracker<'a, 'hir> { - fn consume(&mut self, _place_with_id: &PlaceWithHirId<'hir>, expr_id: hir::HirId, _: ConsumeMode) { - if self.is_value_expr(expr_id) { - // TODO xFrednet 2021-02-17: Check if lint emission and extract lint ID - if let Some(expr) = get_parent_expr_for_hir(self.cx, expr_id) { - log_to_file(&format!("- consume {:?}\n", expr)); } } + _ => {} } - fn borrow(&mut self, _place_with_id: &PlaceWithHirId<'hir>, expr_id: hir::HirId, bk: BorrowKind) { - if_chain! { - if self.is_value_expr(expr_id); - if let BorrowKind::MutBorrow = bk; - if let Some(addr_of_expr) = get_parent_expr_for_hir(self.cx, expr_id); - if let Some(borrower_expr) = get_parent_expr(self.cx, addr_of_expr); - then { - self.process_borrow_expr(borrower_expr); - } - } + + Some("TODO".to_string()) +} + +fn get_parent_local(cx: &LateContext<'hir>, hir_id: hir::HirId) -> Option<&'hir hir::Local<'hir>> { + let map = cx.tcx.hir(); + if let Some(hir::Node::Local(local)) = map.find(map.get_parent_node(hir_id)) { + return Some(local); } - fn mutate(&mut self, _assignee_place: &PlaceWithHirId<'hir>, expr_id: hir::HirId) { - if_chain! { - if self.is_value_expr(expr_id); - if let Some(expr) = get_parent_expr_for_hir(self.cx, expr_id); - if let hir::ExprKind::Assign(_value_expr, assign_expr, ..) = expr.kind; - then { - self.process_assign_expr(assign_expr); - } - } - } -} - -/// The life of a value in Rust is a true adventure. These are the corner stones of such a -/// fairy tale. Let me introduce you to the possible stepping stones a value might have in -/// in our crazy word: -#[derive(Debug)] -#[allow(dead_code)] -enum ApplicabilityModifier<'hir> { - Unknown(String), - /// A simple constant value. - /// - /// This is the actual character of a value. It's baseline. This only defines where the value - /// started. As in real life it can still change and fully decide who it wants to be. - ConstValue(String), - /// A producer is a function that returns an applicability value. - /// - /// This is the heritage of this value. This value comes from a long family tree and is not - /// just a black piece of paper. The evaluation of this stepping stone needs additional - /// context. We therefore only add a reference. This reference will later be used to ask - /// the librarian about the possible initial character that this value might have. - Producer(&'hir hir::Path<'hir>), - /// A modifier that takes the given applicability and might modify it - /// - /// What would an RPG be without it's NPCs. The special thing about modifiers is that they can - /// be actively interested in the story of the value and might make decisions based on the - /// character of this hero. This means that a modifier doesn't just force its way into the life - /// of our hero but it actually asks him how he's been. The possible modification is a result - /// of the situation. - /// - /// Take this part of our heroes life very seriously! - Modifier(&'hir hir::Path<'hir>), - /// The actual emission of a lint - /// - /// All good things must come to an end. Even the life of your awesome applicability hero. He - /// was the bravest soul that has ever wondered this earth. Songs will be written about his - /// heroic deeds. Castles will be named after him and the world how we know it will never be - /// the same! - /// - /// Is this a happy ending? Did he archive what he wanted in his life? Yes, YES, he has lived a - /// life and he will continue to live in all the lint suggestions that can be applied or just - /// displayed by Clippy. He might be no more, but his legacy will serve generations to come. - LintEmit(LintEmission), -} - -#[derive(Debug)] -struct LintEmission { - lint: String, - is_multi_line_sugg: bool, + None } diff --git a/clippy_utils/Cargo.toml b/clippy_utils/Cargo.toml index d04c5f889dd..6e158c8ce72 100644 --- a/clippy_utils/Cargo.toml +++ b/clippy_utils/Cargo.toml @@ -15,6 +15,7 @@ rustc-semver="1.1.0" [features] internal-lints = [] +metadata-collector-lint = [] [package.metadata.rust-analyzer] # This crate uses #[feature(rustc_private)] diff --git a/clippy_utils/src/lib.rs b/clippy_utils/src/lib.rs index 94eade0c932..d4bc42657f4 100644 --- a/clippy_utils/src/lib.rs +++ b/clippy_utils/src/lib.rs @@ -821,7 +821,13 @@ pub fn get_parent_node(tcx: TyCtxt<'_>, id: HirId) -> Option> { /// Gets the parent expression, if any –- this is useful to constrain a lint. pub fn get_parent_expr<'tcx>(cx: &LateContext<'tcx>, e: &Expr<'_>) -> Option<&'tcx Expr<'tcx>> { - match get_parent_node(cx.tcx, e.hir_id) { + get_parent_expr_for_hir(cx, e.hir_id) +} + +/// This retrieves the parent for the given `HirId` if it's an expression. This is useful for +/// constraint lints +pub fn get_parent_expr_for_hir<'tcx>(cx: &LateContext<'tcx>, hir_id: hir::HirId) -> Option<&'tcx Expr<'tcx>> { + match get_parent_node(cx.tcx, hir_id) { Some(Node::Expr(parent)) => Some(parent), _ => None, } From 5830fa7c6064480863d1f90513c0c9b05630a9d3 Mon Sep 17 00:00:00 2001 From: xFrednet Date: Sat, 27 Feb 2021 18:39:02 +0100 Subject: [PATCH 08/15] Metadata Collection: Collecting direct emission applicabilities (324/455) --- .../internal_lints/metadata_collector.rs | 128 +++++++++++++----- 1 file changed, 94 insertions(+), 34 deletions(-) diff --git a/clippy_lints/src/utils/internal_lints/metadata_collector.rs b/clippy_lints/src/utils/internal_lints/metadata_collector.rs index a16f7c2ea5e..964ddb36e26 100644 --- a/clippy_lints/src/utils/internal_lints/metadata_collector.rs +++ b/clippy_lints/src/utils/internal_lints/metadata_collector.rs @@ -14,16 +14,19 @@ //! - [ ] TODO The Applicability for each lint for [#4310](https://github.com/rust-lang/rust-clippy/issues/4310) // # Applicability -// - TODO xFrednet 2021-01-17: Find all methods that take and modify applicability or predefine -// them? // - TODO xFrednet 2021-01-17: Find lint emit and collect applicability +// - TODO xFrednet 2021-02-27: Link applicability from function parameters +// - (Examples: suspicious_operation_groupings:267, needless_bool.rs:311) +// - TODO xFrednet 2021-02-27: Tuple if let thingy +// - (Examples: unused_unit.rs:140, misc.rs:694) // # NITs // - TODO xFrednet 2021-02-13: Collect depreciations and maybe renames use if_chain::if_chain; use rustc_data_structures::fx::FxHashMap; -use rustc_hir::{self as hir, ExprKind, Item, ItemKind, Mutability}; +use rustc_hir::{self as hir, intravisit, ExprKind, Item, ItemKind, Mutability}; use rustc_lint::{CheckLintNameResult, LateContext, LateLintPass, LintContext, LintId}; +use rustc_middle::hir::map::Map; use rustc_session::{declare_tool_lint, impl_lint_pass}; use rustc_span::{sym, Loc, Span, Symbol}; use serde::Serialize; @@ -33,13 +36,15 @@ use crate::utils::internal_lints::is_lint_ref_type; use crate::utils::{ - last_path_segment, match_function_call, match_type, paths, span_lint, walk_ptrs_ty_depth, match_path, + last_path_segment, match_function_call, match_path, match_type, paths, span_lint, walk_ptrs_ty_depth, }; /// This is the output file of the lint collector. const OUTPUT_FILE: &str = "metadata_collection.json"; /// These lints are excluded from the export. const BLACK_LISTED_LINTS: [&str; 2] = ["lint_author", "deep_code_inspection"]; +/// These groups will be ignored by the lint group matcher +const BLACK_LISTED_LINT_GROUP: [&str; 1] = ["clippy::all"]; // TODO xFrednet 2021-02-15: `span_lint_and_then` & `span_lint_hir_and_then` requires special // handling @@ -52,6 +57,9 @@ &["clippy_utils", "diagnostics", "span_lint_and_sugg"], ]; +/// The index of the applicability name of `paths::APPLICABILITY_VALUES` +const APPLICABILITY_NAME_INDEX: usize = 2; + declare_clippy_lint! { /// **What it does:** Collects metadata about clippy lints for the website. /// @@ -297,6 +305,10 @@ fn get_lint_group_or_lint(cx: &LateContext<'_>, lint_name: &str, item: &'hir Ite fn get_lint_group(cx: &LateContext<'_>, lint_id: LintId) -> Option { for (group_name, lints, _) in &cx.lint_store.get_lint_groups() { + if BLACK_LISTED_LINT_GROUP.contains(group_name) { + continue; + } + if lints.iter().any(|x| *x == lint_id) { return Some((*group_name).to_string()); } @@ -341,7 +353,10 @@ fn match_simple_lint_emission<'hir>( } /// This returns the lint name and the possible applicability of this emission -fn extract_emission_info<'hir>(cx: &LateContext<'hir>, args: &[hir::Expr<'_>]) -> Option<(String, Option)> { +fn extract_emission_info<'hir>( + cx: &LateContext<'hir>, + args: &'hir [hir::Expr<'hir>], +) -> Option<(String, Option)> { let mut lint_name = None; let mut applicability = None; @@ -358,41 +373,38 @@ fn extract_emission_info<'hir>(cx: &LateContext<'hir>, args: &[hir::Expr<'_>]) - } } - lint_name.map(|lint_name| { - ( - sym_to_string(lint_name).to_ascii_lowercase(), - applicability, - ) - }) + lint_name.map(|lint_name| (sym_to_string(lint_name).to_ascii_lowercase(), applicability)) } -fn resolve_applicability(cx: &LateContext<'hir>, expr: &hir::Expr<'_>) -> Option { +/// This function tries to resolve the linked applicability to the given expression. +fn resolve_applicability(cx: &LateContext<'hir>, expr: &'hir hir::Expr<'hir>) -> Option { match expr.kind { // We can ignore ifs without an else block because those can't be used as an assignment - hir::ExprKind::If(_con, _if_block, Some(_else_block)) => { - // self.process_assign_expr(if_block); - // self.process_assign_expr(else_block); - return Some("TODO IF EXPR".to_string()); + hir::ExprKind::If(_con, if_block, Some(else_block)) => { + let mut visitor = ApplicabilityVisitor::new(cx); + intravisit::walk_expr(&mut visitor, if_block); + intravisit::walk_expr(&mut visitor, else_block); + visitor.complete() }, - hir::ExprKind::Match(_expr, _arms, _) => { - // for arm in *arms { - // self.process_assign_expr(arm.body); - // } - return Some("TODO MATCH EXPR".to_string()); + hir::ExprKind::Match(_expr, arms, _) => { + let mut visitor = ApplicabilityVisitor::new(cx); + arms.iter() + .for_each(|arm| intravisit::walk_expr(&mut visitor, arm.body)); + visitor.complete() }, hir::ExprKind::Loop(block, ..) | hir::ExprKind::Block(block, ..) => { - if let Some(block_expr) = block.expr { - return resolve_applicability(cx, block_expr); - } + let mut visitor = ApplicabilityVisitor::new(cx); + intravisit::walk_block(&mut visitor, block); + visitor.complete() }, ExprKind::Path(hir::QPath::Resolved(_, path)) => { // direct applicabilities are simple: for enum_value in &paths::APPLICABILITY_VALUES { if match_path(path, enum_value) { - return Some(enum_value[2].to_string()); + return Some(enum_value[APPLICABILITY_NAME_INDEX].to_string()); } } - + // Values yay if let hir::def::Res::Local(local_hir) = path.res { if let Some(local) = get_parent_local(cx, local_hir) { @@ -401,19 +413,67 @@ fn resolve_applicability(cx: &LateContext<'hir>, expr: &hir::Expr<'_>) -> Option } } } - } - _ => {} + + // This is true for paths that are linked to function parameters. They might be a bit more work so + // not today :) + None + }, + _ => None, } - - - Some("TODO".to_string()) } fn get_parent_local(cx: &LateContext<'hir>, hir_id: hir::HirId) -> Option<&'hir hir::Local<'hir>> { let map = cx.tcx.hir(); - if let Some(hir::Node::Local(local)) = map.find(map.get_parent_node(hir_id)) { - return Some(local); + + match map.find(map.get_parent_node(hir_id)) { + Some(hir::Node::Local(local)) => Some(local), + Some(hir::Node::Pat(pattern)) => get_parent_local(cx, pattern.hir_id), + _ => None, + } +} + +/// This visitor finds the highest applicability value in the visited expressions +struct ApplicabilityVisitor<'a, 'hir> { + cx: &'a LateContext<'hir>, + /// This is the index of hightest `Applicability` for + /// `clippy_utils::paths::APPLICABILITY_VALUES` + applicability_index: Option, +} + +impl<'a, 'hir> ApplicabilityVisitor<'a, 'hir> { + fn new(cx: &'a LateContext<'hir>) -> Self { + Self { + cx, + applicability_index: None, + } } - None + fn add_new_index(&mut self, new_index: usize) { + self.applicability_index = self + .applicability_index + .map_or(new_index, |old_index| old_index.min(new_index)) + .into(); + } + + fn complete(self) -> Option { + self.applicability_index + .map(|index| paths::APPLICABILITY_VALUES[index][APPLICABILITY_NAME_INDEX].to_string()) + } +} + +impl<'a, 'hir> intravisit::Visitor<'hir> for ApplicabilityVisitor<'a, 'hir> { + type Map = Map<'hir>; + + fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap { + intravisit::NestedVisitorMap::All(self.cx.tcx.hir()) + } + + fn visit_path(&mut self, path: &hir::Path<'_>, _id: hir::HirId) { + for (index, enum_value) in paths::APPLICABILITY_VALUES.iter().enumerate() { + if match_path(path, enum_value) { + self.add_new_index(index); + break; + } + } + } } From 6658db1044bbd19e70bfbf1b74b39bd16d3c4a2c Mon Sep 17 00:00:00 2001 From: xFrednet Date: Sun, 28 Feb 2021 16:11:45 +0100 Subject: [PATCH 09/15] Metadata collection: processing emission closures (417/455) --- .../src/slow_vector_initialization.rs | 20 +- .../internal_lints/metadata_collector.rs | 197 ++++++++++++++++-- clippy_utils/src/paths.rs | 2 + 3 files changed, 190 insertions(+), 29 deletions(-) diff --git a/clippy_lints/src/slow_vector_initialization.rs b/clippy_lints/src/slow_vector_initialization.rs index 191781be000..5a51e1141fb 100644 --- a/clippy_lints/src/slow_vector_initialization.rs +++ b/clippy_lints/src/slow_vector_initialization.rs @@ -157,26 +157,16 @@ fn lint_initialization<'tcx>( vec_alloc: &VecAllocation<'_>, ) { match initialization { - InitializationType::Extend(e) | InitializationType::Resize(e) => Self::emit_lint( - cx, - e, - vec_alloc, - "slow zero-filling initialization", - SLOW_VECTOR_INITIALIZATION, - ), + InitializationType::Extend(e) | InitializationType::Resize(e) => { + Self::emit_lint(cx, e, vec_alloc, "slow zero-filling initialization") + }, }; } - fn emit_lint<'tcx>( - cx: &LateContext<'tcx>, - slow_fill: &Expr<'_>, - vec_alloc: &VecAllocation<'_>, - msg: &str, - lint: &'static Lint, - ) { + fn emit_lint<'tcx>(cx: &LateContext<'tcx>, slow_fill: &Expr<'_>, vec_alloc: &VecAllocation<'_>, msg: &str) { let len_expr = Sugg::hir(cx, vec_alloc.len_expr, "len"); - span_lint_and_then(cx, lint, slow_fill.span, msg, |diag| { + span_lint_and_then(cx, SLOW_VECTOR_INITIALIZATION, slow_fill.span, msg, |diag| { diag.span_suggestion( vec_alloc.allocation_expr.span, "consider replace allocation with", diff --git a/clippy_lints/src/utils/internal_lints/metadata_collector.rs b/clippy_lints/src/utils/internal_lints/metadata_collector.rs index 964ddb36e26..20bd2a669aa 100644 --- a/clippy_lints/src/utils/internal_lints/metadata_collector.rs +++ b/clippy_lints/src/utils/internal_lints/metadata_collector.rs @@ -15,16 +15,25 @@ // # Applicability // - TODO xFrednet 2021-01-17: Find lint emit and collect applicability -// - TODO xFrednet 2021-02-27: Link applicability from function parameters -// - (Examples: suspicious_operation_groupings:267, needless_bool.rs:311) -// - TODO xFrednet 2021-02-27: Tuple if let thingy -// - (Examples: unused_unit.rs:140, misc.rs:694) +// - TODO xFrednet 2021-02-28: 1x reference to closure +// - See clippy_lints/src/needless_pass_by_value.rs@NeedlessPassByValue::check_fn +// - TODO xFrednet 2021-02-28: 4x weird emission forwarding +// - See clippy_lints/src/enum_variants.rs@EnumVariantNames::check_name +// - TODO xFrednet 2021-02-28: 6x emission forwarding with local that is initializes from +// function. +// - See clippy_lints/src/methods/mod.rs@lint_binary_expr_with_method_call +// - TODO xFrednet 2021-02-28: 2x lint from local from function call +// - See clippy_lints/src/misc.rs@check_binary +// - TODO xFrednet 2021-02-28: 2x lint from local from method call +// - See clippy_lints/src/non_copy_const.rs@lint +// - TODO xFrednet 2021-02-28: 20x lint from local +// - See clippy_lints/src/map_unit_fn.rs@lint_map_unit_fn // # NITs // - TODO xFrednet 2021-02-13: Collect depreciations and maybe renames use if_chain::if_chain; use rustc_data_structures::fx::FxHashMap; -use rustc_hir::{self as hir, intravisit, ExprKind, Item, ItemKind, Mutability}; +use rustc_hir::{self as hir, intravisit, ExprKind, Item, ItemKind, Mutability, QPath}; use rustc_lint::{CheckLintNameResult, LateContext, LateLintPass, LintContext, LintId}; use rustc_middle::hir::map::Map; use rustc_session::{declare_tool_lint, impl_lint_pass}; @@ -44,18 +53,36 @@ /// These lints are excluded from the export. const BLACK_LISTED_LINTS: [&str; 2] = ["lint_author", "deep_code_inspection"]; /// These groups will be ignored by the lint group matcher -const BLACK_LISTED_LINT_GROUP: [&str; 1] = ["clippy::all"]; +const BLACK_LISTED_LINT_GROUP: [&str; 1] = ["clippy::all", "clippy::internal"]; // TODO xFrednet 2021-02-15: `span_lint_and_then` & `span_lint_hir_and_then` requires special // handling -#[rustfmt::skip] -const LINT_EMISSION_FUNCTIONS: [&[&str]; 5] = [ +const SIMPLE_LINT_EMISSION_FUNCTIONS: [&[&str]; 5] = [ &["clippy_utils", "diagnostics", "span_lint"], &["clippy_utils", "diagnostics", "span_lint_and_help"], &["clippy_utils", "diagnostics", "span_lint_and_note"], &["clippy_utils", "diagnostics", "span_lint_hir"], &["clippy_utils", "diagnostics", "span_lint_and_sugg"], ]; +const COMPLEX_LINT_EMISSION_FUNCTIONS: [&[&str]; 2] = [ + &["clippy_utils", "diagnostics", "span_lint_and_then"], + &["clippy_utils", "diagnostics", "span_lint_hir_and_then"], +]; +const SUGGESTION_DIAGNOSTIC_BUILDER_METHODS: [(&str, bool); 9] = [ + ("span_suggestion", false), + ("span_suggestion_short", false), + ("span_suggestion_verbose", false), + ("span_suggestion_hidden", false), + ("tool_only_span_suggestion", false), + ("multipart_suggestion", true), + ("multipart_suggestions", true), + ("tool_only_multipart_suggestion", true), + ("span_suggestions", true), +]; +const SUGGESTION_FUNCTIONS: [&[&str]; 2] = [ + &["clippy_utils", "diagnostics", "mutispan_sugg"], + &["clippy_utils", "diagnostics", "multispan_sugg_with_applicability"], +]; /// The index of the applicability name of `paths::APPLICABILITY_VALUES` const APPLICABILITY_NAME_INDEX: usize = 2; @@ -177,7 +204,7 @@ struct ApplicabilityInfo { /// Indicates if any of the lint emissions uses multiple spans. This is related to /// [rustfix#141](https://github.com/rust-lang/rustfix/issues/141) as such suggestions can /// currently not be applied automatically. - has_multi_suggestion: bool, + is_multi_suggestion: bool, applicability: Option, } @@ -250,6 +277,14 @@ fn check_expr(&mut self, cx: &LateContext<'hir>, expr: &'hir hir::Expr<'_>) { } else { lint_collection_error_span(cx, expr.span, "I found this but I can't get the lint or applicability"); } + } else if let Some(args) = match_complex_lint_emission(cx, expr) { + if let Some((lint_name, applicability, is_multi_span)) = extract_complex_emission_info(cx, args) { + let app_info = self.applicability_into.entry(lint_name).or_default(); + app_info.applicability = applicability; + app_info.is_multi_suggestion = is_multi_span; + } else { + lint_collection_error_span(cx, expr.span, "Look, here ... I have no clue what todo with it"); + } } } } @@ -347,7 +382,16 @@ fn match_simple_lint_emission<'hir>( cx: &LateContext<'hir>, expr: &'hir hir::Expr<'_>, ) -> Option<&'hir [hir::Expr<'hir>]> { - LINT_EMISSION_FUNCTIONS + SIMPLE_LINT_EMISSION_FUNCTIONS + .iter() + .find_map(|emission_fn| match_function_call(cx, expr, emission_fn)) +} + +fn match_complex_lint_emission<'hir>( + cx: &LateContext<'hir>, + expr: &'hir hir::Expr<'_>, +) -> Option<&'hir [hir::Expr<'hir>]> { + COMPLEX_LINT_EMISSION_FUNCTIONS .iter() .find_map(|emission_fn| match_function_call(cx, expr, emission_fn)) } @@ -376,28 +420,60 @@ fn extract_emission_info<'hir>( lint_name.map(|lint_name| (sym_to_string(lint_name).to_ascii_lowercase(), applicability)) } +fn extract_complex_emission_info<'hir>( + cx: &LateContext<'hir>, + args: &'hir [hir::Expr<'hir>], +) -> Option<(String, Option, bool)> { + let mut lint_name = None; + let mut applicability = None; + let mut multi_span = false; + + for arg in args { + let (arg_ty, _) = walk_ptrs_ty_depth(cx.typeck_results().expr_ty(&arg)); + + if match_type(cx, arg_ty, &paths::LINT) { + // If we found the lint arg, extract the lint name + if let ExprKind::Path(ref lint_path) = arg.kind { + lint_name = Some(last_path_segment(lint_path).ident.name); + } + } else if arg_ty.is_closure() { + if let ExprKind::Closure(_, _, body_id, _, _) = arg.kind { + let mut visitor = EmissionClosureVisitor::new(cx); + intravisit::walk_body(&mut visitor, cx.tcx.hir().body(body_id)); + multi_span = visitor.found_multi_span(); + applicability = visitor.complete(); + } else { + // TODO xfrednet 2021-02-28: linked closures, see: needless_pass_by_value.rs:292 + return None; + } + } + } + + lint_name.map(|lint_name| (sym_to_string(lint_name).to_ascii_lowercase(), applicability, multi_span)) +} + /// This function tries to resolve the linked applicability to the given expression. fn resolve_applicability(cx: &LateContext<'hir>, expr: &'hir hir::Expr<'hir>) -> Option { match expr.kind { // We can ignore ifs without an else block because those can't be used as an assignment - hir::ExprKind::If(_con, if_block, Some(else_block)) => { + ExprKind::If(_con, if_block, Some(else_block)) => { let mut visitor = ApplicabilityVisitor::new(cx); intravisit::walk_expr(&mut visitor, if_block); intravisit::walk_expr(&mut visitor, else_block); visitor.complete() }, - hir::ExprKind::Match(_expr, arms, _) => { + ExprKind::Match(_expr, arms, _) => { let mut visitor = ApplicabilityVisitor::new(cx); arms.iter() .for_each(|arm| intravisit::walk_expr(&mut visitor, arm.body)); visitor.complete() }, - hir::ExprKind::Loop(block, ..) | hir::ExprKind::Block(block, ..) => { + ExprKind::Loop(block, ..) | ExprKind::Block(block, ..) => { let mut visitor = ApplicabilityVisitor::new(cx); intravisit::walk_block(&mut visitor, block); visitor.complete() }, - ExprKind::Path(hir::QPath::Resolved(_, path)) => { + ExprKind::Path(QPath::Resolved(_, path)) => { // direct applicabilities are simple: for enum_value in &paths::APPLICABILITY_VALUES { if match_path(path, enum_value) { @@ -477,3 +553,96 @@ fn visit_path(&mut self, path: &hir::Path<'_>, _id: hir::HirId) { } } } + +/// This visitor finds the highest applicability value in the visited expressions +struct EmissionClosureVisitor<'a, 'hir> { + cx: &'a LateContext<'hir>, + /// This is the index of hightest `Applicability` for + /// `clippy_utils::paths::APPLICABILITY_VALUES` + applicability_index: Option, + suggestion_count: usize, +} + +impl<'a, 'hir> EmissionClosureVisitor<'a, 'hir> { + fn new(cx: &'a LateContext<'hir>) -> Self { + Self { + cx, + applicability_index: None, + suggestion_count: 0, + } + } + + fn add_new_index(&mut self, new_index: usize) { + self.applicability_index = self + .applicability_index + .map_or(new_index, |old_index| old_index.min(new_index)) + .into(); + } + + fn found_multi_span(&self) -> bool { + self.suggestion_count > 1 + } + + fn complete(self) -> Option { + self.applicability_index + .map(|index| paths::APPLICABILITY_VALUES[index][APPLICABILITY_NAME_INDEX].to_string()) + } +} + +impl<'a, 'hir> intravisit::Visitor<'hir> for EmissionClosureVisitor<'a, 'hir> { + type Map = Map<'hir>; + + fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap { + intravisit::NestedVisitorMap::All(self.cx.tcx.hir()) + } + + fn visit_path(&mut self, path: &hir::Path<'_>, _id: hir::HirId) { + for (index, enum_value) in paths::APPLICABILITY_VALUES.iter().enumerate() { + if match_path(path, enum_value) { + self.add_new_index(index); + break; + } + } + } + + fn visit_expr(&mut self, expr: &'hir hir::Expr<'hir>) { + match &expr.kind { + ExprKind::Call(fn_expr, _args) => { + let found_function = SUGGESTION_FUNCTIONS + .iter() + .any(|func_path| match_function_call(self.cx, fn_expr, func_path).is_some()); + if found_function { + // These functions are all multi part suggestions + self.suggestion_count += 2; + } + }, + ExprKind::MethodCall(path, _path_span, arg, _arg_span) => { + let (self_ty, _) = walk_ptrs_ty_depth(self.cx.typeck_results().expr_ty(&arg[0])); + if match_type(self.cx, self_ty, &paths::DIAGNOSTIC_BUILDER) { + let called_method = path.ident.name.as_str().to_string(); + let found_suggestion = + SUGGESTION_DIAGNOSTIC_BUILDER_METHODS + .iter() + .find_map(|(method_name, is_multi_part)| { + if *method_name == called_method { + Some(*is_multi_part) + } else { + None + } + }); + if let Some(multi_part) = found_suggestion { + if multi_part { + // two is enough to have it marked as a multipart suggestion + self.suggestion_count += 2; + } else { + self.suggestion_count += 1; + } + } + } + }, + _ => {}, + } + + intravisit::walk_expr(self, expr); + } +} diff --git a/clippy_utils/src/paths.rs b/clippy_utils/src/paths.rs index 46f58b788e6..a6292b87768 100644 --- a/clippy_utils/src/paths.rs +++ b/clippy_utils/src/paths.rs @@ -14,6 +14,8 @@ ["rustc_lint_defs", "Applicability", "HasPlaceholders"], ["rustc_lint_defs", "Applicability", "Unspecified"], ]; +#[cfg(feature = "metadata-collector-lint")] +pub const DIAGNOSTIC_BUILDER: [&str; 3] = ["rustc_errors", "diagnostic_builder", "DiagnosticBuilder"]; pub const ARC_PTR_EQ: [&str; 4] = ["alloc", "sync", "Arc", "ptr_eq"]; pub const ASMUT_TRAIT: [&str; 3] = ["core", "convert", "AsMut"]; pub const ASREF_TRAIT: [&str; 3] = ["core", "convert", "AsRef"]; From 2ce5e368d84887a5a2cee669b467160d4ad7b933 Mon Sep 17 00:00:00 2001 From: xFrednet Date: Mon, 1 Mar 2021 12:25:14 +0100 Subject: [PATCH 10/15] Metadata collection: Refining the implementation --- .gitignore | 2 +- .../src/slow_vector_initialization.rs | 2 +- .../internal_lints/metadata_collector.rs | 334 +- metadata_collection.json | 5698 +++++++++++++++++ 4 files changed, 5836 insertions(+), 200 deletions(-) create mode 100644 metadata_collection.json diff --git a/.gitignore b/.gitignore index 523bab18828..565327a7f83 100644 --- a/.gitignore +++ b/.gitignore @@ -29,7 +29,7 @@ out # gh pages docs util/gh-pages/lints.json -**/metadata_collection.json +# **/metadata_collection.json # rustfmt backups *.rs.bk diff --git a/clippy_lints/src/slow_vector_initialization.rs b/clippy_lints/src/slow_vector_initialization.rs index 5a51e1141fb..a9ae2b77119 100644 --- a/clippy_lints/src/slow_vector_initialization.rs +++ b/clippy_lints/src/slow_vector_initialization.rs @@ -7,7 +7,7 @@ use rustc_errors::Applicability; use rustc_hir::intravisit::{walk_block, walk_expr, walk_stmt, NestedVisitorMap, Visitor}; use rustc_hir::{BindingAnnotation, Block, Expr, ExprKind, HirId, PatKind, QPath, Stmt, StmtKind}; -use rustc_lint::{LateContext, LateLintPass, Lint}; +use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::hir::map::Map; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::symbol::sym; diff --git a/clippy_lints/src/utils/internal_lints/metadata_collector.rs b/clippy_lints/src/utils/internal_lints/metadata_collector.rs index 20bd2a669aa..b2cc6372277 100644 --- a/clippy_lints/src/utils/internal_lints/metadata_collector.rs +++ b/clippy_lints/src/utils/internal_lints/metadata_collector.rs @@ -33,7 +33,7 @@ use if_chain::if_chain; use rustc_data_structures::fx::FxHashMap; -use rustc_hir::{self as hir, intravisit, ExprKind, Item, ItemKind, Mutability, QPath}; +use rustc_hir::{self as hir, intravisit, intravisit::Visitor, ExprKind, Item, ItemKind, Mutability, QPath}; use rustc_lint::{CheckLintNameResult, LateContext, LateLintPass, LintContext, LintId}; use rustc_middle::hir::map::Map; use rustc_session::{declare_tool_lint, impl_lint_pass}; @@ -52,19 +52,18 @@ const OUTPUT_FILE: &str = "metadata_collection.json"; /// These lints are excluded from the export. const BLACK_LISTED_LINTS: [&str; 2] = ["lint_author", "deep_code_inspection"]; -/// These groups will be ignored by the lint group matcher -const BLACK_LISTED_LINT_GROUP: [&str; 1] = ["clippy::all", "clippy::internal"]; +/// These groups will be ignored by the lint group matcher. This is useful for collections like +/// `clippy::all` +const IGNORED_LINT_GROUPS: [&str; 1] = ["clippy::all"]; +/// Lints within this group will be excluded from the collection +const EXCLUDED_LINT_GROUPS: [&str; 1] = ["clippy::internal"]; -// TODO xFrednet 2021-02-15: `span_lint_and_then` & `span_lint_hir_and_then` requires special -// handling -const SIMPLE_LINT_EMISSION_FUNCTIONS: [&[&str]; 5] = [ +const LINT_EMISSION_FUNCTIONS: [&[&str]; 7] = [ &["clippy_utils", "diagnostics", "span_lint"], &["clippy_utils", "diagnostics", "span_lint_and_help"], &["clippy_utils", "diagnostics", "span_lint_and_note"], &["clippy_utils", "diagnostics", "span_lint_hir"], &["clippy_utils", "diagnostics", "span_lint_and_sugg"], -]; -const COMPLEX_LINT_EMISSION_FUNCTIONS: [&[&str]; 2] = [ &["clippy_utils", "diagnostics", "span_lint_and_then"], &["clippy_utils", "diagnostics", "span_lint_hir_and_then"], ]; @@ -270,18 +269,11 @@ fn check_item(&mut self, cx: &LateContext<'hir>, item: &'hir Item<'_>) { /// ); /// ``` fn check_expr(&mut self, cx: &LateContext<'hir>, expr: &'hir hir::Expr<'_>) { - if let Some(args) = match_simple_lint_emission(cx, expr) { - if let Some((lint_name, applicability)) = extract_emission_info(cx, args) { + if let Some(args) = match_lint_emission(cx, expr) { + if let Some((lint_name, applicability, is_multi_part)) = extract_complex_emission_info(cx, args) { let app_info = self.applicability_into.entry(lint_name).or_default(); app_info.applicability = applicability; - } else { - lint_collection_error_span(cx, expr.span, "I found this but I can't get the lint or applicability"); - } - } else if let Some(args) = match_complex_lint_emission(cx, expr) { - if let Some((lint_name, applicability, is_multi_span)) = extract_complex_emission_info(cx, args) { - let app_info = self.applicability_into.entry(lint_name).or_default(); - app_info.applicability = applicability; - app_info.is_multi_suggestion = is_multi_span; + app_info.is_multi_suggestion = is_multi_part; } else { lint_collection_error_span(cx, expr.span, "Look, here ... I have no clue what todo with it"); } @@ -292,7 +284,6 @@ fn check_expr(&mut self, cx: &LateContext<'hir>, expr: &'hir hir::Expr<'_>) { // ================================================================== // Lint definition extraction // ================================================================== - fn sym_to_string(sym: Symbol) -> String { sym.as_str().to_string() } @@ -328,10 +319,12 @@ fn extract_attr_docs(item: &Item<'_>) -> Option { fn get_lint_group_or_lint(cx: &LateContext<'_>, lint_name: &str, item: &'hir Item<'_>) -> Option { let result = cx.lint_store.check_lint_name(lint_name, Some(sym::clippy)); if let CheckLintNameResult::Tool(Ok(lint_lst)) = result { - get_lint_group(cx, lint_lst[0]).or_else(|| { - lint_collection_error_item(cx, item, "Unable to determine lint group"); - None - }) + get_lint_group(cx, lint_lst[0]) + .or_else(|| { + lint_collection_error_item(cx, item, "Unable to determine lint group"); + None + }) + .filter(|group| !EXCLUDED_LINT_GROUPS.contains(&group.as_str())) } else { lint_collection_error_item(cx, item, "Unable to find lint in lint_store"); None @@ -340,7 +333,7 @@ fn get_lint_group_or_lint(cx: &LateContext<'_>, lint_name: &str, item: &'hir Ite fn get_lint_group(cx: &LateContext<'_>, lint_id: LintId) -> Option { for (group_name, lints, _) in &cx.lint_store.get_lint_groups() { - if BLACK_LISTED_LINT_GROUP.contains(group_name) { + if IGNORED_LINT_GROUPS.contains(group_name) { continue; } @@ -378,31 +371,19 @@ fn lint_collection_error_span(cx: &LateContext<'_>, span: Span, message: &str) { // ================================================================== /// This function checks if a given expression is equal to a simple lint emission function call. /// It will return the function arguments if the emission matched any function. -fn match_simple_lint_emission<'hir>( - cx: &LateContext<'hir>, - expr: &'hir hir::Expr<'_>, -) -> Option<&'hir [hir::Expr<'hir>]> { - SIMPLE_LINT_EMISSION_FUNCTIONS +fn match_lint_emission<'hir>(cx: &LateContext<'hir>, expr: &'hir hir::Expr<'_>) -> Option<&'hir [hir::Expr<'hir>]> { + LINT_EMISSION_FUNCTIONS .iter() .find_map(|emission_fn| match_function_call(cx, expr, emission_fn)) } -fn match_complex_lint_emission<'hir>( - cx: &LateContext<'hir>, - expr: &'hir hir::Expr<'_>, -) -> Option<&'hir [hir::Expr<'hir>]> { - COMPLEX_LINT_EMISSION_FUNCTIONS - .iter() - .find_map(|emission_fn| match_function_call(cx, expr, emission_fn)) -} - -/// This returns the lint name and the possible applicability of this emission -fn extract_emission_info<'hir>( +fn extract_complex_emission_info<'hir>( cx: &LateContext<'hir>, args: &'hir [hir::Expr<'hir>], -) -> Option<(String, Option)> { +) -> Option<(String, Option, bool)> { let mut lint_name = None; let mut applicability = None; + let mut multi_part = false; for arg in args { let (arg_ty, _) = walk_ptrs_ty_depth(cx.typeck_results().expr_ty(&arg)); @@ -414,109 +395,45 @@ fn extract_emission_info<'hir>( } } else if match_type(cx, arg_ty, &paths::APPLICABILITY) { applicability = resolve_applicability(cx, arg); - } - } - - lint_name.map(|lint_name| (sym_to_string(lint_name).to_ascii_lowercase(), applicability)) -} - -fn extract_complex_emission_info<'hir>( - cx: &LateContext<'hir>, - args: &'hir [hir::Expr<'hir>], -) -> Option<(String, Option, bool)> { - let mut lint_name = None; - let mut applicability = None; - let mut multi_span = false; - - for arg in args { - let (arg_ty, _) = walk_ptrs_ty_depth(cx.typeck_results().expr_ty(&arg)); - - if match_type(cx, arg_ty, &paths::LINT) { - // If we found the lint arg, extract the lint name - if let ExprKind::Path(ref lint_path) = arg.kind { - lint_name = Some(last_path_segment(lint_path).ident.name); - } } else if arg_ty.is_closure() { - if let ExprKind::Closure(_, _, body_id, _, _) = arg.kind { - let mut visitor = EmissionClosureVisitor::new(cx); - intravisit::walk_body(&mut visitor, cx.tcx.hir().body(body_id)); - multi_span = visitor.found_multi_span(); - applicability = visitor.complete(); - } else { - // TODO xfrednet 2021-02-28: linked closures, see: needless_pass_by_value.rs:292 - return None; - } + multi_part |= check_is_multi_part(cx, arg); + // TODO xFrednet 2021-03-01: don't use or_else but rather a comparison + applicability = applicability.or_else(|| resolve_applicability(cx, arg)); } } - lint_name.map(|lint_name| (sym_to_string(lint_name).to_ascii_lowercase(), applicability, multi_span)) + lint_name.map(|lint_name| (sym_to_string(lint_name).to_ascii_lowercase(), applicability, multi_part)) } /// This function tries to resolve the linked applicability to the given expression. fn resolve_applicability(cx: &LateContext<'hir>, expr: &'hir hir::Expr<'hir>) -> Option { - match expr.kind { - // We can ignore ifs without an else block because those can't be used as an assignment - ExprKind::If(_con, if_block, Some(else_block)) => { - let mut visitor = ApplicabilityVisitor::new(cx); - intravisit::walk_expr(&mut visitor, if_block); - intravisit::walk_expr(&mut visitor, else_block); - visitor.complete() - }, - ExprKind::Match(_expr, arms, _) => { - let mut visitor = ApplicabilityVisitor::new(cx); - arms.iter() - .for_each(|arm| intravisit::walk_expr(&mut visitor, arm.body)); - visitor.complete() - }, - ExprKind::Loop(block, ..) | ExprKind::Block(block, ..) => { - let mut visitor = ApplicabilityVisitor::new(cx); - intravisit::walk_block(&mut visitor, block); - visitor.complete() - }, - ExprKind::Path(QPath::Resolved(_, path)) => { - // direct applicabilities are simple: - for enum_value in &paths::APPLICABILITY_VALUES { - if match_path(path, enum_value) { - return Some(enum_value[APPLICABILITY_NAME_INDEX].to_string()); - } - } - - // Values yay - if let hir::def::Res::Local(local_hir) = path.res { - if let Some(local) = get_parent_local(cx, local_hir) { - if let Some(local_init) = local.init { - return resolve_applicability(cx, local_init); - } - } - } - - // This is true for paths that are linked to function parameters. They might be a bit more work so - // not today :) - None - }, - _ => None, - } + let mut resolver = ApplicabilityResolver::new(cx); + resolver.visit_expr(expr); + resolver.complete() } -fn get_parent_local(cx: &LateContext<'hir>, hir_id: hir::HirId) -> Option<&'hir hir::Local<'hir>> { - let map = cx.tcx.hir(); - - match map.find(map.get_parent_node(hir_id)) { - Some(hir::Node::Local(local)) => Some(local), - Some(hir::Node::Pat(pattern)) => get_parent_local(cx, pattern.hir_id), - _ => None, +fn check_is_multi_part(cx: &LateContext<'hir>, closure_expr: &'hir hir::Expr<'hir>) -> bool { + if let ExprKind::Closure(_, _, body_id, _, _) = closure_expr.kind { + let mut scanner = IsMultiSpanScanner::new(cx); + intravisit::walk_body(&mut scanner, cx.tcx.hir().body(body_id)); + return scanner.is_multi_part(); + } else if let Some(local) = get_parent_local(cx, closure_expr) { + if let Some(local_init) = local.init { + return check_is_multi_part(cx, local_init); + } } + + false } /// This visitor finds the highest applicability value in the visited expressions -struct ApplicabilityVisitor<'a, 'hir> { +struct ApplicabilityResolver<'a, 'hir> { cx: &'a LateContext<'hir>, - /// This is the index of hightest `Applicability` for - /// `clippy_utils::paths::APPLICABILITY_VALUES` + /// This is the index of hightest `Applicability` for `paths::APPLICABILITY_VALUES` applicability_index: Option, } -impl<'a, 'hir> ApplicabilityVisitor<'a, 'hir> { +impl<'a, 'hir> ApplicabilityResolver<'a, 'hir> { fn new(cx: &'a LateContext<'hir>) -> Self { Self { cx, @@ -537,75 +454,104 @@ fn complete(self) -> Option { } } -impl<'a, 'hir> intravisit::Visitor<'hir> for ApplicabilityVisitor<'a, 'hir> { +impl<'a, 'hir> intravisit::Visitor<'hir> for ApplicabilityResolver<'a, 'hir> { type Map = Map<'hir>; fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap { intravisit::NestedVisitorMap::All(self.cx.tcx.hir()) } - fn visit_path(&mut self, path: &hir::Path<'_>, _id: hir::HirId) { + fn visit_path(&mut self, path: &'hir hir::Path<'hir>, _id: hir::HirId) { for (index, enum_value) in paths::APPLICABILITY_VALUES.iter().enumerate() { if match_path(path, enum_value) { self.add_new_index(index); - break; - } - } - } -} - -/// This visitor finds the highest applicability value in the visited expressions -struct EmissionClosureVisitor<'a, 'hir> { - cx: &'a LateContext<'hir>, - /// This is the index of hightest `Applicability` for - /// `clippy_utils::paths::APPLICABILITY_VALUES` - applicability_index: Option, - suggestion_count: usize, -} - -impl<'a, 'hir> EmissionClosureVisitor<'a, 'hir> { - fn new(cx: &'a LateContext<'hir>) -> Self { - Self { - cx, - applicability_index: None, - suggestion_count: 0, - } - } - - fn add_new_index(&mut self, new_index: usize) { - self.applicability_index = self - .applicability_index - .map_or(new_index, |old_index| old_index.min(new_index)) - .into(); - } - - fn found_multi_span(&self) -> bool { - self.suggestion_count > 1 - } - - fn complete(self) -> Option { - self.applicability_index - .map(|index| paths::APPLICABILITY_VALUES[index][APPLICABILITY_NAME_INDEX].to_string()) - } -} - -impl<'a, 'hir> intravisit::Visitor<'hir> for EmissionClosureVisitor<'a, 'hir> { - type Map = Map<'hir>; - - fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap { - intravisit::NestedVisitorMap::All(self.cx.tcx.hir()) - } - - fn visit_path(&mut self, path: &hir::Path<'_>, _id: hir::HirId) { - for (index, enum_value) in paths::APPLICABILITY_VALUES.iter().enumerate() { - if match_path(path, enum_value) { - self.add_new_index(index); - break; + return; } } } fn visit_expr(&mut self, expr: &'hir hir::Expr<'hir>) { + let (expr_ty, _) = walk_ptrs_ty_depth(self.cx.typeck_results().expr_ty(&expr)); + + if_chain! { + if match_type(self.cx, expr_ty, &paths::APPLICABILITY); + if let Some(local) = get_parent_local(self.cx, expr); + if let Some(local_init) = local.init; + then { + intravisit::walk_expr(self, local_init); + } + }; + + // TODO xFrednet 2021-03-01: support function arguments? + + intravisit::walk_expr(self, expr); + } +} + +/// This returns the parent local node if the expression is a reference to +fn get_parent_local(cx: &LateContext<'hir>, expr: &'hir hir::Expr<'hir>) -> Option<&'hir hir::Local<'hir>> { + if let ExprKind::Path(QPath::Resolved(_, path)) = expr.kind { + if let hir::def::Res::Local(local_hir) = path.res { + return get_parent_local_hir_id(cx, local_hir); + } + } + + None +} + +fn get_parent_local_hir_id(cx: &LateContext<'hir>, hir_id: hir::HirId) -> Option<&'hir hir::Local<'hir>> { + let map = cx.tcx.hir(); + + match map.find(map.get_parent_node(hir_id)) { + Some(hir::Node::Local(local)) => Some(local), + Some(hir::Node::Pat(pattern)) => get_parent_local_hir_id(cx, pattern.hir_id), + _ => None, + } +} + +/// This visitor finds the highest applicability value in the visited expressions +struct IsMultiSpanScanner<'a, 'hir> { + cx: &'a LateContext<'hir>, + suggestion_count: usize, +} + +impl<'a, 'hir> IsMultiSpanScanner<'a, 'hir> { + fn new(cx: &'a LateContext<'hir>) -> Self { + Self { + cx, + suggestion_count: 0, + } + } + + /// Add a new single expression suggestion to the counter + fn add_singe_span_suggestion(&mut self) { + self.suggestion_count += 1; + } + + /// Signals that a suggestion with possible multiple spans was found + fn add_multi_part_suggestion(&mut self) { + self.suggestion_count += 2; + } + + /// Checks if the suggestions include multiple spanns + fn is_multi_part(&self) -> bool { + self.suggestion_count > 1 + } +} + +impl<'a, 'hir> intravisit::Visitor<'hir> for IsMultiSpanScanner<'a, 'hir> { + type Map = Map<'hir>; + + fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap { + intravisit::NestedVisitorMap::All(self.cx.tcx.hir()) + } + + fn visit_expr(&mut self, expr: &'hir hir::Expr<'hir>) { + // Early return if the lint is already multi span + if self.is_multi_part() { + return; + } + match &expr.kind { ExprKind::Call(fn_expr, _args) => { let found_function = SUGGESTION_FUNCTIONS @@ -613,29 +559,21 @@ fn visit_expr(&mut self, expr: &'hir hir::Expr<'hir>) { .any(|func_path| match_function_call(self.cx, fn_expr, func_path).is_some()); if found_function { // These functions are all multi part suggestions - self.suggestion_count += 2; + self.add_singe_span_suggestion() } }, ExprKind::MethodCall(path, _path_span, arg, _arg_span) => { let (self_ty, _) = walk_ptrs_ty_depth(self.cx.typeck_results().expr_ty(&arg[0])); if match_type(self.cx, self_ty, &paths::DIAGNOSTIC_BUILDER) { let called_method = path.ident.name.as_str().to_string(); - let found_suggestion = - SUGGESTION_DIAGNOSTIC_BUILDER_METHODS - .iter() - .find_map(|(method_name, is_multi_part)| { - if *method_name == called_method { - Some(*is_multi_part) - } else { - None - } - }); - if let Some(multi_part) = found_suggestion { - if multi_part { - // two is enough to have it marked as a multipart suggestion - self.suggestion_count += 2; - } else { - self.suggestion_count += 1; + for (method_name, is_multi_part) in &SUGGESTION_DIAGNOSTIC_BUILDER_METHODS { + if *method_name == called_method { + if *is_multi_part { + self.add_multi_part_suggestion(); + } else { + self.add_singe_span_suggestion(); + } + break; } } } diff --git a/metadata_collection.json b/metadata_collection.json new file mode 100644 index 00000000000..507752a782c --- /dev/null +++ b/metadata_collection.json @@ -0,0 +1,5698 @@ +[ + { + "id": "approx_constant", + "id_span": { + "path": "clippy_lints/src/approx_const.rs", + "line": 34 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for floating point literals that approximate constants which are defined in\n [`std::f32::consts`](https://doc.rust-lang.org/stable/std/f32/consts/#constants)\n or\n [`std::f64::consts`](https://doc.rust-lang.org/stable/std/f64/consts/#constants),\n respectively, suggesting to use the predefined constant.\n\n **Why is this bad?** Usually, the definition in the standard library is more\n precise than what people come up with. If you find that your definition is\n actually more precise, please [file a Rust\n issue](https://github.com/rust-lang/rust/issues).\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let x = 3.14;\n let y = 1_f64 / x;\n ```\n Use predefined constants instead:\n ```rust\n let x = std::f32::consts::PI;\n let y = std::f64::consts::FRAC_1_PI;\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "integer_arithmetic", + "id_span": { + "path": "clippy_lints/src/arithmetic.rs", + "line": 28 + }, + "group": "clippy::restriction", + "docs": " **What it does:** Checks for integer arithmetic operations which could overflow or panic.\n Specifically, checks for any operators (`+`, `-`, `*`, `<<`, etc) which are capable\n of overflowing according to the [Rust\n Reference](https://doc.rust-lang.org/reference/expressions/operator-expr.html#overflow),\n or which can panic (`/`, `%`). No bounds analysis or sophisticated reasoning is\n attempted.\n\n **Why is this bad?** Integer overflow will trigger a panic in debug builds or will wrap in\n release mode. Division by zero will cause a panic in either mode. In some applications one\n wants explicitly checked, wrapping or saturating arithmetic.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let a = 0;\n a + 1;\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "float_arithmetic", + "id_span": { + "path": "clippy_lints/src/arithmetic.rs", + "line": 46 + }, + "group": "clippy::restriction", + "docs": " **What it does:** Checks for float arithmetic.\n **Why is this bad?** For some embedded systems or kernel development, it\n can be useful to rule out floating-point numbers.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let a = 0.0;\n a + 1.0;\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "as_conversions", + "id_span": { + "path": "clippy_lints/src/as_conversions.rs", + "line": 42 + }, + "group": "clippy::restriction", + "docs": " **What it does:** Checks for usage of `as` conversions.\n Note that this lint is specialized in linting *every single* use of `as`\n regardless of whether good alternatives exist or not.\n If you want more precise lints for `as`, please consider using these separate lints:\n `unnecessary_cast`, `cast_lossless/possible_truncation/possible_wrap/precision_loss/sign_loss`,\n `fn_to_numeric_cast(_with_truncation)`, `char_lit_as_u8`, `ref_to_mut` and `ptr_as_ptr`.\n There is a good explanation the reason why this lint should work in this way and how it is useful\n [in this issue](https://github.com/rust-lang/rust-clippy/issues/5122).\n\n **Why is this bad?** `as` conversions will perform many kinds of\n conversions, including silently lossy conversions and dangerous coercions.\n There are cases when it makes sense to use `as`, so the lint is\n Allow by default.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n let a: u32;\n ...\n f(a as u16);\n ```\n\n Usually better represents the semantics you expect:\n ```rust,ignore\n f(a.try_into()?);\n ```\n or\n ```rust,ignore\n f(a.try_into().expect(\"Unexpected u16 overflow in f\"));\n ```\n\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "inline_asm_x86_intel_syntax", + "id_span": { + "path": "clippy_lints/src/asm_syntax.rs", + "line": 78 + }, + "group": "clippy::restriction", + "docs": " **What it does:** Checks for usage of Intel x86 assembly syntax.\n **Why is this bad?** The lint has been enabled to indicate a preference\n for AT&T x86 assembly syntax.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust,no_run\n # #![feature(asm)]\n # unsafe { let ptr = \"\".as_ptr();\n asm!(\"lea {}, [{}]\", lateout(reg) _, in(reg) ptr);\n # }\n ```\n Use instead:\n ```rust,no_run\n # #![feature(asm)]\n # unsafe { let ptr = \"\".as_ptr();\n asm!(\"lea ({}), {}\", in(reg) ptr, lateout(reg) _, options(att_syntax));\n # }\n ```\n", + "applicability": null + }, + { + "id": "inline_asm_x86_att_syntax", + "id_span": { + "path": "clippy_lints/src/asm_syntax.rs", + "line": 114 + }, + "group": "clippy::restriction", + "docs": " **What it does:** Checks for usage of AT&T x86 assembly syntax.\n **Why is this bad?** The lint has been enabled to indicate a preference\n for Intel x86 assembly syntax.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust,no_run\n # #![feature(asm)]\n # unsafe { let ptr = \"\".as_ptr();\n asm!(\"lea ({}), {}\", in(reg) ptr, lateout(reg) _, options(att_syntax));\n # }\n ```\n Use instead:\n ```rust,no_run\n # #![feature(asm)]\n # unsafe { let ptr = \"\".as_ptr();\n asm!(\"lea {}, [{}]\", lateout(reg) _, in(reg) ptr);\n # }\n ```\n", + "applicability": null + }, + { + "id": "assertions_on_constants", + "id_span": { + "path": "clippy_lints/src/assertions_on_constants.rs", + "line": 23 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for `assert!(true)` and `assert!(false)` calls.\n **Why is this bad?** Will be optimized out by the compiler or should probably be replaced by a\n `panic!()` or `unreachable!()`\n\n **Known problems:** None\n\n **Example:**\n ```rust,ignore\n assert!(false)\n assert!(true)\n const B: bool = false;\n assert!(B)\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "assign_op_pattern", + "id_span": { + "path": "clippy_lints/src/assign_ops.rs", + "line": 33 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for `a = a op b` or `a = b commutative_op a` patterns.\n\n **Why is this bad?** These can be written as the shorter `a op= b`.\n\n **Known problems:** While forbidden by the spec, `OpAssign` traits may have\n implementations that differ from the regular `Op` impl.\n\n **Example:**\n ```rust\n let mut a = 5;\n let b = 0;\n // ...\n // Bad\n a = a + b;\n\n // Good\n a += b;\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "misrefactored_assign_op", + "id_span": { + "path": "clippy_lints/src/assign_ops.rs", + "line": 56 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for `a op= a op b` or `a op= b op a` patterns.\n **Why is this bad?** Most likely these are bugs where one meant to write `a\n op= b`.\n\n **Known problems:** Clippy cannot know for sure if `a op= a op b` should have\n been `a = a op a op b` or `a = a op b`/`a op= b`. Therefore, it suggests both.\n If `a op= a op b` is really the correct behaviour it should be\n written as `a = a op a op b` as it's less confusing.\n\n **Example:**\n ```rust\n let mut a = 5;\n let b = 2;\n // ...\n a += a + b;\n ```\n", + "applicability": { + "is_multi_suggestion": true, + "applicability": "MaybeIncorrect" + } + }, + { + "id": "async_yields_async", + "id_span": { + "path": "clippy_lints/src/async_yields_async.rs", + "line": 36 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for async blocks that yield values of types that can themselves be awaited.\n\n **Why is this bad?** An await is likely missing.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n async fn foo() {}\n\n fn bar() {\n let x = async {\n foo()\n };\n }\n ```\n Use instead:\n ```rust\n async fn foo() {}\n\n fn bar() {\n let x = async {\n foo().await\n };\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MaybeIncorrect" + } + }, + { + "id": "invalid_atomic_ordering", + "id_span": { + "path": "clippy_lints/src/atomic_ordering.rs", + "line": 47 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for usage of invalid atomic ordering in atomic loads/stores/exchanges/updates and\n memory fences.\n\n **Why is this bad?** Using an invalid atomic ordering\n will cause a panic at run-time.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,no_run\n # use std::sync::atomic::{self, AtomicU8, Ordering};\n\n let x = AtomicU8::new(0);\n\n // Bad: `Release` and `AcqRel` cannot be used for `load`.\n let _ = x.load(Ordering::Release);\n let _ = x.load(Ordering::AcqRel);\n\n // Bad: `Acquire` and `AcqRel` cannot be used for `store`.\n x.store(1, Ordering::Acquire);\n x.store(2, Ordering::AcqRel);\n\n // Bad: `Relaxed` cannot be used as a fence's ordering.\n atomic::fence(Ordering::Relaxed);\n atomic::compiler_fence(Ordering::Relaxed);\n\n // Bad: `Release` and `AcqRel` are both always invalid\n // for the failure ordering (the last arg).\n let _ = x.compare_exchange(1, 2, Ordering::SeqCst, Ordering::Release);\n let _ = x.compare_exchange_weak(2, 3, Ordering::AcqRel, Ordering::AcqRel);\n\n // Bad: The failure ordering is not allowed to be\n // stronger than the success order, and `SeqCst` is\n // stronger than `Relaxed`.\n let _ = x.fetch_update(Ordering::Relaxed, Ordering::SeqCst, |val| Some(val + val));\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "inline_always", + "id_span": { + "path": "clippy_lints/src/attrs.rs", + "line": 65 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for items annotated with `#[inline(always)]`, unless the annotated function is empty or simply panics.\n\n **Why is this bad?** While there are valid uses of this annotation (and once\n you know when to use it, by all means `allow` this lint), it's a common\n newbie-mistake to pepper one's code with it.\n\n As a rule of thumb, before slapping `#[inline(always)]` on a function,\n measure if that additional function call really affects your runtime profile\n sufficiently to make up for the increase in compile time.\n\n **Known problems:** False positives, big time. This lint is meant to be\n deactivated by everyone doing serious performance work. This means having\n done the measurement.\n\n **Example:**\n ```ignore\n #[inline(always)]\n fn not_quite_hot_code(..) { ... }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "useless_attribute", + "id_span": { + "path": "clippy_lints/src/attrs.rs", + "line": 99 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for `extern crate` and `use` items annotated with lint attributes.\n\n This lint permits `#[allow(unused_imports)]`, `#[allow(deprecated)]`,\n `#[allow(unreachable_pub)]`, `#[allow(clippy::wildcard_imports)]` and\n `#[allow(clippy::enum_glob_use)]` on `use` items and `#[allow(unused_imports)]` on\n `extern crate` items with a `#[macro_use]` attribute.\n\n **Why is this bad?** Lint attributes have no effect on crate imports. Most\n likely a `!` was forgotten.\n\n **Known problems:** None.\n\n **Example:**\n ```ignore\n // Bad\n #[deny(dead_code)]\n extern crate foo;\n #[forbid(dead_code)]\n use foo::bar;\n\n // Ok\n #[allow(unused_imports)]\n use foo::baz;\n #[allow(unused_imports)]\n #[macro_use]\n extern crate baz;\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MaybeIncorrect" + } + }, + { + "id": "deprecated_semver", + "id_span": { + "path": "clippy_lints/src/attrs.rs", + "line": 118 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for `#[deprecated]` annotations with a `since` field that is not a valid semantic version.\n\n **Why is this bad?** For checking the version of the deprecation, it must be\n a valid semver. Failing that, the contained information is useless.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n #[deprecated(since = \"forever\")]\n fn something_else() { /* ... */ }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "empty_line_after_outer_attr", + "id_span": { + "path": "clippy_lints/src/attrs.rs", + "line": 153 + }, + "group": "clippy::nursery", + "docs": " **What it does:** Checks for empty lines after outer attributes\n **Why is this bad?**\n Most likely the attribute was meant to be an inner attribute using a '!'.\n If it was meant to be an outer attribute, then the following item\n should not be separated by empty lines.\n\n **Known problems:** Can cause false positives.\n\n From the clippy side it's difficult to detect empty lines between an attributes and the\n following item because empty lines and comments are not part of the AST. The parsing\n currently works for basic cases but is not perfect.\n\n **Example:**\n ```rust\n // Good (as inner attribute)\n #![allow(dead_code)]\n\n fn this_is_fine() { }\n\n // Bad\n #[allow(dead_code)]\n\n fn not_quite_good_code() { }\n\n // Good (as outer attribute)\n #[allow(dead_code)]\n fn this_is_fine_too() { }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "blanket_clippy_restriction_lints", + "id_span": { + "path": "clippy_lints/src/attrs.rs", + "line": 176 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for `warn`/`deny`/`forbid` attributes targeting the whole clippy::restriction category.\n **Why is this bad?** Restriction lints sometimes are in contrast with other lints or even go against idiomatic rust.\n These lints should only be enabled on a lint-by-lint basis and with careful consideration.\n\n **Known problems:** None.\n\n **Example:**\n Bad:\n ```rust\n #![deny(clippy::restriction)]\n ```\n\n Good:\n ```rust\n #![deny(clippy::as_conversions)]\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "deprecated_cfg_attr", + "id_span": { + "path": "clippy_lints/src/attrs.rs", + "line": 205 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for `#[cfg_attr(rustfmt, rustfmt_skip)]` and suggests to replace it with `#[rustfmt::skip]`.\n\n **Why is this bad?** Since tool_attributes ([rust-lang/rust#44690](https://github.com/rust-lang/rust/issues/44690))\n are stable now, they should be used instead of the old `cfg_attr(rustfmt)` attributes.\n\n **Known problems:** This lint doesn't detect crate level inner attributes, because they get\n processed before the PreExpansionPass lints get executed. See\n [#3123](https://github.com/rust-lang/rust-clippy/pull/3123#issuecomment-422321765)\n\n **Example:**\n\n Bad:\n ```rust\n #[cfg_attr(rustfmt, rustfmt_skip)]\n fn main() { }\n ```\n\n Good:\n ```rust\n #[rustfmt::skip]\n fn main() { }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "mismatched_target_os", + "id_span": { + "path": "clippy_lints/src/attrs.rs", + "line": 238 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for cfg attributes having operating systems used in target family position.\n **Why is this bad?** The configuration option will not be recognised and the related item will not be included\n by the conditional compilation engine.\n\n **Known problems:** None.\n\n **Example:**\n\n Bad:\n ```rust\n #[cfg(linux)]\n fn conditional() { }\n ```\n\n Good:\n ```rust\n #[cfg(target_os = \"linux\")]\n fn conditional() { }\n ```\n\n Or:\n ```rust\n #[cfg(unix)]\n fn conditional() { }\n ```\n Check the [Rust Reference](https://doc.rust-lang.org/reference/conditional-compilation.html#target_os) for more details.\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MaybeIncorrect" + } + }, + { + "id": "await_holding_lock", + "id_span": { + "path": "clippy_lints/src/await_holding_invalid.rs", + "line": 47 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for calls to await while holding a non-async-aware MutexGuard.\n\n **Why is this bad?** The Mutex types found in std::sync and parking_lot\n are not designed to operate in an async context across await points.\n\n There are two potential solutions. One is to use an asynx-aware Mutex\n type. Many asynchronous foundation crates provide such a Mutex type. The\n other solution is to ensure the mutex is unlocked before calling await,\n either by introducing a scope or an explicit call to Drop::drop.\n\n **Known problems:** Will report false positive for explicitly dropped guards ([#6446](https://github.com/rust-lang/rust-clippy/issues/6446)).\n\n **Example:**\n\n ```rust,ignore\n use std::sync::Mutex;\n\n async fn foo(x: &Mutex) {\n let guard = x.lock().unwrap();\n *guard += 1;\n bar.await;\n }\n ```\n\n Use instead:\n ```rust,ignore\n use std::sync::Mutex;\n\n async fn foo(x: &Mutex) {\n {\n let guard = x.lock().unwrap();\n *guard += 1;\n }\n bar.await;\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "await_holding_refcell_ref", + "id_span": { + "path": "clippy_lints/src/await_holding_invalid.rs", + "line": 86 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for calls to await while holding a `RefCell` `Ref` or `RefMut`.\n\n **Why is this bad?** `RefCell` refs only check for exclusive mutable access\n at runtime. Holding onto a `RefCell` ref across an `await` suspension point\n risks panics from a mutable ref shared while other refs are outstanding.\n\n **Known problems:** Will report false positive for explicitly dropped refs ([#6353](https://github.com/rust-lang/rust-clippy/issues/6353)).\n\n **Example:**\n\n ```rust,ignore\n use std::cell::RefCell;\n\n async fn foo(x: &RefCell) {\n let mut y = x.borrow_mut();\n *y += 1;\n bar.await;\n }\n ```\n\n Use instead:\n ```rust,ignore\n use std::cell::RefCell;\n\n async fn foo(x: &RefCell) {\n {\n let mut y = x.borrow_mut();\n *y += 1;\n }\n bar.await;\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "bad_bit_mask", + "id_span": { + "path": "clippy_lints/src/bit_mask.rs", + "line": 44 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for incompatible bit masks in comparisons.\n The formula for detecting if an expression of the type `_ m\n c` (where `` is one of {`&`, `|`} and `` is one of\n {`!=`, `>=`, `>`, `!=`, `>=`, `>`}) can be determined from the following\n table:\n\n |Comparison |Bit Op|Example |is always|Formula |\n |------------|------|------------|---------|----------------------|\n |`==` or `!=`| `&` |`x & 2 == 3`|`false` |`c & m != c` |\n |`<` or `>=`| `&` |`x & 2 < 3` |`true` |`m < c` |\n |`>` or `<=`| `&` |`x & 1 > 1` |`false` |`m <= c` |\n |`==` or `!=`| `|` |`x | 1 == 0`|`false` |`c | m != c` |\n |`<` or `>=`| `|` |`x | 1 < 1` |`false` |`m >= c` |\n |`<=` or `>` | `|` |`x | 1 > 0` |`true` |`m > c` |\n\n **Why is this bad?** If the bits that the comparison cares about are always\n set to zero or one by the bit mask, the comparison is constant `true` or\n `false` (depending on mask, compared value, and operators).\n\n So the code is actively misleading, and the only reason someone would write\n this intentionally is to win an underhanded Rust contest or create a\n test-case for this lint.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let x = 1;\n if (x & 1 == 2) { }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "ineffective_bit_mask", + "id_span": { + "path": "clippy_lints/src/bit_mask.rs", + "line": 73 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for bit masks in comparisons which can be removed without changing the outcome. The basic structure can be seen in the\n following table:\n\n |Comparison| Bit Op |Example |equals |\n |----------|---------|-----------|-------|\n |`>` / `<=`|`|` / `^`|`x | 2 > 3`|`x > 3`|\n |`<` / `>=`|`|` / `^`|`x ^ 1 < 4`|`x < 4`|\n\n **Why is this bad?** Not equally evil as [`bad_bit_mask`](#bad_bit_mask),\n but still a bit misleading, because the bit mask is ineffective.\n\n **Known problems:** False negatives: This lint will only match instances\n where we have figured out the math (which is for a power-of-two compared\n value). This means things like `x | 1 >= 7` (which would be better written\n as `x >= 6`) will not be reported (but bit masks like this are fairly\n uncommon).\n\n **Example:**\n ```rust\n # let x = 1;\n if (x | 1 > 3) { }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "verbose_bit_mask", + "id_span": { + "path": "clippy_lints/src/bit_mask.rs", + "line": 92 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for bit masks that can be replaced by a call to `trailing_zeros`\n\n **Why is this bad?** `x.trailing_zeros() > 4` is much clearer than `x & 15\n == 0`\n\n **Known problems:** llvm generates better code for `x & 15 == 0` on x86\n\n **Example:**\n ```rust\n # let x = 1;\n if x & 0b1111 == 0 { }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MaybeIncorrect" + } + }, + { + "id": "blacklisted_name", + "id_span": { + "path": "clippy_lints/src/blacklisted_name.rs", + "line": 20 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for usage of blacklisted names for variables, such as `foo`.\n\n **Why is this bad?** These names are usually placeholder names and should be\n avoided.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let foo = 3.14;\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "blocks_in_if_conditions", + "id_span": { + "path": "clippy_lints/src/blocks_in_if_conditions.rs", + "line": 42 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for `if` conditions that use blocks containing an expression, statements or conditions that use closures with blocks.\n\n **Why is this bad?** Style, using blocks in the condition makes it hard to read.\n\n **Known problems:** None.\n\n **Examples:**\n ```rust\n // Bad\n if { true } { /* ... */ }\n\n // Good\n if true { /* ... */ }\n ```\n\n // or\n\n ```rust\n # fn somefunc() -> bool { true };\n // Bad\n if { let x = somefunc(); x } { /* ... */ }\n\n // Good\n let res = { let x = somefunc(); x };\n if res { /* ... */ }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "nonminimal_bool", + "id_span": { + "path": "clippy_lints/src/booleans.rs", + "line": 31 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for boolean expressions that can be written more concisely.\n\n **Why is this bad?** Readability of boolean expressions suffers from\n unnecessary duplication.\n\n **Known problems:** Ignores short circuiting behavior of `||` and\n `&&`. Ignores `|`, `&` and `^`.\n\n **Example:**\n ```ignore\n if a && true // should be: if a\n if !(a == b) // should be: if a != b\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "logic_bug", + "id_span": { + "path": "clippy_lints/src/booleans.rs", + "line": 49 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for boolean expressions that contain terminals that can be eliminated.\n\n **Why is this bad?** This is most likely a logic bug.\n\n **Known problems:** Ignores short circuiting behavior.\n\n **Example:**\n ```ignore\n if a && b || a { ... }\n ```\n The `b` is unnecessary, the expression is equivalent to `if a`.\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "Unspecified" + } + }, + { + "id": "naive_bytecount", + "id_span": { + "path": "clippy_lints/src/bytecount.rs", + "line": 30 + }, + "group": "clippy::perf", + "docs": " **What it does:** Checks for naive byte counts\n **Why is this bad?** The [`bytecount`](https://crates.io/crates/bytecount)\n crate has methods to count your bytes faster, especially for large slices.\n\n **Known problems:** If you have predominantly small slices, the\n `bytecount::count(..)` method may actually be slower. However, if you can\n ensure that less than 2³²-1 matches arise, the `naive_count_32(..)` can be\n faster in those cases.\n\n **Example:**\n\n ```rust\n # let vec = vec![1_u8];\n &vec.iter().filter(|x| **x == 0u8).count(); // use bytecount::count instead\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MaybeIncorrect" + } + }, + { + "id": "cargo_common_metadata", + "id_span": { + "path": "clippy_lints/src/cargo_common_metadata.rs", + "line": 49 + }, + "group": "clippy::cargo", + "docs": " **What it does:** Checks to see if all common metadata is defined in `Cargo.toml`. See: https://rust-lang-nursery.github.io/api-guidelines/documentation.html#cargotoml-includes-all-common-metadata-c-metadata\n\n **Why is this bad?** It will be more difficult for users to discover the\n purpose of the crate, and key information related to it.\n\n **Known problems:** None.\n\n **Example:**\n ```toml\n # This `Cargo.toml` is missing an authors field:\n [package]\n name = \"clippy\"\n version = \"0.0.212\"\n description = \"A bunch of helpful lints to avoid common pitfalls in Rust\"\n repository = \"https://github.com/rust-lang/rust-clippy\"\n readme = \"README.md\"\n license = \"MIT OR Apache-2.0\"\n keywords = [\"clippy\", \"lint\", \"plugin\"]\n categories = [\"development-tools\", \"development-tools::cargo-plugins\"]\n ```\n\n Should include an authors field like:\n\n ```toml\n # This `Cargo.toml` includes all common metadata\n [package]\n name = \"clippy\"\n version = \"0.0.212\"\n authors = [\"Someone \"]\n description = \"A bunch of helpful lints to avoid common pitfalls in Rust\"\n repository = \"https://github.com/rust-lang/rust-clippy\"\n readme = \"README.md\"\n license = \"MIT OR Apache-2.0\"\n keywords = [\"clippy\", \"lint\", \"plugin\"]\n categories = [\"development-tools\", \"development-tools::cargo-plugins\"]\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "case_sensitive_file_extension_comparisons", + "id_span": { + "path": "clippy_lints/src/case_sensitive_file_extension_comparisons.rs", + "line": 34 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for calls to `ends_with` with possible file extensions\n and suggests to use a case-insensitive approach instead.\n\n **Why is this bad?**\n `ends_with` is case-sensitive and may not detect files with a valid extension.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n fn is_rust_file(filename: &str) -> bool {\n filename.ends_with(\".rs\")\n }\n ```\n Use instead:\n ```rust\n fn is_rust_file(filename: &str) -> bool {\n filename.rsplit('.').next().map(|ext| ext.eq_ignore_ascii_case(\"rs\")) == Some(true)\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "checked_conversions", + "id_span": { + "path": "clippy_lints/src/checked_conversions.rs", + "line": 40 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for explicit bounds checking when casting.\n **Why is this bad?** Reduces the readability of statements & is error prone.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let foo: u32 = 5;\n # let _ =\n foo <= i32::MAX as u32\n # ;\n ```\n\n Could be written:\n\n ```rust\n # use std::convert::TryFrom;\n # let foo = 1;\n # let _ =\n i32::try_from(foo).is_ok()\n # ;\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "cognitive_complexity", + "id_span": { + "path": "clippy_lints/src/cognitive_complexity.rs", + "line": 24 + }, + "group": "clippy::nursery", + "docs": " **What it does:** Checks for methods with high cognitive complexity.\n **Why is this bad?** Methods of high cognitive complexity tend to be hard to\n both read and maintain. Also LLVM will tend to optimize small methods better.\n\n **Known problems:** Sometimes it's hard to find a way to reduce the\n complexity.\n\n **Example:** No. You'll see it when you get the warning.\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "collapsible_if", + "id_span": { + "path": "clippy_lints/src/collapsible_if.rs", + "line": 50 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for nested `if` statements which can be collapsed by `&&`-combining their conditions.\n\n **Why is this bad?** Each `if`-statement adds one level of nesting, which\n makes code look more complex than it really is.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n if x {\n if y {\n …\n }\n }\n\n ```\n\n Should be written:\n\n ```rust.ignore\n if x && y {\n …\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "collapsible_else_if", + "id_span": { + "path": "clippy_lints/src/collapsible_if.rs", + "line": 85 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for collapsible `else { if ... }` expressions that can be collapsed to `else if ...`.\n\n **Why is this bad?** Each `if`-statement adds one level of nesting, which\n makes code look more complex than it really is.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n\n if x {\n …\n } else {\n if y {\n …\n }\n }\n ```\n\n Should be written:\n\n ```rust.ignore\n if x {\n …\n } else if y {\n …\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "collapsible_match", + "id_span": { + "path": "clippy_lints/src/collapsible_match.rs", + "line": 44 + }, + "group": "clippy::style", + "docs": " **What it does:** Finds nested `match` or `if let` expressions where the patterns may be \"collapsed\" together without adding any branches.\n\n Note that this lint is not intended to find _all_ cases where nested match patterns can be merged, but only\n cases where merging would most likely make the code more readable.\n\n **Why is this bad?** It is unnecessarily verbose and complex.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n fn func(opt: Option>) {\n let n = match opt {\n Some(n) => match n {\n Ok(n) => n,\n _ => return,\n }\n None => return,\n };\n }\n ```\n Use instead:\n ```rust\n fn func(opt: Option>) {\n let n = match opt {\n Some(Ok(n)) => n,\n _ => return,\n };\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "comparison_chain", + "id_span": { + "path": "clippy_lints/src/comparison_chain.rs", + "line": 49 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks comparison chains written with `if` that can be rewritten with `match` and `cmp`.\n\n **Why is this bad?** `if` is not guaranteed to be exhaustive and conditionals can get\n repetitive\n\n **Known problems:** The match statement may be slower due to the compiler\n not inlining the call to cmp. See issue [#5354](https://github.com/rust-lang/rust-clippy/issues/5354)\n\n **Example:**\n ```rust,ignore\n # fn a() {}\n # fn b() {}\n # fn c() {}\n fn f(x: u8, y: u8) {\n if x > y {\n a()\n } else if x < y {\n b()\n } else {\n c()\n }\n }\n ```\n\n Could be written:\n\n ```rust,ignore\n use std::cmp::Ordering;\n # fn a() {}\n # fn b() {}\n # fn c() {}\n fn f(x: u8, y: u8) {\n match x.cmp(&y) {\n Ordering::Greater => a(),\n Ordering::Less => b(),\n Ordering::Equal => c()\n }\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "ifs_same_cond", + "id_span": { + "path": "clippy_lints/src/copies.rs", + "line": 33 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for consecutive `if`s with the same condition.\n **Why is this bad?** This is probably a copy & paste error.\n\n **Known problems:** Hopefully none.\n\n **Example:**\n ```ignore\n if a == b {\n …\n } else if a == b {\n …\n }\n ```\n\n Note that this lint ignores all conditions with a function call as it could\n have side effects:\n\n ```ignore\n if foo() {\n …\n } else if foo() { // not linted\n …\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "same_functions_in_if_condition", + "id_span": { + "path": "clippy_lints/src/copies.rs", + "line": 80 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for consecutive `if`s with the same function call.\n **Why is this bad?** This is probably a copy & paste error.\n Despite the fact that function can have side effects and `if` works as\n intended, such an approach is implicit and can be considered a \"code smell\".\n\n **Known problems:** Hopefully none.\n\n **Example:**\n ```ignore\n if foo() == bar {\n …\n } else if foo() == bar {\n …\n }\n ```\n\n This probably should be:\n ```ignore\n if foo() == bar {\n …\n } else if foo() == baz {\n …\n }\n ```\n\n or if the original code was not a typo and called function mutates a state,\n consider move the mutation out of the `if` condition to avoid similarity to\n a copy & paste error:\n\n ```ignore\n let first = foo();\n if first == bar {\n …\n } else {\n let second = foo();\n if second == bar {\n …\n }\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "if_same_then_else", + "id_span": { + "path": "clippy_lints/src/copies.rs", + "line": 101 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for `if/else` with the same body as the *then* part and the *else* part.\n\n **Why is this bad?** This is probably a copy & paste error.\n\n **Known problems:** Hopefully none.\n\n **Example:**\n ```ignore\n let foo = if … {\n 42\n } else {\n 42\n };\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "copy_iterator", + "id_span": { + "path": "clippy_lints/src/copy_iterator.rs", + "line": 27 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for types that implement `Copy` as well as `Iterator`.\n\n **Why is this bad?** Implicit copies can be confusing when working with\n iterator combinators.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n #[derive(Copy, Clone)]\n struct Countdown(u8);\n\n impl Iterator for Countdown {\n // ...\n }\n\n let a: Vec<_> = my_iterator.take(1).collect();\n let b: Vec<_> = my_iterator.collect();\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "create_dir", + "id_span": { + "path": "clippy_lints/src/create_dir.rs", + "line": 24 + }, + "group": "clippy::restriction", + "docs": " **What it does:** Checks usage of `std::fs::create_dir` and suggest using `std::fs::create_dir_all` instead.\n **Why is this bad?** Sometimes `std::fs::create_dir` is mistakenly chosen over `std::fs::create_dir_all`.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n std::fs::create_dir(\"foo\");\n ```\n Use instead:\n ```rust\n std::fs::create_dir_all(\"foo\");\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MaybeIncorrect" + } + }, + { + "id": "dbg_macro", + "id_span": { + "path": "clippy_lints/src/dbg_macro.rs", + "line": 25 + }, + "group": "clippy::restriction", + "docs": " **What it does:** Checks for usage of dbg!() macro.\n **Why is this bad?** `dbg!` macro is intended as a debugging tool. It\n should not be in version control.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n // Bad\n dbg!(true)\n\n // Good\n true\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "default_trait_access", + "id_span": { + "path": "clippy_lints/src/default.rs", + "line": 33 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for literal calls to `Default::default()`.\n **Why is this bad?** It's more clear to the reader to use the name of the type whose default is\n being gotten than the generic `Default`.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n // Bad\n let s: String = Default::default();\n\n // Good\n let s = String::default();\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "Unspecified" + } + }, + { + "id": "field_reassign_with_default", + "id_span": { + "path": "clippy_lints/src/default.rs", + "line": 63 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for immediate reassignment of fields initialized with Default::default().\n\n **Why is this bad?**It's more idiomatic to use the [functional update syntax](https://doc.rust-lang.org/reference/expressions/struct-expr.html#functional-update-syntax).\n\n **Known problems:** Assignments to patterns that are of tuple type are not linted.\n\n **Example:**\n Bad:\n ```\n # #[derive(Default)]\n # struct A { i: i32 }\n let mut a: A = Default::default();\n a.i = 42;\n ```\n Use instead:\n ```\n # #[derive(Default)]\n # struct A { i: i32 }\n let a = A {\n i: 42,\n .. Default::default()\n };\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "default_numeric_fallback", + "id_span": { + "path": "clippy_lints/src/default_numeric_fallback.rs", + "line": 44 + }, + "group": "clippy::restriction", + "docs": " **What it does:** Checks for usage of unconstrained numeric literals which may cause default numeric fallback in type inference.\n\n Default numeric fallback means that if numeric types have not yet been bound to concrete\n types at the end of type inference, then integer type is bound to `i32`, and similarly\n floating type is bound to `f64`.\n\n See [RFC0212](https://github.com/rust-lang/rfcs/blob/master/text/0212-restore-int-fallback.md) for more information about the fallback.\n\n **Why is this bad?** For those who are very careful about types, default numeric fallback\n can be a pitfall that cause unexpected runtime behavior.\n\n **Known problems:** This lint can only be allowed at the function level or above.\n\n **Example:**\n ```rust\n let i = 10;\n let f = 1.23;\n ```\n\n Use instead:\n ```rust\n let i = 10i32;\n let f = 1.23f64;\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MaybeIncorrect" + } + }, + { + "id": "explicit_deref_methods", + "id_span": { + "path": "clippy_lints/src/dereference.rs", + "line": 32 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for explicit `deref()` or `deref_mut()` method calls.\n **Why is this bad?** Dereferencing by `&*x` or `&mut *x` is clearer and more concise,\n when not part of a method chain.\n\n **Example:**\n ```rust\n use std::ops::Deref;\n let a: &mut String = &mut String::from(\"foo\");\n let b: &str = a.deref();\n ```\n Could be written as:\n ```rust\n let a: &mut String = &mut String::from(\"foo\");\n let b = &*a;\n ```\n\n This lint excludes\n ```rust,ignore\n let _ = d.unwrap().deref();\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "derive_hash_xor_eq", + "id_span": { + "path": "clippy_lints/src/derive.rs", + "line": 42 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for deriving `Hash` but implementing `PartialEq` explicitly or vice versa.\n\n **Why is this bad?** The implementation of these traits must agree (for\n example for use with `HashMap`) so it’s probably a bad idea to use a\n default-generated `Hash` implementation with an explicitly defined\n `PartialEq`. In particular, the following must hold for any type:\n\n ```text\n k1 == k2 ⇒ hash(k1) == hash(k2)\n ```\n\n **Known problems:** None.\n\n **Example:**\n ```ignore\n #[derive(Hash)]\n struct Foo;\n\n impl PartialEq for Foo {\n ...\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "derive_ord_xor_partial_ord", + "id_span": { + "path": "clippy_lints/src/derive.rs", + "line": 93 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for deriving `Ord` but implementing `PartialOrd` explicitly or vice versa.\n\n **Why is this bad?** The implementation of these traits must agree (for\n example for use with `sort`) so it’s probably a bad idea to use a\n default-generated `Ord` implementation with an explicitly defined\n `PartialOrd`. In particular, the following must hold for any type\n implementing `Ord`:\n\n ```text\n k1.cmp(&k2) == k1.partial_cmp(&k2).unwrap()\n ```\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust,ignore\n #[derive(Ord, PartialEq, Eq)]\n struct Foo;\n\n impl PartialOrd for Foo {\n ...\n }\n ```\n Use instead:\n ```rust,ignore\n #[derive(PartialEq, Eq)]\n struct Foo;\n\n impl PartialOrd for Foo {\n fn partial_cmp(&self, other: &Foo) -> Option {\n Some(self.cmp(other))\n }\n }\n\n impl Ord for Foo {\n ...\n }\n ```\n or, if you don't need a custom ordering:\n ```rust,ignore\n #[derive(Ord, PartialOrd, PartialEq, Eq)]\n struct Foo;\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "expl_impl_clone_on_copy", + "id_span": { + "path": "clippy_lints/src/derive.rs", + "line": 119 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for explicit `Clone` implementations for `Copy` types.\n\n **Why is this bad?** To avoid surprising behaviour, these traits should\n agree and the behaviour of `Copy` cannot be overridden. In almost all\n situations a `Copy` type should have a `Clone` implementation that does\n nothing more than copy the object, which is what `#[derive(Copy, Clone)]`\n gets you.\n\n **Known problems:** Bounds of generic types are sometimes wrong: https://github.com/rust-lang/rust/issues/26925\n\n **Example:**\n ```rust,ignore\n #[derive(Copy)]\n struct Foo;\n\n impl Clone for Foo {\n // ..\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "unsafe_derive_deserialize", + "id_span": { + "path": "clippy_lints/src/derive.rs", + "line": 153 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for deriving `serde::Deserialize` on a type that has methods using `unsafe`.\n\n **Why is this bad?** Deriving `serde::Deserialize` will create a constructor\n that may violate invariants hold by another constructor.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust,ignore\n use serde::Deserialize;\n\n #[derive(Deserialize)]\n pub struct Foo {\n // ..\n }\n\n impl Foo {\n pub fn new() -> Self {\n // setup here ..\n }\n\n pub unsafe fn parts() -> (&str, &str) {\n // assumes invariants hold\n }\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "disallowed_method", + "id_span": { + "path": "clippy_lints/src/disallowed_method.rs", + "line": 46 + }, + "group": "clippy::nursery", + "docs": " **What it does:** Denies the configured methods and functions in clippy.toml\n **Why is this bad?** Some methods are undesirable in certain contexts,\n and it's beneficial to lint for them as needed.\n\n **Known problems:** Currently, you must write each function as a\n fully-qualified path. This lint doesn't support aliases or reexported\n names; be aware that many types in `std` are actually reexports.\n\n For example, if you want to disallow `Duration::as_secs`, your clippy.toml\n configuration would look like\n `disallowed-methods = [\"core::time::Duration::as_secs\"]` and not\n `disallowed-methods = [\"std::time::Duration::as_secs\"]` as you might expect.\n\n **Example:**\n\n An example clippy.toml configuration:\n ```toml\n # clippy.toml\n disallowed-methods = [\"alloc::vec::Vec::leak\", \"std::time::Instant::now\"]\n ```\n\n ```rust,ignore\n // Example code where clippy issues a warning\n let xs = vec![1, 2, 3, 4];\n xs.leak(); // Vec::leak is disallowed in the config.\n\n let _now = Instant::now(); // Instant::now is disallowed in the config.\n ```\n\n Use instead:\n ```rust,ignore\n // Example code which does not raise clippy warning\n let mut xs = Vec::new(); // Vec::new is _not_ disallowed in the config.\n xs.push(123); // Vec::push is _not_ disallowed in the config.\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "doc_markdown", + "id_span": { + "path": "clippy_lints/src/doc.rs", + "line": 63 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for the presence of `_`, `::` or camel-case words outside ticks in documentation.\n\n **Why is this bad?** *Rustdoc* supports markdown formatting, `_`, `::` and\n camel-case probably indicates some code which should be included between\n ticks. `_` can also be used for emphasis in markdown, this lint tries to\n consider that.\n\n **Known problems:** Lots of bad docs won’t be fixed, what the lint checks\n for is limited, and there are still false positives.\n\n In addition, when writing documentation comments, including `[]` brackets\n inside a link text would trip the parser. Therfore, documenting link with\n `[`SmallVec<[T; INLINE_CAPACITY]>`]` and then [`SmallVec<[T; INLINE_CAPACITY]>`]: SmallVec\n would fail.\n\n **Examples:**\n ```rust\n /// Do something with the foo_bar parameter. See also\n /// that::other::module::foo.\n // ^ `foo_bar` and `that::other::module::foo` should be ticked.\n fn doit(foo_bar: usize) {}\n ```\n\n ```rust\n // Link text with `[]` brackets should be written as following:\n /// Consume the array and return the inner\n /// [`SmallVec<[T; INLINE_CAPACITY]>`][SmallVec].\n /// [SmallVec]: SmallVec\n fn main() {}\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "missing_safety_doc", + "id_span": { + "path": "clippy_lints/src/doc.rs", + "line": 97 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for the doc comments of publicly visible unsafe functions and warns if there is no `# Safety` section.\n\n **Why is this bad?** Unsafe functions should document their safety\n preconditions, so that users can be sure they are using them safely.\n\n **Known problems:** None.\n\n **Examples:**\n ```rust\n# type Universe = ();\n /// This function should really be documented\n pub unsafe fn start_apocalypse(u: &mut Universe) {\n unimplemented!();\n }\n ```\n\n At least write a line about safety:\n\n ```rust\n# type Universe = ();\n /// # Safety\n ///\n /// This function should not be called before the horsemen are ready.\n pub unsafe fn start_apocalypse(u: &mut Universe) {\n unimplemented!();\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "missing_errors_doc", + "id_span": { + "path": "clippy_lints/src/doc.rs", + "line": 126 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks the doc comments of publicly visible functions that return a `Result` type and warns if there is no `# Errors` section.\n\n **Why is this bad?** Documenting the type of errors that can be returned from a\n function can help callers write code to handle the errors appropriately.\n\n **Known problems:** None.\n\n **Examples:**\n\n Since the following function returns a `Result` it has an `# Errors` section in\n its doc comment:\n\n ```rust\n# use std::io;\n /// # Errors\n ///\n /// Will return `Err` if `filename` does not exist or the user does not have\n /// permission to read it.\n pub fn read(filename: String) -> io::Result {\n unimplemented!();\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "missing_panics_doc", + "id_span": { + "path": "clippy_lints/src/doc.rs", + "line": 157 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks the doc comments of publicly visible functions that may panic and warns if there is no `# Panics` section.\n\n **Why is this bad?** Documenting the scenarios in which panicking occurs\n can help callers who do not want to panic to avoid those situations.\n\n **Known problems:** None.\n\n **Examples:**\n\n Since the following function may panic it has a `# Panics` section in\n its doc comment:\n\n ```rust\n /// # Panics\n ///\n /// Will panic if y is 0\n pub fn divide_by(x: i32, y: i32) -> i32 {\n if y == 0 {\n panic!(\"Cannot divide by 0\")\n } else {\n x / y\n }\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "needless_doctest_main", + "id_span": { + "path": "clippy_lints/src/doc.rs", + "line": 185 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for `fn main() { .. }` in doctests\n **Why is this bad?** The test can be shorter (and likely more readable)\n if the `fn main()` is left implicit.\n\n **Known problems:** None.\n\n **Examples:**\n ``````rust\n /// An example of a doctest with a `main()` function\n ///\n /// # Examples\n ///\n /// ```\n /// fn main() {\n /// // this needs not be in an `fn`\n /// }\n /// ```\n fn needless_main() {\n unimplemented!();\n }\n ``````\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "double_comparisons", + "id_span": { + "path": "clippy_lints/src/double_comparison.rs", + "line": 33 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for double comparisons that could be simplified to a single expression.\n\n **Why is this bad?** Readability.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let x = 1;\n # let y = 2;\n if x == y || x < y {}\n ```\n\n Could be written as:\n\n ```rust\n # let x = 1;\n # let y = 2;\n if x <= y {}\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "double_parens", + "id_span": { + "path": "clippy_lints/src/double_parens.rs", + "line": 35 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for unnecessary double parentheses.\n **Why is this bad?** This makes code harder to read and might indicate a\n mistake.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n // Bad\n fn simple_double_parens() -> i32 {\n ((0))\n }\n\n // Good\n fn simple_no_parens() -> i32 {\n 0\n }\n\n // or\n\n # fn foo(bar: usize) {}\n // Bad\n foo((0));\n\n // Good\n foo(0);\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "drop_ref", + "id_span": { + "path": "clippy_lints/src/drop_forget_ref.rs", + "line": 26 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for calls to `std::mem::drop` with a reference instead of an owned value.\n\n **Why is this bad?** Calling `drop` on a reference will only drop the\n reference itself, which is a no-op. It will not call the `drop` method (from\n the `Drop` trait implementation) on the underlying referenced value, which\n is likely what was intended.\n\n **Known problems:** None.\n\n **Example:**\n ```ignore\n let mut lock_guard = mutex.lock();\n std::mem::drop(&lock_guard) // Should have been drop(lock_guard), mutex\n // still locked\n operation_that_requires_mutex_to_be_unlocked();\n ```\n", + "applicability": null + }, + { + "id": "forget_ref", + "id_span": { + "path": "clippy_lints/src/drop_forget_ref.rs", + "line": 47 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for calls to `std::mem::forget` with a reference instead of an owned value.\n\n **Why is this bad?** Calling `forget` on a reference will only forget the\n reference itself, which is a no-op. It will not forget the underlying\n referenced\n value, which is likely what was intended.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let x = Box::new(1);\n std::mem::forget(&x) // Should have been forget(x), x will still be dropped\n ```\n", + "applicability": null + }, + { + "id": "drop_copy", + "id_span": { + "path": "clippy_lints/src/drop_forget_ref.rs", + "line": 68 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for calls to `std::mem::drop` with a value that derives the Copy trait\n\n **Why is this bad?** Calling `std::mem::drop` [does nothing for types that\n implement Copy](https://doc.rust-lang.org/std/mem/fn.drop.html), since the\n value will be copied and moved into the function on invocation.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let x: i32 = 42; // i32 implements Copy\n std::mem::drop(x) // A copy of x is passed to the function, leaving the\n // original unaffected\n ```\n", + "applicability": null + }, + { + "id": "forget_copy", + "id_span": { + "path": "clippy_lints/src/drop_forget_ref.rs", + "line": 95 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for calls to `std::mem::forget` with a value that derives the Copy trait\n\n **Why is this bad?** Calling `std::mem::forget` [does nothing for types that\n implement Copy](https://doc.rust-lang.org/std/mem/fn.drop.html) since the\n value will be copied and moved into the function on invocation.\n\n An alternative, but also valid, explanation is that Copy types do not\n implement\n the Drop trait, which means they have no destructors. Without a destructor,\n there\n is nothing for `std::mem::forget` to ignore.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let x: i32 = 42; // i32 implements Copy\n std::mem::forget(x) // A copy of x is passed to the function, leaving the\n // original unaffected\n ```\n", + "applicability": null + }, + { + "id": "duration_subsec", + "id_span": { + "path": "clippy_lints/src/duration_subsec.rs", + "line": 34 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for calculation of subsecond microseconds or milliseconds from other `Duration` methods.\n\n **Why is this bad?** It's more concise to call `Duration::subsec_micros()` or\n `Duration::subsec_millis()` than to calculate them.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # use std::time::Duration;\n let dur = Duration::new(5, 0);\n\n // Bad\n let _micros = dur.subsec_nanos() / 1_000;\n let _millis = dur.subsec_nanos() / 1_000_000;\n\n // Good\n let _micros = dur.subsec_micros();\n let _millis = dur.subsec_millis();\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "else_if_without_else", + "id_span": { + "path": "clippy_lints/src/else_if_without_else.rs", + "line": 44 + }, + "group": "clippy::restriction", + "docs": " **What it does:** Checks for usage of if expressions with an `else if` branch, but without a final `else` branch.\n\n **Why is this bad?** Some coding guidelines require this (e.g., MISRA-C:2004 Rule 14.10).\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # fn a() {}\n # fn b() {}\n # let x: i32 = 1;\n if x.is_positive() {\n a();\n } else if x.is_negative() {\n b();\n }\n ```\n\n Could be written:\n\n ```rust\n # fn a() {}\n # fn b() {}\n # let x: i32 = 1;\n if x.is_positive() {\n a();\n } else if x.is_negative() {\n b();\n } else {\n // We don't care about zero.\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "empty_enum", + "id_span": { + "path": "clippy_lints/src/empty_enum.rs", + "line": 38 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for `enum`s with no variants.\n As of this writing, the `never_type` is still a\n nightly-only experimental API. Therefore, this lint is only triggered\n if the `never_type` is enabled.\n\n **Why is this bad?** If you want to introduce a type which\n can't be instantiated, you should use `!` (the primitive type \"never\"),\n or a wrapper around it, because `!` has more extensive\n compiler support (type inference, etc...) and wrappers\n around it are the conventional way to define an uninhabited type.\n For further information visit [never type documentation](https://doc.rust-lang.org/std/primitive.never.html)\n\n\n **Known problems:** None.\n\n **Example:**\n\n Bad:\n ```rust\n enum Test {}\n ```\n\n Good:\n ```rust\n #![feature(never_type)]\n\n struct Test(!);\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "map_entry", + "id_span": { + "path": "clippy_lints/src/entry.rs", + "line": 48 + }, + "group": "clippy::perf", + "docs": " **What it does:** Checks for uses of `contains_key` + `insert` on `HashMap` or `BTreeMap`.\n\n **Why is this bad?** Using `entry` is more efficient.\n\n **Known problems:** Some false negatives, eg.:\n ```rust\n # use std::collections::HashMap;\n # let mut map = HashMap::new();\n # let v = 1;\n # let k = 1;\n if !map.contains_key(&k) {\n map.insert(k.clone(), v);\n }\n ```\n\n **Example:**\n ```rust\n # use std::collections::HashMap;\n # let mut map = HashMap::new();\n # let k = 1;\n # let v = 1;\n if !map.contains_key(&k) {\n map.insert(k, v);\n }\n ```\n can both be rewritten as:\n ```rust\n # use std::collections::HashMap;\n # let mut map = HashMap::new();\n # let k = 1;\n # let v = 1;\n map.entry(k).or_insert(v);\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "enum_clike_unportable_variant", + "id_span": { + "path": "clippy_lints/src/enum_clike.rs", + "line": 31 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for C-like enumerations that are `repr(isize/usize)` and have values that don't fit into an `i32`.\n\n **Why is this bad?** This will truncate the variant value on 32 bit\n architectures, but works fine on 64 bit.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # #[cfg(target_pointer_width = \"64\")]\n #[repr(usize)]\n enum NonPortable {\n X = 0x1_0000_0000,\n Y = 0,\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "enum_variant_names", + "id_span": { + "path": "clippy_lints/src/enum_variants.rs", + "line": 36 + }, + "group": "clippy::style", + "docs": " **What it does:** Detects enumeration variants that are prefixed or suffixed by the same characters.\n\n **Why is this bad?** Enumeration variant names should specify their variant,\n not repeat the enumeration name.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n enum Cake {\n BlackForestCake,\n HummingbirdCake,\n BattenbergCake,\n }\n ```\n Could be written as:\n ```rust\n enum Cake {\n BlackForest,\n Hummingbird,\n Battenberg,\n }\n ```\n", + "applicability": null + }, + { + "id": "pub_enum_variant_names", + "id_span": { + "path": "clippy_lints/src/enum_variants.rs", + "line": 66 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Detects public enumeration variants that are prefixed or suffixed by the same characters.\n\n **Why is this bad?** Public enumeration variant names should specify their variant,\n not repeat the enumeration name.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n pub enum Cake {\n BlackForestCake,\n HummingbirdCake,\n BattenbergCake,\n }\n ```\n Could be written as:\n ```rust\n pub enum Cake {\n BlackForest,\n Hummingbird,\n Battenberg,\n }\n ```\n", + "applicability": null + }, + { + "id": "module_name_repetitions", + "id_span": { + "path": "clippy_lints/src/enum_variants.rs", + "line": 91 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Detects type names that are prefixed or suffixed by the containing module's name.\n\n **Why is this bad?** It requires the user to type the module name twice.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n mod cake {\n struct BlackForestCake;\n }\n ```\n Could be written as:\n ```rust\n mod cake {\n struct BlackForest;\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "module_inception", + "id_span": { + "path": "clippy_lints/src/enum_variants.rs", + "line": 121 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for modules that have the same name as their parent module\n\n **Why is this bad?** A typical beginner mistake is to have `mod foo;` and\n again `mod foo { ..\n }` in `foo.rs`.\n The expectation is that items inside the inner `mod foo { .. }` are then\n available\n through `foo::x`, but they are only available through\n `foo::foo::x`.\n If this is done on purpose, it would be better to choose a more\n representative module name.\n\n **Known problems:** None.\n\n **Example:**\n ```ignore\n // lib.rs\n mod foo;\n // foo.rs\n mod foo {\n ...\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "eq_op", + "id_span": { + "path": "clippy_lints/src/eq_op.rs", + "line": 34 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for equal operands to comparison, logical and bitwise, difference and division binary operators (`==`, `>`, etc., `&&`,\n `||`, `&`, `|`, `^`, `-` and `/`).\n\n **Why is this bad?** This is usually just a typo or a copy and paste error.\n\n **Known problems:** False negatives: We had some false positives regarding\n calls (notably [racer](https://github.com/phildawes/racer) had one instance\n of `x.pop() && x.pop()`), so we removed matching any function or method\n calls. We may introduce a list of known pure functions in the future.\n\n **Example:**\n ```rust\n # let x = 1;\n if x + 1 == x + 1 {}\n ```\n or\n ```rust\n # let a = 3;\n # let b = 4;\n assert_eq!(a, a);\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "op_ref", + "id_span": { + "path": "clippy_lints/src/eq_op.rs", + "line": 56 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for arguments to `==` which have their address taken to satisfy a bound\n and suggests to dereference the other argument instead\n\n **Why is this bad?** It is more idiomatic to dereference the other argument.\n\n **Known problems:** None\n\n **Example:**\n ```ignore\n // Bad\n &x == y\n\n // Good\n x == *y\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MaybeIncorrect" + } + }, + { + "id": "erasing_op", + "id_span": { + "path": "clippy_lints/src/erasing_op.rs", + "line": 25 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for erasing operations, e.g., `x * 0`.\n **Why is this bad?** The whole expression can be replaced by zero.\n This is most likely not the intended outcome and should probably be\n corrected\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let x = 1;\n 0 / x;\n 0 * x;\n x & 0;\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "boxed_local", + "id_span": { + "path": "clippy_lints/src/escape.rs", + "line": 43 + }, + "group": "clippy::perf", + "docs": " **What it does:** Checks for usage of `Box` where an unboxed `T` would work fine.\n\n **Why is this bad?** This is an unnecessary allocation, and bad for\n performance. It is only necessary to allocate if you wish to move the box\n into something.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # fn foo(bar: usize) {}\n // Bad\n let x = Box::new(1);\n foo(*x);\n println!(\"{}\", *x);\n\n // Good\n let x = 1;\n foo(x);\n println!(\"{}\", x);\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "redundant_closure", + "id_span": { + "path": "clippy_lints/src/eta_reduction.rs", + "line": 37 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for closures which just call another function where the function can be called directly. `unsafe` functions or calls where types\n get adjusted are ignored.\n\n **Why is this bad?** Needlessly creating a closure adds code for no benefit\n and gives the optimizer more work.\n\n **Known problems:** If creating the closure inside the closure has a side-\n effect then moving the closure creation out will change when that side-\n effect runs.\n See [#1439](https://github.com/rust-lang/rust-clippy/issues/1439) for more details.\n\n **Example:**\n ```rust,ignore\n // Bad\n xs.map(|x| foo(x))\n\n // Good\n xs.map(foo)\n ```\n where `foo(_)` is a plain function that takes the exact argument type of\n `x`.\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "redundant_closure_for_method_calls", + "id_span": { + "path": "clippy_lints/src/eta_reduction.rs", + "line": 61 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for closures which only invoke a method on the closure argument and can be replaced by referencing the method directly.\n\n **Why is this bad?** It's unnecessary to create the closure.\n\n **Known problems:** [#3071](https://github.com/rust-lang/rust-clippy/issues/3071),\n [#3942](https://github.com/rust-lang/rust-clippy/issues/3942),\n [#4002](https://github.com/rust-lang/rust-clippy/issues/4002)\n\n\n **Example:**\n ```rust,ignore\n Some('a').map(|s| s.to_uppercase());\n ```\n may be rewritten as\n ```rust,ignore\n Some('a').map(char::to_uppercase);\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "eval_order_dependence", + "id_span": { + "path": "clippy_lints/src/eval_order_dependence.rs", + "line": 38 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for a read and a write to the same variable where whether the read occurs before or after the write depends on the evaluation\n order of sub-expressions.\n\n **Why is this bad?** It is often confusing to read. In addition, the\n sub-expression evaluation order for Rust is not well documented.\n\n **Known problems:** Code which intentionally depends on the evaluation\n order, or which is correct for any evaluation order.\n\n **Example:**\n ```rust\n let mut x = 0;\n\n // Bad\n let a = {\n x = 1;\n 1\n } + x;\n // Unclear whether a is 1 or 2.\n\n // Good\n let tmp = {\n x = 1;\n 1\n };\n let a = tmp + x;\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "diverging_sub_expression", + "id_span": { + "path": "clippy_lints/src/eval_order_dependence.rs", + "line": 62 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for diverging calls that are not match arms or statements.\n\n **Why is this bad?** It is often confusing to read. In addition, the\n sub-expression evaluation order for Rust is not well documented.\n\n **Known problems:** Someone might want to use `some_bool || panic!()` as a\n shorthand.\n\n **Example:**\n ```rust,no_run\n # fn b() -> bool { true }\n # fn c() -> bool { true }\n let a = b() || panic!() || c();\n // `c()` is dead, `panic!()` is only called if `b()` returns `false`\n let x = (a, b, c, panic!());\n // can simply be replaced by `panic!()`\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "struct_excessive_bools", + "id_span": { + "path": "clippy_lints/src/excessive_bools.rs", + "line": 40 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for excessive use of bools in structs.\n\n **Why is this bad?** Excessive bools in a struct\n is often a sign that it's used as a state machine,\n which is much better implemented as an enum.\n If it's not the case, excessive bools usually benefit\n from refactoring into two-variant enums for better\n readability and API.\n\n **Known problems:** None.\n\n **Example:**\n Bad:\n ```rust\n struct S {\n is_pending: bool,\n is_processing: bool,\n is_finished: bool,\n }\n ```\n\n Good:\n ```rust\n enum S {\n Pending,\n Processing,\n Finished,\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "fn_params_excessive_bools", + "id_span": { + "path": "clippy_lints/src/excessive_bools.rs", + "line": 78 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for excessive use of bools in function definitions.\n\n **Why is this bad?** Calls to such functions\n are confusing and error prone, because it's\n hard to remember argument order and you have\n no type system support to back you up. Using\n two-variant enums instead of bools often makes\n API easier to use.\n\n **Known problems:** None.\n\n **Example:**\n Bad:\n ```rust,ignore\n fn f(is_round: bool, is_hot: bool) { ... }\n ```\n\n Good:\n ```rust,ignore\n enum Shape {\n Round,\n Spiky,\n }\n\n enum Temperature {\n Hot,\n IceCold,\n }\n\n fn f(shape: Shape, temperature: Temperature) { ... }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "exhaustive_enums", + "id_span": { + "path": "clippy_lints/src/exhaustive_items.rs", + "line": 34 + }, + "group": "clippy::restriction", + "docs": " **What it does:** Warns on any exported `enum`s that are not tagged `#[non_exhaustive]`\n **Why is this bad?** Exhaustive enums are typically fine, but a project which does\n not wish to make a stability commitment around exported enums may wish to\n disable them by default.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n enum Foo {\n Bar,\n Baz\n }\n ```\n Use instead:\n ```rust\n #[non_exhaustive]\n enum Foo {\n Bar,\n Baz\n }\n ```\n", + "applicability": null + }, + { + "id": "exhaustive_structs", + "id_span": { + "path": "clippy_lints/src/exhaustive_items.rs", + "line": 64 + }, + "group": "clippy::restriction", + "docs": " **What it does:** Warns on any exported `structs`s that are not tagged `#[non_exhaustive]`\n **Why is this bad?** Exhaustive structs are typically fine, but a project which does\n not wish to make a stability commitment around exported structs may wish to\n disable them by default.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n struct Foo {\n bar: u8,\n baz: String,\n }\n ```\n Use instead:\n ```rust\n #[non_exhaustive]\n struct Foo {\n bar: u8,\n baz: String,\n }\n ```\n", + "applicability": null + }, + { + "id": "exit", + "id_span": { + "path": "clippy_lints/src/exit.rs", + "line": 20 + }, + "group": "clippy::restriction", + "docs": " **What it does:** `exit()` terminates the program and doesn't provide a stack trace.\n\n **Why is this bad?** Ideally a program is terminated by finishing\n the main function.\n\n **Known problems:** None.\n\n **Example:**\n ```ignore\n std::process::exit(0)\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "explicit_write", + "id_span": { + "path": "clippy_lints/src/explicit_write.rs", + "line": 25 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for usage of `write!()` / `writeln()!` which can be replaced with `(e)print!()` / `(e)println!()`\n\n **Why is this bad?** Using `(e)println! is clearer and more concise\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # use std::io::Write;\n # let bar = \"furchtbar\";\n // this would be clearer as `eprintln!(\"foo: {:?}\", bar);`\n writeln!(&mut std::io::stderr(), \"foo: {:?}\", bar).unwrap();\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "fallible_impl_from", + "id_span": { + "path": "clippy_lints/src/fallible_impl_from.rs", + "line": 45 + }, + "group": "clippy::nursery", + "docs": " **What it does:** Checks for impls of `From<..>` that contain `panic!()` or `unwrap()`\n **Why is this bad?** `TryFrom` should be used if there's a possibility of failure.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n struct Foo(i32);\n\n // Bad\n impl From for Foo {\n fn from(s: String) -> Self {\n Foo(s.parse().unwrap())\n }\n }\n ```\n\n ```rust\n // Good\n struct Foo(i32);\n\n use std::convert::TryFrom;\n impl TryFrom for Foo {\n type Error = ();\n fn try_from(s: String) -> Result {\n if let Ok(parsed) = s.parse() {\n Ok(Foo(parsed))\n } else {\n Err(())\n }\n }\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "float_equality_without_abs", + "id_span": { + "path": "clippy_lints/src/float_equality_without_abs.rs", + "line": 37 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for statements of the form `(a - b) < f32::EPSILON` or `(a - b) < f64::EPSILON`. Notes the missing `.abs()`.\n\n **Why is this bad?** The code without `.abs()` is more likely to have a bug.\n\n **Known problems:** If the user can ensure that b is larger than a, the `.abs()` is\n technically unneccessary. However, it will make the code more robust and doesn't have any\n large performance implications. If the abs call was deliberately left out for performance\n reasons, it is probably better to state this explicitly in the code, which then can be done\n with an allow.\n\n **Example:**\n\n ```rust\n pub fn is_roughly_equal(a: f32, b: f32) -> bool {\n (a - b) < f32::EPSILON\n }\n ```\n Use instead:\n ```rust\n pub fn is_roughly_equal(a: f32, b: f32) -> bool {\n (a - b).abs() < f32::EPSILON\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MaybeIncorrect" + } + }, + { + "id": "excessive_precision", + "id_span": { + "path": "clippy_lints/src/float_literal.rs", + "line": 30 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for float literals with a precision greater than that supported by the underlying type.\n\n **Why is this bad?** Rust will truncate the literal silently.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n // Bad\n let v: f32 = 0.123_456_789_9;\n println!(\"{}\", v); // 0.123_456_789\n\n // Good\n let v: f64 = 0.123_456_789_9;\n println!(\"{}\", v); // 0.123_456_789_9\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "lossy_float_literal", + "id_span": { + "path": "clippy_lints/src/float_literal.rs", + "line": 54 + }, + "group": "clippy::restriction", + "docs": " **What it does:** Checks for whole number float literals that cannot be represented as the underlying type without loss.\n\n **Why is this bad?** Rust will silently lose precision during\n conversion to a float.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n // Bad\n let _: f32 = 16_777_217.0; // 16_777_216.0\n\n // Good\n let _: f32 = 16_777_216.0;\n let _: f64 = 16_777_217.0;\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "imprecise_flops", + "id_span": { + "path": "clippy_lints/src/floating_point_arithmetic.rs", + "line": 45 + }, + "group": "clippy::nursery", + "docs": " **What it does:** Looks for floating-point expressions that can be expressed using built-in methods to improve accuracy\n at the cost of performance.\n\n **Why is this bad?** Negatively impacts accuracy.\n\n **Known problems:** None\n\n **Example:**\n\n ```rust\n let a = 3f32;\n let _ = a.powf(1.0 / 3.0);\n let _ = (1.0 + a).ln();\n let _ = a.exp() - 1.0;\n ```\n\n is better expressed as\n\n ```rust\n let a = 3f32;\n let _ = a.cbrt();\n let _ = a.ln_1p();\n let _ = a.exp_m1();\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "suboptimal_flops", + "id_span": { + "path": "clippy_lints/src/floating_point_arithmetic.rs", + "line": 102 + }, + "group": "clippy::nursery", + "docs": " **What it does:** Looks for floating-point expressions that can be expressed using built-in methods to improve both\n accuracy and performance.\n\n **Why is this bad?** Negatively impacts accuracy and performance.\n\n **Known problems:** None\n\n **Example:**\n\n ```rust\n use std::f32::consts::E;\n\n let a = 3f32;\n let _ = (2f32).powf(a);\n let _ = E.powf(a);\n let _ = a.powf(1.0 / 2.0);\n let _ = a.log(2.0);\n let _ = a.log(10.0);\n let _ = a.log(E);\n let _ = a.powf(2.0);\n let _ = a * 2.0 + 4.0;\n let _ = if a < 0.0 {\n -a\n } else {\n a\n };\n let _ = if a < 0.0 {\n a\n } else {\n -a\n };\n ```\n\n is better expressed as\n\n ```rust\n use std::f32::consts::E;\n\n let a = 3f32;\n let _ = a.exp2();\n let _ = a.exp();\n let _ = a.sqrt();\n let _ = a.log2();\n let _ = a.log10();\n let _ = a.ln();\n let _ = a.powi(2);\n let _ = a.mul_add(2.0, 4.0);\n let _ = a.abs();\n let _ = -a.abs();\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "useless_format", + "id_span": { + "path": "clippy_lints/src/format.rs", + "line": 37 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for the use of `format!(\"string literal with no argument\")` and `format!(\"{}\", foo)` where `foo` is a string.\n\n **Why is this bad?** There is no point of doing that. `format!(\"foo\")` can\n be replaced by `\"foo\".to_owned()` if you really need a `String`. The even\n worse `&format!(\"foo\")` is often encountered in the wild. `format!(\"{}\",\n foo)` can be replaced by `foo.clone()` if `foo: String` or `foo.to_owned()`\n if `foo: &str`.\n\n **Known problems:** None.\n\n **Examples:**\n ```rust\n\n // Bad\n # let foo = \"foo\";\n format!(\"{}\", foo);\n\n // Good\n format!(\"foo\");\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "suspicious_assignment_formatting", + "id_span": { + "path": "clippy_lints/src/formatting.rs", + "line": 22 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for use of the non-existent `=*`, `=!` and `=-` operators.\n\n **Why is this bad?** This is either a typo of `*=`, `!=` or `-=` or\n confusing.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n a =- 42; // confusing, should it be `a -= 42` or `a = -42`?\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "suspicious_unary_op_formatting", + "id_span": { + "path": "clippy_lints/src/formatting.rs", + "line": 44 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks the formatting of a unary operator on the right hand side of a binary operator. It lints if there is no space between the binary and unary operators,\n but there is a space between the unary and its operand.\n\n **Why is this bad?** This is either a typo in the binary operator or confusing.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n if foo <- 30 { // this should be `foo < -30` but looks like a different operator\n }\n\n if foo &&! bar { // this should be `foo && !bar` but looks like a different operator\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "suspicious_else_formatting", + "id_span": { + "path": "clippy_lints/src/formatting.rs", + "line": 80 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for formatting of `else`. It lints if the `else` is followed immediately by a newline or the `else` seems to be missing.\n\n **Why is this bad?** This is probably some refactoring remnant, even if the\n code is correct, it might look confusing.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n if foo {\n } { // looks like an `else` is missing here\n }\n\n if foo {\n } if bar { // looks like an `else` is missing here\n }\n\n if foo {\n } else\n\n { // this is the `else` block of the previous `if`, but should it be?\n }\n\n if foo {\n } else\n\n if bar { // this is the `else` block of the previous `if`, but should it be?\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "possible_missing_comma", + "id_span": { + "path": "clippy_lints/src/formatting.rs", + "line": 100 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for possible missing comma in an array. It lints if an array element is a binary operator expression and it lies on two lines.\n\n **Why is this bad?** This could lead to unexpected results.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n let a = &[\n -1, -2, -3 // <= no comma here\n -4, -5, -6\n ];\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "from_over_into", + "id_span": { + "path": "clippy_lints/src/from_over_into.rs", + "line": 39 + }, + "group": "clippy::style", + "docs": " **What it does:** Searches for implementations of the `Into<..>` trait and suggests to implement `From<..>` instead.\n **Why is this bad?** According the std docs implementing `From<..>` is preferred since it gives you `Into<..>` for free where the reverse isn't true.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n struct StringWrapper(String);\n\n impl Into for String {\n fn into(self) -> StringWrapper {\n StringWrapper(self)\n }\n }\n ```\n Use instead:\n ```rust\n struct StringWrapper(String);\n\n impl From for StringWrapper {\n fn from(s: String) -> StringWrapper {\n StringWrapper(s)\n }\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "from_str_radix_10", + "id_span": { + "path": "clippy_lints/src/from_str_radix_10.rs", + "line": 37 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for function invocations of the form `primitive::from_str_radix(s, 10)`\n\n **Why is this bad?**\n This specific common use case can be rewritten as `s.parse::()`\n (and in most cases, the turbofish can be removed), which reduces code length\n and complexity.\n\n **Known problems:**\n This lint may suggest using (&).parse() instead of .parse() directly\n in some cases, which is correct but adds unnecessary complexity to the code.\n\n **Example:**\n\n ```ignore\n let input: &str = get_input();\n let num = u16::from_str_radix(input, 10)?;\n ```\n Use instead:\n ```ignore\n let input: &str = get_input();\n let num: u16 = input.parse()?;\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MaybeIncorrect" + } + }, + { + "id": "too_many_arguments", + "id_span": { + "path": "clippy_lints/src/functions.rs", + "line": 39 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for functions with too many parameters.\n **Why is this bad?** Functions with lots of parameters are considered bad\n style and reduce readability (“what does the 5th parameter mean?”). Consider\n grouping some parameters into a new type.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # struct Color;\n fn foo(x: u32, y: u32, name: &str, c: Color, w: f32, h: f32, a: f32, b: f32) {\n // ..\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "too_many_lines", + "id_span": { + "path": "clippy_lints/src/functions.rs", + "line": 62 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for functions with a large amount of lines.\n **Why is this bad?** Functions with a lot of lines are harder to understand\n due to having to look at a larger amount of code to understand what the\n function is doing. Consider splitting the body of the function into\n multiple functions.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n fn im_too_long() {\n println!(\"\");\n // ... 100 more LoC\n println!(\"\");\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "not_unsafe_ptr_arg_deref", + "id_span": { + "path": "clippy_lints/src/functions.rs", + "line": 96 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for public functions that dereference raw pointer arguments but are not marked unsafe.\n\n **Why is this bad?** The function should probably be marked `unsafe`, since\n for an arbitrary raw pointer, there is no way of telling for sure if it is\n valid.\n\n **Known problems:**\n\n * It does not check functions recursively so if the pointer is passed to a\n private non-`unsafe` function which does the dereferencing, the lint won't\n trigger.\n * It only checks for arguments whose type are raw pointers, not raw pointers\n got from an argument in some other way (`fn foo(bar: &[*const u8])` or\n `some_argument.get_raw_ptr()`).\n\n **Example:**\n ```rust,ignore\n // Bad\n pub fn foo(x: *const u8) {\n println!(\"{}\", unsafe { *x });\n }\n\n // Good\n pub unsafe fn foo(x: *const u8) {\n println!(\"{}\", unsafe { *x });\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "must_use_unit", + "id_span": { + "path": "clippy_lints/src/functions.rs", + "line": 117 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for a [`#[must_use]`] attribute on unit-returning functions and methods.\n\n [`#[must_use]`]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute\n\n **Why is this bad?** Unit values are useless. The attribute is likely\n a remnant of a refactoring that removed the return type.\n\n **Known problems:** None.\n\n **Examples:**\n ```rust\n #[must_use]\n fn useless() { }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "double_must_use", + "id_span": { + "path": "clippy_lints/src/functions.rs", + "line": 142 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for a [`#[must_use]`] attribute without further information on functions and methods that return a type already\n marked as `#[must_use]`.\n\n [`#[must_use]`]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute\n\n **Why is this bad?** The attribute isn't needed. Not using the result\n will already be reported. Alternatively, one can add some text to the\n attribute to improve the lint message.\n\n **Known problems:** None.\n\n **Examples:**\n ```rust\n #[must_use]\n fn double_must_use() -> Result<(), ()> {\n unimplemented!();\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "must_use_candidate", + "id_span": { + "path": "clippy_lints/src/functions.rs", + "line": 170 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for public functions that have no [`#[must_use]`] attribute, but return something not already marked\n must-use, have no mutable arg and mutate no statics.\n\n [`#[must_use]`]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute\n\n **Why is this bad?** Not bad at all, this lint just shows places where\n you could add the attribute.\n\n **Known problems:** The lint only checks the arguments for mutable\n types without looking if they are actually changed. On the other hand,\n it also ignores a broad range of potentially interesting side effects,\n because we cannot decide whether the programmer intends the function to\n be called for the side effect or the result. Expect many false\n positives. At least we don't lint if the result type is unit or already\n `#[must_use]`.\n\n **Examples:**\n ```rust\n // this could be annotated with `#[must_use]`.\n fn id(t: T) -> T { t }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "result_unit_err", + "id_span": { + "path": "clippy_lints/src/functions.rs", + "line": 216 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for public functions that return a `Result` with an `Err` type of `()`. It suggests using a custom type that\n implements [`std::error::Error`].\n\n **Why is this bad?** Unit does not implement `Error` and carries no\n further information about what went wrong.\n\n **Known problems:** Of course, this lint assumes that `Result` is used\n for a fallible operation (which is after all the intended use). However\n code may opt to (mis)use it as a basic two-variant-enum. In that case,\n the suggestion is misguided, and the code should use a custom enum\n instead.\n\n **Examples:**\n ```rust\n pub fn read_u8() -> Result { Err(()) }\n ```\n should become\n ```rust,should_panic\n use std::fmt;\n\n #[derive(Debug)]\n pub struct EndOfStream;\n\n impl fmt::Display for EndOfStream {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"End of Stream\")\n }\n }\n\n impl std::error::Error for EndOfStream { }\n\n pub fn read_u8() -> Result { Err(EndOfStream) }\n# fn main() {\n# read_u8().unwrap();\n# }\n ```\n\n Note that there are crates that simplify creating the error type, e.g.\n [`thiserror`](https://docs.rs/thiserror).\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "future_not_send", + "id_span": { + "path": "clippy_lints/src/future_not_send.rs", + "line": 44 + }, + "group": "clippy::nursery", + "docs": " **What it does:** This lint requires Future implementations returned from functions and methods to implement the `Send` marker trait. It is mostly\n used by library authors (public and internal) that target an audience where\n multithreaded executors are likely to be used for running these Futures.\n\n **Why is this bad?** A Future implementation captures some state that it\n needs to eventually produce its final value. When targeting a multithreaded\n executor (which is the norm on non-embedded devices) this means that this\n state may need to be transported to other threads, in other words the\n whole Future needs to implement the `Send` marker trait. If it does not,\n then the resulting Future cannot be submitted to a thread pool in the\n end user’s code.\n\n Especially for generic functions it can be confusing to leave the\n discovery of this problem to the end user: the reported error location\n will be far from its cause and can in many cases not even be fixed without\n modifying the library where the offending Future implementation is\n produced.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n async fn not_send(bytes: std::rc::Rc<[u8]>) {}\n ```\n Use instead:\n ```rust\n async fn is_send(bytes: std::sync::Arc<[u8]>) {}\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "get_last_with_len", + "id_span": { + "path": "clippy_lints/src/get_last_with_len.rs", + "line": 40 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for using `x.get(x.len() - 1)` instead of `x.last()`.\n\n **Why is this bad?** Using `x.last()` is easier to read and has the same\n result.\n\n Note that using `x[x.len() - 1]` is semantically different from\n `x.last()`. Indexing into the array will panic on out-of-bounds\n accesses, while `x.get()` and `x.last()` will return `None`.\n\n There is another lint (get_unwrap) that covers the case of using\n `x.get(index).unwrap()` instead of `x[index]`.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n // Bad\n let x = vec![2, 3, 5];\n let last_element = x.get(x.len() - 1);\n\n // Good\n let x = vec![2, 3, 5];\n let last_element = x.last();\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "identity_op", + "id_span": { + "path": "clippy_lints/src/identity_op.rs", + "line": 24 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for identity operations, e.g., `x + 0`.\n **Why is this bad?** This code can be removed without changing the\n meaning. So it just obscures what's going on. Delete it mercilessly.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let x = 1;\n x / 1 + 0 * 1 - 0 | 0;\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "if_let_mutex", + "id_span": { + "path": "clippy_lints/src/if_let_mutex.rs", + "line": 36 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for `Mutex::lock` calls in `if let` expression with lock calls in any of the else blocks.\n\n **Why is this bad?** The Mutex lock remains held for the whole\n `if let ... else` block and deadlocks.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust,ignore\n if let Ok(thing) = mutex.lock() {\n do_thing();\n } else {\n mutex.lock();\n }\n ```\n Should be written\n ```rust,ignore\n let locked = mutex.lock();\n if let Ok(thing) = locked {\n do_thing(thing);\n } else {\n use_locked(locked);\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "if_let_some_result", + "id_span": { + "path": "clippy_lints/src/if_let_some_result.rs", + "line": 34 + }, + "group": "clippy::style", + "docs": " **What it does:*** Checks for unnecessary `ok()` in if let.\n **Why is this bad?** Calling `ok()` in if let is unnecessary, instead match\n on `Ok(pat)`\n\n **Known problems:** None.\n\n **Example:**\n ```ignore\n for i in iter {\n if let Some(value) = i.parse().ok() {\n vec.push(value)\n }\n }\n ```\n Could be written:\n\n ```ignore\n for i in iter {\n if let Ok(value) = i.parse() {\n vec.push(value)\n }\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "if_not_else", + "id_span": { + "path": "clippy_lints/src/if_not_else.rs", + "line": 43 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for usage of `!` or `!=` in an if condition with an else branch.\n\n **Why is this bad?** Negations reduce the readability of statements.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let v: Vec = vec![];\n # fn a() {}\n # fn b() {}\n if !v.is_empty() {\n a()\n } else {\n b()\n }\n ```\n\n Could be written:\n\n ```rust\n # let v: Vec = vec![];\n # fn a() {}\n # fn b() {}\n if v.is_empty() {\n b()\n } else {\n a()\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "implicit_return", + "id_span": { + "path": "clippy_lints/src/implicit_return.rs", + "line": 33 + }, + "group": "clippy::restriction", + "docs": " **What it does:** Checks for missing return statements at the end of a block.\n **Why is this bad?** Actually omitting the return keyword is idiomatic Rust code. Programmers\n coming from other languages might prefer the expressiveness of `return`. It's possible to miss\n the last returning statement because the only difference is a missing `;`. Especially in bigger\n code with multiple return paths having a `return` keyword makes it easier to find the\n corresponding statements.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n fn foo(x: usize) -> usize {\n x\n }\n ```\n add return\n ```rust\n fn foo(x: usize) -> usize {\n return x;\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "implicit_saturating_sub", + "id_span": { + "path": "clippy_lints/src/implicit_saturating_sub.rs", + "line": 32 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for implicit saturating subtraction.\n **Why is this bad?** Simplicity and readability. Instead we can easily use an builtin function.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n let end: u32 = 10;\n let start: u32 = 5;\n\n let mut i: u32 = end - start;\n\n // Bad\n if i != 0 {\n i -= 1;\n }\n\n // Good\n i = i.saturating_sub(1);\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "inconsistent_struct_constructor", + "id_span": { + "path": "clippy_lints/src/inconsistent_struct_constructor.rs", + "line": 58 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for struct constructors where the order of the field init shorthand in the constructor is inconsistent with the order in the struct definition.\n\n **Why is this bad?** Since the order of fields in a constructor doesn't affect the\n resulted instance as the below example indicates,\n\n ```rust\n #[derive(Debug, PartialEq, Eq)]\n struct Foo {\n x: i32,\n y: i32,\n }\n let x = 1;\n let y = 2;\n\n // This assertion never fails.\n assert_eq!(Foo { x, y }, Foo { y, x });\n ```\n\n inconsistent order means nothing and just decreases readability and consistency.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n struct Foo {\n x: i32,\n y: i32,\n }\n let x = 1;\n let y = 2;\n Foo { y, x };\n ```\n\n Use instead:\n ```rust\n # struct Foo {\n # x: i32,\n # y: i32,\n # }\n # let x = 1;\n # let y = 2;\n Foo { x, y };\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "out_of_bounds_indexing", + "id_span": { + "path": "clippy_lints/src/indexing_slicing.rs", + "line": 32 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for out of bounds array indexing with a constant index.\n\n **Why is this bad?** This will always panic at runtime.\n\n **Known problems:** Hopefully none.\n\n **Example:**\n ```no_run\n # #![allow(const_err)]\n let x = [1, 2, 3, 4];\n\n // Bad\n x[9];\n &x[2..9];\n\n // Good\n x[0];\n x[3];\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "indexing_slicing", + "id_span": { + "path": "clippy_lints/src/indexing_slicing.rs", + "line": 81 + }, + "group": "clippy::restriction", + "docs": " **What it does:** Checks for usage of indexing or slicing. Arrays are special cases, this lint does report on arrays if we can tell that slicing operations are in bounds and does not\n lint on constant `usize` indexing on arrays because that is handled by rustc's `const_err` lint.\n\n **Why is this bad?** Indexing and slicing can panic at runtime and there are\n safe alternatives.\n\n **Known problems:** Hopefully none.\n\n **Example:**\n ```rust,no_run\n // Vector\n let x = vec![0; 5];\n\n // Bad\n x[2];\n &x[2..100];\n &x[2..];\n &x[..100];\n\n // Good\n x.get(2);\n x.get(2..100);\n x.get(2..);\n x.get(..100);\n\n // Array\n let y = [0, 1, 2, 3];\n\n // Bad\n &y[10..100];\n &y[10..];\n &y[..100];\n\n // Good\n &y[2..];\n &y[..2];\n &y[0..3];\n y.get(10);\n y.get(10..100);\n y.get(10..);\n y.get(..100);\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "infinite_iter", + "id_span": { + "path": "clippy_lints/src/infinite_iter.rs", + "line": 21 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for iteration that is guaranteed to be infinite.\n **Why is this bad?** While there may be places where this is acceptable\n (e.g., in event streams), in most cases this is simply an error.\n\n **Known problems:** None.\n\n **Example:**\n ```no_run\n use std::iter;\n\n iter::repeat(1_u8).collect::>();\n ```\n", + "applicability": null + }, + { + "id": "maybe_infinite_iter", + "id_span": { + "path": "clippy_lints/src/infinite_iter.rs", + "line": 40 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for iteration that may be infinite.\n **Why is this bad?** While there may be places where this is acceptable\n (e.g., in event streams), in most cases this is simply an error.\n\n **Known problems:** The code may have a condition to stop iteration, but\n this lint is not clever enough to analyze it.\n\n **Example:**\n ```rust\n let infinite_iter = 0..;\n [0..].iter().zip(infinite_iter.take_while(|x| *x > 5));\n ```\n", + "applicability": null + }, + { + "id": "multiple_inherent_impl", + "id_span": { + "path": "clippy_lints/src/inherent_impl.rs", + "line": 37 + }, + "group": "clippy::restriction", + "docs": " **What it does:** Checks for multiple inherent implementations of a struct\n **Why is this bad?** Splitting the implementation of a type makes the code harder to navigate.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n struct X;\n impl X {\n fn one() {}\n }\n impl X {\n fn other() {}\n }\n ```\n\n Could be written:\n\n ```rust\n struct X;\n impl X {\n fn one() {}\n fn other() {}\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "inherent_to_string", + "id_span": { + "path": "clippy_lints/src/inherent_to_string.rs", + "line": 44 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for the definition of inherent methods with a signature of `to_string(&self) -> String`.\n **Why is this bad?** This method is also implicitly defined if a type implements the `Display` trait. As the functionality of `Display` is much more versatile, it should be preferred.\n\n **Known problems:** None\n\n ** Example:**\n\n ```rust\n // Bad\n pub struct A;\n\n impl A {\n pub fn to_string(&self) -> String {\n \"I am A\".to_string()\n }\n }\n ```\n\n ```rust\n // Good\n use std::fmt;\n\n pub struct A;\n\n impl fmt::Display for A {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n write!(f, \"I am A\")\n }\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "inherent_to_string_shadow_display", + "id_span": { + "path": "clippy_lints/src/inherent_to_string.rs", + "line": 89 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for the definition of inherent methods with a signature of `to_string(&self) -> String` and if the type implementing this method also implements the `Display` trait.\n **Why is this bad?** This method is also implicitly defined if a type implements the `Display` trait. The less versatile inherent method will then shadow the implementation introduced by `Display`.\n\n **Known problems:** None\n\n ** Example:**\n\n ```rust\n // Bad\n use std::fmt;\n\n pub struct A;\n\n impl A {\n pub fn to_string(&self) -> String {\n \"I am A\".to_string()\n }\n }\n\n impl fmt::Display for A {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n write!(f, \"I am A, too\")\n }\n }\n ```\n\n ```rust\n // Good\n use std::fmt;\n\n pub struct A;\n\n impl fmt::Display for A {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n write!(f, \"I am A\")\n }\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "inline_fn_without_body", + "id_span": { + "path": "clippy_lints/src/inline_fn_without_body.rs", + "line": 27 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for `#[inline]` on trait methods without bodies\n **Why is this bad?** Only implementations of trait methods may be inlined.\n The inline attribute is ignored for trait methods without bodies.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n trait Animal {\n #[inline]\n fn name(&self) -> &'static str;\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "int_plus_one", + "id_span": { + "path": "clippy_lints/src/int_plus_one.rs", + "line": 31 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for usage of `x >= y + 1` or `x - 1 >= y` (and `<=`) in a block\n **Why is this bad?** Readability -- better to use `> y` instead of `>= y + 1`.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let x = 1;\n # let y = 1;\n if x >= y + 1 {}\n ```\n\n Could be written as:\n\n ```rust\n # let x = 1;\n # let y = 1;\n if x > y {}\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "integer_division", + "id_span": { + "path": "clippy_lints/src/integer_division.rs", + "line": 26 + }, + "group": "clippy::restriction", + "docs": " **What it does:** Checks for division of integers\n **Why is this bad?** When outside of some very specific algorithms,\n integer division is very often a mistake because it discards the\n remainder.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n // Bad\n let x = 3 / 2;\n println!(\"{}\", x);\n\n // Good\n let x = 3f32 / 2f32;\n println!(\"{}\", x);\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "items_after_statements", + "id_span": { + "path": "clippy_lints/src/items_after_statements.rs", + "line": 48 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for items declared after some statement in a block.\n **Why is this bad?** Items live for the entire scope they are declared\n in. But statements are processed in order. This might cause confusion as\n it's hard to figure out which item is meant in a statement.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n // Bad\n fn foo() {\n println!(\"cake\");\n }\n\n fn main() {\n foo(); // prints \"foo\"\n fn foo() {\n println!(\"foo\");\n }\n foo(); // prints \"foo\"\n }\n ```\n\n ```rust\n // Good\n fn foo() {\n println!(\"cake\");\n }\n\n fn main() {\n fn foo() {\n println!(\"foo\");\n }\n foo(); // prints \"foo\"\n foo(); // prints \"foo\"\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "large_const_arrays", + "id_span": { + "path": "clippy_lints/src/large_const_arrays.rs", + "line": 30 + }, + "group": "clippy::perf", + "docs": " **What it does:** Checks for large `const` arrays that should be defined as `static` instead.\n\n **Why is this bad?** Performance: const variables are inlined upon use.\n Static items result in only one instance and has a fixed location in memory.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n // Bad\n pub const a = [0u32; 1_000_000];\n\n // Good\n pub static a = [0u32; 1_000_000];\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "large_enum_variant", + "id_span": { + "path": "clippy_lints/src/large_enum_variant.rs", + "line": 39 + }, + "group": "clippy::perf", + "docs": " **What it does:** Checks for large size differences between variants on `enum`s.\n\n **Why is this bad?** Enum size is bounded by the largest variant. Having a\n large variant can penalize the memory layout of that enum.\n\n **Known problems:** This lint obviously cannot take the distribution of\n variants in your running program into account. It is possible that the\n smaller variants make up less than 1% of all instances, in which case\n the overhead is negligible and the boxing is counter-productive. Always\n measure the change this lint suggests.\n\n **Example:**\n\n ```rust\n // Bad\n enum Test {\n A(i32),\n B([i32; 8000]),\n }\n\n // Possibly better\n enum Test2 {\n A(i32),\n B(Box<[i32; 8000]>),\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MaybeIncorrect" + } + }, + { + "id": "large_stack_arrays", + "id_span": { + "path": "clippy_lints/src/large_stack_arrays.rs", + "line": 23 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for local arrays that may be too large.\n **Why is this bad?** Large local arrays may cause stack overflow.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n let a = [0u32; 1_000_000];\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "len_zero", + "id_span": { + "path": "clippy_lints/src/len_zero.rs", + "line": 41 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for getting the length of something via `.len()` just to compare to zero, and suggests using `.is_empty()` where applicable.\n\n **Why is this bad?** Some structures can answer `.is_empty()` much faster\n than calculating their length. So it is good to get into the habit of using\n `.is_empty()`, and having it is cheap.\n Besides, it makes the intent clearer than a manual comparison in some contexts.\n\n **Known problems:** None.\n\n **Example:**\n ```ignore\n if x.len() == 0 {\n ..\n }\n if y.len() != 0 {\n ..\n }\n ```\n instead use\n ```ignore\n if x.is_empty() {\n ..\n }\n if !y.is_empty() {\n ..\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "len_without_is_empty", + "id_span": { + "path": "clippy_lints/src/len_zero.rs", + "line": 66 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for items that implement `.len()` but not `.is_empty()`.\n\n **Why is this bad?** It is good custom to have both methods, because for\n some data structures, asking about the length will be a costly operation,\n whereas `.is_empty()` can usually answer in constant time. Also it used to\n lead to false positives on the [`len_zero`](#len_zero) lint – currently that\n lint will ignore such entities.\n\n **Known problems:** None.\n\n **Example:**\n ```ignore\n impl X {\n pub fn len(&self) -> usize {\n ..\n }\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "comparison_to_empty", + "id_span": { + "path": "clippy_lints/src/len_zero.rs", + "line": 103 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for comparing to an empty slice such as `\"\"` or `[]`, and suggests using `.is_empty()` where applicable.\n\n **Why is this bad?** Some structures can answer `.is_empty()` much faster\n than checking for equality. So it is good to get into the habit of using\n `.is_empty()`, and having it is cheap.\n Besides, it makes the intent clearer than a manual comparison in some contexts.\n\n **Known problems:** None.\n\n **Example:**\n\n ```ignore\n if s == \"\" {\n ..\n }\n\n if arr == [] {\n ..\n }\n ```\n Use instead:\n ```ignore\n if s.is_empty() {\n ..\n }\n\n if arr.is_empty() {\n ..\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "useless_let_if_seq", + "id_span": { + "path": "clippy_lints/src/let_if_seq.rs", + "line": 49 + }, + "group": "clippy::nursery", + "docs": " **What it does:** Checks for variable declarations immediately followed by a conditional affectation.\n\n **Why is this bad?** This is not idiomatic Rust.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n let foo;\n\n if bar() {\n foo = 42;\n } else {\n foo = 0;\n }\n\n let mut baz = None;\n\n if bar() {\n baz = Some(42);\n }\n ```\n\n should be written\n\n ```rust,ignore\n let foo = if bar() {\n 42\n } else {\n 0\n };\n\n let baz = if bar() {\n Some(42)\n } else {\n None\n };\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "HasPlaceholders" + } + }, + { + "id": "let_underscore_must_use", + "id_span": { + "path": "clippy_lints/src/let_underscore.rs", + "line": 29 + }, + "group": "clippy::restriction", + "docs": " **What it does:** Checks for `let _ = ` where expr is #[must_use]\n\n **Why is this bad?** It's better to explicitly\n handle the value of a #[must_use] expr\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n fn f() -> Result {\n Ok(0)\n }\n\n let _ = f();\n // is_ok() is marked #[must_use]\n let _ = f().is_ok();\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "let_underscore_lock", + "id_span": { + "path": "clippy_lints/src/let_underscore.rs", + "line": 56 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for `let _ = sync_lock`\n **Why is this bad?** This statement immediately drops the lock instead of\n extending its lifetime to the end of the scope, which is often not intended.\n To extend lock lifetime to the end of the scope, use an underscore-prefixed\n name instead (i.e. _lock). If you want to explicitly drop the lock,\n `std::mem::drop` conveys your intention better and is less error-prone.\n\n **Known problems:** None.\n\n **Example:**\n\n Bad:\n ```rust,ignore\n let _ = mutex.lock();\n ```\n\n Good:\n ```rust,ignore\n let _lock = mutex.lock();\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "let_underscore_drop", + "id_span": { + "path": "clippy_lints/src/let_underscore.rs", + "line": 97 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for `let _ = ` where expr has a type that implements `Drop`\n\n **Why is this bad?** This statement immediately drops the initializer\n expression instead of extending its lifetime to the end of the scope, which\n is often not intended. To extend the expression's lifetime to the end of the\n scope, use an underscore-prefixed name instead (i.e. _var). If you want to\n explicitly drop the expression, `std::mem::drop` conveys your intention\n better and is less error-prone.\n\n **Known problems:** None.\n\n **Example:**\n\n Bad:\n ```rust,ignore\n struct Droppable;\n impl Drop for Droppable {\n fn drop(&mut self) {}\n }\n {\n let _ = Droppable;\n // ^ dropped here\n /* more code */\n }\n ```\n\n Good:\n ```rust,ignore\n {\n let _droppable = Droppable;\n /* more code */\n // dropped at end of scope\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "needless_lifetimes", + "id_span": { + "path": "clippy_lints/src/lifetimes.rs", + "line": 46 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for lifetime annotations which can be removed by relying on lifetime elision.\n\n **Why is this bad?** The additional lifetimes make the code look more\n complicated, while there is nothing out of the ordinary going on. Removing\n them leads to more readable code.\n\n **Known problems:**\n - We bail out if the function has a `where` clause where lifetimes\n are mentioned due to potenial false positives.\n - Lifetime bounds such as `impl Foo + 'a` and `T: 'a` must be elided with the\n placeholder notation `'_` because the fully elided notation leaves the type bound to `'static`.\n\n **Example:**\n ```rust\n // Bad: unnecessary lifetime annotations\n fn in_and_out<'a>(x: &'a u8, y: u8) -> &'a u8 {\n x\n }\n\n // Good\n fn elided(x: &u8, y: u8) -> &u8 {\n x\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "extra_unused_lifetimes", + "id_span": { + "path": "clippy_lints/src/lifetimes.rs", + "line": 74 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for lifetimes in generics that are never used anywhere else.\n\n **Why is this bad?** The additional lifetimes make the code look more\n complicated, while there is nothing out of the ordinary going on. Removing\n them leads to more readable code.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n // Bad: unnecessary lifetimes\n fn unused_lifetime<'a>(x: u8) {\n // ..\n }\n\n // Good\n fn no_lifetime(x: u8) {\n // ...\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "unreadable_literal", + "id_span": { + "path": "clippy_lints/src/literal_representation.rs", + "line": 33 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Warns if a long integral or floating-point constant does not contain underscores.\n\n **Why is this bad?** Reading long numbers is difficult without separators.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n // Bad\n let x: u64 = 61864918973511;\n\n // Good\n let x: u64 = 61_864_918_973_511;\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "mistyped_literal_suffixes", + "id_span": { + "path": "clippy_lints/src/literal_representation.rs", + "line": 57 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Warns for mistyped suffix in literals\n **Why is this bad?** This is most probably a typo\n\n **Known problems:**\n - Recommends a signed suffix, even though the number might be too big and an unsigned\n suffix is required\n - Does not match on `_127` since that is a valid grouping for decimal and octal numbers\n\n **Example:**\n\n ```rust\n // Probably mistyped\n 2_32;\n\n // Good\n 2_i32;\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MaybeIncorrect" + } + }, + { + "id": "inconsistent_digit_grouping", + "id_span": { + "path": "clippy_lints/src/literal_representation.rs", + "line": 80 + }, + "group": "clippy::style", + "docs": " **What it does:** Warns if an integral or floating-point constant is grouped inconsistently with underscores.\n\n **Why is this bad?** Readers may incorrectly interpret inconsistently\n grouped digits.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n // Bad\n let x: u64 = 618_64_9189_73_511;\n\n // Good\n let x: u64 = 61_864_918_973_511;\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "unusual_byte_groupings", + "id_span": { + "path": "clippy_lints/src/literal_representation.rs", + "line": 99 + }, + "group": "clippy::style", + "docs": " **What it does:** Warns if hexadecimal or binary literals are not grouped by nibble or byte.\n\n **Why is this bad?** Negatively impacts readability.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n let x: u32 = 0xFFF_FFF;\n let y: u8 = 0b01_011_101;\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "large_digit_groups", + "id_span": { + "path": "clippy_lints/src/literal_representation.rs", + "line": 118 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Warns if the digits of an integral or floating-point constant are grouped into groups that\n are too large.\n\n **Why is this bad?** Negatively impacts readability.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n let x: u64 = 6186491_8973511;\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "decimal_literal_representation", + "id_span": { + "path": "clippy_lints/src/literal_representation.rs", + "line": 136 + }, + "group": "clippy::restriction", + "docs": " **What it does:** Warns if there is a better representation for a numeric literal.\n **Why is this bad?** Especially for big powers of 2 a hexadecimal representation is more\n readable than a decimal representation.\n\n **Known problems:** None.\n\n **Example:**\n\n `255` => `0xFF`\n `65_535` => `0xFFFF`\n `4_042_322_160` => `0xF0F0_F0F0`\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "manual_memcpy", + "id_span": { + "path": "clippy_lints/src/loops.rs", + "line": 57 + }, + "group": "clippy::perf", + "docs": " **What it does:** Checks for for-loops that manually copy items between slices that could be optimized by having a memcpy.\n\n **Why is this bad?** It is not as fast as a memcpy.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let src = vec![1];\n # let mut dst = vec![0; 65];\n for i in 0..src.len() {\n dst[i + 64] = src[i];\n }\n ```\n Could be written as:\n ```rust\n # let src = vec![1];\n # let mut dst = vec![0; 65];\n dst[64..(src.len() + 64)].clone_from_slice(&src[..]);\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "Unspecified" + } + }, + { + "id": "needless_range_loop", + "id_span": { + "path": "clippy_lints/src/loops.rs", + "line": 85 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for looping over the range of `0..len` of some collection just to get the values by index.\n\n **Why is this bad?** Just iterating the collection itself makes the intent\n more clear and is probably faster.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let vec = vec!['a', 'b', 'c'];\n for i in 0..vec.len() {\n println!(\"{}\", vec[i]);\n }\n ```\n Could be written as:\n ```rust\n let vec = vec!['a', 'b', 'c'];\n for i in vec {\n println!(\"{}\", i);\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "explicit_iter_loop", + "id_span": { + "path": "clippy_lints/src/loops.rs", + "line": 114 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for loops on `x.iter()` where `&x` will do, and suggests the latter.\n\n **Why is this bad?** Readability.\n\n **Known problems:** False negatives. We currently only warn on some known\n types.\n\n **Example:**\n ```rust\n // with `y` a `Vec` or slice:\n # let y = vec![1];\n for x in y.iter() {\n // ..\n }\n ```\n can be rewritten to\n ```rust\n # let y = vec![1];\n for x in &y {\n // ..\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "explicit_into_iter_loop", + "id_span": { + "path": "clippy_lints/src/loops.rs", + "line": 142 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for loops on `y.into_iter()` where `y` will do, and suggests the latter.\n\n **Why is this bad?** Readability.\n\n **Known problems:** None\n\n **Example:**\n ```rust\n # let y = vec![1];\n // with `y` a `Vec` or slice:\n for x in y.into_iter() {\n // ..\n }\n ```\n can be rewritten to\n ```rust\n # let y = vec![1];\n for x in y {\n // ..\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "iter_next_loop", + "id_span": { + "path": "clippy_lints/src/loops.rs", + "line": 165 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for loops on `x.next()`.\n **Why is this bad?** `next()` returns either `Some(value)` if there was a\n value, or `None` otherwise. The insidious thing is that `Option<_>`\n implements `IntoIterator`, so that possibly one value will be iterated,\n leading to some hard to find bugs. No one will want to write such code\n [except to win an Underhanded Rust\n Contest](https://www.reddit.com/r/rust/comments/3hb0wm/underhanded_rust_contest/cu5yuhr).\n\n **Known problems:** None.\n\n **Example:**\n ```ignore\n for x in y.next() {\n ..\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "for_loops_over_fallibles", + "id_span": { + "path": "clippy_lints/src/loops.rs", + "line": 208 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for `for` loops over `Option` or `Result` values.\n **Why is this bad?** Readability. This is more clearly expressed as an `if\n let`.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let opt = Some(1);\n\n // Bad\n for x in opt {\n // ..\n }\n\n // Good\n if let Some(x) = opt {\n // ..\n }\n ```\n\n // or\n\n ```rust\n # let res: Result = Ok(1);\n\n // Bad\n for x in &res {\n // ..\n }\n\n // Good\n if let Ok(x) = res {\n // ..\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "while_let_loop", + "id_span": { + "path": "clippy_lints/src/loops.rs", + "line": 237 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Detects `loop + match` combinations that are easier written as a `while let` loop.\n\n **Why is this bad?** The `while let` loop is usually shorter and more\n readable.\n\n **Known problems:** Sometimes the wrong binding is displayed ([#383](https://github.com/rust-lang/rust-clippy/issues/383)).\n\n **Example:**\n ```rust,no_run\n # let y = Some(1);\n loop {\n let x = match y {\n Some(x) => x,\n None => break,\n };\n // .. do something with x\n }\n // is easier written as\n while let Some(x) = y {\n // .. do something with x\n };\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "HasPlaceholders" + } + }, + { + "id": "needless_collect", + "id_span": { + "path": "clippy_lints/src/loops.rs", + "line": 259 + }, + "group": "clippy::perf", + "docs": " **What it does:** Checks for functions collecting an iterator when collect is not needed.\n\n **Why is this bad?** `collect` causes the allocation of a new data structure,\n when this allocation may not be needed.\n\n **Known problems:**\n None\n\n **Example:**\n ```rust\n # let iterator = vec![1].into_iter();\n let len = iterator.clone().collect::>().len();\n // should be\n let len = iterator.count();\n ```\n", + "applicability": { + "is_multi_suggestion": true, + "applicability": "MachineApplicable" + } + }, + { + "id": "explicit_counter_loop", + "id_span": { + "path": "clippy_lints/src/loops.rs", + "line": 289 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks `for` loops over slices with an explicit counter and suggests the use of `.enumerate()`.\n\n **Why is it bad?** Using `.enumerate()` makes the intent more clear,\n declutters the code and may be faster in some instances.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let v = vec![1];\n # fn bar(bar: usize, baz: usize) {}\n let mut i = 0;\n for item in &v {\n bar(i, *item);\n i += 1;\n }\n ```\n Could be written as\n ```rust\n # let v = vec![1];\n # fn bar(bar: usize, baz: usize) {}\n for (i, item) in v.iter().enumerate() { bar(i, *item); }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "empty_loop", + "id_span": { + "path": "clippy_lints/src/loops.rs", + "line": 322 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for empty `loop` expressions.\n **Why is this bad?** These busy loops burn CPU cycles without doing\n anything. It is _almost always_ a better idea to `panic!` than to have\n a busy loop.\n\n If panicking isn't possible, think of the environment and either:\n - block on something\n - sleep the thread for some microseconds\n - yield or pause the thread\n\n For `std` targets, this can be done with\n [`std::thread::sleep`](https://doc.rust-lang.org/std/thread/fn.sleep.html)\n or [`std::thread::yield_now`](https://doc.rust-lang.org/std/thread/fn.yield_now.html).\n\n For `no_std` targets, doing this is more complicated, especially because\n `#[panic_handler]`s can't panic. To stop/pause the thread, you will\n probably need to invoke some target-specific intrinsic. Examples include:\n - [`x86_64::instructions::hlt`](https://docs.rs/x86_64/0.12.2/x86_64/instructions/fn.hlt.html)\n - [`cortex_m::asm::wfi`](https://docs.rs/cortex-m/0.6.3/cortex_m/asm/fn.wfi.html)\n\n **Known problems:** None.\n\n **Example:**\n ```no_run\n loop {}\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "while_let_on_iterator", + "id_span": { + "path": "clippy_lints/src/loops.rs", + "line": 341 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for `while let` expressions on iterators.\n **Why is this bad?** Readability. A simple `for` loop is shorter and conveys\n the intent better.\n\n **Known problems:** None.\n\n **Example:**\n ```ignore\n while let Some(val) = iter() {\n ..\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "for_kv_map", + "id_span": { + "path": "clippy_lints/src/loops.rs", + "line": 369 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for iterating a map (`HashMap` or `BTreeMap`) and ignoring either the keys or values.\n\n **Why is this bad?** Readability. There are `keys` and `values` methods that\n can be used to express that don't need the values or keys.\n\n **Known problems:** None.\n\n **Example:**\n ```ignore\n for (k, _) in &map {\n ..\n }\n ```\n\n could be replaced by\n\n ```ignore\n for k in map.keys() {\n ..\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "never_loop", + "id_span": { + "path": "clippy_lints/src/loops.rs", + "line": 390 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for loops that will always `break`, `return` or `continue` an outer loop.\n\n **Why is this bad?** This loop never loops, all it does is obfuscating the\n code.\n\n **Known problems:** None\n\n **Example:**\n ```rust\n loop {\n ..;\n break;\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "mut_range_bound", + "id_span": { + "path": "clippy_lints/src/loops.rs", + "line": 410 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for loops which have a range bound that is a mutable variable\n **Why is this bad?** One might think that modifying the mutable variable changes the loop bounds\n\n **Known problems:** None\n\n **Example:**\n ```rust\n let mut foo = 42;\n for i in 0..foo {\n foo -= 1;\n println!(\"{}\", i); // prints numbers from 0 to 42, not 0 to 21\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "while_immutable_condition", + "id_span": { + "path": "clippy_lints/src/loops.rs", + "line": 433 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks whether variables used within while loop condition can be (and are) mutated in the body.\n\n **Why is this bad?** If the condition is unchanged, entering the body of the loop\n will lead to an infinite loop.\n\n **Known problems:** If the `while`-loop is in a closure, the check for mutation of the\n condition variables in the body can cause false negatives. For example when only `Upvar` `a` is\n in the condition and only `Upvar` `b` gets mutated in the body, the lint will not trigger.\n\n **Example:**\n ```rust\n let i = 0;\n while i > 10 {\n println!(\"let me loop forever!\");\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "same_item_push", + "id_span": { + "path": "clippy_lints/src/loops.rs", + "line": 466 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks whether a for loop is being used to push a constant value into a Vec.\n\n **Why is this bad?** This kind of operation can be expressed more succinctly with\n `vec![item;SIZE]` or `vec.resize(NEW_SIZE, item)` and using these alternatives may also\n have better performance.\n **Known problems:** None\n\n **Example:**\n ```rust\n let item1 = 2;\n let item2 = 3;\n let mut vec: Vec = Vec::new();\n for _ in 0..20 {\n vec.push(item1);\n }\n for _ in 0..30 {\n vec.push(item2);\n }\n ```\n could be written as\n ```rust\n let item1 = 2;\n let item2 = 3;\n let mut vec: Vec = vec![item1; 20];\n vec.resize(20 + 30, item2);\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "single_element_loop", + "id_span": { + "path": "clippy_lints/src/loops.rs", + "line": 491 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks whether a for loop has a single element.\n **Why is this bad?** There is no reason to have a loop of a\n single element.\n **Known problems:** None\n\n **Example:**\n ```rust\n let item1 = 2;\n for item in &[item1] {\n println!(\"{}\", item);\n }\n ```\n could be written as\n ```rust\n let item1 = 2;\n let item = &item1;\n println!(\"{}\", item);\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "manual_flatten", + "id_span": { + "path": "clippy_lints/src/loops.rs", + "line": 522 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Check for unnecessary `if let` usage in a for loop where only the `Some` or `Ok` variant of the iterator element is used.\n\n **Why is this bad?** It is verbose and can be simplified\n by first calling the `flatten` method on the `Iterator`.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n let x = vec![Some(1), Some(2), Some(3)];\n for n in x {\n if let Some(n) = n {\n println!(\"{}\", n);\n }\n }\n ```\n Use instead:\n ```rust\n let x = vec![Some(1), Some(2), Some(3)];\n for n in x.into_iter().flatten() {\n println!(\"{}\", n);\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MaybeIncorrect" + } + }, + { + "id": "macro_use_imports", + "id_span": { + "path": "clippy_lints/src/macro_use.rs", + "line": 25 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for `#[macro_use] use...`.\n **Why is this bad?** Since the Rust 2018 edition you can import\n macro's directly, this is considered idiomatic.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n #[macro_use]\n use some_macro;\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MaybeIncorrect" + } + }, + { + "id": "main_recursion", + "id_span": { + "path": "clippy_lints/src/main_recursion.rs", + "line": 22 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for recursion using the entrypoint.\n **Why is this bad?** Apart from special setups (which we could detect following attributes like #![no_std]),\n recursing into main() seems like an unintuitive antipattern we should be able to detect.\n\n **Known problems:** None.\n\n **Example:**\n ```no_run\n fn main() {\n main();\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "manual_async_fn", + "id_span": { + "path": "clippy_lints/src/manual_async_fn.rs", + "line": 32 + }, + "group": "clippy::style", + "docs": " **What it does:** It checks for manual implementations of `async` functions.\n **Why is this bad?** It's more idiomatic to use the dedicated syntax.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n use std::future::Future;\n\n fn foo() -> impl Future { async { 42 } }\n ```\n Use instead:\n ```rust\n async fn foo() -> i32 { 42 }\n ```\n", + "applicability": { + "is_multi_suggestion": true, + "applicability": "MachineApplicable" + } + }, + { + "id": "manual_map", + "id_span": { + "path": "clippy_lints/src/manual_map.rs", + "line": 36 + }, + "group": "clippy::nursery", + "docs": " **What it does:** Checks for usages of `match` which could be implemented using `map`\n **Why is this bad?** Using the `map` method is clearer and more concise.\n\n **Known problems:** `map` is not capable of representing some control flow which works fine in `match`.\n\n **Example:**\n\n ```rust\n match Some(0) {\n Some(x) => Some(x + 1),\n None => None,\n };\n ```\n Use instead:\n ```rust\n Some(0).map(|x| x + 1);\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "manual_non_exhaustive", + "id_span": { + "path": "clippy_lints/src/manual_non_exhaustive.rs", + "line": 56 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for manual implementations of the non-exhaustive pattern.\n **Why is this bad?** Using the #[non_exhaustive] attribute expresses better the intent\n and allows possible optimizations when applied to enums.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n struct S {\n pub a: i32,\n pub b: i32,\n _c: (),\n }\n\n enum E {\n A,\n B,\n #[doc(hidden)]\n _C,\n }\n\n struct T(pub i32, pub i32, ());\n ```\n Use instead:\n ```rust\n #[non_exhaustive]\n struct S {\n pub a: i32,\n pub b: i32,\n }\n\n #[non_exhaustive]\n enum E {\n A,\n B,\n }\n\n #[non_exhaustive]\n struct T(pub i32, pub i32);\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "Unspecified" + } + }, + { + "id": "manual_ok_or", + "id_span": { + "path": "clippy_lints/src/manual_ok_or.rs", + "line": 34 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Finds patterns that reimplement `Option::ok_or`.\n\n **Why is this bad?**\n Concise code helps focusing on behavior instead of boilerplate.\n\n **Known problems:** None.\n\n **Examples:**\n ```rust\n let foo: Option = None;\n foo.map_or(Err(\"error\"), |v| Ok(v));\n ```\n\n Use instead:\n ```rust\n let foo: Option = None;\n foo.ok_or(\"error\");\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "manual_strip", + "id_span": { + "path": "clippy_lints/src/manual_strip.rs", + "line": 52 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Suggests using `strip_{prefix,suffix}` over `str::{starts,ends}_with` and slicing using\n the pattern's length.\n\n **Why is this bad?**\n Using `str:strip_{prefix,suffix}` is safer and may have better performance as there is no\n slicing which may panic and the compiler does not need to insert this panic code. It is\n also sometimes more readable as it removes the need for duplicating or storing the pattern\n used by `str::{starts,ends}_with` and in the slicing.\n\n **Known problems:**\n None.\n\n **Example:**\n\n ```rust\n let s = \"hello, world!\";\n if s.starts_with(\"hello, \") {\n assert_eq!(s[\"hello, \".len()..].to_uppercase(), \"WORLD!\");\n }\n ```\n Use instead:\n ```rust\n let s = \"hello, world!\";\n if let Some(end) = s.strip_prefix(\"hello, \") {\n assert_eq!(end.to_uppercase(), \"WORLD!\");\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "manual_unwrap_or", + "id_span": { + "path": "clippy_lints/src/manual_unwrap_or.rs", + "line": 36 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Finds patterns that reimplement `Option::unwrap_or` or `Result::unwrap_or`.\n\n **Why is this bad?**\n Concise code helps focusing on behavior instead of boilerplate.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let foo: Option = None;\n match foo {\n Some(v) => v,\n None => 1,\n };\n ```\n\n Use instead:\n ```rust\n let foo: Option = None;\n foo.unwrap_or(1);\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "map_clone", + "id_span": { + "path": "clippy_lints/src/map_clone.rs", + "line": 40 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for usage of `map(|x| x.clone())` or dereferencing closures for `Copy` types, on `Iterator` or `Option`,\n and suggests `cloned()` or `copied()` instead\n\n **Why is this bad?** Readability, this can be written more concisely\n\n **Known problems:** None\n\n **Example:**\n\n ```rust\n let x = vec![42, 43];\n let y = x.iter();\n let z = y.map(|i| *i);\n ```\n\n The correct use would be:\n\n ```rust\n let x = vec![42, 43];\n let y = x.iter();\n let z = y.cloned();\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "map_err_ignore", + "id_span": { + "path": "clippy_lints/src/map_err_ignore.rs", + "line": 101 + }, + "group": "clippy::restriction", + "docs": " **What it does:** Checks for instances of `map_err(|_| Some::Enum)`\n **Why is this bad?** This `map_err` throws away the original error rather than allowing the enum to contain and report the cause of the error\n\n **Known problems:** None.\n\n **Example:**\n Before:\n ```rust\n use std::fmt;\n\n #[derive(Debug)]\n enum Error {\n Indivisible,\n Remainder(u8),\n }\n\n impl fmt::Display for Error {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n match self {\n Error::Indivisible => write!(f, \"could not divide input by three\"),\n Error::Remainder(remainder) => write!(\n f,\n \"input is not divisible by three, remainder = {}\",\n remainder\n ),\n }\n }\n }\n\n impl std::error::Error for Error {}\n\n fn divisible_by_3(input: &str) -> Result<(), Error> {\n input\n .parse::()\n .map_err(|_| Error::Indivisible)\n .map(|v| v % 3)\n .and_then(|remainder| {\n if remainder == 0 {\n Ok(())\n } else {\n Err(Error::Remainder(remainder as u8))\n }\n })\n }\n ```\n\n After:\n ```rust\n use std::{fmt, num::ParseIntError};\n\n #[derive(Debug)]\n enum Error {\n Indivisible(ParseIntError),\n Remainder(u8),\n }\n\n impl fmt::Display for Error {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n match self {\n Error::Indivisible(_) => write!(f, \"could not divide input by three\"),\n Error::Remainder(remainder) => write!(\n f,\n \"input is not divisible by three, remainder = {}\",\n remainder\n ),\n }\n }\n }\n\n impl std::error::Error for Error {\n fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {\n match self {\n Error::Indivisible(source) => Some(source),\n _ => None,\n }\n }\n }\n\n fn divisible_by_3(input: &str) -> Result<(), Error> {\n input\n .parse::()\n .map_err(Error::Indivisible)\n .map(|v| v % 3)\n .and_then(|remainder| {\n if remainder == 0 {\n Ok(())\n } else {\n Err(Error::Remainder(remainder as u8))\n }\n })\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "map_identity", + "id_span": { + "path": "clippy_lints/src/map_identity.rs", + "line": 30 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for instances of `map(f)` where `f` is the identity function.\n **Why is this bad?** It can be written more concisely without the call to `map`.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n let x = [1, 2, 3];\n let y: Vec<_> = x.iter().map(|x| x).map(|x| 2*x).collect();\n ```\n Use instead:\n ```rust\n let x = [1, 2, 3];\n let y: Vec<_> = x.iter().map(|x| 2*x).collect();\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "option_map_unit_fn", + "id_span": { + "path": "clippy_lints/src/map_unit_fn.rs", + "line": 48 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for usage of `option.map(f)` where f is a function or closure that returns the unit type `()`.\n\n **Why is this bad?** Readability, this can be written more clearly with\n an if let statement\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n # fn do_stuff() -> Option { Some(String::new()) }\n # fn log_err_msg(foo: String) -> Option { Some(foo) }\n # fn format_msg(foo: String) -> String { String::new() }\n let x: Option = do_stuff();\n x.map(log_err_msg);\n # let x: Option = do_stuff();\n x.map(|msg| log_err_msg(format_msg(msg)));\n ```\n\n The correct use would be:\n\n ```rust\n # fn do_stuff() -> Option { Some(String::new()) }\n # fn log_err_msg(foo: String) -> Option { Some(foo) }\n # fn format_msg(foo: String) -> String { String::new() }\n let x: Option = do_stuff();\n if let Some(msg) = x {\n log_err_msg(msg);\n }\n\n # let x: Option = do_stuff();\n if let Some(msg) = x {\n log_err_msg(format_msg(msg));\n }\n ```\n", + "applicability": null + }, + { + "id": "result_map_unit_fn", + "id_span": { + "path": "clippy_lints/src/map_unit_fn.rs", + "line": 89 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for usage of `result.map(f)` where f is a function or closure that returns the unit type `()`.\n\n **Why is this bad?** Readability, this can be written more clearly with\n an if let statement\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n # fn do_stuff() -> Result { Ok(String::new()) }\n # fn log_err_msg(foo: String) -> Result { Ok(foo) }\n # fn format_msg(foo: String) -> String { String::new() }\n let x: Result = do_stuff();\n x.map(log_err_msg);\n # let x: Result = do_stuff();\n x.map(|msg| log_err_msg(format_msg(msg)));\n ```\n\n The correct use would be:\n\n ```rust\n # fn do_stuff() -> Result { Ok(String::new()) }\n # fn log_err_msg(foo: String) -> Result { Ok(foo) }\n # fn format_msg(foo: String) -> String { String::new() }\n let x: Result = do_stuff();\n if let Ok(msg) = x {\n log_err_msg(msg);\n };\n # let x: Result = do_stuff();\n if let Ok(msg) = x {\n log_err_msg(format_msg(msg));\n };\n ```\n", + "applicability": null + }, + { + "id": "match_on_vec_items", + "id_span": { + "path": "clippy_lints/src/match_on_vec_items.rs", + "line": 41 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for `match vec[idx]` or `match vec[n..m]`.\n **Why is this bad?** This can panic at runtime.\n\n **Known problems:** None.\n\n **Example:**\n ```rust, no_run\n let arr = vec![0, 1, 2, 3];\n let idx = 1;\n\n // Bad\n match arr[idx] {\n 0 => println!(\"{}\", 0),\n 1 => println!(\"{}\", 3),\n _ => {},\n }\n ```\n Use instead:\n ```rust, no_run\n let arr = vec![0, 1, 2, 3];\n let idx = 1;\n\n // Good\n match arr.get(idx) {\n Some(0) => println!(\"{}\", 0),\n Some(1) => println!(\"{}\", 3),\n _ => {},\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MaybeIncorrect" + } + }, + { + "id": "single_match", + "id_span": { + "path": "clippy_lints/src/matches.rs", + "line": 55 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for matches with a single arm where an `if let` will usually suffice.\n\n **Why is this bad?** Just readability – `if let` nests less than a `match`.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # fn bar(stool: &str) {}\n # let x = Some(\"abc\");\n // Bad\n match x {\n Some(ref foo) => bar(foo),\n _ => (),\n }\n\n // Good\n if let Some(ref foo) = x {\n bar(foo);\n }\n ```\n", + "applicability": null + }, + { + "id": "single_match_else", + "id_span": { + "path": "clippy_lints/src/matches.rs", + "line": 94 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for matches with two arms where an `if let else` will usually suffice.\n\n **Why is this bad?** Just readability – `if let` nests less than a `match`.\n\n **Known problems:** Personal style preferences may differ.\n\n **Example:**\n\n Using `match`:\n\n ```rust\n # fn bar(foo: &usize) {}\n # let other_ref: usize = 1;\n # let x: Option<&usize> = Some(&1);\n match x {\n Some(ref foo) => bar(foo),\n _ => bar(&other_ref),\n }\n ```\n\n Using `if let` with `else`:\n\n ```rust\n # fn bar(foo: &usize) {}\n # let other_ref: usize = 1;\n # let x: Option<&usize> = Some(&1);\n if let Some(ref foo) = x {\n bar(foo);\n } else {\n bar(&other_ref);\n }\n ```\n", + "applicability": null + }, + { + "id": "match_ref_pats", + "id_span": { + "path": "clippy_lints/src/matches.rs", + "line": 125 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for matches where all arms match a reference, suggesting to remove the reference and deref the matched expression\n instead. It also checks for `if let &foo = bar` blocks.\n\n **Why is this bad?** It just makes the code less readable. That reference\n destructuring adds nothing to the code.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n // Bad\n match x {\n &A(ref y) => foo(y),\n &B => bar(),\n _ => frob(&x),\n }\n\n // Good\n match *x {\n A(ref y) => foo(y),\n B => bar(),\n _ => frob(x),\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "match_bool", + "id_span": { + "path": "clippy_lints/src/matches.rs", + "line": 159 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for matches where match expression is a `bool`. It suggests to replace the expression with an `if...else` block.\n\n **Why is this bad?** It makes the code less readable.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # fn foo() {}\n # fn bar() {}\n let condition: bool = true;\n match condition {\n true => foo(),\n false => bar(),\n }\n ```\n Use if/else instead:\n ```rust\n # fn foo() {}\n # fn bar() {}\n let condition: bool = true;\n if condition {\n foo();\n } else {\n bar();\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "HasPlaceholders" + } + }, + { + "id": "match_overlapping_arm", + "id_span": { + "path": "clippy_lints/src/matches.rs", + "line": 181 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for overlapping match arms.\n **Why is this bad?** It is likely to be an error and if not, makes the code\n less obvious.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let x = 5;\n match x {\n 1...10 => println!(\"1 ... 10\"),\n 5...15 => println!(\"5 ... 15\"),\n _ => (),\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "match_wild_err_arm", + "id_span": { + "path": "clippy_lints/src/matches.rs", + "line": 203 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for arm which matches all errors with `Err(_)` and take drastic actions like `panic!`.\n\n **Why is this bad?** It is generally a bad practice, similar to\n catching all exceptions in java with `catch(Exception)`\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let x: Result = Ok(3);\n match x {\n Ok(_) => println!(\"ok\"),\n Err(_) => panic!(\"err\"),\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "match_as_ref", + "id_span": { + "path": "clippy_lints/src/matches.rs", + "line": 229 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for match which is used to add a reference to an `Option` value.\n\n **Why is this bad?** Using `as_ref()` or `as_mut()` instead is shorter.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let x: Option<()> = None;\n\n // Bad\n let r: Option<&()> = match x {\n None => None,\n Some(ref v) => Some(v),\n };\n\n // Good\n let r: Option<&()> = x.as_ref();\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "wildcard_enum_match_arm", + "id_span": { + "path": "clippy_lints/src/matches.rs", + "line": 258 + }, + "group": "clippy::restriction", + "docs": " **What it does:** Checks for wildcard enum matches using `_`.\n **Why is this bad?** New enum variants added by library updates can be missed.\n\n **Known problems:** Suggested replacements may be incorrect if guards exhaustively cover some\n variants, and also may not use correct path to enum if it's not present in the current scope.\n\n **Example:**\n ```rust\n # enum Foo { A(usize), B(usize) }\n # let x = Foo::B(1);\n // Bad\n match x {\n Foo::A(_) => {},\n _ => {},\n }\n\n // Good\n match x {\n Foo::A(_) => {},\n Foo::B(_) => {},\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MaybeIncorrect" + } + }, + { + "id": "match_wildcard_for_single_variants", + "id_span": { + "path": "clippy_lints/src/matches.rs", + "line": 290 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for wildcard enum matches for a single variant.\n **Why is this bad?** New enum variants added by library updates can be missed.\n\n **Known problems:** Suggested replacements may not use correct path to enum\n if it's not present in the current scope.\n\n **Example:**\n\n ```rust\n # enum Foo { A, B, C }\n # let x = Foo::B;\n // Bad\n match x {\n Foo::A => {},\n Foo::B => {},\n _ => {},\n }\n\n // Good\n match x {\n Foo::A => {},\n Foo::B => {},\n Foo::C => {},\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MaybeIncorrect" + } + }, + { + "id": "wildcard_in_or_patterns", + "id_span": { + "path": "clippy_lints/src/matches.rs", + "line": 317 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for wildcard pattern used with others patterns in same match arm.\n **Why is this bad?** Wildcard pattern already covers any other pattern as it will match anyway.\n It makes the code less readable, especially to spot wildcard pattern use in match arm.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n // Bad\n match \"foo\" {\n \"a\" => {},\n \"bar\" | _ => {},\n }\n\n // Good\n match \"foo\" {\n \"a\" => {},\n _ => {},\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "infallible_destructuring_match", + "id_span": { + "path": "clippy_lints/src/matches.rs", + "line": 352 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for matches being used to destructure a single-variant enum or tuple struct where a `let` will suffice.\n\n **Why is this bad?** Just readability – `let` doesn't nest, whereas a `match` does.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n enum Wrapper {\n Data(i32),\n }\n\n let wrapper = Wrapper::Data(42);\n\n let data = match wrapper {\n Wrapper::Data(i) => i,\n };\n ```\n\n The correct use would be:\n ```rust\n enum Wrapper {\n Data(i32),\n }\n\n let wrapper = Wrapper::Data(42);\n let Wrapper::Data(data) = wrapper;\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "match_single_binding", + "id_span": { + "path": "clippy_lints/src/matches.rs", + "line": 380 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for useless match that binds to only one value.\n **Why is this bad?** Readability and needless complexity.\n\n **Known problems:** Suggested replacements may be incorrect when `match`\n is actually binding temporary value, bringing a 'dropped while borrowed' error.\n\n **Example:**\n ```rust\n # let a = 1;\n # let b = 2;\n\n // Bad\n match (a, b) {\n (c, d) => {\n // useless match\n }\n }\n\n // Good\n let (c, d) = (a, b);\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "rest_pat_in_fully_bound_structs", + "id_span": { + "path": "clippy_lints/src/matches.rs", + "line": 410 + }, + "group": "clippy::restriction", + "docs": " **What it does:** Checks for unnecessary '..' pattern binding on struct when all fields are explicitly matched.\n **Why is this bad?** Correctness and readability. It's like having a wildcard pattern after\n matching all enum variants explicitly.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # struct A { a: i32 }\n let a = A { a: 5 };\n\n // Bad\n match a {\n A { a: 5, .. } => {},\n _ => {},\n }\n\n // Good\n match a {\n A { a: 5 } => {},\n _ => {},\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "redundant_pattern_matching", + "id_span": { + "path": "clippy_lints/src/matches.rs", + "line": 458 + }, + "group": "clippy::style", + "docs": " **What it does:** Lint for redundant pattern matching over `Result`, `Option`, `std::task::Poll` or `std::net::IpAddr`\n\n **Why is this bad?** It's more concise and clear to just use the proper\n utility function\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n # use std::task::Poll;\n # use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};\n if let Ok(_) = Ok::(42) {}\n if let Err(_) = Err::(42) {}\n if let None = None::<()> {}\n if let Some(_) = Some(42) {}\n if let Poll::Pending = Poll::Pending::<()> {}\n if let Poll::Ready(_) = Poll::Ready(42) {}\n if let IpAddr::V4(_) = IpAddr::V4(Ipv4Addr::LOCALHOST) {}\n if let IpAddr::V6(_) = IpAddr::V6(Ipv6Addr::LOCALHOST) {}\n match Ok::(42) {\n Ok(_) => true,\n Err(_) => false,\n };\n ```\n\n The more idiomatic use would be:\n\n ```rust\n # use std::task::Poll;\n # use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};\n if Ok::(42).is_ok() {}\n if Err::(42).is_err() {}\n if None::<()>.is_none() {}\n if Some(42).is_some() {}\n if Poll::Pending::<()>.is_pending() {}\n if Poll::Ready(42).is_ready() {}\n if IpAddr::V4(Ipv4Addr::LOCALHOST).is_ipv4() {}\n if IpAddr::V6(Ipv6Addr::LOCALHOST).is_ipv6() {}\n Ok::(42).is_ok();\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MaybeIncorrect" + } + }, + { + "id": "match_like_matches_macro", + "id_span": { + "path": "clippy_lints/src/matches.rs", + "line": 491 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for `match` or `if let` expressions producing a `bool` that could be written using `matches!`\n\n **Why is this bad?** Readability and needless complexity.\n\n **Known problems:** This lint falsely triggers, if there are arms with\n `cfg` attributes that remove an arm evaluating to `false`.\n\n **Example:**\n ```rust\n let x = Some(5);\n\n // Bad\n let a = match x {\n Some(0) => true,\n _ => false,\n };\n\n let a = if let Some(0) = x {\n true\n } else {\n false\n };\n\n // Good\n let a = matches!(x, Some(0));\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MaybeIncorrect" + } + }, + { + "id": "match_same_arms", + "id_span": { + "path": "clippy_lints/src/matches.rs", + "line": 532 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for `match` with identical arm bodies.\n **Why is this bad?** This is probably a copy & paste error. If arm bodies\n are the same on purpose, you can factor them\n [using `|`](https://doc.rust-lang.org/book/patterns.html#multiple-patterns).\n\n **Known problems:** False positive possible with order dependent `match`\n (see issue\n [#860](https://github.com/rust-lang/rust-clippy/issues/860)).\n\n **Example:**\n ```rust,ignore\n match foo {\n Bar => bar(),\n Quz => quz(),\n Baz => bar(), // <= oops\n }\n ```\n\n This should probably be\n ```rust,ignore\n match foo {\n Bar => bar(),\n Quz => quz(),\n Baz => baz(), // <= fixed\n }\n ```\n\n or if the original code was not a typo:\n ```rust,ignore\n match foo {\n Bar | Baz => bar(), // <= shows the intent better\n Quz => quz(),\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "mem_discriminant_non_enum", + "id_span": { + "path": "clippy_lints/src/mem_discriminant.rs", + "line": 25 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for calls of `mem::discriminant()` on a non-enum type.\n **Why is this bad?** The value of `mem::discriminant()` on non-enum types\n is unspecified.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n use std::mem;\n\n mem::discriminant(&\"hello\");\n mem::discriminant(&&Some(2));\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "mem_forget", + "id_span": { + "path": "clippy_lints/src/mem_forget.rs", + "line": 21 + }, + "group": "clippy::restriction", + "docs": " **What it does:** Checks for usage of `std::mem::forget(t)` where `t` is `Drop`.\n\n **Why is this bad?** `std::mem::forget(t)` prevents `t` from running its\n destructor, possibly causing leaks.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # use std::mem;\n # use std::rc::Rc;\n mem::forget(Rc::new(55))\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "mem_replace_option_with_none", + "id_span": { + "path": "clippy_lints/src/mem_replace.rs", + "line": 37 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for `mem::replace()` on an `Option` with `None`.\n\n **Why is this bad?** `Option` already has the method `take()` for\n taking its current value (Some(..) or None) and replacing it with\n `None`.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n use std::mem;\n\n let mut an_option = Some(0);\n let replaced = mem::replace(&mut an_option, None);\n ```\n Is better expressed with:\n ```rust\n let mut an_option = Some(0);\n let taken = an_option.take();\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "mem_replace_with_uninit", + "id_span": { + "path": "clippy_lints/src/mem_replace.rs", + "line": 69 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for `mem::replace(&mut _, mem::uninitialized())` and `mem::replace(&mut _, mem::zeroed())`.\n\n **Why is this bad?** This will lead to undefined behavior even if the\n value is overwritten later, because the uninitialized value may be\n observed in the case of a panic.\n\n **Known problems:** None.\n\n **Example:**\n\n ```\n use std::mem;\n# fn may_panic(v: Vec) -> Vec { v }\n\n #[allow(deprecated, invalid_value)]\n fn myfunc (v: &mut Vec) {\n let taken_v = unsafe { mem::replace(v, mem::uninitialized()) };\n let new_v = may_panic(taken_v); // undefined behavior on panic\n mem::forget(mem::replace(v, new_v));\n }\n ```\n\n The [take_mut](https://docs.rs/take_mut) crate offers a sound solution,\n at the cost of either lazily creating a replacement value or aborting\n on panic, to ensure that the uninitialized value cannot be observed.\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "mem_replace_with_default", + "id_span": { + "path": "clippy_lints/src/mem_replace.rs", + "line": 93 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for `std::mem::replace` on a value of type `T` with `T::default()`.\n\n **Why is this bad?** `std::mem` module already has the method `take` to\n take the current value and replace it with the default value of that type.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let mut text = String::from(\"foo\");\n let replaced = std::mem::replace(&mut text, String::default());\n ```\n Is better expressed with:\n ```rust\n let mut text = String::from(\"foo\");\n let taken = std::mem::take(&mut text);\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "unwrap_used", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 82 + }, + "group": "clippy::restriction", + "docs": " **What it does:** Checks for `.unwrap()` calls on `Option`s and on `Result`s.\n **Why is this bad?** It is better to handle the `None` or `Err` case,\n or at least call `.expect(_)` with a more helpful message. Still, for a lot of\n quick-and-dirty code, `unwrap` is a good choice, which is why this lint is\n `Allow` by default.\n\n `result.unwrap()` will let the thread panic on `Err` values.\n Normally, you want to implement more sophisticated error handling,\n and propagate errors upwards with `?` operator.\n\n Even if you want to panic on errors, not all `Error`s implement good\n messages on display. Therefore, it may be beneficial to look at the places\n where they may get displayed. Activate this lint to do just that.\n\n **Known problems:** None.\n\n **Examples:**\n ```rust\n # let opt = Some(1);\n\n // Bad\n opt.unwrap();\n\n // Good\n opt.expect(\"more helpful message\");\n ```\n\n // or\n\n ```rust\n # let res: Result = Ok(1);\n\n // Bad\n res.unwrap();\n\n // Good\n res.expect(\"more helpful message\");\n ```\n", + "applicability": null + }, + { + "id": "expect_used", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 124 + }, + "group": "clippy::restriction", + "docs": " **What it does:** Checks for `.expect()` calls on `Option`s and `Result`s.\n **Why is this bad?** Usually it is better to handle the `None` or `Err` case.\n Still, for a lot of quick-and-dirty code, `expect` is a good choice, which is why\n this lint is `Allow` by default.\n\n `result.expect()` will let the thread panic on `Err`\n values. Normally, you want to implement more sophisticated error handling,\n and propagate errors upwards with `?` operator.\n\n **Known problems:** None.\n\n **Examples:**\n ```rust,ignore\n # let opt = Some(1);\n\n // Bad\n opt.expect(\"one\");\n\n // Good\n let opt = Some(1);\n opt?;\n ```\n\n // or\n\n ```rust\n # let res: Result = Ok(1);\n\n // Bad\n res.expect(\"one\");\n\n // Good\n res?;\n # Ok::<(), ()>(())\n ```\n", + "applicability": null + }, + { + "id": "should_implement_trait", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 153 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for methods that should live in a trait implementation of a `std` trait (see [llogiq's blog\n post](http://llogiq.github.io/2015/07/30/traits.html) for further\n information) instead of an inherent implementation.\n\n **Why is this bad?** Implementing the traits improve ergonomics for users of\n the code, often with very little cost. Also people seeing a `mul(...)`\n method\n may expect `*` to work equally, so you should have good reason to disappoint\n them.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n struct X;\n impl X {\n fn add(&self, other: &X) -> X {\n // ..\n # X\n }\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "wrong_self_convention", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 186 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for methods with certain name prefixes and which doesn't match how self is taken. The actual rules are:\n\n |Prefix |`self` taken |\n |-------|----------------------|\n |`as_` |`&self` or `&mut self`|\n |`from_`| none |\n |`into_`|`self` |\n |`is_` |`&self` or none |\n |`to_` |`&self` |\n\n **Why is this bad?** Consistency breeds readability. If you follow the\n conventions, your users won't be surprised that they, e.g., need to supply a\n mutable reference to a `as_..` function.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # struct X;\n impl X {\n fn as_str(self) -> &'static str {\n // ..\n # \"\"\n }\n }\n ```\n", + "applicability": null + }, + { + "id": "wrong_pub_self_convention", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 210 + }, + "group": "clippy::restriction", + "docs": " **What it does:** This is the same as [`wrong_self_convention`](#wrong_self_convention), but for public items.\n\n **Why is this bad?** See [`wrong_self_convention`](#wrong_self_convention).\n\n **Known problems:** Actually *renaming* the function may break clients if\n the function is part of the public interface. In that case, be mindful of\n the stability guarantees you've given your users.\n\n **Example:**\n ```rust\n # struct X;\n impl<'a> X {\n pub fn as_str(self) -> &'a str {\n \"foo\"\n }\n }\n ```\n", + "applicability": null + }, + { + "id": "ok_expect", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 233 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for usage of `ok().expect(..)`.\n **Why is this bad?** Because you usually call `expect()` on the `Result`\n directly to get a better error message.\n\n **Known problems:** The error type needs to implement `Debug`\n\n **Example:**\n ```rust\n # let x = Ok::<_, ()>(());\n\n // Bad\n x.ok().expect(\"why did I do this again?\");\n\n // Good\n x.expect(\"why did I do this again?\");\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "map_unwrap_or", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 270 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for usage of `option.map(_).unwrap_or(_)` or `option.map(_).unwrap_or_else(_)` or `result.map(_).unwrap_or_else(_)`.\n\n **Why is this bad?** Readability, these can be written more concisely (resp.) as\n `option.map_or(_, _)`, `option.map_or_else(_, _)` and `result.map_or_else(_, _)`.\n\n **Known problems:** The order of the arguments is not in execution order\n\n **Examples:**\n ```rust\n # let x = Some(1);\n\n // Bad\n x.map(|a| a + 1).unwrap_or(0);\n\n // Good\n x.map_or(0, |a| a + 1);\n ```\n\n // or\n\n ```rust\n # let x: Result = Ok(1);\n # fn some_function(foo: ()) -> usize { 1 }\n\n // Bad\n x.map(|a| a + 1).unwrap_or_else(some_function);\n\n // Good\n x.map_or_else(some_function, |a| a + 1);\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "option_map_or_none", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 293 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for usage of `_.map_or(None, _)`.\n **Why is this bad?** Readability, this can be written more concisely as\n `_.and_then(_)`.\n\n **Known problems:** The order of the arguments is not in execution order.\n\n **Example:**\n ```rust\n # let opt = Some(1);\n\n // Bad\n opt.map_or(None, |a| Some(a + 1));\n\n // Good\n opt.and_then(|a| Some(a + 1));\n ```\n", + "applicability": null + }, + { + "id": "result_map_or_into_option", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 319 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for usage of `_.map_or(None, Some)`.\n **Why is this bad?** Readability, this can be written more concisely as\n `_.ok()`.\n\n **Known problems:** None.\n\n **Example:**\n\n Bad:\n ```rust\n # let r: Result = Ok(1);\n assert_eq!(Some(1), r.map_or(None, Some));\n ```\n\n Good:\n ```rust\n # let r: Result = Ok(1);\n assert_eq!(Some(1), r.ok());\n ```\n", + "applicability": null + }, + { + "id": "bind_instead_of_map", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 352 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for usage of `_.and_then(|x| Some(y))`, `_.and_then(|x| Ok(y))` or `_.or_else(|x| Err(y))`.\n\n **Why is this bad?** Readability, this can be written more concisely as\n `_.map(|x| y)` or `_.map_err(|x| y)`.\n\n **Known problems:** None\n\n **Example:**\n\n ```rust\n # fn opt() -> Option<&'static str> { Some(\"42\") }\n # fn res() -> Result<&'static str, &'static str> { Ok(\"42\") }\n let _ = opt().and_then(|s| Some(s.len()));\n let _ = res().and_then(|s| if s.len() == 42 { Ok(10) } else { Ok(20) });\n let _ = res().or_else(|s| if s.len() == 42 { Err(10) } else { Err(20) });\n ```\n\n The correct use would be:\n\n ```rust\n # fn opt() -> Option<&'static str> { Some(\"42\") }\n # fn res() -> Result<&'static str, &'static str> { Ok(\"42\") }\n let _ = opt().map(|s| s.len());\n let _ = res().map(|s| if s.len() == 42 { 10 } else { 20 });\n let _ = res().map_err(|s| if s.len() == 42 { 10 } else { 20 });\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "filter_next", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 375 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for usage of `_.filter(_).next()`.\n **Why is this bad?** Readability, this can be written more concisely as\n `_.find(_)`.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let vec = vec![1];\n vec.iter().filter(|x| **x == 0).next();\n ```\n Could be written as\n ```rust\n # let vec = vec![1];\n vec.iter().find(|x| **x == 0);\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "skip_while_next", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 398 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for usage of `_.skip_while(condition).next()`.\n **Why is this bad?** Readability, this can be written more concisely as\n `_.find(!condition)`.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let vec = vec![1];\n vec.iter().skip_while(|x| **x == 0).next();\n ```\n Could be written as\n ```rust\n # let vec = vec![1];\n vec.iter().find(|x| **x != 0);\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "map_flatten", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 421 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for usage of `_.map(_).flatten(_)`,\n **Why is this bad?** Readability, this can be written more concisely as\n `_.flat_map(_)`\n\n **Known problems:**\n\n **Example:**\n ```rust\n let vec = vec![vec![1]];\n\n // Bad\n vec.iter().map(|x| x.iter()).flatten();\n\n // Good\n vec.iter().flat_map(|x| x.iter());\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "filter_map", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 450 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for usage of `_.filter(_).map(_)`, `_.filter(_).flat_map(_)`, `_.filter_map(_).flat_map(_)` and similar.\n\n **Why is this bad?** Readability, this can be written more concisely as\n `_.filter_map(_)`.\n\n **Known problems:** Often requires a condition + Option/Iterator creation\n inside the closure.\n\n **Example:**\n ```rust\n let vec = vec![1];\n\n // Bad\n vec.iter().filter(|x| **x == 0).map(|x| *x * 2);\n\n // Good\n vec.iter().filter_map(|x| if *x == 0 {\n Some(*x * 2)\n } else {\n None\n });\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "manual_filter_map", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 476 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for usage of `_.filter(_).map(_)` that can be written more simply as `filter_map(_)`.\n\n **Why is this bad?** Redundant code in the `filter` and `map` operations is poor style and\n less performant.\n\n **Known problems:** None.\n\n **Example:**\n Bad:\n ```rust\n (0_i32..10)\n .filter(|n| n.checked_add(1).is_some())\n .map(|n| n.checked_add(1).unwrap());\n ```\n\n Good:\n ```rust\n (0_i32..10).filter_map(|n| n.checked_add(1));\n ```\n", + "applicability": null + }, + { + "id": "manual_find_map", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 502 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for usage of `_.find(_).map(_)` that can be written more simply as `find_map(_)`.\n\n **Why is this bad?** Redundant code in the `find` and `map` operations is poor style and\n less performant.\n\n **Known problems:** None.\n\n **Example:**\n Bad:\n ```rust\n (0_i32..10)\n .find(|n| n.checked_add(1).is_some())\n .map(|n| n.checked_add(1).unwrap());\n ```\n\n Good:\n ```rust\n (0_i32..10).find_map(|n| n.checked_add(1));\n ```\n", + "applicability": null + }, + { + "id": "filter_map_next", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 524 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for usage of `_.filter_map(_).next()`.\n **Why is this bad?** Readability, this can be written more concisely as\n `_.find_map(_)`.\n\n **Known problems:** None\n\n **Example:**\n ```rust\n (0..3).filter_map(|x| if x == 2 { Some(x) } else { None }).next();\n ```\n Can be written as\n\n ```rust\n (0..3).find_map(|x| if x == 2 { Some(x) } else { None });\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "flat_map_identity", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 546 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for usage of `flat_map(|x| x)`.\n **Why is this bad?** Readability, this can be written more concisely by using `flatten`.\n\n **Known problems:** None\n\n **Example:**\n ```rust\n # let iter = vec![vec![0]].into_iter();\n iter.flat_map(|x| x);\n ```\n Can be written as\n ```rust\n # let iter = vec![vec![0]].into_iter();\n iter.flatten();\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "search_is_some", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 570 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for an iterator or string search (such as `find()`, `position()`, or `rposition()`) followed by a call to `is_some()`.\n\n **Why is this bad?** Readability, this can be written more concisely as\n `_.any(_)` or `_.contains(_)`.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let vec = vec![1];\n vec.iter().find(|x| **x == 0).is_some();\n ```\n Could be written as\n ```rust\n # let vec = vec![1];\n vec.iter().any(|x| *x == 0);\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "chars_next_cmp", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 594 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for usage of `.chars().next()` on a `str` to check if it starts with a given char.\n\n **Why is this bad?** Readability, this can be written more concisely as\n `_.starts_with(_)`.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let name = \"foo\";\n if name.chars().next() == Some('_') {};\n ```\n Could be written as\n ```rust\n let name = \"foo\";\n if name.starts_with('_') {};\n ```\n", + "applicability": null + }, + { + "id": "or_fun_call", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 625 + }, + "group": "clippy::perf", + "docs": " **What it does:** Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`, etc., and suggests to use `or_else`, `unwrap_or_else`, etc., or\n `unwrap_or_default` instead.\n\n **Why is this bad?** The function will always be called and potentially\n allocate an object acting as the default.\n\n **Known problems:** If the function has side-effects, not calling it will\n change the semantic of the program, but you shouldn't rely on that anyway.\n\n **Example:**\n ```rust\n # let foo = Some(String::new());\n foo.unwrap_or(String::new());\n ```\n this can instead be written:\n ```rust\n # let foo = Some(String::new());\n foo.unwrap_or_else(String::new);\n ```\n or\n ```rust\n # let foo = Some(String::new());\n foo.unwrap_or_default();\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "HasPlaceholders" + } + }, + { + "id": "expect_fun_call", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 660 + }, + "group": "clippy::perf", + "docs": " **What it does:** Checks for calls to `.expect(&format!(...))`, `.expect(foo(..))`, etc., and suggests to use `unwrap_or_else` instead\n\n **Why is this bad?** The function will always be called.\n\n **Known problems:** If the function has side-effects, not calling it will\n change the semantics of the program, but you shouldn't rely on that anyway.\n\n **Example:**\n ```rust\n # let foo = Some(String::new());\n # let err_code = \"418\";\n # let err_msg = \"I'm a teapot\";\n foo.expect(&format!(\"Err {}: {}\", err_code, err_msg));\n ```\n or\n ```rust\n # let foo = Some(String::new());\n # let err_code = \"418\";\n # let err_msg = \"I'm a teapot\";\n foo.expect(format!(\"Err {}: {}\", err_code, err_msg).as_str());\n ```\n this can instead be written:\n ```rust\n # let foo = Some(String::new());\n # let err_code = \"418\";\n # let err_msg = \"I'm a teapot\";\n foo.unwrap_or_else(|| panic!(\"Err {}: {}\", err_code, err_msg));\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "clone_on_copy", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 677 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for usage of `.clone()` on a `Copy` type.\n **Why is this bad?** The only reason `Copy` types implement `Clone` is for\n generics, not for using the `clone` method on a concrete type.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n 42u64.clone();\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "clone_on_ref_ptr", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 702 + }, + "group": "clippy::restriction", + "docs": " **What it does:** Checks for usage of `.clone()` on a ref-counted pointer, (`Rc`, `Arc`, `rc::Weak`, or `sync::Weak`), and suggests calling Clone via unified\n function syntax instead (e.g., `Rc::clone(foo)`).\n\n **Why is this bad?** Calling '.clone()' on an Rc, Arc, or Weak\n can obscure the fact that only the pointer is being cloned, not the underlying\n data.\n\n **Example:**\n ```rust\n # use std::rc::Rc;\n let x = Rc::new(1);\n\n // Bad\n x.clone();\n\n // Good\n Rc::clone(&x);\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "Unspecified" + } + }, + { + "id": "clone_double_ref", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 724 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for usage of `.clone()` on an `&&T`.\n **Why is this bad?** Cloning an `&&T` copies the inner `&T`, instead of\n cloning the underlying `T`.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n fn main() {\n let x = vec![1];\n let y = &&x;\n let z = y.clone();\n println!(\"{:p} {:p}\", *y, z); // prints out the same pointer\n }\n ```\n", + "applicability": { + "is_multi_suggestion": true, + "applicability": "MaybeIncorrect" + } + }, + { + "id": "inefficient_to_string", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 747 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for usage of `.to_string()` on an `&&T` where `T` implements `ToString` directly (like `&&str` or `&&String`).\n\n **Why is this bad?** This bypasses the specialized implementation of\n `ToString` and instead goes through the more expensive string formatting\n facilities.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n // Generic implementation for `T: Display` is used (slow)\n [\"foo\", \"bar\"].iter().map(|s| s.to_string());\n\n // OK, the specialized impl is used\n [\"foo\", \"bar\"].iter().map(|&s| s.to_string());\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "new_ret_no_self", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 808 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for `new` not returning a type that contains `Self`.\n **Why is this bad?** As a convention, `new` methods are used to make a new\n instance of a type.\n\n **Known problems:** None.\n\n **Example:**\n In an impl block:\n ```rust\n # struct Foo;\n # struct NotAFoo;\n impl Foo {\n fn new() -> NotAFoo {\n # NotAFoo\n }\n }\n ```\n\n ```rust\n # struct Foo;\n struct Bar(Foo);\n impl Foo {\n // Bad. The type name must contain `Self`\n fn new() -> Bar {\n # Bar(Foo)\n }\n }\n ```\n\n ```rust\n # struct Foo;\n # struct FooError;\n impl Foo {\n // Good. Return type contains `Self`\n fn new() -> Result {\n # Ok(Foo)\n }\n }\n ```\n\n Or in a trait definition:\n ```rust\n pub trait Trait {\n // Bad. The type name must contain `Self`\n fn new();\n }\n ```\n\n ```rust\n pub trait Trait {\n // Good. Return type contains `Self`\n fn new() -> Self;\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "single_char_pattern", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 829 + }, + "group": "clippy::perf", + "docs": " **What it does:** Checks for string methods that receive a single-character `str` as an argument, e.g., `_.split(\"x\")`.\n\n **Why is this bad?** Performing these methods using a `char` is faster than\n using a `str`.\n\n **Known problems:** Does not catch multi-byte unicode characters.\n\n **Example:**\n ```rust,ignore\n // Bad\n _.split(\"x\");\n\n // Good\n _.split('x');\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "iterator_step_by_zero", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 848 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for calling `.step_by(0)` on iterators which panics.\n **Why is this bad?** This very much looks like an oversight. Use `panic!()` instead if you\n actually intend to panic.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,should_panic\n for x in (0..100).step_by(0) {\n //..\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "iter_nth_zero", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 876 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for the use of `iter.nth(0)`.\n **Why is this bad?** `iter.next()` is equivalent to\n `iter.nth(0)`, as they both consume the next element,\n but is more readable.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n # use std::collections::HashSet;\n // Bad\n # let mut s = HashSet::new();\n # s.insert(1);\n let x = s.iter().nth(0);\n\n // Good\n # let mut s = HashSet::new();\n # s.insert(1);\n let x = s.iter().next();\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "iter_nth", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 902 + }, + "group": "clippy::perf", + "docs": " **What it does:** Checks for use of `.iter().nth()` (and the related `.iter_mut().nth()`) on standard library types with O(1) element access.\n\n **Why is this bad?** `.get()` and `.get_mut()` are more efficient and more\n readable.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let some_vec = vec![0, 1, 2, 3];\n let bad_vec = some_vec.iter().nth(3);\n let bad_slice = &some_vec[..].iter().nth(3);\n ```\n The correct use would be:\n ```rust\n let some_vec = vec![0, 1, 2, 3];\n let bad_vec = some_vec.get(3);\n let bad_slice = &some_vec[..].get(3);\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "iter_skip_next", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 926 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for use of `.skip(x).next()` on iterators.\n **Why is this bad?** `.nth(x)` is cleaner\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let some_vec = vec![0, 1, 2, 3];\n let bad_vec = some_vec.iter().skip(3).next();\n let bad_slice = &some_vec[..].iter().skip(3).next();\n ```\n The correct use would be:\n ```rust\n let some_vec = vec![0, 1, 2, 3];\n let bad_vec = some_vec.iter().nth(3);\n let bad_slice = &some_vec[..].iter().nth(3);\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "get_unwrap", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 959 + }, + "group": "clippy::restriction", + "docs": " **What it does:** Checks for use of `.get().unwrap()` (or `.get_mut().unwrap`) on a standard library type which implements `Index`\n\n **Why is this bad?** Using the Index trait (`[]`) is more clear and more\n concise.\n\n **Known problems:** Not a replacement for error handling: Using either\n `.unwrap()` or the Index trait (`[]`) carries the risk of causing a `panic`\n if the value being accessed is `None`. If the use of `.get().unwrap()` is a\n temporary placeholder for dealing with the `Option` type, then this does\n not mitigate the need for error handling. If there is a chance that `.get()`\n will be `None` in your program, then it is advisable that the `None` case\n is handled in a future refactor instead of using `.unwrap()` or the Index\n trait.\n\n **Example:**\n ```rust\n let mut some_vec = vec![0, 1, 2, 3];\n let last = some_vec.get(3).unwrap();\n *some_vec.get_mut(0).unwrap() = 1;\n ```\n The correct use would be:\n ```rust\n let mut some_vec = vec![0, 1, 2, 3];\n let last = some_vec[3];\n some_vec[0] = 1;\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "string_extend_chars", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 988 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for the use of `.extend(s.chars())` where s is a `&str` or `String`.\n\n **Why is this bad?** `.push_str(s)` is clearer\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let abc = \"abc\";\n let def = String::from(\"def\");\n let mut s = String::new();\n s.extend(abc.chars());\n s.extend(def.chars());\n ```\n The correct use would be:\n ```rust\n let abc = \"abc\";\n let def = String::from(\"def\");\n let mut s = String::new();\n s.push_str(abc);\n s.push_str(&def);\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "iter_cloned_collect", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 1011 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for the use of `.cloned().collect()` on slice to create a `Vec`.\n\n **Why is this bad?** `.to_vec()` is clearer\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let s = [1, 2, 3, 4, 5];\n let s2: Vec = s[..].iter().cloned().collect();\n ```\n The better use would be:\n ```rust\n let s = [1, 2, 3, 4, 5];\n let s2: Vec = s.to_vec();\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "chars_last_cmp", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 1035 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for usage of `_.chars().last()` or `_.chars().next_back()` on a `str` to check if it ends with a given char.\n\n **Why is this bad?** Readability, this can be written more concisely as\n `_.ends_with(_)`.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let name = \"_\";\n\n // Bad\n name.chars().last() == Some('_') || name.chars().next_back() == Some('-');\n\n // Good\n name.ends_with('_') || name.ends_with('-');\n ```\n", + "applicability": null + }, + { + "id": "useless_asref", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 1060 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for usage of `.as_ref()` or `.as_mut()` where the types before and after the call are the same.\n\n **Why is this bad?** The call is unnecessary.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # fn do_stuff(x: &[i32]) {}\n let x: &[i32] = &[1, 2, 3, 4, 5];\n do_stuff(x.as_ref());\n ```\n The correct use would be:\n ```rust\n # fn do_stuff(x: &[i32]) {}\n let x: &[i32] = &[1, 2, 3, 4, 5];\n do_stuff(x);\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "unnecessary_fold", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 1082 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for using `fold` when a more succinct alternative exists. Specifically, this checks for `fold`s which could be replaced by `any`, `all`,\n `sum` or `product`.\n\n **Why is this bad?** Readability.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let _ = (0..3).fold(false, |acc, x| acc || x > 2);\n ```\n This could be written as:\n ```rust\n let _ = (0..3).any(|x| x > 2);\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "unnecessary_filter_map", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 1111 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for `filter_map` calls which could be replaced by `filter` or `map`. More specifically it checks if the closure provided is only performing one of the\n filter or map operations and suggests the appropriate option.\n\n **Why is this bad?** Complexity. The intent is also clearer if only a single\n operation is being performed.\n\n **Known problems:** None\n\n **Example:**\n ```rust\n let _ = (0..3).filter_map(|x| if x > 2 { Some(x) } else { None });\n\n // As there is no transformation of the argument this could be written as:\n let _ = (0..3).filter(|&x| x > 2);\n ```\n\n ```rust\n let _ = (0..4).filter_map(|x| Some(x + 1));\n\n // As there is no conditional check on the argument this could be written as:\n let _ = (0..4).map(|x| x + 1);\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "into_iter_on_ref", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 1135 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for `into_iter` calls on references which should be replaced by `iter` or `iter_mut`.\n\n **Why is this bad?** Readability. Calling `into_iter` on a reference will not move out its\n content into the resulting iterator, which is confusing. It is better just call `iter` or\n `iter_mut` directly.\n\n **Known problems:** None\n\n **Example:**\n\n ```rust\n // Bad\n let _ = (&vec![3, 4, 5]).into_iter();\n\n // Good\n let _ = (&vec![3, 4, 5]).iter();\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "suspicious_map", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 1154 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for calls to `map` followed by a `count`.\n **Why is this bad?** It looks suspicious. Maybe `map` was confused with `filter`.\n If the `map` call is intentional, this should be rewritten. Or, if you intend to\n drive the iterator to completion, you can just use `for_each` instead.\n\n **Known problems:** None\n\n **Example:**\n\n ```rust\n let _ = (0..3).map(|x| x + 2).count();\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "uninit_assumed_init", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 1186 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for `MaybeUninit::uninit().assume_init()`.\n **Why is this bad?** For most types, this is undefined behavior.\n\n **Known problems:** For now, we accept empty tuples and tuples / arrays\n of `MaybeUninit`. There may be other types that allow uninitialized\n data, but those are not yet rigorously defined.\n\n **Example:**\n\n ```rust\n // Beware the UB\n use std::mem::MaybeUninit;\n\n let _: usize = unsafe { MaybeUninit::uninit().assume_init() };\n ```\n\n Note that the following is OK:\n\n ```rust\n use std::mem::MaybeUninit;\n\n let _: [MaybeUninit; 5] = unsafe {\n MaybeUninit::uninit().assume_init()\n };\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "manual_saturating_arithmetic", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 1213 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for `.checked_add/sub(x).unwrap_or(MAX/MIN)`.\n **Why is this bad?** These can be written simply with `saturating_add/sub` methods.\n\n **Example:**\n\n ```rust\n # let y: u32 = 0;\n # let x: u32 = 100;\n let add = x.checked_add(y).unwrap_or(u32::MAX);\n let sub = x.checked_sub(y).unwrap_or(u32::MIN);\n ```\n\n can be written using dedicated methods for saturating addition/subtraction as:\n\n ```rust\n # let y: u32 = 0;\n # let x: u32 = 100;\n let add = x.saturating_add(y);\n let sub = x.saturating_sub(y);\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "zst_offset", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 1230 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for `offset(_)`, `wrapping_`{`add`, `sub`}, etc. on raw pointers to zero-sized types\n\n **Why is this bad?** This is a no-op, and likely unintended\n\n **Known problems:** None\n\n **Example:**\n ```rust\n unsafe { (&() as *const ()).offset(1) };\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "filetype_is_file", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 1270 + }, + "group": "clippy::restriction", + "docs": " **What it does:** Checks for `FileType::is_file()`.\n **Why is this bad?** When people testing a file type with `FileType::is_file`\n they are testing whether a path is something they can get bytes from. But\n `is_file` doesn't cover special file types in unix-like systems, and doesn't cover\n symlink in windows. Using `!FileType::is_dir()` is a better way to that intention.\n\n **Example:**\n\n ```rust\n # || {\n let metadata = std::fs::metadata(\"foo.txt\")?;\n let filetype = metadata.file_type();\n\n if filetype.is_file() {\n // read file\n }\n # Ok::<_, std::io::Error>(())\n # };\n ```\n\n should be written as:\n\n ```rust\n # || {\n let metadata = std::fs::metadata(\"foo.txt\")?;\n let filetype = metadata.file_type();\n\n if !filetype.is_dir() {\n // read file\n }\n # Ok::<_, std::io::Error>(())\n # };\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "option_as_ref_deref", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 1295 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for usage of `_.as_ref().map(Deref::deref)` or it's aliases (such as String::as_str).\n **Why is this bad?** Readability, this can be written more concisely as\n `_.as_deref()`.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let opt = Some(\"\".to_string());\n opt.as_ref().map(String::as_str)\n # ;\n ```\n Can be written as\n ```rust\n # let opt = Some(\"\".to_string());\n opt.as_deref()\n # ;\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "iter_next_slice", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 1321 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for usage of `iter().next()` on a Slice or an Array\n **Why is this bad?** These can be shortened into `.get()`\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let a = [1, 2, 3];\n # let b = vec![1, 2, 3];\n a[2..].iter().next();\n b.iter().next();\n ```\n should be written as:\n ```rust\n # let a = [1, 2, 3];\n # let b = vec![1, 2, 3];\n a.get(2);\n b.get(0);\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "single_char_add_str", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 1346 + }, + "group": "clippy::style", + "docs": " **What it does:** Warns when using `push_str`/`insert_str` with a single-character string literal where `push`/`insert` with a `char` would work fine.\n\n **Why is this bad?** It's less clear that we are pushing a single character.\n\n **Known problems:** None\n\n **Example:**\n ```rust\n let mut string = String::new();\n string.insert_str(0, \"R\");\n string.push_str(\"R\");\n ```\n Could be written as\n ```rust\n let mut string = String::new();\n string.insert(0, 'R');\n string.push('R');\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "unnecessary_lazy_evaluations", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 1382 + }, + "group": "clippy::style", + "docs": " **What it does:** As the counterpart to `or_fun_call`, this lint looks for unnecessary lazily evaluated closures on `Option` and `Result`.\n\n This lint suggests changing the following functions, when eager evaluation results in\n simpler code:\n - `unwrap_or_else` to `unwrap_or`\n - `and_then` to `and`\n - `or_else` to `or`\n - `get_or_insert_with` to `get_or_insert`\n - `ok_or_else` to `ok_or`\n\n **Why is this bad?** Using eager evaluation is shorter and simpler in some cases.\n\n **Known problems:** It is possible, but not recommended for `Deref` and `Index` to have\n side effects. Eagerly evaluating them can change the semantics of the program.\n\n **Example:**\n\n ```rust\n // example code where clippy issues a warning\n let opt: Option = None;\n\n opt.unwrap_or_else(|| 42);\n ```\n Use instead:\n ```rust\n let opt: Option = None;\n\n opt.unwrap_or(42);\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "map_collect_result_unit", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 1403 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for usage of `_.map(_).collect::()`.\n **Why is this bad?** Using `try_for_each` instead is more readable and idiomatic.\n\n **Known problems:** None\n\n **Example:**\n\n ```rust\n (0..3).map(|t| Err(t)).collect::>();\n ```\n Use instead:\n ```rust\n (0..3).try_for_each(|t| Err(t));\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "from_iter_instead_of_collect", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 1436 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for `from_iter()` function calls on types that implement the `FromIterator` trait.\n\n **Why is this bad?** It is recommended style to use collect. See\n [FromIterator documentation](https://doc.rust-lang.org/std/iter/trait.FromIterator.html)\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n use std::iter::FromIterator;\n\n let five_fives = std::iter::repeat(5).take(5);\n\n let v = Vec::from_iter(five_fives);\n\n assert_eq!(v, vec![5, 5, 5, 5, 5]);\n ```\n Use instead:\n ```rust\n let five_fives = std::iter::repeat(5).take(5);\n\n let v: Vec = five_fives.collect();\n\n assert_eq!(v, vec![5, 5, 5, 5, 5]);\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MaybeIncorrect" + } + }, + { + "id": "inspect_for_each", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 1466 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for usage of `inspect().for_each()`.\n **Why is this bad?** It is the same as performing the computation\n inside `inspect` at the beginning of the closure in `for_each`.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n [1,2,3,4,5].iter()\n .inspect(|&x| println!(\"inspect the number: {}\", x))\n .for_each(|&x| {\n assert!(x >= 0);\n });\n ```\n Can be written as\n ```rust\n [1,2,3,4,5].iter()\n .for_each(|&x| {\n println!(\"inspect the number: {}\", x);\n assert!(x >= 0);\n });\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "filter_map_identity", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 1489 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for usage of `filter_map(|x| x)`.\n **Why is this bad?** Readability, this can be written more concisely by using `flatten`.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n # let iter = vec![Some(1)].into_iter();\n iter.filter_map(|x| x);\n ```\n Use instead:\n ```rust\n # let iter = vec![Some(1)].into_iter();\n iter.flatten();\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "bytes_nth", + "id_span": { + "path": "clippy_lints/src/methods/mod.rs", + "line": 1511 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for the use of `.bytes().nth()`.\n **Why is this bad?** `.as_bytes().get()` is more efficient and more\n readable.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n // Bad\n let _ = \"Hello\".bytes().nth(3);\n\n // Good\n let _ = \"Hello\".as_bytes().get(3);\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "min_max", + "id_span": { + "path": "clippy_lints/src/minmax.rs", + "line": 28 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for expressions where `std::cmp::min` and `max` are used to clamp values, but switched so that the result is constant.\n\n **Why is this bad?** This is in all probability not the intended outcome. At\n the least it hurts readability of the code.\n\n **Known problems:** None\n\n **Example:**\n ```ignore\n min(0, max(100, x))\n ```\n or\n ```ignore\n x.max(100).min(0)\n ```\n It will always be equal to `0`. Probably the author meant to clamp the value\n between 0 and 100, but has erroneously swapped `min` and `max`.\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "toplevel_ref_arg", + "id_span": { + "path": "clippy_lints/src/misc.rs", + "line": 53 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for function arguments and let bindings denoted as `ref`.\n\n **Why is this bad?** The `ref` declaration makes the function take an owned\n value, but turns the argument into a reference (which means that the value\n is destroyed when exiting the function). This adds not much value: either\n take a reference type, or take an owned value and create references in the\n body.\n\n For let bindings, `let x = &foo;` is preferred over `let ref x = foo`. The\n type of `x` is more obvious with the former.\n\n **Known problems:** If the argument is dereferenced within the function,\n removing the `ref` will lead to errors. This can be fixed by removing the\n dereferences, e.g., changing `*x` to `x` within the function.\n\n **Example:**\n ```rust,ignore\n // Bad\n fn foo(ref x: u8) -> bool {\n true\n }\n\n // Good\n fn foo(x: &u8) -> bool {\n true\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "cmp_nan", + "id_span": { + "path": "clippy_lints/src/misc.rs", + "line": 76 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for comparisons to NaN.\n **Why is this bad?** NaN does not compare meaningfully to anything – not\n even itself – so those comparisons are simply wrong.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let x = 1.0;\n\n // Bad\n if x == f32::NAN { }\n\n // Good\n if x.is_nan() { }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "float_cmp", + "id_span": { + "path": "clippy_lints/src/misc.rs", + "line": 109 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for (in-)equality comparisons on floating-point values (apart from zero), except in functions called `*eq*` (which probably\n implement equality for a type involving floats).\n\n **Why is this bad?** Floating point calculations are usually imprecise, so\n asking if two values are *exactly* equal is asking for trouble. For a good\n guide on what to do, see [the floating point\n guide](http://www.floating-point-gui.de/errors/comparison).\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let x = 1.2331f64;\n let y = 1.2332f64;\n\n // Bad\n if y == 1.23f64 { }\n if y != x {} // where both are floats\n\n // Good\n let error_margin = f64::EPSILON; // Use an epsilon for comparison\n // Or, if Rust <= 1.42, use `std::f64::EPSILON` constant instead.\n // let error_margin = std::f64::EPSILON;\n if (y - 1.23f64).abs() < error_margin { }\n if (y - x).abs() > error_margin { }\n ```\n", + "applicability": null + }, + { + "id": "cmp_owned", + "id_span": { + "path": "clippy_lints/src/misc.rs", + "line": 136 + }, + "group": "clippy::perf", + "docs": " **What it does:** Checks for conversions to owned values just for the sake of a comparison.\n\n **Why is this bad?** The comparison can operate on a reference, so creating\n an owned value effectively throws it away directly afterwards, which is\n needlessly consuming code and heap space.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let x = \"foo\";\n # let y = String::from(\"foo\");\n if x.to_owned() == y {}\n ```\n Could be written as\n ```rust\n # let x = \"foo\";\n # let y = String::from(\"foo\");\n if x == y {}\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "modulo_one", + "id_span": { + "path": "clippy_lints/src/misc.rs", + "line": 159 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for getting the remainder of a division by one or minus one.\n\n **Why is this bad?** The result for a divisor of one can only ever be zero; for\n minus one it can cause panic/overflow (if the left operand is the minimal value of\n the respective integer type) or results in zero. No one will write such code\n deliberately, unless trying to win an Underhanded Rust Contest. Even for that\n contest, it's probably a bad idea. Use something more underhanded.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let x = 1;\n let a = x % 1;\n let a = x % -1;\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "used_underscore_binding", + "id_span": { + "path": "clippy_lints/src/misc.rs", + "line": 181 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for the use of bindings with a single leading underscore.\n\n **Why is this bad?** A single leading underscore is usually used to indicate\n that a binding will not be used. Using such a binding breaks this\n expectation.\n\n **Known problems:** The lint does not work properly with desugaring and\n macro, it has been allowed in the mean time.\n\n **Example:**\n ```rust\n let _x = 0;\n let y = _x + 1; // Here we are using `_x`, even though it has a leading\n // underscore. We should rename `_x` to `x`\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "short_circuit_statement", + "id_span": { + "path": "clippy_lints/src/misc.rs", + "line": 201 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for the use of short circuit boolean conditions as a\n statement.\n\n **Why is this bad?** Using a short circuit boolean condition as a statement\n may hide the fact that the second part is executed or not depending on the\n outcome of the first part.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n f() && g(); // We should write `if f() { g(); }`.\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "zero_ptr", + "id_span": { + "path": "clippy_lints/src/misc.rs", + "line": 223 + }, + "group": "clippy::style", + "docs": " **What it does:** Catch casts from `0` to some pointer type\n **Why is this bad?** This generally means `null` and is better expressed as\n {`std`, `core`}`::ptr::`{`null`, `null_mut`}.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n // Bad\n let a = 0 as *const u32;\n\n // Good\n let a = std::ptr::null::();\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "float_cmp_const", + "id_span": { + "path": "clippy_lints/src/misc.rs", + "line": 254 + }, + "group": "clippy::restriction", + "docs": " **What it does:** Checks for (in-)equality comparisons on floating-point value and constant, except in functions called `*eq*` (which probably\n implement equality for a type involving floats).\n\n **Why is this bad?** Floating point calculations are usually imprecise, so\n asking if two values are *exactly* equal is asking for trouble. For a good\n guide on what to do, see [the floating point\n guide](http://www.floating-point-gui.de/errors/comparison).\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let x: f64 = 1.0;\n const ONE: f64 = 1.00;\n\n // Bad\n if x == ONE { } // where both are floats\n\n // Good\n let error_margin = f64::EPSILON; // Use an epsilon for comparison\n // Or, if Rust <= 1.42, use `std::f64::EPSILON` constant instead.\n // let error_margin = std::f64::EPSILON;\n if (x - ONE).abs() < error_margin { }\n ```\n", + "applicability": null + }, + { + "id": "unneeded_field_pattern", + "id_span": { + "path": "clippy_lints/src/misc_early.rs", + "line": 44 + }, + "group": "clippy::restriction", + "docs": " **What it does:** Checks for structure field patterns bound to wildcards.\n **Why is this bad?** Using `..` instead is shorter and leaves the focus on\n the fields that are actually bound.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # struct Foo {\n # a: i32,\n # b: i32,\n # c: i32,\n # }\n let f = Foo { a: 0, b: 0, c: 0 };\n\n // Bad\n match f {\n Foo { a: _, b: 0, .. } => {},\n Foo { a: _, b: _, c: _ } => {},\n }\n\n // Good\n match f {\n Foo { b: 0, .. } => {},\n Foo { .. } => {},\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "duplicate_underscore_argument", + "id_span": { + "path": "clippy_lints/src/misc_early.rs", + "line": 65 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for function arguments having the similar names differing by an underscore.\n\n **Why is this bad?** It affects code readability.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n // Bad\n fn foo(a: i32, _a: i32) {}\n\n // Good\n fn bar(a: i32, _b: i32) {}\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "double_neg", + "id_span": { + "path": "clippy_lints/src/misc_early.rs", + "line": 83 + }, + "group": "clippy::style", + "docs": " **What it does:** Detects expressions of the form `--x`.\n **Why is this bad?** It can mislead C/C++ programmers to think `x` was\n decremented.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let mut x = 3;\n --x;\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "mixed_case_hex_literals", + "id_span": { + "path": "clippy_lints/src/misc_early.rs", + "line": 104 + }, + "group": "clippy::style", + "docs": " **What it does:** Warns on hexadecimal literals with mixed-case letter digits.\n\n **Why is this bad?** It looks confusing.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n // Bad\n let y = 0x1a9BAcD;\n\n // Good\n let y = 0x1A9BACD;\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "unseparated_literal_suffix", + "id_span": { + "path": "clippy_lints/src/misc_early.rs", + "line": 125 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Warns if literal suffixes are not separated by an underscore.\n\n **Why is this bad?** It is much less readable.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n // Bad\n let y = 123832i32;\n\n // Good\n let y = 123832_i32;\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "zero_prefixed_literal", + "id_span": { + "path": "clippy_lints/src/misc_early.rs", + "line": 163 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Warns if an integral constant literal starts with `0`.\n **Why is this bad?** In some languages (including the infamous C language\n and most of its\n family), this marks an octal constant. In Rust however, this is a decimal\n constant. This could\n be confusing for both the writer and a reader of the constant.\n\n **Known problems:** None.\n\n **Example:**\n\n In Rust:\n ```rust\n fn main() {\n let a = 0123;\n println!(\"{}\", a);\n }\n ```\n\n prints `123`, while in C:\n\n ```c\n #include \n\n int main() {\n int a = 0123;\n printf(\"%d\\n\", a);\n }\n ```\n\n prints `83` (as `83 == 0o123` while `123 == 0o173`).\n", + "applicability": { + "is_multi_suggestion": true, + "applicability": "MaybeIncorrect" + } + }, + { + "id": "builtin_type_shadow", + "id_span": { + "path": "clippy_lints/src/misc_early.rs", + "line": 184 + }, + "group": "clippy::style", + "docs": " **What it does:** Warns if a generic shadows a built-in type.\n **Why is this bad?** This gives surprising type errors.\n\n **Known problems:** None.\n\n **Example:**\n\n ```ignore\n impl Foo {\n fn impl_func(&self) -> u32 {\n 42\n }\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "redundant_pattern", + "id_span": { + "path": "clippy_lints/src/misc_early.rs", + "line": 213 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for patterns in the form `name @ _`.\n **Why is this bad?** It's almost always more readable to just use direct\n bindings.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let v = Some(\"abc\");\n\n // Bad\n match v {\n Some(x) => (),\n y @ _ => (),\n }\n\n // Good\n match v {\n Some(x) => (),\n y => (),\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "unneeded_wildcard_pattern", + "id_span": { + "path": "clippy_lints/src/misc_early.rs", + "line": 247 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for tuple patterns with a wildcard pattern (`_`) is next to a rest pattern (`..`).\n\n _NOTE_: While `_, ..` means there is at least one element left, `..`\n means there are 0 or more elements left. This can make a difference\n when refactoring, but shouldn't result in errors in the refactored code,\n since the wildcard pattern isn't used anyway.\n **Why is this bad?** The wildcard pattern is unneeded as the rest pattern\n can match that element as well.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # struct TupleStruct(u32, u32, u32);\n # let t = TupleStruct(1, 2, 3);\n // Bad\n match t {\n TupleStruct(0, .., _) => (),\n _ => (),\n }\n\n // Good\n match t {\n TupleStruct(0, ..) => (),\n _ => (),\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "missing_const_for_fn", + "id_span": { + "path": "clippy_lints/src/missing_const_for_fn.rs", + "line": 72 + }, + "group": "clippy::nursery", + "docs": " **What it does:**\n Suggests the use of `const` in functions and methods where possible.\n\n **Why is this bad?**\n\n Not having the function const prevents callers of the function from being const as well.\n\n **Known problems:**\n\n Const functions are currently still being worked on, with some features only being available\n on nightly. This lint does not consider all edge cases currently and the suggestions may be\n incorrect if you are using this lint on stable.\n\n Also, the lint only runs one pass over the code. Consider these two non-const functions:\n\n ```rust\n fn a() -> i32 {\n 0\n }\n fn b() -> i32 {\n a()\n }\n ```\n\n When running Clippy, the lint will only suggest to make `a` const, because `b` at this time\n can't be const as it calls a non-const function. Making `a` const and running Clippy again,\n will suggest to make `b` const, too.\n\n **Example:**\n\n ```rust\n # struct Foo {\n # random_number: usize,\n # }\n # impl Foo {\n fn new() -> Self {\n Self { random_number: 42 }\n }\n # }\n ```\n\n Could be a const fn:\n\n ```rust\n # struct Foo {\n # random_number: usize,\n # }\n # impl Foo {\n const fn new() -> Self {\n Self { random_number: 42 }\n }\n # }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "missing_docs_in_private_items", + "id_span": { + "path": "clippy_lints/src/missing_doc.rs", + "line": 29 + }, + "group": "clippy::restriction", + "docs": " **What it does:** Warns if there is missing doc for any documentable item (public or private).\n\n **Why is this bad?** Doc is good. *rustc* has a `MISSING_DOCS`\n allowed-by-default lint for\n public members, but has no way to enforce documentation of private items.\n This lint fixes that.\n\n **Known problems:** None.\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "missing_inline_in_public_items", + "id_span": { + "path": "clippy_lints/src/missing_inline.rs", + "line": 55 + }, + "group": "clippy::restriction", + "docs": " **What it does:** it lints if an exported function, method, trait method with default impl, or trait method impl is not `#[inline]`.\n\n **Why is this bad?** In general, it is not. Functions can be inlined across\n crates when that's profitable as long as any form of LTO is used. When LTO is disabled,\n functions that are not `#[inline]` cannot be inlined across crates. Certain types of crates\n might intend for most of the methods in their public API to be able to be inlined across\n crates even when LTO is disabled. For these types of crates, enabling this lint might make\n sense. It allows the crate to require all exported methods to be `#[inline]` by default, and\n then opt out for specific methods where this might not make sense.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n pub fn foo() {} // missing #[inline]\n fn ok() {} // ok\n #[inline] pub fn bar() {} // ok\n #[inline(always)] pub fn baz() {} // ok\n\n pub trait Bar {\n fn bar(); // ok\n fn def_bar() {} // missing #[inline]\n }\n\n struct Baz;\n impl Baz {\n fn private() {} // ok\n }\n\n impl Bar for Baz {\n fn bar() {} // ok - Baz is not exported\n }\n\n pub struct PubBaz;\n impl PubBaz {\n fn private() {} // ok\n pub fn not_ptrivate() {} // missing #[inline]\n }\n\n impl Bar for PubBaz {\n fn bar() {} // missing #[inline]\n fn def_bar() {} // missing #[inline]\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "modulo_arithmetic", + "id_span": { + "path": "clippy_lints/src/modulo_arithmetic.rs", + "line": 26 + }, + "group": "clippy::restriction", + "docs": " **What it does:** Checks for modulo arithmetic.\n **Why is this bad?** The results of modulo (%) operation might differ\n depending on the language, when negative numbers are involved.\n If you interop with different languages it might be beneficial\n to double check all places that use modulo arithmetic.\n\n For example, in Rust `17 % -3 = 2`, but in Python `17 % -3 = -1`.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let x = -17 % 3;\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "multiple_crate_versions", + "id_span": { + "path": "clippy_lints/src/multiple_crate_versions.rs", + "line": 32 + }, + "group": "clippy::cargo", + "docs": " **What it does:** Checks to see if multiple versions of a crate are being used.\n\n **Why is this bad?** This bloats the size of targets, and can lead to\n confusing error messages when structs or traits are used interchangeably\n between different versions of a crate.\n\n **Known problems:** Because this can be caused purely by the dependencies\n themselves, it's not always possible to fix this issue.\n\n **Example:**\n ```toml\n # This will pull in both winapi v0.3.x and v0.2.x, triggering a warning.\n [dependencies]\n ctrlc = \"=3.1.0\"\n ansi_term = \"=0.11.0\"\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "mutable_key_type", + "id_span": { + "path": "clippy_lints/src/mut_key.rs", + "line": 50 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for sets/maps with mutable key types.\n **Why is this bad?** All of `HashMap`, `HashSet`, `BTreeMap` and\n `BtreeSet` rely on either the hash or the order of keys be unchanging,\n so having types with interior mutability is a bad idea.\n\n **Known problems:** It's correct to use a struct, that contains interior mutability\n as a key, when its `Hash` implementation doesn't access any of the interior mutable types.\n However, this lint is unable to recognize this, so it causes a false positive in theses cases.\n The `bytes` crate is a great example of this.\n\n **Example:**\n ```rust\n use std::cmp::{PartialEq, Eq};\n use std::collections::HashSet;\n use std::hash::{Hash, Hasher};\n use std::sync::atomic::AtomicUsize;\n# #[allow(unused)]\n\n struct Bad(AtomicUsize);\n impl PartialEq for Bad {\n fn eq(&self, rhs: &Self) -> bool {\n ..\n ; unimplemented!();\n }\n }\n\n impl Eq for Bad {}\n\n impl Hash for Bad {\n fn hash(&self, h: &mut H) {\n ..\n ; unimplemented!();\n }\n }\n\n fn main() {\n let _: HashSet = HashSet::new();\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "mut_mut", + "id_span": { + "path": "clippy_lints/src/mut_mut.rs", + "line": 24 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for instances of `mut mut` references.\n **Why is this bad?** Multiple `mut`s don't add anything meaningful to the\n source. This is either a copy'n'paste error, or it shows a fundamental\n misunderstanding of references.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let mut y = 1;\n let x = &mut &mut y;\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "mut_mutex_lock", + "id_span": { + "path": "clippy_lints/src/mut_mutex_lock.rs", + "line": 40 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for `&mut Mutex::lock` calls\n **Why is this bad?** `Mutex::lock` is less efficient than\n calling `Mutex::get_mut`. In addition you also have a statically\n guarantee that the mutex isn't locked, instead of just a runtime\n guarantee.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n use std::sync::{Arc, Mutex};\n\n let mut value_rc = Arc::new(Mutex::new(42_u8));\n let value_mutex = Arc::get_mut(&mut value_rc).unwrap();\n\n let mut value = value_mutex.lock().unwrap();\n *value += 1;\n ```\n Use instead:\n ```rust\n use std::sync::{Arc, Mutex};\n\n let mut value_rc = Arc::new(Mutex::new(42_u8));\n let value_mutex = Arc::get_mut(&mut value_rc).unwrap();\n\n let value = value_mutex.get_mut().unwrap();\n *value += 1;\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MaybeIncorrect" + } + }, + { + "id": "unnecessary_mut_passed", + "id_span": { + "path": "clippy_lints/src/mut_reference.rs", + "line": 25 + }, + "group": "clippy::style", + "docs": " **What it does:** Detects passing a mutable reference to a function that only requires an immutable reference.\n\n **Why is this bad?** The mutable reference rules out all other references to\n the value. Also the code misleads about the intent of the call site.\n\n **Known problems:** None.\n\n **Example:**\n ```ignore\n // Bad\n my_vec.push(&mut value)\n\n // Good\n my_vec.push(&value)\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "debug_assert_with_mut_call", + "id_span": { + "path": "clippy_lints/src/mutable_debug_assertion.rs", + "line": 28 + }, + "group": "clippy::nursery", + "docs": " **What it does:** Checks for function/method calls with a mutable parameter in `debug_assert!`, `debug_assert_eq!` and `debug_assert_ne!` macros.\n\n **Why is this bad?** In release builds `debug_assert!` macros are optimized out by the\n compiler.\n Therefore mutating something in a `debug_assert!` macro results in different behaviour\n between a release and debug build.\n\n **Known problems:** None\n\n **Example:**\n ```rust,ignore\n debug_assert_eq!(vec![3].pop(), Some(3));\n // or\n fn take_a_mut_parameter(_: &mut u32) -> bool { unimplemented!() }\n debug_assert!(take_a_mut_parameter(&mut 5));\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "mutex_atomic", + "id_span": { + "path": "clippy_lints/src/mutex_atomic.rs", + "line": 34 + }, + "group": "clippy::perf", + "docs": " **What it does:** Checks for usages of `Mutex` where an atomic will do.\n **Why is this bad?** Using a mutex just to make access to a plain bool or\n reference sequential is shooting flies with cannons.\n `std::sync::atomic::AtomicBool` and `std::sync::atomic::AtomicPtr` are leaner and\n faster.\n\n **Known problems:** This lint cannot detect if the mutex is actually used\n for waiting before a critical section.\n\n **Example:**\n ```rust\n # let y = true;\n\n // Bad\n # use std::sync::Mutex;\n let x = Mutex::new(&y);\n\n // Good\n # use std::sync::atomic::AtomicBool;\n let x = AtomicBool::new(y);\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "mutex_integer", + "id_span": { + "path": "clippy_lints/src/mutex_atomic.rs", + "line": 59 + }, + "group": "clippy::nursery", + "docs": " **What it does:** Checks for usages of `Mutex` where `X` is an integral type.\n\n **Why is this bad?** Using a mutex just to make access to a plain integer\n sequential is\n shooting flies with cannons. `std::sync::atomic::AtomicUsize` is leaner and faster.\n\n **Known problems:** This lint cannot detect if the mutex is actually used\n for waiting before a critical section.\n\n **Example:**\n ```rust\n # use std::sync::Mutex;\n let x = Mutex::new(0usize);\n\n // Good\n # use std::sync::atomic::AtomicUsize;\n let x = AtomicUsize::new(0usize);\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "needless_arbitrary_self_type", + "id_span": { + "path": "clippy_lints/src/needless_arbitrary_self_type.rs", + "line": 55 + }, + "group": "clippy::complexity", + "docs": " **What it does:** The lint checks for `self` in fn parameters that specify the `Self`-type explicitly\n **Why is this bad?** Increases the amount and decreases the readability of code\n\n **Known problems:** None\n\n **Example:**\n ```rust\n enum ValType {\n I32,\n I64,\n F32,\n F64,\n }\n\n impl ValType {\n pub fn bytes(self: Self) -> usize {\n match self {\n Self::I32 | Self::F32 => 4,\n Self::I64 | Self::F64 => 8,\n }\n }\n }\n ```\n\n Could be rewritten as\n\n ```rust\n enum ValType {\n I32,\n I64,\n F32,\n F64,\n }\n\n impl ValType {\n pub fn bytes(self) -> usize {\n match self {\n Self::I32 | Self::F32 => 4,\n Self::I64 | Self::F64 => 8,\n }\n }\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "needless_bool", + "id_span": { + "path": "clippy_lints/src/needless_bool.rs", + "line": 38 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for expressions of the form `if c { true } else { false }` (or vice versa) and suggests using the condition directly.\n\n **Why is this bad?** Redundant code.\n\n **Known problems:** Maybe false positives: Sometimes, the two branches are\n painstakingly documented (which we, of course, do not detect), so they *may*\n have some value. Even then, the documentation can be rewritten to match the\n shorter code.\n\n **Example:**\n ```rust,ignore\n if x {\n false\n } else {\n true\n }\n ```\n Could be written as\n ```rust,ignore\n !x\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "bool_comparison", + "id_span": { + "path": "clippy_lints/src/needless_bool.rs", + "line": 62 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for expressions of the form `x == true`, `x != true` and order comparisons such as `x < true` (or vice versa) and\n suggest using the variable directly.\n\n **Why is this bad?** Unnecessary code.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n if x == true {}\n if y == false {}\n ```\n use `x` directly:\n ```rust,ignore\n if x {}\n if !y {}\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "needless_borrow", + "id_span": { + "path": "clippy_lints/src/needless_borrow.rs", + "line": 32 + }, + "group": "clippy::nursery", + "docs": " **What it does:** Checks for address of operations (`&`) that are going to be dereferenced immediately by the compiler.\n\n **Why is this bad?** Suggests that the receiver of the expression borrows\n the expression.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n // Bad\n let x: &i32 = &&&&&&5;\n\n // Good\n let x: &i32 = &5;\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "needless_borrowed_reference", + "id_span": { + "path": "clippy_lints/src/needless_borrowed_ref.rs", + "line": 48 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for useless borrowed references.\n **Why is this bad?** It is mostly useless and make the code look more\n complex than it\n actually is.\n\n **Known problems:** It seems that the `&ref` pattern is sometimes useful.\n For instance in the following snippet:\n ```rust,ignore\n enum Animal {\n Cat(u64),\n Dog(u64),\n }\n\n fn foo(a: &Animal, b: &Animal) {\n match (a, b) {\n (&Animal::Cat(v), k) | (k, &Animal::Cat(v)) => (), // lifetime mismatch error\n (&Animal::Dog(ref c), &Animal::Dog(_)) => ()\n }\n }\n ```\n There is a lifetime mismatch error for `k` (indeed a and b have distinct\n lifetime).\n This can be fixed by using the `&ref` pattern.\n However, the code can also be fixed by much cleaner ways\n\n **Example:**\n ```rust\n let mut v = Vec::::new();\n let _ = v.iter_mut().filter(|&ref a| a.is_empty());\n ```\n This closure takes a reference on something that has been matched as a\n reference and\n de-referenced.\n As such, it could just be |a| a.is_empty()\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "needless_continue", + "id_span": { + "path": "clippy_lints/src/needless_continue.rs", + "line": 114 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** The lint checks for `if`-statements appearing in loops that contain a `continue` statement in either their main blocks or their\n `else`-blocks, when omitting the `else`-block possibly with some\n rearrangement of code can make the code easier to understand.\n\n **Why is this bad?** Having explicit `else` blocks for `if` statements\n containing `continue` in their THEN branch adds unnecessary branching and\n nesting to the code. Having an else block containing just `continue` can\n also be better written by grouping the statements following the whole `if`\n statement within the THEN block and omitting the else block completely.\n\n **Known problems:** None\n\n **Example:**\n ```rust\n # fn condition() -> bool { false }\n # fn update_condition() {}\n # let x = false;\n while condition() {\n update_condition();\n if x {\n // ...\n } else {\n continue;\n }\n println!(\"Hello, world\");\n }\n ```\n\n Could be rewritten as\n\n ```rust\n # fn condition() -> bool { false }\n # fn update_condition() {}\n # let x = false;\n while condition() {\n update_condition();\n if x {\n // ...\n println!(\"Hello, world\");\n }\n }\n ```\n\n As another example, the following code\n\n ```rust\n # fn waiting() -> bool { false }\n loop {\n if waiting() {\n continue;\n } else {\n // Do something useful\n }\n # break;\n }\n ```\n Could be rewritten as\n\n ```rust\n # fn waiting() -> bool { false }\n loop {\n if waiting() {\n continue;\n }\n // Do something useful\n # break;\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "needless_pass_by_value", + "id_span": { + "path": "clippy_lints/src/needless_pass_by_value.rs", + "line": 50 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for functions taking arguments by value, but not consuming them in its\n body.\n\n **Why is this bad?** Taking arguments by reference is more flexible and can\n sometimes avoid\n unnecessary allocations.\n\n **Known problems:**\n * This lint suggests taking an argument by reference,\n however sometimes it is better to let users decide the argument type\n (by using `Borrow` trait, for example), depending on how the function is used.\n\n **Example:**\n ```rust\n fn foo(v: Vec) {\n assert_eq!(v.len(), 42);\n }\n ```\n should be\n ```rust\n fn foo(v: &[i32]) {\n assert_eq!(v.len(), 42);\n }\n ```\n", + "applicability": { + "is_multi_suggestion": true, + "applicability": null + } + }, + { + "id": "needless_question_mark", + "id_span": { + "path": "clippy_lints/src/needless_question_mark.rs", + "line": 57 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Suggests alternatives for useless applications of `?` in terminating expressions\n\n **Why is this bad?** There's no reason to use `?` to short-circuit when execution of the body will end there anyway.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n struct TO {\n magic: Option,\n }\n\n fn f(to: TO) -> Option {\n Some(to.magic?)\n }\n\n struct TR {\n magic: Result,\n }\n\n fn g(tr: Result) -> Result {\n tr.and_then(|t| Ok(t.magic?))\n }\n\n ```\n Use instead:\n ```rust\n struct TO {\n magic: Option,\n }\n\n fn f(to: TO) -> Option {\n to.magic\n }\n\n struct TR {\n magic: Result,\n }\n\n fn g(tr: Result) -> Result {\n tr.and_then(|t| t.magic)\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "needless_update", + "id_span": { + "path": "clippy_lints/src/needless_update.rs", + "line": 43 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for needlessly including a base struct on update when all fields are changed anyway.\n\n This lint is not applied to structs marked with\n [non_exhaustive](https://doc.rust-lang.org/reference/attributes/type_system.html).\n\n **Why is this bad?** This will cost resources (because the base has to be\n somewhere), and make the code less readable.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # struct Point {\n # x: i32,\n # y: i32,\n # z: i32,\n # }\n # let zero_point = Point { x: 0, y: 0, z: 0 };\n\n // Bad\n Point {\n x: 1,\n y: 1,\n z: 1,\n ..zero_point\n };\n\n // Ok\n Point {\n x: 1,\n y: 1,\n ..zero_point\n };\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "neg_cmp_op_on_partial_ord", + "id_span": { + "path": "clippy_lints/src/neg_cmp_op_on_partial_ord.rs", + "line": 41 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for the usage of negated comparison operators on types which only implement\n `PartialOrd` (e.g., `f64`).\n\n **Why is this bad?**\n These operators make it easy to forget that the underlying types actually allow not only three\n potential Orderings (Less, Equal, Greater) but also a fourth one (Uncomparable). This is\n especially easy to miss if the operator based comparison result is negated.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n use std::cmp::Ordering;\n\n // Bad\n let a = 1.0;\n let b = f64::NAN;\n\n let _not_less_or_equal = !(a <= b);\n\n // Good\n let a = 1.0;\n let b = f64::NAN;\n\n let _not_less_or_equal = match a.partial_cmp(&b) {\n None | Some(Ordering::Greater) => true,\n _ => false,\n };\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "neg_multiply", + "id_span": { + "path": "clippy_lints/src/neg_multiply.rs", + "line": 21 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for multiplication by -1 as a form of negation.\n **Why is this bad?** It's more readable to just negate.\n\n **Known problems:** This only catches integers (for now).\n\n **Example:**\n ```ignore\n x * -1\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "new_without_default", + "id_span": { + "path": "clippy_lints/src/new_without_default.rs", + "line": 48 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for types with a `fn new() -> Self` method and no implementation of\n [`Default`](https://doc.rust-lang.org/std/default/trait.Default.html).\n\n **Why is this bad?** The user might expect to be able to use\n [`Default`](https://doc.rust-lang.org/std/default/trait.Default.html) as the\n type can be constructed without arguments.\n\n **Known problems:** Hopefully none.\n\n **Example:**\n\n ```ignore\n struct Foo(Bar);\n\n impl Foo {\n fn new() -> Self {\n Foo(Bar::new())\n }\n }\n ```\n\n To fix the lint, add a `Default` implementation that delegates to `new`:\n\n ```ignore\n struct Foo(Bar);\n\n impl Default for Foo {\n fn default() -> Self {\n Foo::new()\n }\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MaybeIncorrect" + } + }, + { + "id": "no_effect", + "id_span": { + "path": "clippy_lints/src/no_effect.rs", + "line": 22 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for statements which have no effect.\n **Why is this bad?** Similar to dead code, these statements are actually\n executed. However, as they have no effect, all they do is make the code less\n readable.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n 0;\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "unnecessary_operation", + "id_span": { + "path": "clippy_lints/src/no_effect.rs", + "line": 40 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for expression statements that can be reduced to a sub-expression.\n\n **Why is this bad?** Expressions by themselves often have no side-effects.\n Having such expressions reduces readability.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n compute_array()[0];\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "declare_interior_mutable_const", + "id_span": { + "path": "clippy_lints/src/non_copy_const.rs", + "line": 69 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for declaration of `const` items which is interior mutable (e.g., contains a `Cell`, `Mutex`, `AtomicXxxx`, etc.).\n\n **Why is this bad?** Consts are copied everywhere they are referenced, i.e.,\n every time you refer to the const a fresh instance of the `Cell` or `Mutex`\n or `AtomicXxxx` will be created, which defeats the whole purpose of using\n these types in the first place.\n\n The `const` should better be replaced by a `static` item if a global\n variable is wanted, or replaced by a `const fn` if a constructor is wanted.\n\n **Known problems:** A \"non-constant\" const item is a legacy way to supply an\n initialized value to downstream `static` items (e.g., the\n `std::sync::ONCE_INIT` constant). In this case the use of `const` is legit,\n and this lint should be suppressed.\n\n Even though the lint avoids triggering on a constant whose type has enums that have variants\n with interior mutability, and its value uses non interior mutable variants (see\n [#3962](https://github.com/rust-lang/rust-clippy/issues/3962) and\n [#3825](https://github.com/rust-lang/rust-clippy/issues/3825) for examples);\n it complains about associated constants without default values only based on its types;\n which might not be preferable.\n There're other enums plus associated constants cases that the lint cannot handle.\n\n Types that have underlying or potential interior mutability trigger the lint whether\n the interior mutable field is used or not. See issues\n [#5812](https://github.com/rust-lang/rust-clippy/issues/5812) and\n\n **Example:**\n ```rust\n use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};\n\n // Bad.\n const CONST_ATOM: AtomicUsize = AtomicUsize::new(12);\n CONST_ATOM.store(6, SeqCst); // the content of the atomic is unchanged\n assert_eq!(CONST_ATOM.load(SeqCst), 12); // because the CONST_ATOM in these lines are distinct\n\n // Good.\n static STATIC_ATOM: AtomicUsize = AtomicUsize::new(15);\n STATIC_ATOM.store(9, SeqCst);\n assert_eq!(STATIC_ATOM.load(SeqCst), 9); // use a `static` item to refer to the same instance\n ```\n", + "applicability": null + }, + { + "id": "borrow_interior_mutable_const", + "id_span": { + "path": "clippy_lints/src/non_copy_const.rs", + "line": 110 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks if `const` items which is interior mutable (e.g., contains a `Cell`, `Mutex`, `AtomicXxxx`, etc.) has been borrowed directly.\n\n **Why is this bad?** Consts are copied everywhere they are referenced, i.e.,\n every time you refer to the const a fresh instance of the `Cell` or `Mutex`\n or `AtomicXxxx` will be created, which defeats the whole purpose of using\n these types in the first place.\n\n The `const` value should be stored inside a `static` item.\n\n **Known problems:** When an enum has variants with interior mutability, use of its non\n interior mutable variants can generate false positives. See issue\n [#3962](https://github.com/rust-lang/rust-clippy/issues/3962)\n\n Types that have underlying or potential interior mutability trigger the lint whether\n the interior mutable field is used or not. See issues\n [#5812](https://github.com/rust-lang/rust-clippy/issues/5812) and\n [#3825](https://github.com/rust-lang/rust-clippy/issues/3825)\n\n **Example:**\n ```rust\n use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};\n const CONST_ATOM: AtomicUsize = AtomicUsize::new(12);\n\n // Bad.\n CONST_ATOM.store(6, SeqCst); // the content of the atomic is unchanged\n assert_eq!(CONST_ATOM.load(SeqCst), 12); // because the CONST_ATOM in these lines are distinct\n\n // Good.\n static STATIC_ATOM: AtomicUsize = CONST_ATOM;\n STATIC_ATOM.store(9, SeqCst);\n assert_eq!(STATIC_ATOM.load(SeqCst), 9); // use a `static` item to refer to the same instance\n ```\n", + "applicability": null + }, + { + "id": "similar_names", + "id_span": { + "path": "clippy_lints/src/non_expressive_names.rs", + "line": 27 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for names that are very similar and thus confusing.\n **Why is this bad?** It's hard to distinguish between names that differ only\n by a single character.\n\n **Known problems:** None?\n\n **Example:**\n ```ignore\n let checked_exp = something;\n let checked_expr = something_else;\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "many_single_char_names", + "id_span": { + "path": "clippy_lints/src/non_expressive_names.rs", + "line": 45 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for too many variables whose name consists of a single character.\n\n **Why is this bad?** It's hard to memorize what a variable means without a\n descriptive name.\n\n **Known problems:** None?\n\n **Example:**\n ```ignore\n let (a, b, c, d, e, f, g) = (...);\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "just_underscores_and_digits", + "id_span": { + "path": "clippy_lints/src/non_expressive_names.rs", + "line": 65 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks if you have variables whose name consists of just underscores and digits.\n\n **Why is this bad?** It's hard to memorize what a variable means without a\n descriptive name.\n\n **Known problems:** None?\n\n **Example:**\n ```rust\n let _1 = 1;\n let ___1 = 1;\n let __1___2 = 11;\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "nonsensical_open_options", + "id_span": { + "path": "clippy_lints/src/open_options.rs", + "line": 23 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for duplicate open options as well as combinations that make no sense.\n\n **Why is this bad?** In the best case, the code will be harder to read than\n necessary. I don't know the worst case.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n use std::fs::OpenOptions;\n\n OpenOptions::new().read(true).truncate(true);\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "option_env_unwrap", + "id_span": { + "path": "clippy_lints/src/option_env_unwrap.rs", + "line": 28 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for usage of `option_env!(...).unwrap()` and suggests usage of the `env!` macro.\n\n **Why is this bad?** Unwrapping the result of `option_env!` will panic\n at run-time if the environment variable doesn't exist, whereas `env!`\n catches it at compile-time.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust,no_run\n let _ = option_env!(\"HOME\").unwrap();\n ```\n\n Is better expressed as:\n\n ```rust,no_run\n let _ = env!(\"HOME\");\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "option_if_let_else", + "id_span": { + "path": "clippy_lints/src/option_if_let_else.rs", + "line": 59 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Lints usage of `if let Some(v) = ... { y } else { x }` which is more\n idiomatically done with `Option::map_or` (if the else bit is a pure\n expression) or `Option::map_or_else` (if the else bit is an impure\n expression).\n\n **Why is this bad?**\n Using the dedicated functions of the Option type is clearer and\n more concise than an `if let` expression.\n\n **Known problems:**\n This lint uses a deliberately conservative metric for checking\n if the inside of either body contains breaks or continues which will\n cause it to not suggest a fix if either block contains a loop with\n continues or breaks contained within the loop.\n\n **Example:**\n\n ```rust\n # let optional: Option = Some(0);\n # fn do_complicated_function() -> u32 { 5 };\n let _ = if let Some(foo) = optional {\n foo\n } else {\n 5\n };\n let _ = if let Some(foo) = optional {\n foo\n } else {\n let y = do_complicated_function();\n y*y\n };\n ```\n\n should be\n\n ```rust\n # let optional: Option = Some(0);\n # fn do_complicated_function() -> u32 { 5 };\n let _ = optional.map_or(5, |foo| foo);\n let _ = optional.map_or_else(||{\n let y = do_complicated_function();\n y*y\n }, |foo| foo);\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MaybeIncorrect" + } + }, + { + "id": "overflow_check_conditional", + "id_span": { + "path": "clippy_lints/src/overflow_check_conditional.rs", + "line": 21 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Detects classic underflow/overflow checks.\n **Why is this bad?** Most classic C underflow/overflow checks will fail in\n Rust. Users can use functions like `overflowing_*` and `wrapping_*` instead.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let a = 1;\n # let b = 2;\n a + b < a;\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "panic_in_result_fn", + "id_span": { + "path": "clippy_lints/src/panic_in_result_fn.rs", + "line": 29 + }, + "group": "clippy::restriction", + "docs": " **What it does:** Checks for usage of `panic!`, `unimplemented!`, `todo!`, `unreachable!` or assertions in a function of type result.\n **Why is this bad?** For some codebases, it is desirable for functions of type result to return an error instead of crashing. Hence panicking macros should be avoided.\n\n **Known problems:** Functions called from a function returning a `Result` may invoke a panicking macro. This is not checked.\n\n **Example:**\n\n ```rust\n fn result_with_panic() -> Result\n {\n panic!(\"error\");\n }\n ```\n Use instead:\n ```rust\n fn result_without_panic() -> Result {\n Err(String::from(\"error\"))\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "panic", + "id_span": { + "path": "clippy_lints/src/panic_unimplemented.rs", + "line": 19 + }, + "group": "clippy::restriction", + "docs": " **What it does:** Checks for usage of `panic!`.\n **Why is this bad?** `panic!` will stop the execution of the executable\n\n **Known problems:** None.\n\n **Example:**\n ```no_run\n panic!(\"even with a good reason\");\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "unimplemented", + "id_span": { + "path": "clippy_lints/src/panic_unimplemented.rs", + "line": 35 + }, + "group": "clippy::restriction", + "docs": " **What it does:** Checks for usage of `unimplemented!`.\n **Why is this bad?** This macro should not be present in production code\n\n **Known problems:** None.\n\n **Example:**\n ```no_run\n unimplemented!();\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "todo", + "id_span": { + "path": "clippy_lints/src/panic_unimplemented.rs", + "line": 51 + }, + "group": "clippy::restriction", + "docs": " **What it does:** Checks for usage of `todo!`.\n **Why is this bad?** This macro should not be present in production code\n\n **Known problems:** None.\n\n **Example:**\n ```no_run\n todo!();\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "unreachable", + "id_span": { + "path": "clippy_lints/src/panic_unimplemented.rs", + "line": 67 + }, + "group": "clippy::restriction", + "docs": " **What it does:** Checks for usage of `unreachable!`.\n **Why is this bad?** This macro can cause code to panic\n\n **Known problems:** None.\n\n **Example:**\n ```no_run\n unreachable!();\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "partialeq_ne_impl", + "id_span": { + "path": "clippy_lints/src/partialeq_ne_impl.rs", + "line": 27 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for manual re-implementations of `PartialEq::ne`.\n **Why is this bad?** `PartialEq::ne` is required to always return the\n negated result of `PartialEq::eq`, which is exactly what the default\n implementation does. Therefore, there should never be any need to\n re-implement it.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n struct Foo;\n\n impl PartialEq for Foo {\n fn eq(&self, other: &Foo) -> bool { true }\n fn ne(&self, other: &Foo) -> bool { !(self == other) }\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "trivially_copy_pass_by_ref", + "id_span": { + "path": "clippy_lints/src/pass_by_ref_or_value.rs", + "line": 52 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for functions taking arguments by reference, where the argument type is `Copy` and small enough to be more efficient to always\n pass by value.\n\n **Why is this bad?** In many calling conventions instances of structs will\n be passed through registers if they fit into two or less general purpose\n registers.\n\n **Known problems:** This lint is target register size dependent, it is\n limited to 32-bit to try and reduce portability problems between 32 and\n 64-bit, but if you are compiling for 8 or 16-bit targets then the limit\n will be different.\n\n The configuration option `trivial_copy_size_limit` can be set to override\n this limit for a project.\n\n This lint attempts to allow passing arguments by reference if a reference\n to that argument is returned. This is implemented by comparing the lifetime\n of the argument and return value for equality. However, this can cause\n false positives in cases involving multiple lifetimes that are bounded by\n each other.\n\n **Example:**\n\n ```rust\n // Bad\n fn foo(v: &u32) {}\n ```\n\n ```rust\n // Better\n fn foo(v: u32) {}\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "Unspecified" + } + }, + { + "id": "large_types_passed_by_value", + "id_span": { + "path": "clippy_lints/src/pass_by_ref_or_value.rs", + "line": 84 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for functions taking arguments by value, where the argument type is `Copy` and large enough to be worth considering\n passing by reference. Does not trigger if the function is being exported,\n because that might induce API breakage, if the parameter is declared as mutable,\n or if the argument is a `self`.\n\n **Why is this bad?** Arguments passed by value might result in an unnecessary\n shallow copy, taking up more space in the stack and requiring a call to\n `memcpy`, which can be expensive.\n\n **Example:**\n\n ```rust\n #[derive(Clone, Copy)]\n struct TooLarge([u8; 2048]);\n\n // Bad\n fn foo(v: TooLarge) {}\n ```\n ```rust\n #[derive(Clone, Copy)]\n struct TooLarge([u8; 2048]);\n\n // Good\n fn foo(v: &TooLarge) {}\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MaybeIncorrect" + } + }, + { + "id": "path_buf_push_overwrite", + "id_span": { + "path": "clippy_lints/src/path_buf_push_overwrite.rs", + "line": 36 + }, + "group": "clippy::nursery", + "docs": " **What it does:*** Checks for [push](https://doc.rust-lang.org/std/path/struct.PathBuf.html#method.push) calls on `PathBuf` that can cause overwrites.\n\n **Why is this bad?** Calling `push` with a root path at the start can overwrite the\n previous defined path.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n use std::path::PathBuf;\n\n let mut x = PathBuf::from(\"/foo\");\n x.push(\"/bar\");\n assert_eq!(x, PathBuf::from(\"/bar\"));\n ```\n Could be written:\n\n ```rust\n use std::path::PathBuf;\n\n let mut x = PathBuf::from(\"/foo\");\n x.push(\"bar\");\n assert_eq!(x, PathBuf::from(\"/foo/bar\"));\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "pattern_type_mismatch", + "id_span": { + "path": "clippy_lints/src/pattern_type_mismatch.rs", + "line": 79 + }, + "group": "clippy::restriction", + "docs": " **What it does:** Checks for patterns that aren't exact representations of the types they are applied to.\n\n To satisfy this lint, you will have to adjust either the expression that is matched\n against or the pattern itself, as well as the bindings that are introduced by the\n adjusted patterns. For matching you will have to either dereference the expression\n with the `*` operator, or amend the patterns to explicitly match against `&`\n or `&mut ` depending on the reference mutability. For the bindings you need\n to use the inverse. You can leave them as plain bindings if you wish for the value\n to be copied, but you must use `ref mut ` or `ref ` to construct\n a reference into the matched structure.\n\n If you are looking for a way to learn about ownership semantics in more detail, it\n is recommended to look at IDE options available to you to highlight types, lifetimes\n and reference semantics in your code. The available tooling would expose these things\n in a general way even outside of the various pattern matching mechanics. Of course\n this lint can still be used to highlight areas of interest and ensure a good understanding\n of ownership semantics.\n\n **Why is this bad?** It isn't bad in general. But in some contexts it can be desirable\n because it increases ownership hints in the code, and will guard against some changes\n in ownership.\n\n **Known problems:** None.\n\n **Example:**\n\n This example shows the basic adjustments necessary to satisfy the lint. Note how\n the matched expression is explicitly dereferenced with `*` and the `inner` variable\n is bound to a shared borrow via `ref inner`.\n\n ```rust,ignore\n // Bad\n let value = &Some(Box::new(23));\n match value {\n Some(inner) => println!(\"{}\", inner),\n None => println!(\"none\"),\n }\n\n // Good\n let value = &Some(Box::new(23));\n match *value {\n Some(ref inner) => println!(\"{}\", inner),\n None => println!(\"none\"),\n }\n ```\n\n The following example demonstrates one of the advantages of the more verbose style.\n Note how the second version uses `ref mut a` to explicitly declare `a` a shared mutable\n borrow, while `b` is simply taken by value. This ensures that the loop body cannot\n accidentally modify the wrong part of the structure.\n\n ```rust,ignore\n // Bad\n let mut values = vec![(2, 3), (3, 4)];\n for (a, b) in &mut values {\n *a += *b;\n }\n\n // Good\n let mut values = vec![(2, 3), (3, 4)];\n for &mut (ref mut a, b) in &mut values {\n *a += b;\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "precedence", + "id_span": { + "path": "clippy_lints/src/precedence.rs", + "line": 44 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for operations where precedence may be unclear and suggests to add parentheses. Currently it catches the following:\n * mixed usage of arithmetic and bit shifting/combining operators without\n parentheses\n * a \"negative\" numeric literal (which is really a unary `-` followed by a\n numeric literal)\n followed by a method call\n\n **Why is this bad?** Not everyone knows the precedence of those operators by\n heart, so expressions like these may trip others trying to reason about the\n code.\n\n **Known problems:** None.\n\n **Example:**\n * `1 << 2 + 3` equals 32, while `(1 << 2) + 3` equals 7\n * `-1i32.abs()` equals -1, while `(-1i32).abs()` equals 1\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "ptr_arg", + "id_span": { + "path": "clippy_lints/src/ptr.rs", + "line": 69 + }, + "group": "clippy::style", + "docs": " **What it does:** This lint checks for function arguments of type `&String` or `&Vec` unless the references are mutable. It will also suggest you\n replace `.clone()` calls with the appropriate `.to_owned()`/`to_string()`\n calls.\n\n **Why is this bad?** Requiring the argument to be of the specific size\n makes the function less useful for no benefit; slices in the form of `&[T]`\n or `&str` usually suffice and can be obtained from other types, too.\n\n **Known problems:** The lint does not follow data. So if you have an\n argument `x` and write `let y = x; y.clone()` the lint will not suggest\n changing that `.clone()` to `.to_owned()`.\n\n Other functions called from this function taking a `&String` or `&Vec`\n argument may also fail to compile if you change the argument. Applying\n this lint on them will fix the problem, but they may be in other crates.\n\n One notable example of a function that may cause issues, and which cannot\n easily be changed due to being in the standard library is `Vec::contains`.\n when called on a `Vec>`. If a `&Vec` is passed to that method then\n it will compile, but if a `&[T]` is passed then it will not compile.\n\n ```ignore\n fn cannot_take_a_slice(v: &Vec) -> bool {\n let vec_of_vecs: Vec> = some_other_fn();\n\n vec_of_vecs.contains(v)\n }\n ```\n\n Also there may be `fn(&Vec)`-typed references pointing to your function.\n If you have them, you will get a compiler error after applying this lint's\n suggestions. You then have the choice to undo your changes or change the\n type of the reference.\n\n Note that if the function is part of your public interface, there may be\n other crates referencing it, of which you may not be aware. Carefully\n deprecate the function before applying the lint suggestions in this case.\n\n **Example:**\n ```ignore\n // Bad\n fn foo(&Vec) { .. }\n\n // Good\n fn foo(&[u32]) { .. }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "Unspecified" + } + }, + { + "id": "cmp_null", + "id_span": { + "path": "clippy_lints/src/ptr.rs", + "line": 95 + }, + "group": "clippy::style", + "docs": " **What it does:** This lint checks for equality comparisons with `ptr::null`\n **Why is this bad?** It's easier and more readable to use the inherent\n `.is_null()`\n method instead\n\n **Known problems:** None.\n\n **Example:**\n ```ignore\n // Bad\n if x == ptr::null {\n ..\n }\n\n // Good\n if x.is_null() {\n ..\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "mut_from_ref", + "id_span": { + "path": "clippy_lints/src/ptr.rs", + "line": 117 + }, + "group": "clippy::correctness", + "docs": " **What it does:** This lint checks for functions that take immutable references and return mutable ones.\n\n **Why is this bad?** This is trivially unsound, as one can create two\n mutable references from the same (immutable!) source.\n This [error](https://github.com/rust-lang/rust/issues/39465)\n actually lead to an interim Rust release 1.15.1.\n\n **Known problems:** To be on the conservative side, if there's at least one\n mutable reference with the output lifetime, this lint will not trigger.\n In practice, this case is unlikely anyway.\n\n **Example:**\n ```ignore\n fn foo(&Foo) -> &mut Bar { .. }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "ptr_eq", + "id_span": { + "path": "clippy_lints/src/ptr_eq.rs", + "line": 32 + }, + "group": "clippy::style", + "docs": " **What it does:** Use `std::ptr::eq` when applicable\n **Why is this bad?** `ptr::eq` can be used to compare `&T` references\n (which coerce to `*const T` implicitly) by their address rather than\n comparing the values they point to.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n let a = &[1, 2, 3];\n let b = &[1, 2, 3];\n\n assert!(a as *const _ as usize == b as *const _ as usize);\n ```\n Use instead:\n ```rust\n let a = &[1, 2, 3];\n let b = &[1, 2, 3];\n\n assert!(std::ptr::eq(a, b));\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "ptr_offset_with_cast", + "id_span": { + "path": "clippy_lints/src/ptr_offset_with_cast.rs", + "line": 40 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for usage of the `offset` pointer method with a `usize` casted to an `isize`.\n\n **Why is this bad?** If we’re always increasing the pointer address, we can avoid the numeric\n cast by using the `add` method instead.\n\n **Known problems:** None\n\n **Example:**\n ```rust\n let vec = vec![b'a', b'b', b'c'];\n let ptr = vec.as_ptr();\n let offset = 1_usize;\n\n unsafe {\n ptr.offset(offset as isize);\n }\n ```\n\n Could be written:\n\n ```rust\n let vec = vec![b'a', b'b', b'c'];\n let ptr = vec.as_ptr();\n let offset = 1_usize;\n\n unsafe {\n ptr.add(offset);\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "question_mark", + "id_span": { + "path": "clippy_lints/src/question_mark.rs", + "line": 34 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for expressions that could be replaced by the question mark operator.\n **Why is this bad?** Question mark usage is more idiomatic.\n\n **Known problems:** None\n\n **Example:**\n ```ignore\n if option.is_none() {\n return None;\n }\n ```\n\n Could be written:\n\n ```ignore\n option?;\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "range_zip_with_len", + "id_span": { + "path": "clippy_lints/src/ranges.rs", + "line": 40 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for zipping a collection with the range of `0.._.len()`.\n\n **Why is this bad?** The code is better expressed with `.enumerate()`.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let x = vec![1];\n x.iter().zip(0..x.len());\n ```\n Could be written as\n ```rust\n # let x = vec![1];\n x.iter().enumerate();\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "range_plus_one", + "id_span": { + "path": "clippy_lints/src/ranges.rs", + "line": 74 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for exclusive ranges where 1 is added to the upper bound, e.g., `x..(y+1)`.\n\n **Why is this bad?** The code is more readable with an inclusive range\n like `x..=y`.\n\n **Known problems:** Will add unnecessary pair of parentheses when the\n expression is not wrapped in a pair but starts with a opening parenthesis\n and ends with a closing one.\n I.e., `let _ = (f()+1)..(f()+1)` results in `let _ = ((f()+1)..=f())`.\n\n Also in many cases, inclusive ranges are still slower to run than\n exclusive ranges, because they essentially add an extra branch that\n LLVM may fail to hoist out of the loop.\n\n This will cause a warning that cannot be fixed if the consumer of the\n range only accepts a specific range type, instead of the generic\n `RangeBounds` trait\n ([#3307](https://github.com/rust-lang/rust-clippy/issues/3307)).\n\n **Example:**\n ```rust,ignore\n for x..(y+1) { .. }\n ```\n Could be written as\n ```rust,ignore\n for x..=y { .. }\n ```\n", + "applicability": { + "is_multi_suggestion": true, + "applicability": "MachineApplicable" + } + }, + { + "id": "range_minus_one", + "id_span": { + "path": "clippy_lints/src/ranges.rs", + "line": 99 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for inclusive ranges where 1 is subtracted from the upper bound, e.g., `x..=(y-1)`.\n\n **Why is this bad?** The code is more readable with an exclusive range\n like `x..y`.\n\n **Known problems:** This will cause a warning that cannot be fixed if\n the consumer of the range only accepts a specific range type, instead of\n the generic `RangeBounds` trait\n ([#3307](https://github.com/rust-lang/rust-clippy/issues/3307)).\n\n **Example:**\n ```rust,ignore\n for x..=(y-1) { .. }\n ```\n Could be written as\n ```rust,ignore\n for x..y { .. }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "reversed_empty_ranges", + "id_span": { + "path": "clippy_lints/src/ranges.rs", + "line": 132 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for range expressions `x..y` where both `x` and `y` are constant and `x` is greater or equal to `y`.\n\n **Why is this bad?** Empty ranges yield no values so iterating them is a no-op.\n Moreover, trying to use a reversed range to index a slice will panic at run-time.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust,no_run\n fn main() {\n (10..=0).for_each(|x| println!(\"{}\", x));\n\n let arr = [1, 2, 3, 4, 5];\n let sub = &arr[3..1];\n }\n ```\n Use instead:\n ```rust\n fn main() {\n (0..=10).rev().for_each(|x| println!(\"{}\", x));\n\n let arr = [1, 2, 3, 4, 5];\n let sub = &arr[1..3];\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MaybeIncorrect" + } + }, + { + "id": "manual_range_contains", + "id_span": { + "path": "clippy_lints/src/ranges.rs", + "line": 159 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for expressions like `x >= 3 && x < 8` that could be more readably expressed as `(3..8).contains(x)`.\n\n **Why is this bad?** `contains` expresses the intent better and has less\n failure modes (such as fencepost errors or using `||` instead of `&&`).\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n // given\n let x = 6;\n\n assert!(x >= 3 && x < 8);\n ```\n Use instead:\n ```rust\n# let x = 6;\n assert!((3..8).contains(&x));\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "redundant_clone", + "id_span": { + "path": "clippy_lints/src/redundant_clone.rs", + "line": 63 + }, + "group": "clippy::perf", + "docs": " **What it does:** Checks for a redundant `clone()` (and its relatives) which clones an owned value that is going to be dropped without further use.\n\n **Why is this bad?** It is not always possible for the compiler to eliminate useless\n allocations and deallocations generated by redundant `clone()`s.\n\n **Known problems:**\n\n False-negatives: analysis performed by this lint is conservative and limited.\n\n **Example:**\n ```rust\n # use std::path::Path;\n # #[derive(Clone)]\n # struct Foo;\n # impl Foo {\n # fn new() -> Self { Foo {} }\n # }\n # fn call(x: Foo) {}\n {\n let x = Foo::new();\n call(x.clone());\n call(x.clone()); // this can just pass `x`\n }\n\n [\"lorem\", \"ipsum\"].join(\" \").to_string();\n\n Path::new(\"/a/b\").join(\"c\").to_path_buf();\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "redundant_closure_call", + "id_span": { + "path": "clippy_lints/src/redundant_closure_call.rs", + "line": 32 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Detects closures called in the same expression where they are defined.\n\n **Why is this bad?** It is unnecessarily adding to the expression's\n complexity.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n // Bad\n let a = (|| 42)()\n\n // Good\n let a = 42\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "redundant_else", + "id_span": { + "path": "clippy_lints/src/redundant_else.rs", + "line": 37 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for `else` blocks that can be removed without changing semantics.\n **Why is this bad?** The `else` block adds unnecessary indentation and verbosity.\n\n **Known problems:** Some may prefer to keep the `else` block for clarity.\n\n **Example:**\n\n ```rust\n fn my_func(count: u32) {\n if count == 0 {\n print!(\"Nothing to do\");\n return;\n } else {\n print!(\"Moving on...\");\n }\n }\n ```\n Use instead:\n ```rust\n fn my_func(count: u32) {\n if count == 0 {\n print!(\"Nothing to do\");\n return;\n }\n print!(\"Moving on...\");\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "redundant_field_names", + "id_span": { + "path": "clippy_lints/src/redundant_field_names.rs", + "line": 34 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for fields in struct literals where shorthands could be used.\n\n **Why is this bad?** If the field and variable names are the same,\n the field name is redundant.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let bar: u8 = 123;\n\n struct Foo {\n bar: u8,\n }\n\n let foo = Foo { bar: bar };\n ```\n the last line can be simplified to\n ```ignore\n let foo = Foo { bar };\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "redundant_pub_crate", + "id_span": { + "path": "clippy_lints/src/redundant_pub_crate.rs", + "line": 30 + }, + "group": "clippy::nursery", + "docs": " **What it does:** Checks for items declared `pub(crate)` that are not crate visible because they are inside a private module.\n\n **Why is this bad?** Writing `pub(crate)` is misleading when it's redundant due to the parent\n module's visibility.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n mod internal {\n pub(crate) fn internal_fn() { }\n }\n ```\n This function is not visible outside the module and it can be declared with `pub` or\n private visibility\n ```rust\n mod internal {\n pub fn internal_fn() { }\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "redundant_slicing", + "id_span": { + "path": "clippy_lints/src/redundant_slicing.rs", + "line": 33 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for redundant slicing expressions which use the full range, and do not change the type.\n\n **Why is this bad?** It unnecessarily adds complexity to the expression.\n\n **Known problems:** If the type being sliced has an implementation of `Index`\n that actually changes anything then it can't be removed. However, this would be surprising\n to people reading the code and should have a note with it.\n\n **Example:**\n\n ```ignore\n fn get_slice(x: &[u32]) -> &[u32] {\n &x[..]\n }\n ```\n Use instead:\n ```ignore\n fn get_slice(x: &[u32]) -> &[u32] {\n x\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "redundant_static_lifetimes", + "id_span": { + "path": "clippy_lints/src/redundant_static_lifetimes.rs", + "line": 30 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for constants and statics with an explicit `'static` lifetime.\n **Why is this bad?** Adding `'static` to every reference can create very\n complicated types.\n\n **Known problems:** None.\n\n **Example:**\n ```ignore\n const FOO: &'static [(&'static str, &'static str, fn(&Bar) -> bool)] =\n &[...]\n static FOO: &'static [(&'static str, &'static str, fn(&Bar) -> bool)] =\n &[...]\n ```\n This code can be rewritten as\n ```ignore\n const FOO: &[(&str, &str, fn(&Bar) -> bool)] = &[...]\n static FOO: &[(&str, &str, fn(&Bar) -> bool)] = &[...]\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "ref_option_ref", + "id_span": { + "path": "clippy_lints/src/ref_option_ref.rs", + "line": 28 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for usage of `&Option<&T>`.\n **Why is this bad?** Since `&` is Copy, it's useless to have a\n reference on `Option<&T>`.\n\n **Known problems:** It may be irrelevant to use this lint on\n public API code as it will make a breaking change to apply it.\n\n **Example:**\n\n ```rust,ignore\n let x: &Option<&u32> = &Some(&0u32);\n ```\n Use instead:\n ```rust,ignore\n let x: Option<&u32> = Some(&0u32);\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MaybeIncorrect" + } + }, + { + "id": "deref_addrof", + "id_span": { + "path": "clippy_lints/src/reference.rs", + "line": 29 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for usage of `*&` and `*&mut` in expressions.\n **Why is this bad?** Immediately dereferencing a reference is no-op and\n makes the code less clear.\n\n **Known problems:** Multiple dereference/addrof pairs are not handled so\n the suggested fix for `x = **&&y` is `x = *&y`, which is still incorrect.\n\n **Example:**\n ```rust,ignore\n // Bad\n let a = f(*&mut b);\n let c = *&d;\n\n // Good\n let a = f(b);\n let c = d;\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "ref_in_deref", + "id_span": { + "path": "clippy_lints/src/reference.rs", + "line": 120 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for references in expressions that use auto dereference.\n\n **Why is this bad?** The reference is a no-op and is automatically\n dereferenced by the compiler and makes the code less clear.\n\n **Example:**\n ```rust\n struct Point(u32, u32);\n let point = Point(30, 20);\n let x = (&point).0;\n ```\n Use instead:\n ```rust\n # struct Point(u32, u32);\n # let point = Point(30, 20);\n let x = point.0;\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "invalid_regex", + "id_span": { + "path": "clippy_lints/src/regex.rs", + "line": 25 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks [regex](https://crates.io/crates/regex) creation (with `Regex::new`, `RegexBuilder::new`, or `RegexSet::new`) for correct\n regex syntax.\n\n **Why is this bad?** This will lead to a runtime panic.\n\n **Known problems:** None.\n\n **Example:**\n ```ignore\n Regex::new(\"|\")\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "trivial_regex", + "id_span": { + "path": "clippy_lints/src/regex.rs", + "line": 46 + }, + "group": "clippy::nursery", + "docs": " **What it does:** Checks for trivial [regex](https://crates.io/crates/regex) creation (with `Regex::new`, `RegexBuilder::new`, or `RegexSet::new`).\n\n **Why is this bad?** Matching the regex can likely be replaced by `==` or\n `str::starts_with`, `str::ends_with` or `std::contains` or other `str`\n methods.\n\n **Known problems:** If the same regex is going to be applied to multiple\n inputs, the precomputations done by `Regex` construction can give\n significantly better performance than any of the `str`-based methods.\n\n **Example:**\n ```ignore\n Regex::new(\"^foobar\")\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "repeat_once", + "id_span": { + "path": "clippy_lints/src/repeat_once.rs", + "line": 33 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for usage of `.repeat(1)` and suggest the following method for each types. - `.to_string()` for `str`\n - `.clone()` for `String`\n - `.to_vec()` for `slice`\n\n **Why is this bad?** For example, `String.repeat(1)` is equivalent to `.clone()`. If cloning the string is the intention behind this, `clone()` should be used.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n fn main() {\n let x = String::from(\"hello world\").repeat(1);\n }\n ```\n Use instead:\n ```rust\n fn main() {\n let x = String::from(\"hello world\").clone();\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "let_and_return", + "id_span": { + "path": "clippy_lints/src/returns.rs", + "line": 38 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for `let`-bindings, which are subsequently returned.\n\n **Why is this bad?** It is just extraneous code. Remove it to make your code\n more rusty.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n fn foo() -> String {\n let x = String::new();\n x\n }\n ```\n instead, use\n ```\n fn foo() -> String {\n String::new()\n }\n ```\n", + "applicability": { + "is_multi_suggestion": true, + "applicability": "MachineApplicable" + } + }, + { + "id": "needless_return", + "id_span": { + "path": "clippy_lints/src/returns.rs", + "line": 63 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for return statements at the end of a block.\n **Why is this bad?** Removing the `return` and semicolon will make the code\n more rusty.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n fn foo(x: usize) -> usize {\n return x;\n }\n ```\n simplify to\n ```rust\n fn foo(x: usize) -> usize {\n x\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "self_assignment", + "id_span": { + "path": "clippy_lints/src/self_assignment.rs", + "line": 29 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for explicit self-assignments.\n **Why is this bad?** Self-assignments are redundant and unlikely to be\n intentional.\n\n **Known problems:** If expression contains any deref coercions or\n indexing operations they are assumed not to have any side effects.\n\n **Example:**\n\n ```rust\n struct Event {\n id: usize,\n x: i32,\n y: i32,\n }\n\n fn copy_position(a: &mut Event, b: &Event) {\n a.x = b.x;\n a.y = a.y;\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "semicolon_if_nothing_returned", + "id_span": { + "path": "clippy_lints/src/semicolon_if_nothing_returned.rs", + "line": 30 + }, + "group": "clippy::restriction", + "docs": " **What it does:** Looks for blocks of expressions and fires if the last expression returns `()` but is not followed by a semicolon.\n\n **Why is this bad?** The semicolon might be optional but when\n extending the block with new code, it doesn't require a change in previous last line.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n fn main() {\n println!(\"Hello world\")\n }\n ```\n Use instead:\n ```rust\n fn main() {\n println!(\"Hello world\");\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MaybeIncorrect" + } + }, + { + "id": "serde_api_misuse", + "id_span": { + "path": "clippy_lints/src/serde_api.rs", + "line": 16 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for mis-uses of the serde API.\n **Why is this bad?** Serde is very finnicky about how its API should be\n used, but the type system can't be used to enforce it (yet?).\n\n **Known problems:** None.\n\n **Example:** Implementing `Visitor::visit_string` but not\n `Visitor::visit_str`.\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "shadow_same", + "id_span": { + "path": "clippy_lints/src/shadow.rs", + "line": 34 + }, + "group": "clippy::restriction", + "docs": " **What it does:** Checks for bindings that shadow other bindings already in scope, while just changing reference level or mutability.\n\n **Why is this bad?** Not much, in fact it's a very common pattern in Rust\n code. Still, some may opt to avoid it in their code base, they can set this\n lint to `Warn`.\n\n **Known problems:** This lint, as the other shadowing related lints,\n currently only catches very simple patterns.\n\n **Example:**\n ```rust\n # let x = 1;\n // Bad\n let x = &x;\n\n // Good\n let y = &x; // use different variable name\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "shadow_reuse", + "id_span": { + "path": "clippy_lints/src/shadow.rs", + "line": 61 + }, + "group": "clippy::restriction", + "docs": " **What it does:** Checks for bindings that shadow other bindings already in scope, while reusing the original value.\n\n **Why is this bad?** Not too much, in fact it's a common pattern in Rust\n code. Still, some argue that name shadowing like this hurts readability,\n because a value may be bound to different things depending on position in\n the code.\n\n **Known problems:** This lint, as the other shadowing related lints,\n currently only catches very simple patterns.\n\n **Example:**\n ```rust\n let x = 2;\n let x = x + 1;\n ```\n use different variable name:\n ```rust\n let x = 2;\n let y = x + 1;\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "shadow_unrelated", + "id_span": { + "path": "clippy_lints/src/shadow.rs", + "line": 93 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for bindings that shadow other bindings already in scope, either without a initialization or with one that does not even use\n the original value.\n\n **Why is this bad?** Name shadowing can hurt readability, especially in\n large code bases, because it is easy to lose track of the active binding at\n any place in the code. This can be alleviated by either giving more specific\n names to bindings or introducing more scopes to contain the bindings.\n\n **Known problems:** This lint, as the other shadowing related lints,\n currently only catches very simple patterns. Note that\n `allow`/`warn`/`deny`/`forbid` attributes only work on the function level\n for this lint.\n\n **Example:**\n ```rust\n # let y = 1;\n # let z = 2;\n let x = y;\n\n // Bad\n let x = z; // shadows the earlier binding\n\n // Good\n let w = z; // use different variable name\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "single_component_path_imports", + "id_span": { + "path": "clippy_lints/src/single_component_path_imports.rs", + "line": 32 + }, + "group": "clippy::style", + "docs": " **What it does:** Checking for imports with single component use path.\n **Why is this bad?** Import with single component use path such as `use cratename;`\n is not necessary, and thus should be removed.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust,ignore\n use regex;\n\n fn main() {\n regex::Regex::new(r\"^\\d{4}-\\d{2}-\\d{2}$\").unwrap();\n }\n ```\n Better as\n ```rust,ignore\n fn main() {\n regex::Regex::new(r\"^\\d{4}-\\d{2}-\\d{2}$\").unwrap();\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "size_of_in_element_count", + "id_span": { + "path": "clippy_lints/src/size_of_in_element_count.rs", + "line": 31 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Detects expressions where `size_of::` or `size_of_val::` is used as a\n count of elements of type `T`\n\n **Why is this bad?** These functions expect a count\n of `T` and not a number of bytes\n\n **Known problems:** None.\n\n **Example:**\n ```rust,no_run\n # use std::ptr::copy_nonoverlapping;\n # use std::mem::size_of;\n const SIZE: usize = 128;\n let x = [2u8; SIZE];\n let mut y = [2u8; SIZE];\n unsafe { copy_nonoverlapping(x.as_ptr(), y.as_mut_ptr(), size_of::() * SIZE) };\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "slow_vector_initialization", + "id_span": { + "path": "clippy_lints/src/slow_vector_initialization.rs", + "line": 37 + }, + "group": "clippy::perf", + "docs": " **What it does:** Checks slow zero-filled vector initialization\n **Why is this bad?** These structures are non-idiomatic and less efficient than simply using\n `vec![0; len]`.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # use core::iter::repeat;\n # let len = 4;\n\n // Bad\n let mut vec1 = Vec::with_capacity(len);\n vec1.resize(len, 0);\n\n let mut vec2 = Vec::with_capacity(len);\n vec2.extend(repeat(0).take(len));\n\n // Good\n let mut vec1 = vec![0; len];\n let mut vec2 = vec![0; len];\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "Unspecified" + } + }, + { + "id": "stable_sort_primitive", + "id_span": { + "path": "clippy_lints/src/stable_sort_primitive.rs", + "line": 36 + }, + "group": "clippy::perf", + "docs": " **What it does:** When sorting primitive values (integers, bools, chars, as well\n as arrays, slices, and tuples of such items), it is better to\n use an unstable sort than a stable sort.\n\n **Why is this bad?**\n Using a stable sort consumes more memory and cpu cycles. Because\n values which compare equal are identical, preserving their\n relative order (the guarantee that a stable sort provides) means\n nothing, while the extra costs still apply.\n\n **Known problems:**\n None\n\n **Example:**\n\n ```rust\n let mut vec = vec![2, 1, 3];\n vec.sort();\n ```\n Use instead:\n ```rust\n let mut vec = vec![2, 1, 3];\n vec.sort_unstable();\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "string_add_assign", + "id_span": { + "path": "clippy_lints/src/strings.rs", + "line": 37 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for string appends of the form `x = x + y` (without `let`!).\n\n **Why is this bad?** It's not really bad, but some people think that the\n `.push_str(_)` method is more readable.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n let mut x = \"Hello\".to_owned();\n x = x + \", World\";\n\n // More readable\n x += \", World\";\n x.push_str(\", World\");\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "string_add", + "id_span": { + "path": "clippy_lints/src/strings.rs", + "line": 65 + }, + "group": "clippy::restriction", + "docs": " **What it does:** Checks for all instances of `x + _` where `x` is of type `String`, but only if [`string_add_assign`](#string_add_assign) does *not*\n match.\n\n **Why is this bad?** It's not bad in and of itself. However, this particular\n `Add` implementation is asymmetric (the other operand need not be `String`,\n but `x` does), while addition as mathematically defined is symmetric, also\n the `String::push_str(_)` function is a perfectly good replacement.\n Therefore, some dislike it and wish not to have it in their code.\n\n That said, other people think that string addition, having a long tradition\n in other languages is actually fine, which is why we decided to make this\n particular lint `allow` by default.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n let x = \"Hello\".to_owned();\n x + \", World\";\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "string_lit_as_bytes", + "id_span": { + "path": "clippy_lints/src/strings.rs", + "line": 107 + }, + "group": "clippy::nursery", + "docs": " **What it does:** Checks for the `as_bytes` method called on string literals that contain only ASCII characters.\n\n **Why is this bad?** Byte string literals (e.g., `b\"foo\"`) can be used\n instead. They are shorter but less discoverable than `as_bytes()`.\n\n **Known Problems:**\n `\"str\".as_bytes()` and the suggested replacement of `b\"str\"` are not\n equivalent because they have different types. The former is `&[u8]`\n while the latter is `&[u8; 3]`. That means in general they will have a\n different set of methods and different trait implementations.\n\n ```compile_fail\n fn f(v: Vec) {}\n\n f(\"...\".as_bytes().to_owned()); // works\n f(b\"...\".to_owned()); // does not work, because arg is [u8; 3] not Vec\n\n fn g(r: impl std::io::Read) {}\n\n g(\"...\".as_bytes()); // works\n g(b\"...\"); // does not work\n ```\n\n The actual equivalent of `\"str\".as_bytes()` with the same type is not\n `b\"str\"` but `&b\"str\"[..]`, which is a great deal of punctuation and not\n more readable than a function call.\n\n **Example:**\n ```rust\n // Bad\n let bs = \"a byte string\".as_bytes();\n\n // Good\n let bs = b\"a byte string\";\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "string_from_utf8_as_bytes", + "id_span": { + "path": "clippy_lints/src/strings.rs", + "line": 196 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Check if the string is transformed to byte array and casted back to string.\n **Why is this bad?** It's unnecessary, the string can be used directly.\n\n **Known problems:** None\n\n **Example:**\n ```rust\n let _ = std::str::from_utf8(&\"Hello World!\".as_bytes()[6..11]).unwrap();\n ```\n could be written as\n ```rust\n let _ = &\"Hello World!\"[6..11];\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "str_to_string", + "id_span": { + "path": "clippy_lints/src/strings.rs", + "line": 313 + }, + "group": "clippy::restriction", + "docs": " **What it does:** This lint checks for `.to_string()` method calls on values of type `&str`.\n **Why is this bad?** The `to_string` method is also used on other types to convert them to a string.\n When called on a `&str` it turns the `&str` into the owned variant `String`, which can be better\n expressed with `.to_owned()`.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n // example code where clippy issues a warning\n let _ = \"str\".to_string();\n ```\n Use instead:\n ```rust\n // example code which does not raise clippy warning\n let _ = \"str\".to_owned();\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "string_to_string", + "id_span": { + "path": "clippy_lints/src/strings.rs", + "line": 362 + }, + "group": "clippy::restriction", + "docs": " **What it does:** This lint checks for `.to_string()` method calls on values of type `String`.\n **Why is this bad?** The `to_string` method is also used on other types to convert them to a string.\n When called on a `String` it only clones the `String`, which can be better expressed with `.clone()`.\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n // example code where clippy issues a warning\n let msg = String::from(\"Hello World\");\n let _ = msg.to_string();\n ```\n Use instead:\n ```rust\n // example code which does not raise clippy warning\n let msg = String::from(\"Hello World\");\n let _ = msg.clone();\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "suspicious_operation_groupings", + "id_span": { + "path": "clippy_lints/src/suspicious_operation_groupings.rs", + "line": 60 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for unlikely usages of binary operators that are almost\n certainly typos and/or copy/paste errors, given the other usages\n of binary operators nearby.\n **Why is this bad?**\n They are probably bugs and if they aren't then they look like bugs\n and you should add a comment explaining why you are doing such an\n odd set of operations.\n **Known problems:**\n There may be some false positives if you are trying to do something\n unusual that happens to look like a typo.\n\n **Example:**\n\n ```rust\n struct Vec3 {\n x: f64,\n y: f64,\n z: f64,\n }\n\n impl Eq for Vec3 {}\n\n impl PartialEq for Vec3 {\n fn eq(&self, other: &Self) -> bool {\n // This should trigger the lint because `self.x` is compared to `other.y`\n self.x == other.y && self.y == other.y && self.z == other.z\n }\n }\n ```\n Use instead:\n ```rust\n # struct Vec3 {\n # x: f64,\n # y: f64,\n # z: f64,\n # }\n // same as above except:\n impl PartialEq for Vec3 {\n fn eq(&self, other: &Self) -> bool {\n // Note we now compare other.x to self.x\n self.x == other.x && self.y == other.y && self.z == other.z\n }\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "suspicious_arithmetic_impl", + "id_span": { + "path": "clippy_lints/src/suspicious_trait_impl.rs", + "line": 27 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Lints for suspicious operations in impls of arithmetic operators, e.g. subtracting elements in an Add impl.\n\n **Why this is bad?** This is probably a typo or copy-and-paste error and not intended.\n\n **Known problems:** None.\n\n **Example:**\n ```ignore\n impl Add for Foo {\n type Output = Foo;\n\n fn add(self, other: Foo) -> Foo {\n Foo(self.0 - other.0)\n }\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "suspicious_op_assign_impl", + "id_span": { + "path": "clippy_lints/src/suspicious_trait_impl.rs", + "line": 48 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Lints for suspicious operations in impls of OpAssign, e.g. subtracting elements in an AddAssign impl.\n\n **Why this is bad?** This is probably a typo or copy-and-paste error and not intended.\n\n **Known problems:** None.\n\n **Example:**\n ```ignore\n impl AddAssign for Foo {\n fn add_assign(&mut self, other: Foo) {\n *self = *self - other;\n }\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "manual_swap", + "id_span": { + "path": "clippy_lints/src/swap.rs", + "line": 36 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for manual swapping.\n **Why is this bad?** The `std::mem::swap` function exposes the intent better\n without deinitializing or copying either variable.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let mut a = 42;\n let mut b = 1337;\n\n let t = b;\n b = a;\n a = t;\n ```\n Use std::mem::swap():\n ```rust\n let mut a = 1;\n let mut b = 2;\n std::mem::swap(&mut a, &mut b);\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "almost_swapped", + "id_span": { + "path": "clippy_lints/src/swap.rs", + "line": 61 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for `foo = bar; bar = foo` sequences.\n **Why is this bad?** This looks like a failed attempt to swap.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let mut a = 1;\n # let mut b = 2;\n a = b;\n b = a;\n ```\n If swapping is intended, use `swap()` instead:\n ```rust\n # let mut a = 1;\n # let mut b = 2;\n std::mem::swap(&mut a, &mut b);\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MaybeIncorrect" + } + }, + { + "id": "tabs_in_doc_comments", + "id_span": { + "path": "clippy_lints/src/tabs_in_doc_comments.rs", + "line": 54 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks doc comments for usage of tab characters.\n **Why is this bad?** The rust style-guide promotes spaces instead of tabs for indentation.\n To keep a consistent view on the source, also doc comments should not have tabs.\n Also, explaining ascii-diagrams containing tabs can get displayed incorrectly when the\n display settings of the author and reader differ.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n ///\n /// Struct to hold two strings:\n /// \t- first\t\tone\n /// \t- second\tone\n pub struct DoubleString {\n ///\n /// \t- First String:\n /// \t\t- needs to be inside here\n first_string: String,\n ///\n /// \t- Second String:\n /// \t\t- needs to be inside here\n second_string: String,\n}\n ```\n\n Will be converted to:\n ```rust\n ///\n /// Struct to hold two strings:\n /// - first one\n /// - second one\n pub struct DoubleString {\n ///\n /// - First String:\n /// - needs to be inside here\n first_string: String,\n ///\n /// - Second String:\n /// - needs to be inside here\n second_string: String,\n}\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MaybeIncorrect" + } + }, + { + "id": "temporary_assignment", + "id_span": { + "path": "clippy_lints/src/temporary_assignment.rs", + "line": 19 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for construction of a structure or tuple just to assign a value in it.\n\n **Why is this bad?** Readability. If the structure is only created to be\n updated, why not write the structure you want in the first place?\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n (0, 0).0 = 1\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "to_digit_is_some", + "id_span": { + "path": "clippy_lints/src/to_digit_is_some.rs", + "line": 27 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for `.to_digit(..).is_some()` on `char`s.\n **Why is this bad?** This is a convoluted way of checking if a `char` is a digit. It's\n more straight forward to use the dedicated `is_digit` method.\n\n **Example:**\n ```rust\n # let c = 'c';\n # let radix = 10;\n let is_digit = c.to_digit(radix).is_some();\n ```\n can be written as:\n ```\n # let c = 'c';\n # let radix = 10;\n let is_digit = c.is_digit(radix);\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "to_string_in_display", + "id_span": { + "path": "clippy_lints/src/to_string_in_display.rs", + "line": 40 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for uses of `to_string()` in `Display` traits.\n **Why is this bad?** Usually `to_string` is implemented indirectly\n via `Display`. Hence using it while implementing `Display` would\n lead to infinite recursion.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n use std::fmt;\n\n struct Structure(i32);\n impl fmt::Display for Structure {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n write!(f, \"{}\", self.to_string())\n }\n }\n\n ```\n Use instead:\n ```rust\n use std::fmt;\n\n struct Structure(i32);\n impl fmt::Display for Structure {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n write!(f, \"{}\", self.0)\n }\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "type_repetition_in_bounds", + "id_span": { + "path": "clippy_lints/src/trait_bounds.rs", + "line": 28 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** This lint warns about unnecessary type repetitions in trait bounds\n **Why is this bad?** Repeating the type for every bound makes the code\n less readable than combining the bounds\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n pub fn foo(t: T) where T: Copy, T: Clone {}\n ```\n\n Could be written as:\n\n ```rust\n pub fn foo(t: T) where T: Copy + Clone {}\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "trait_duplication_in_bounds", + "id_span": { + "path": "clippy_lints/src/trait_bounds.rs", + "line": 57 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for cases where generics are being used and multiple syntax specifications for trait bounds are used simultaneously.\n\n **Why is this bad?** Duplicate bounds makes the code\n less readable than specifing them only once.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n fn func(arg: T) where T: Clone + Default {}\n ```\n\n Could be written as:\n\n ```rust\n fn func(arg: T) {}\n ```\n or\n\n ```rust\n fn func(arg: T) where T: Clone + Default {}\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "wrong_transmute", + "id_span": { + "path": "clippy_lints/src/transmute.rs", + "line": 29 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for transmutes that can't ever be correct on any architecture.\n\n **Why is this bad?** It's basically guaranteed to be undefined behaviour.\n\n **Known problems:** When accessing C, users might want to store pointer\n sized objects in `extradata` arguments to save an allocation.\n\n **Example:**\n ```ignore\n let ptr: *const T = core::intrinsics::transmute('x')\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "useless_transmute", + "id_span": { + "path": "clippy_lints/src/transmute.rs", + "line": 48 + }, + "group": "clippy::nursery", + "docs": " **What it does:** Checks for transmutes to the original type of the object and transmutes that could be a cast.\n\n **Why is this bad?** Readability. The code tricks people into thinking that\n something complex is going on.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n core::intrinsics::transmute(t); // where the result type is the same as `t`'s\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "Unspecified" + } + }, + { + "id": "transmutes_expressible_as_ptr_casts", + "id_span": { + "path": "clippy_lints/src/transmute.rs", + "line": 73 + }, + "group": "clippy::complexity", + "docs": " **What it does:**Checks for transmutes that could be a pointer cast.\n **Why is this bad?** Readability. The code tricks people into thinking that\n something complex is going on.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n # let p: *const [i32] = &[];\n unsafe { std::mem::transmute::<*const [i32], *const [u16]>(p) };\n ```\n Use instead:\n ```rust\n # let p: *const [i32] = &[];\n p as *const [u16];\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "crosspointer_transmute", + "id_span": { + "path": "clippy_lints/src/transmute.rs", + "line": 91 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for transmutes between a type `T` and `*T`.\n **Why is this bad?** It's easy to mistakenly transmute between a type and a\n pointer to that type.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n core::intrinsics::transmute(t) // where the result type is the same as\n // `*t` or `&t`'s\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "transmute_ptr_to_ref", + "id_span": { + "path": "clippy_lints/src/transmute.rs", + "line": 116 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for transmutes from a pointer to a reference.\n **Why is this bad?** This can always be rewritten with `&` and `*`.\n\n **Known problems:**\n - `mem::transmute` in statics and constants is stable from Rust 1.46.0,\n while dereferencing raw pointer is not stable yet.\n If you need to do this in those places,\n you would have to use `transmute` instead.\n\n **Example:**\n ```rust,ignore\n unsafe {\n let _: &T = std::mem::transmute(p); // where p: *const T\n }\n\n // can be written:\n let _: &T = &*p;\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "Unspecified" + } + }, + { + "id": "transmute_int_to_char", + "id_span": { + "path": "clippy_lints/src/transmute.rs", + "line": 147 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for transmutes from an integer to a `char`.\n **Why is this bad?** Not every integer is a Unicode scalar value.\n\n **Known problems:**\n - [`from_u32`] which this lint suggests using is slower than `transmute`\n as it needs to validate the input.\n If you are certain that the input is always a valid Unicode scalar value,\n use [`from_u32_unchecked`] which is as fast as `transmute`\n but has a semantically meaningful name.\n - You might want to handle `None` returned from [`from_u32`] instead of calling `unwrap`.\n\n [`from_u32`]: https://doc.rust-lang.org/std/char/fn.from_u32.html\n [`from_u32_unchecked`]: https://doc.rust-lang.org/std/char/fn.from_u32_unchecked.html\n\n **Example:**\n ```rust\n let x = 1_u32;\n unsafe {\n let _: char = std::mem::transmute(x); // where x: u32\n }\n\n // should be:\n let _ = std::char::from_u32(x).unwrap();\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "Unspecified" + } + }, + { + "id": "transmute_bytes_to_str", + "id_span": { + "path": "clippy_lints/src/transmute.rs", + "line": 178 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for transmutes from a `&[u8]` to a `&str`.\n **Why is this bad?** Not every byte slice is a valid UTF-8 string.\n\n **Known problems:**\n - [`from_utf8`] which this lint suggests using is slower than `transmute`\n as it needs to validate the input.\n If you are certain that the input is always a valid UTF-8,\n use [`from_utf8_unchecked`] which is as fast as `transmute`\n but has a semantically meaningful name.\n - You might want to handle errors returned from [`from_utf8`] instead of calling `unwrap`.\n\n [`from_utf8`]: https://doc.rust-lang.org/std/str/fn.from_utf8.html\n [`from_utf8_unchecked`]: https://doc.rust-lang.org/std/str/fn.from_utf8_unchecked.html\n\n **Example:**\n ```rust\n let b: &[u8] = &[1_u8, 2_u8];\n unsafe {\n let _: &str = std::mem::transmute(b); // where b: &[u8]\n }\n\n // should be:\n let _ = std::str::from_utf8(b).unwrap();\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "Unspecified" + } + }, + { + "id": "transmute_int_to_bool", + "id_span": { + "path": "clippy_lints/src/transmute.rs", + "line": 200 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for transmutes from an integer to a `bool`.\n **Why is this bad?** This might result in an invalid in-memory representation of a `bool`.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let x = 1_u8;\n unsafe {\n let _: bool = std::mem::transmute(x); // where x: u8\n }\n\n // should be:\n let _: bool = x != 0;\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "Unspecified" + } + }, + { + "id": "transmute_int_to_float", + "id_span": { + "path": "clippy_lints/src/transmute.rs", + "line": 222 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for transmutes from an integer to a float.\n **Why is this bad?** Transmutes are dangerous and error-prone, whereas `from_bits` is intuitive\n and safe.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n unsafe {\n let _: f32 = std::mem::transmute(1_u32); // where x: u32\n }\n\n // should be:\n let _: f32 = f32::from_bits(1_u32);\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "Unspecified" + } + }, + { + "id": "transmute_float_to_int", + "id_span": { + "path": "clippy_lints/src/transmute.rs", + "line": 244 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for transmutes from a float to an integer.\n **Why is this bad?** Transmutes are dangerous and error-prone, whereas `to_bits` is intuitive\n and safe.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n unsafe {\n let _: u32 = std::mem::transmute(1f32);\n }\n\n // should be:\n let _: u32 = 1f32.to_bits();\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "Unspecified" + } + }, + { + "id": "transmute_ptr_to_ptr", + "id_span": { + "path": "clippy_lints/src/transmute.rs", + "line": 271 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for transmutes from a pointer to a pointer, or from a reference to a reference.\n\n **Why is this bad?** Transmutes are dangerous, and these can instead be\n written as casts.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let ptr = &1u32 as *const u32;\n unsafe {\n // pointer-to-pointer transmute\n let _: *const f32 = std::mem::transmute(ptr);\n // ref-ref transmute\n let _: &f32 = std::mem::transmute(&1u32);\n }\n // These can be respectively written:\n let _ = ptr as *const f32;\n let _ = unsafe{ &*(&1u32 as *const u32 as *const f32) };\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "Unspecified" + } + }, + { + "id": "unsound_collection_transmute", + "id_span": { + "path": "clippy_lints/src/transmute.rs", + "line": 299 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for transmutes between collections whose types have different ABI, size or alignment.\n\n **Why is this bad?** This is undefined behavior.\n\n **Known problems:** Currently, we cannot know whether a type is a\n collection, so we just lint the ones that come with `std`.\n\n **Example:**\n ```rust\n // different size, therefore likely out-of-bounds memory access\n // You absolutely do not want this in your code!\n unsafe {\n std::mem::transmute::<_, Vec>(vec![2_u16])\n };\n ```\n\n You must always iterate, map and collect the values:\n\n ```rust\n vec![2_u16].into_iter().map(u32::from).collect::>();\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "transmuting_null", + "id_span": { + "path": "clippy_lints/src/transmuting_null.rs", + "line": 23 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for transmute calls which would receive a null pointer.\n **Why is this bad?** Transmuting a null pointer is undefined behavior.\n\n **Known problems:** Not all cases can be detected at the moment of this writing.\n For example, variables which hold a null pointer and are then fed to a `transmute`\n call, aren't detectable yet.\n\n **Example:**\n ```rust\n let null_ref: &u64 = unsafe { std::mem::transmute(0 as *const u64) };\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "try_err", + "id_span": { + "path": "clippy_lints/src/try_err.rs", + "line": 43 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for usages of `Err(x)?`.\n **Why is this bad?** The `?` operator is designed to allow calls that\n can fail to be easily chained. For example, `foo()?.bar()` or\n `foo(bar()?)`. Because `Err(x)?` can't be used that way (it will\n always return), it is more clear to write `return Err(x)`.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n fn foo(fail: bool) -> Result {\n if fail {\n Err(\"failed\")?;\n }\n Ok(0)\n }\n ```\n Could be written:\n\n ```rust\n fn foo(fail: bool) -> Result {\n if fail {\n return Err(\"failed\".into());\n }\n Ok(0)\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "box_vec", + "id_span": { + "path": "clippy_lints/src/types.rs", + "line": 66 + }, + "group": "clippy::perf", + "docs": " **What it does:** Checks for use of `Box>` anywhere in the code. Check the [Box documentation](https://doc.rust-lang.org/std/boxed/index.html) for more information.\n\n **Why is this bad?** `Vec` already keeps its contents in a separate area on\n the heap. So if you `Box` it, you just add another level of indirection\n without any benefit whatsoever.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n struct X {\n values: Box>,\n }\n ```\n\n Better:\n\n ```rust,ignore\n struct X {\n values: Vec,\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "vec_box", + "id_span": { + "path": "clippy_lints/src/types.rs", + "line": 95 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for use of `Vec>` where T: Sized anywhere in the code. Check the [Box documentation](https://doc.rust-lang.org/std/boxed/index.html) for more information.\n\n **Why is this bad?** `Vec` already keeps its contents in a separate area on\n the heap. So if you `Box` its contents, you just add another level of indirection.\n\n **Known problems:** Vec> makes sense if T is a large type (see [#3530](https://github.com/rust-lang/rust-clippy/issues/3530),\n 1st comment).\n\n **Example:**\n ```rust\n struct X {\n values: Vec>,\n }\n ```\n\n Better:\n\n ```rust\n struct X {\n values: Vec,\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "option_option", + "id_span": { + "path": "clippy_lints/src/types.rs", + "line": 133 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for use of `Option>` in function signatures and type definitions\n\n **Why is this bad?** `Option<_>` represents an optional value. `Option>`\n represents an optional optional value which is logically the same thing as an optional\n value but has an unneeded extra level of wrapping.\n\n If you have a case where `Some(Some(_))`, `Some(None)` and `None` are distinct cases,\n consider a custom `enum` instead, with clear names for each case.\n\n **Known problems:** None.\n\n **Example**\n ```rust\n fn get_data() -> Option> {\n None\n }\n ```\n\n Better:\n\n ```rust\n pub enum Contents {\n Data(Vec), // Was Some(Some(Vec))\n NotYetFetched, // Was Some(None)\n None, // Was None\n }\n\n fn get_data() -> Contents {\n Contents::None\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "linkedlist", + "id_span": { + "path": "clippy_lints/src/types.rs", + "line": 169 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for usage of any `LinkedList`, suggesting to use a `Vec` or a `VecDeque` (formerly called `RingBuf`).\n\n **Why is this bad?** Gankro says:\n\n > The TL;DR of `LinkedList` is that it's built on a massive amount of\n pointers and indirection.\n > It wastes memory, it has terrible cache locality, and is all-around slow.\n `RingBuf`, while\n > \"only\" amortized for push/pop, should be faster in the general case for\n almost every possible\n > workload, and isn't even amortized at all if you can predict the capacity\n you need.\n >\n > `LinkedList`s are only really good if you're doing a lot of merging or\n splitting of lists.\n > This is because they can just mangle some pointers instead of actually\n copying the data. Even\n > if you're doing a lot of insertion in the middle of the list, `RingBuf`\n can still be better\n > because of how expensive it is to seek to the middle of a `LinkedList`.\n\n **Known problems:** False positives – the instances where using a\n `LinkedList` makes sense are few and far between, but they can still happen.\n\n **Example:**\n ```rust\n # use std::collections::LinkedList;\n let x: LinkedList = LinkedList::new();\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "borrowed_box", + "id_span": { + "path": "clippy_lints/src/types.rs", + "line": 193 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for use of `&Box` anywhere in the code. Check the [Box documentation](https://doc.rust-lang.org/std/boxed/index.html) for more information.\n\n **Why is this bad?** Any `&Box` can also be a `&T`, which is more\n general.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n fn foo(bar: &Box) { ... }\n ```\n\n Better:\n\n ```rust,ignore\n fn foo(bar: &T) { ... }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "Unspecified" + } + }, + { + "id": "redundant_allocation", + "id_span": { + "path": "clippy_lints/src/types.rs", + "line": 217 + }, + "group": "clippy::perf", + "docs": " **What it does:** Checks for use of redundant allocations anywhere in the code.\n **Why is this bad?** Expressions such as `Rc<&T>`, `Rc>`, `Rc>`, `Box<&T>`\n add an unnecessary level of indirection.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # use std::rc::Rc;\n fn foo(bar: Rc<&usize>) {}\n ```\n\n Better:\n\n ```rust\n fn foo(bar: &usize) {}\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "rc_buffer", + "id_span": { + "path": "clippy_lints/src/types.rs", + "line": 248 + }, + "group": "clippy::restriction", + "docs": " **What it does:** Checks for `Rc` and `Arc` when `T` is a mutable buffer type such as `String` or `Vec`.\n **Why is this bad?** Expressions such as `Rc` usually have no advantage over `Rc`, since\n it is larger and involves an extra level of indirection, and doesn't implement `Borrow`.\n\n While mutating a buffer type would still be possible with `Rc::get_mut()`, it only\n works if there are no additional references yet, which usually defeats the purpose of\n enclosing it in a shared ownership type. Instead, additionally wrapping the inner\n type with an interior mutable container (such as `RefCell` or `Mutex`) would normally\n be used.\n\n **Known problems:** This pattern can be desirable to avoid the overhead of a `RefCell` or `Mutex` for\n cases where mutation only happens before there are any additional references.\n\n **Example:**\n ```rust,ignore\n # use std::rc::Rc;\n fn foo(interned: Rc) { ... }\n ```\n\n Better:\n\n ```rust,ignore\n fn foo(interned: Rc) { ... }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "let_unit_value", + "id_span": { + "path": "clippy_lints/src/types.rs", + "line": 768 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for binding a unit value.\n **Why is this bad?** A unit value cannot usefully be used anywhere. So\n binding one is kind of pointless.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let x = {\n 1;\n };\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "unit_cmp", + "id_span": { + "path": "clippy_lints/src/types.rs", + "line": 849 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for comparisons to unit. This includes all binary comparisons (like `==` and `<`) and asserts.\n\n **Why is this bad?** Unit is always equal to itself, and thus is just a\n clumsily written constant. Mostly this happens when someone accidentally\n adds semicolons at the end of the operands.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # fn foo() {};\n # fn bar() {};\n # fn baz() {};\n if {\n foo();\n } == {\n bar();\n } {\n baz();\n }\n ```\n is equal to\n ```rust\n # fn foo() {};\n # fn bar() {};\n # fn baz() {};\n {\n foo();\n bar();\n baz();\n }\n ```\n\n For asserts:\n ```rust\n # fn foo() {};\n # fn bar() {};\n assert_eq!({ foo(); }, { bar(); });\n ```\n will always succeed\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "unit_arg", + "id_span": { + "path": "clippy_lints/src/types.rs", + "line": 922 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for passing a unit value as an argument to a function without using a unit literal (`()`).\n\n **Why is this bad?** This is likely the result of an accidental semicolon.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n foo({\n let a = bar();\n baz(a);\n })\n ```\n", + "applicability": { + "is_multi_suggestion": true, + "applicability": "MachineApplicable" + } + }, + { + "id": "cast_precision_loss", + "id_span": { + "path": "clippy_lints/src/types.rs", + "line": 1158 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for casts from any numerical to a float type where the receiving type cannot store all values from the original type without\n rounding errors. This possible rounding is to be expected, so this lint is\n `Allow` by default.\n\n Basically, this warns on casting any integer with 32 or more bits to `f32`\n or any 64-bit integer to `f64`.\n\n **Why is this bad?** It's not bad at all. But in some applications it can be\n helpful to know where precision loss can take place. This lint can help find\n those places in the code.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let x = u64::MAX;\n x as f64;\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "cast_sign_loss", + "id_span": { + "path": "clippy_lints/src/types.rs", + "line": 1179 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for casts from a signed to an unsigned numerical type. In this case, negative values wrap around to large positive values,\n which can be quite surprising in practice. However, as the cast works as\n defined, this lint is `Allow` by default.\n\n **Why is this bad?** Possibly surprising results. You can activate this lint\n as a one-time check to see where numerical wrapping can arise.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let y: i8 = -1;\n y as u128; // will return 18446744073709551615\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "cast_possible_truncation", + "id_span": { + "path": "clippy_lints/src/types.rs", + "line": 1201 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for casts between numerical types that may truncate large values. This is expected behavior, so the cast is `Allow` by\n default.\n\n **Why is this bad?** In some problem domains, it is good practice to avoid\n truncation. This lint can be activated to help assess where additional\n checks could be beneficial.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n fn as_u8(x: u64) -> u8 {\n x as u8\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "cast_possible_wrap", + "id_span": { + "path": "clippy_lints/src/types.rs", + "line": 1224 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for casts from an unsigned type to a signed type of the same size. Performing such a cast is a 'no-op' for the compiler,\n i.e., nothing is changed at the bit level, and the binary representation of\n the value is reinterpreted. This can cause wrapping if the value is too big\n for the target signed type. However, the cast works as defined, so this lint\n is `Allow` by default.\n\n **Why is this bad?** While such a cast is not bad in itself, the results can\n be surprising when this is not the intended behavior, as demonstrated by the\n example below.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n u32::MAX as i32; // will yield a value of `-1`\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "cast_lossless", + "id_span": { + "path": "clippy_lints/src/types.rs", + "line": 1256 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for casts between numerical types that may be replaced by safe conversion functions.\n\n **Why is this bad?** Rust's `as` keyword will perform many kinds of\n conversions, including silently lossy conversions. Conversion functions such\n as `i32::from` will only perform lossless conversions. Using the conversion\n functions prevents conversions from turning into silent lossy conversions if\n the types of the input expressions ever change, and make it easier for\n people reading the code to know that the conversion is lossless.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n fn as_u64(x: u8) -> u64 {\n x as u64\n }\n ```\n\n Using `::from` would look like this:\n\n ```rust\n fn as_u64(x: u8) -> u64 {\n u64::from(x)\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "unnecessary_cast", + "id_span": { + "path": "clippy_lints/src/types.rs", + "line": 1281 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for casts to the same type, casts of int literals to integer types and casts of float literals to float types.\n\n **Why is this bad?** It's just unnecessary.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let _ = 2i32 as i32;\n let _ = 0.5 as f32;\n ```\n\n Better:\n\n ```rust\n let _ = 2_i32;\n let _ = 0.5_f32;\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "cast_ptr_alignment", + "id_span": { + "path": "clippy_lints/src/types.rs", + "line": 1305 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for casts, using `as` or `pointer::cast`, from a less-strictly-aligned pointer to a more-strictly-aligned pointer\n\n **Why is this bad?** Dereferencing the resulting pointer may be undefined\n behavior.\n\n **Known problems:** Using `std::ptr::read_unaligned` and `std::ptr::write_unaligned` or similar\n on the resulting pointer is fine. Is over-zealous: Casts with manual alignment checks or casts like\n u64-> u8 -> u16 can be fine. Miri is able to do a more in-depth analysis.\n\n **Example:**\n ```rust\n let _ = (&1u8 as *const u8) as *const u16;\n let _ = (&mut 1u8 as *mut u8) as *mut u16;\n\n (&1u8 as *const u8).cast::();\n (&mut 1u8 as *mut u8).cast::();\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "fn_to_numeric_cast", + "id_span": { + "path": "clippy_lints/src/types.rs", + "line": 1332 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for casts of function pointers to something other than usize\n **Why is this bad?**\n Casting a function pointer to anything other than usize/isize is not portable across\n architectures, because you end up losing bits if the target type is too small or end up with a\n bunch of extra bits that waste space and add more instructions to the final binary than\n strictly necessary for the problem\n\n Casting to isize also doesn't make sense since there are no signed addresses.\n\n **Example**\n\n ```rust\n // Bad\n fn fun() -> i32 { 1 }\n let a = fun as i64;\n\n // Good\n fn fun2() -> i32 { 1 }\n let a = fun2 as usize;\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MaybeIncorrect" + } + }, + { + "id": "fn_to_numeric_cast_with_truncation", + "id_span": { + "path": "clippy_lints/src/types.rs", + "line": 1362 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for casts of a function pointer to a numeric type not wide enough to store address.\n\n **Why is this bad?**\n Such a cast discards some bits of the function's address. If this is intended, it would be more\n clearly expressed by casting to usize first, then casting the usize to the intended type (with\n a comment) to perform the truncation.\n\n **Example**\n\n ```rust\n // Bad\n fn fn1() -> i16 {\n 1\n };\n let _ = fn1 as i32;\n\n // Better: Cast to usize first, then comment with the reason for the truncation\n fn fn2() -> i16 {\n 1\n };\n let fn_ptr = fn2 as usize;\n let fn_ptr_truncated = fn_ptr as i32;\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MaybeIncorrect" + } + }, + { + "id": "type_complexity", + "id_span": { + "path": "clippy_lints/src/types.rs", + "line": 1897 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for types used in structs, parameters and `let` declarations above a certain complexity threshold.\n\n **Why is this bad?** Too complex types make the code less readable. Consider\n using a `type` definition to simplify them.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # use std::rc::Rc;\n struct Foo {\n inner: Rc>>>,\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "char_lit_as_u8", + "id_span": { + "path": "clippy_lints/src/types.rs", + "line": 2068 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for expressions where a character literal is cast to `u8` and suggests using a byte literal instead.\n\n **Why is this bad?** In general, casting values to smaller types is\n error-prone and should be avoided where possible. In the particular case of\n converting a character literal to u8, it is easy to avoid by just using a\n byte literal instead. As an added bonus, `b'a'` is even slightly shorter\n than `'a' as u8`.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n 'x' as u8\n ```\n\n A better version, using the byte literal:\n\n ```rust,ignore\n b'x'\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "absurd_extreme_comparisons", + "id_span": { + "path": "clippy_lints/src/types.rs", + "line": 2133 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for comparisons where one side of the relation is either the minimum or maximum value for its type and warns if it involves a\n case that is always true or always false. Only integer and boolean types are\n checked.\n\n **Why is this bad?** An expression like `min <= x` may misleadingly imply\n that it is possible for `x` to be less than the minimum. Expressions like\n `max < x` are probably mistakes.\n\n **Known problems:** For `usize` the size of the current compile target will\n be assumed (e.g., 64 bits on 64 bit systems). This means code that uses such\n a comparison to detect target pointer width will trigger this lint. One can\n use `mem::sizeof` and compare its value or conditional compilation\n attributes\n like `#[cfg(target_pointer_width = \"64\")] ..` instead.\n\n **Example:**\n\n ```rust\n let vec: Vec = Vec::new();\n if vec.len() <= 0 {}\n if 100 > i32::MAX {}\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "invalid_upcast_comparisons", + "id_span": { + "path": "clippy_lints/src/types.rs", + "line": 2294 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for comparisons where the relation is always either true or false, but where one side has been upcast so that the comparison is\n necessary. Only integer types are checked.\n\n **Why is this bad?** An expression like `let x : u8 = ...; (x as u32) > 300`\n will mistakenly imply that it is possible for `x` to be outside the range of\n `u8`.\n\n **Known problems:**\n https://github.com/rust-lang/rust-clippy/issues/886\n\n **Example:**\n ```rust\n let x: u8 = 1;\n (x as u32) > 300;\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "implicit_hasher", + "id_span": { + "path": "clippy_lints/src/types.rs", + "line": 2515 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for public `impl` or `fn` missing generalization over different hashers and implicitly defaulting to the default hashing\n algorithm (`SipHash`).\n\n **Why is this bad?** `HashMap` or `HashSet` with custom hashers cannot be\n used with them.\n\n **Known problems:** Suggestions for replacing constructors can contain\n false-positives. Also applying suggestions can require modification of other\n pieces of code, possibly including external crates.\n\n **Example:**\n ```rust\n # use std::collections::HashMap;\n # use std::hash::{Hash, BuildHasher};\n # trait Serialize {};\n impl Serialize for HashMap { }\n\n pub fn foo(map: &mut HashMap) { }\n ```\n could be rewritten as\n ```rust\n # use std::collections::HashMap;\n # use std::hash::{Hash, BuildHasher};\n # trait Serialize {};\n impl Serialize for HashMap { }\n\n pub fn foo(map: &mut HashMap) { }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "cast_ref_to_mut", + "id_span": { + "path": "clippy_lints/src/types.rs", + "line": 2866 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for casts of `&T` to `&mut T` anywhere in the code.\n **Why is this bad?** It’s basically guaranteed to be undefined behaviour.\n `UnsafeCell` is the only way to obtain aliasable data that is considered\n mutable.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n fn x(r: &i32) {\n unsafe {\n *(r as *const _ as *mut _) += 1;\n }\n }\n ```\n\n Instead consider using interior mutability types.\n\n ```rust\n use std::cell::UnsafeCell;\n\n fn x(r: &UnsafeCell) {\n unsafe {\n *r.get() += 1;\n }\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "ptr_as_ptr", + "id_span": { + "path": "clippy_lints/src/types.rs", + "line": 2922 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for `as` casts between raw pointers without changing its mutability,\n namely `*const T` to `*const U` and `*mut T` to `*mut U`.\n\n **Why is this bad?**\n Though `as` casts between raw pointers is not terrible, `pointer::cast` is safer because\n it cannot accidentally change the pointer's mutability nor cast the pointer to other types like `usize`.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n let ptr: *const u32 = &42_u32;\n let mut_ptr: *mut u32 = &mut 42_u32;\n let _ = ptr as *const i32;\n let _ = mut_ptr as *mut i32;\n ```\n Use instead:\n ```rust\n let ptr: *const u32 = &42_u32;\n let mut_ptr: *mut u32 = &mut 42_u32;\n let _ = ptr.cast::();\n let _ = mut_ptr.cast::();\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "undropped_manually_drops", + "id_span": { + "path": "clippy_lints/src/undropped_manually_drops.rs", + "line": 27 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Prevents the safe `std::mem::drop` function from being called on `std::mem::ManuallyDrop`.\n **Why is this bad?** The safe `drop` function does not drop the inner value of a `ManuallyDrop`.\n\n **Known problems:** Does not catch cases if the user binds `std::mem::drop`\n to a different name and calls it that way.\n\n **Example:**\n\n ```rust\n struct S;\n drop(std::mem::ManuallyDrop::new(S));\n ```\n Use instead:\n ```rust\n struct S;\n unsafe {\n std::mem::ManuallyDrop::drop(&mut std::mem::ManuallyDrop::new(S));\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "invisible_characters", + "id_span": { + "path": "clippy_lints/src/unicode.rs", + "line": 20 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for invisible Unicode characters in the code.\n **Why is this bad?** Having an invisible character in the code makes for all\n sorts of April fools, but otherwise is very much frowned upon.\n\n **Known problems:** None.\n\n **Example:** You don't see it, but there may be a zero-width space or soft hyphen\n some­where in this text.\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "non_ascii_literal", + "id_span": { + "path": "clippy_lints/src/unicode.rs", + "line": 44 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for non-ASCII characters in string literals.\n **Why is this bad?** Yeah, we know, the 90's called and wanted their charset\n back. Even so, there still are editors and other programs out there that\n don't work well with Unicode. So if the code is meant to be used\n internationally, on multiple operating systems, or has other portability\n requirements, activating this lint could be useful.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let x = String::from(\"€\");\n ```\n Could be written as:\n ```rust\n let x = String::from(\"\\u{20ac}\");\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "unicode_not_nfc", + "id_span": { + "path": "clippy_lints/src/unicode.rs", + "line": 61 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for string literals that contain Unicode in a form that is not equal to its\n [NFC-recomposition](http://www.unicode.org/reports/tr15/#Norm_Forms).\n\n **Why is this bad?** If such a string is compared to another, the results\n may be surprising.\n\n **Known problems** None.\n\n **Example:** You may not see it, but \"à\"\" and \"à\"\" aren't the same string. The\n former when escaped is actually `\"a\\u{300}\"` while the latter is `\"\\u{e0}\"`.\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "unit_return_expecting_ord", + "id_span": { + "path": "clippy_lints/src/unit_return_expecting_ord.rs", + "line": 30 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for functions that expect closures of type Fn(...) -> Ord where the implemented closure returns the unit type.\n The lint also suggests to remove the semi-colon at the end of the statement if present.\n\n **Why is this bad?** Likely, returning the unit type is unintentional, and\n could simply be caused by an extra semi-colon. Since () implements Ord\n it doesn't cause a compilation error.\n This is the same reasoning behind the unit_cmp lint.\n\n **Known problems:** If returning unit is intentional, then there is no\n way of specifying this without triggering needless_return lint\n\n **Example:**\n\n ```rust\n let mut twins = vec!((1, 1), (2, 2));\n twins.sort_by_key(|x| { x.1; });\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "fn_address_comparisons", + "id_span": { + "path": "clippy_lints/src/unnamed_address.rs", + "line": 27 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for comparisons with an address of a function item.\n **Why is this bad?** Function item address is not guaranteed to be unique and could vary\n between different code generation units. Furthermore different function items could have\n the same address after being merged together.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n type F = fn();\n fn a() {}\n let f: F = a;\n if f == a {\n // ...\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "vtable_address_comparisons", + "id_span": { + "path": "clippy_lints/src/unnamed_address.rs", + "line": 51 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for comparisons with an address of a trait vtable.\n **Why is this bad?** Comparing trait objects pointers compares an vtable addresses which\n are not guaranteed to be unique and could vary between different code generation units.\n Furthermore vtables for different types could have the same address after being merged\n together.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust,ignore\n let a: Rc = ...\n let b: Rc = ...\n if Rc::ptr_eq(&a, &b) {\n ...\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "unnecessary_sort_by", + "id_span": { + "path": "clippy_lints/src/unnecessary_sort_by.rs", + "line": 41 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Detects uses of `Vec::sort_by` passing in a closure\n which compares the two arguments, either directly or indirectly.\n\n **Why is this bad?**\n It is more clear to use `Vec::sort_by_key` (or `Vec::sort` if\n possible) than to use `Vec::sort_by` and a more complicated\n closure.\n\n **Known problems:**\n If the suggested `Vec::sort_by_key` uses Reverse and it isn't already\n imported by a use statement, then it will need to be added manually.\n\n **Example:**\n\n ```rust\n # struct A;\n # impl A { fn foo(&self) {} }\n # let mut vec: Vec = Vec::new();\n vec.sort_by(|a, b| a.foo().cmp(&b.foo()));\n ```\n Use instead:\n ```rust\n # struct A;\n # impl A { fn foo(&self) {} }\n # let mut vec: Vec = Vec::new();\n vec.sort_by_key(|a| a.foo());\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "unnecessary_wraps", + "id_span": { + "path": "clippy_lints/src/unnecessary_wraps.rs", + "line": 50 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for private functions that only return `Ok` or `Some`.\n **Why is this bad?** It is not meaningful to wrap values when no `None` or `Err` is returned.\n\n **Known problems:** There can be false positives if the function signature is designed to\n fit some external requirement.\n\n **Example:**\n\n ```rust\n fn get_cool_number(a: bool, b: bool) -> Option {\n if a && b {\n return Some(50);\n }\n if a {\n Some(0)\n } else {\n Some(10)\n }\n }\n ```\n Use instead:\n ```rust\n fn get_cool_number(a: bool, b: bool) -> i32 {\n if a && b {\n return 50;\n }\n if a {\n 0\n } else {\n 10\n }\n }\n ```\n", + "applicability": { + "is_multi_suggestion": true, + "applicability": "MaybeIncorrect" + } + }, + { + "id": "unnested_or_patterns", + "id_span": { + "path": "clippy_lints/src/unnested_or_patterns.rs", + "line": 47 + }, + "group": "clippy::pedantic", + "docs": " **What it does:**\n Checks for unnested or-patterns, e.g., `Some(0) | Some(2)` and\n suggests replacing the pattern with a nested one, `Some(0 | 2)`.\n\n Another way to think of this is that it rewrites patterns in\n *disjunctive normal form (DNF)* into *conjunctive normal form (CNF)*.\n\n **Why is this bad?**\n\n In the example above, `Some` is repeated, which unncessarily complicates the pattern.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n fn main() {\n if let Some(0) | Some(2) = Some(0) {}\n }\n ```\n Use instead:\n ```rust\n #![feature(or_patterns)]\n\n fn main() {\n if let Some(0 | 2) = Some(0) {}\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "unsafe_removed_from_name", + "id_span": { + "path": "clippy_lints/src/unsafe_removed_from_name.rs", + "line": 24 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for imports that remove \"unsafe\" from an item's name.\n\n **Why is this bad?** Renaming makes it less clear which traits and\n structures are unsafe.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n use std::cell::{UnsafeCell as TotallySafeCell};\n\n extern crate crossbeam;\n use crossbeam::{spawn_unsafe as spawn};\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "unused_io_amount", + "id_span": { + "path": "clippy_lints/src/unused_io_amount.rs", + "line": 28 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for unused written/read amount.\n **Why is this bad?** `io::Write::write(_vectored)` and\n `io::Read::read(_vectored)` are not guaranteed to\n process the entire buffer. They return how many bytes were processed, which\n might be smaller\n than a given buffer's length. If you don't need to deal with\n partial-write/read, use\n `write_all`/`read_exact` instead.\n\n **Known problems:** Detects only common patterns.\n\n **Example:**\n ```rust,ignore\n use std::io;\n fn foo(w: &mut W) -> io::Result<()> {\n // must be `w.write_all(b\"foo\")?;`\n w.write(b\"foo\")?;\n Ok(())\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "unused_self", + "id_span": { + "path": "clippy_lints/src/unused_self.rs", + "line": 33 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks methods that contain a `self` argument but don't use it\n **Why is this bad?** It may be clearer to define the method as an associated function instead\n of an instance method if it doesn't require `self`.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n struct A;\n impl A {\n fn method(&self) {}\n }\n ```\n\n Could be written:\n\n ```rust,ignore\n struct A;\n impl A {\n fn method() {}\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "unused_unit", + "id_span": { + "path": "clippy_lints/src/unused_unit.rs", + "line": 27 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for unit (`()`) expressions that can be removed.\n **Why is this bad?** Such expressions add no value, but can make the code\n less readable. Depending on formatting they can make a `break` or `return`\n statement look like a function call.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n fn return_unit() -> () {\n ()\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "unnecessary_unwrap", + "id_span": { + "path": "clippy_lints/src/unwrap.rs", + "line": 40 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for calls of `unwrap[_err]()` that cannot fail.\n **Why is this bad?** Using `if let` or `match` is more idiomatic.\n\n **Known problems:** None\n\n **Example:**\n ```rust\n # let option = Some(0);\n # fn do_something_with(_x: usize) {}\n if option.is_some() {\n do_something_with(option.unwrap())\n }\n ```\n\n Could be written:\n\n ```rust\n # let option = Some(0);\n # fn do_something_with(_x: usize) {}\n if let Some(value) = option {\n do_something_with(value)\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "panicking_unwrap", + "id_span": { + "path": "clippy_lints/src/unwrap.rs", + "line": 63 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Checks for calls of `unwrap[_err]()` that will always fail.\n **Why is this bad?** If panicking is desired, an explicit `panic!()` should be used.\n\n **Known problems:** This lint only checks `if` conditions not assignments.\n So something like `let x: Option<()> = None; x.unwrap();` will not be recognized.\n\n **Example:**\n ```rust\n # let option = Some(0);\n # fn do_something_with(_x: usize) {}\n if option.is_none() {\n do_something_with(option.unwrap())\n }\n ```\n\n This code will always panic. The if condition should probably be inverted.\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "unwrap_in_result", + "id_span": { + "path": "clippy_lints/src/unwrap_in_result.rs", + "line": 47 + }, + "group": "clippy::restriction", + "docs": " **What it does:** Checks for functions of type Result that contain `expect()` or `unwrap()`\n **Why is this bad?** These functions promote recoverable errors to non-recoverable errors which may be undesirable in code bases which wish to avoid panics.\n\n **Known problems:** This can cause false positives in functions that handle both recoverable and non recoverable errors.\n\n **Example:**\n Before:\n ```rust\n fn divisible_by_3(i_str: String) -> Result<(), String> {\n let i = i_str\n .parse::()\n .expect(\"cannot divide the input by three\");\n\n if i % 3 != 0 {\n Err(\"Number is not divisible by 3\")?\n }\n\n Ok(())\n }\n ```\n\n After:\n ```rust\n fn divisible_by_3(i_str: String) -> Result<(), String> {\n let i = i_str\n .parse::()\n .map_err(|e| format!(\"cannot divide the input by three: {}\", e))?;\n\n if i % 3 != 0 {\n Err(\"Number is not divisible by 3\")?\n }\n\n Ok(())\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "upper_case_acronyms", + "id_span": { + "path": "clippy_lints/src/upper_case_acronyms.rs", + "line": 35 + }, + "group": "clippy::style", + "docs": " **What it does:** Checks for fully capitalized names and optionally names containing a capitalized acronym.\n **Why is this bad?** In CamelCase, acronyms count as one word.\n See [naming conventions](https://rust-lang.github.io/api-guidelines/naming.html#casing-conforms-to-rfc-430-c-case)\n for more.\n\n By default, the lint only triggers on fully-capitalized names.\n You can use the `upper-case-acronyms-aggressive: true` config option to enable linting\n on all camel case names\n\n **Known problems:** When two acronyms are contiguous, the lint can't tell where\n the first acronym ends and the second starts, so it suggests to lowercase all of\n the letters in the second acronym.\n\n **Example:**\n\n ```rust\n struct HTTPResponse;\n ```\n Use instead:\n ```rust\n struct HttpResponse;\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MaybeIncorrect" + } + }, + { + "id": "use_self", + "id_span": { + "path": "clippy_lints/src/use_self.rs", + "line": 53 + }, + "group": "clippy::nursery", + "docs": " **What it does:** Checks for unnecessary repetition of structure name when a replacement with `Self` is applicable.\n\n **Why is this bad?** Unnecessary repetition. Mixed use of `Self` and struct\n name\n feels inconsistent.\n\n **Known problems:**\n - Unaddressed false negative in fn bodies of trait implementations\n - False positive with assotiated types in traits (#4140)\n\n **Example:**\n\n ```rust\n struct Foo {}\n impl Foo {\n fn new() -> Foo {\n Foo {}\n }\n }\n ```\n could be\n ```rust\n struct Foo {}\n impl Foo {\n fn new() -> Self {\n Self {}\n }\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "useless_conversion", + "id_span": { + "path": "clippy_lints/src/useless_conversion.rs", + "line": 32 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for `Into`, `TryInto`, `From`, `TryFrom`, or `IntoIter` calls which uselessly convert to the same type.\n\n **Why is this bad?** Redundant code.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n // Bad\n // format!() returns a `String`\n let s: String = format!(\"hello\").into();\n\n // Good\n let s: String = format!(\"hello\");\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "useless_vec", + "id_span": { + "path": "clippy_lints/src/vec.rs", + "line": 36 + }, + "group": "clippy::perf", + "docs": " **What it does:** Checks for usage of `&vec![..]` when using `&[..]` would be possible.\n\n **Why is this bad?** This is less efficient.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # fn foo(my_vec: &[u8]) {}\n\n // Bad\n foo(&vec![1, 2]);\n\n // Good\n foo(&[1, 2]);\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "vec_init_then_push", + "id_span": { + "path": "clippy_lints/src/vec_init_then_push.rs", + "line": 32 + }, + "group": "clippy::perf", + "docs": " **What it does:** Checks for calls to `push` immediately after creating a new `Vec`.\n **Why is this bad?** The `vec![]` macro is both more performant and easier to read than\n multiple `push` calls.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n let mut v = Vec::new();\n v.push(0);\n ```\n Use instead:\n ```rust\n let v = vec![0];\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "HasPlaceholders" + } + }, + { + "id": "vec_resize_to_zero", + "id_span": { + "path": "clippy_lints/src/vec_resize_to_zero.rs", + "line": 24 + }, + "group": "clippy::correctness", + "docs": " **What it does:** Finds occurrences of `Vec::resize(0, an_int)`\n **Why is this bad?** This is probably an argument inversion mistake.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n vec!(1, 2, 3, 4, 5).resize(0, 5)\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MaybeIncorrect" + } + }, + { + "id": "verbose_file_reads", + "id_span": { + "path": "clippy_lints/src/verbose_file_reads.rs", + "line": 29 + }, + "group": "clippy::restriction", + "docs": " **What it does:** Checks for use of File::read_to_end and File::read_to_string.\n **Why is this bad?** `fs::{read, read_to_string}` provide the same functionality when `buf` is empty with fewer imports and no intermediate values.\n See also: [fs::read docs](https://doc.rust-lang.org/std/fs/fn.read.html), [fs::read_to_string docs](https://doc.rust-lang.org/std/fs/fn.read_to_string.html)\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust,no_run\n # use std::io::Read;\n # use std::fs::File;\n let mut f = File::open(\"foo.txt\").unwrap();\n let mut bytes = Vec::new();\n f.read_to_end(&mut bytes).unwrap();\n ```\n Can be written more concisely as\n ```rust,no_run\n # use std::fs;\n let mut bytes = fs::read(\"foo.txt\").unwrap();\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "wildcard_dependencies", + "id_span": { + "path": "clippy_lints/src/wildcard_dependencies.rs", + "line": 24 + }, + "group": "clippy::cargo", + "docs": " **What it does:** Checks for wildcard dependencies in the `Cargo.toml`.\n **Why is this bad?** [As the edition guide says](https://rust-lang-nursery.github.io/edition-guide/rust-2018/cargo-and-crates-io/crates-io-disallows-wildcard-dependencies.html),\n it is highly unlikely that you work with any possible version of your dependency,\n and wildcard dependencies would cause unnecessary breakage in the ecosystem.\n\n **Known problems:** None.\n\n **Example:**\n\n ```toml\n [dependencies]\n regex = \"*\"\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "enum_glob_use", + "id_span": { + "path": "clippy_lints/src/wildcard_imports.rs", + "line": 32 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for `use Enum::*`.\n **Why is this bad?** It is usually better style to use the prefixed name of\n an enumeration variant, rather than importing variants.\n\n **Known problems:** Old-style enumerations that prefix the variants are\n still around.\n\n **Example:**\n ```rust,ignore\n // Bad\n use std::cmp::Ordering::*;\n foo(Less);\n\n // Good\n use std::cmp::Ordering;\n foo(Ordering::Less)\n ```\n", + "applicability": null + }, + { + "id": "wildcard_imports", + "id_span": { + "path": "clippy_lints/src/wildcard_imports.rs", + "line": 83 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for wildcard imports `use _::*`.\n **Why is this bad?** wildcard imports can pollute the namespace. This is especially bad if\n you try to import something through a wildcard, that already has been imported by name from\n a different source:\n\n ```rust,ignore\n use crate1::foo; // Imports a function named foo\n use crate2::*; // Has a function named foo\n\n foo(); // Calls crate1::foo\n ```\n\n This can lead to confusing error messages at best and to unexpected behavior at worst.\n\n **Exceptions:**\n\n Wildcard imports are allowed from modules named `prelude`. Many crates (including the standard library)\n provide modules named \"prelude\" specifically designed for wildcard import.\n\n `use super::*` is allowed in test modules. This is defined as any module with \"test\" in the name.\n\n These exceptions can be disabled using the `warn-on-all-wildcard-imports` configuration flag.\n\n **Known problems:** If macros are imported through the wildcard, this macro is not included\n by the suggestion and has to be added by hand.\n\n Applying the suggestion when explicit imports of the things imported with a glob import\n exist, may result in `unused_imports` warnings.\n\n **Example:**\n\n ```rust,ignore\n // Bad\n use crate1::*;\n\n foo();\n ```\n\n ```rust,ignore\n // Good\n use crate1::foo;\n\n foo();\n ```\n", + "applicability": null + }, + { + "id": "println_empty_string", + "id_span": { + "path": "clippy_lints/src/write.rs", + "line": 33 + }, + "group": "clippy::style", + "docs": " **What it does:** This lint warns when you use `println!(\"\")` to print a newline.\n\n **Why is this bad?** You should use `println!()`, which is simpler.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n // Bad\n println!(\"\");\n\n // Good\n println!();\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "print_with_newline", + "id_span": { + "path": "clippy_lints/src/write.rs", + "line": 57 + }, + "group": "clippy::style", + "docs": " **What it does:** This lint warns when you use `print!()` with a format string that ends in a newline.\n\n **Why is this bad?** You should use `println!()` instead, which appends the\n newline.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let name = \"World\";\n print!(\"Hello {}!\\n\", name);\n ```\n use println!() instead\n ```rust\n # let name = \"World\";\n println!(\"Hello {}!\", name);\n ```\n", + "applicability": { + "is_multi_suggestion": true, + "applicability": "MachineApplicable" + } + }, + { + "id": "print_stdout", + "id_span": { + "path": "clippy_lints/src/write.rs", + "line": 75 + }, + "group": "clippy::restriction", + "docs": " **What it does:** Checks for printing on *stdout*. The purpose of this lint is to catch debugging remnants.\n\n **Why is this bad?** People often print on *stdout* while debugging an\n application and might forget to remove those prints afterward.\n\n **Known problems:** Only catches `print!` and `println!` calls.\n\n **Example:**\n ```rust\n println!(\"Hello world!\");\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "print_stderr", + "id_span": { + "path": "clippy_lints/src/write.rs", + "line": 93 + }, + "group": "clippy::restriction", + "docs": " **What it does:** Checks for printing on *stderr*. The purpose of this lint is to catch debugging remnants.\n\n **Why is this bad?** People often print on *stderr* while debugging an\n application and might forget to remove those prints afterward.\n\n **Known problems:** Only catches `eprint!` and `eprintln!` calls.\n\n **Example:**\n ```rust\n eprintln!(\"Hello world!\");\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "use_debug", + "id_span": { + "path": "clippy_lints/src/write.rs", + "line": 110 + }, + "group": "clippy::restriction", + "docs": " **What it does:** Checks for use of `Debug` formatting. The purpose of this lint is to catch debugging remnants.\n\n **Why is this bad?** The purpose of the `Debug` trait is to facilitate\n debugging Rust code. It should not be used in user-facing output.\n\n **Example:**\n ```rust\n # let foo = \"bar\";\n println!(\"{:?}\", foo);\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "print_literal", + "id_span": { + "path": "clippy_lints/src/write.rs", + "line": 133 + }, + "group": "clippy::style", + "docs": " **What it does:** This lint warns about the use of literals as `print!`/`println!` args.\n **Why is this bad?** Using literals as `println!` args is inefficient\n (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary\n (i.e., just put the literal in the format string)\n\n **Known problems:** Will also warn with macro calls as arguments that expand to literals\n -- e.g., `println!(\"{}\", env!(\"FOO\"))`.\n\n **Example:**\n ```rust\n println!(\"{}\", \"foo\");\n ```\n use the literal without formatting:\n ```rust\n println!(\"foo\");\n ```\n", + "applicability": null + }, + { + "id": "writeln_empty_string", + "id_span": { + "path": "clippy_lints/src/write.rs", + "line": 156 + }, + "group": "clippy::style", + "docs": " **What it does:** This lint warns when you use `writeln!(buf, \"\")` to print a newline.\n\n **Why is this bad?** You should use `writeln!(buf)`, which is simpler.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # use std::fmt::Write;\n # let mut buf = String::new();\n // Bad\n writeln!(buf, \"\");\n\n // Good\n writeln!(buf);\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "write_with_newline", + "id_span": { + "path": "clippy_lints/src/write.rs", + "line": 182 + }, + "group": "clippy::style", + "docs": " **What it does:** This lint warns when you use `write!()` with a format string that\n ends in a newline.\n\n **Why is this bad?** You should use `writeln!()` instead, which appends the\n newline.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # use std::fmt::Write;\n # let mut buf = String::new();\n # let name = \"World\";\n // Bad\n write!(buf, \"Hello {}!\\n\", name);\n\n // Good\n writeln!(buf, \"Hello {}!\", name);\n ```\n", + "applicability": { + "is_multi_suggestion": true, + "applicability": "MachineApplicable" + } + }, + { + "id": "write_literal", + "id_span": { + "path": "clippy_lints/src/write.rs", + "line": 207 + }, + "group": "clippy::style", + "docs": " **What it does:** This lint warns about the use of literals as `write!`/`writeln!` args.\n **Why is this bad?** Using literals as `writeln!` args is inefficient\n (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary\n (i.e., just put the literal in the format string)\n\n **Known problems:** Will also warn with macro calls as arguments that expand to literals\n -- e.g., `writeln!(buf, \"{}\", env!(\"FOO\"))`.\n\n **Example:**\n ```rust\n # use std::fmt::Write;\n # let mut buf = String::new();\n // Bad\n writeln!(buf, \"{}\", \"foo\");\n\n // Good\n writeln!(buf, \"foo\");\n ```\n", + "applicability": null + }, + { + "id": "zero_divided_by_zero", + "id_span": { + "path": "clippy_lints/src/zero_div_zero.rs", + "line": 23 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for `0.0 / 0.0`.\n **Why is this bad?** It's less readable than `f32::NAN` or `f64::NAN`.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n // Bad\n let nan = 0.0f32 / 0.0;\n\n // Good\n let nan = f32::NAN;\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + }, + { + "id": "zero_sized_map_values", + "id_span": { + "path": "clippy_lints/src/zero_sized_map_values.rs", + "line": 37 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for maps with zero-sized value types anywhere in the code.\n **Why is this bad?** Since there is only a single value for a zero-sized type, a map\n containing zero sized values is effectively a set. Using a set in that case improves\n readability and communicates intent more clearly.\n\n **Known problems:**\n * A zero-sized type cannot be recovered later if it contains private fields.\n * This lints the signature of public items\n\n **Example:**\n\n ```rust\n # use std::collections::HashMap;\n fn unique_words(text: &str) -> HashMap<&str, ()> {\n todo!();\n }\n ```\n Use instead:\n ```rust\n # use std::collections::HashSet;\n fn unique_words(text: &str) -> HashSet<&str> {\n todo!();\n }\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } + } +] From 35844d0a48e0a644072ae81857782a6e0bd54740 Mon Sep 17 00:00:00 2001 From: xFrednet Date: Sat, 6 Mar 2021 01:11:41 +0100 Subject: [PATCH 11/15] Metadata collection: Resolve lint from locals --- .../internal_lints/metadata_collector.rs | 82 +- clippy_utils/src/paths.rs | 2 +- metadata_collection.json | 1184 +++++++++-------- 3 files changed, 699 insertions(+), 569 deletions(-) diff --git a/clippy_lints/src/utils/internal_lints/metadata_collector.rs b/clippy_lints/src/utils/internal_lints/metadata_collector.rs index b2cc6372277..0425689b0dd 100644 --- a/clippy_lints/src/utils/internal_lints/metadata_collector.rs +++ b/clippy_lints/src/utils/internal_lints/metadata_collector.rs @@ -15,8 +15,6 @@ // # Applicability // - TODO xFrednet 2021-01-17: Find lint emit and collect applicability -// - TODO xFrednet 2021-02-28: 1x reference to closure -// - See clippy_lints/src/needless_pass_by_value.rs@NeedlessPassByValue::check_fn // - TODO xFrednet 2021-02-28: 4x weird emission forwarding // - See clippy_lints/src/enum_variants.rs@EnumVariantNames::check_name // - TODO xFrednet 2021-02-28: 6x emission forwarding with local that is initializes from @@ -26,14 +24,12 @@ // - See clippy_lints/src/misc.rs@check_binary // - TODO xFrednet 2021-02-28: 2x lint from local from method call // - See clippy_lints/src/non_copy_const.rs@lint -// - TODO xFrednet 2021-02-28: 20x lint from local -// - See clippy_lints/src/map_unit_fn.rs@lint_map_unit_fn // # NITs // - TODO xFrednet 2021-02-13: Collect depreciations and maybe renames use if_chain::if_chain; use rustc_data_structures::fx::FxHashMap; -use rustc_hir::{self as hir, intravisit, intravisit::Visitor, ExprKind, Item, ItemKind, Mutability, QPath}; +use rustc_hir::{self as hir, intravisit, intravisit::Visitor, ExprKind, Item, ItemKind, Mutability, QPath, def::DefKind}; use rustc_lint::{CheckLintNameResult, LateContext, LateLintPass, LintContext, LintId}; use rustc_middle::hir::map::Map; use rustc_session::{declare_tool_lint, impl_lint_pass}; @@ -49,7 +45,7 @@ }; /// This is the output file of the lint collector. -const OUTPUT_FILE: &str = "metadata_collection.json"; +const OUTPUT_FILE: &str = "../metadata_collection.json"; /// These lints are excluded from the export. const BLACK_LISTED_LINTS: [&str; 2] = ["lint_author", "deep_code_inspection"]; /// These groups will be ignored by the lint group matcher. This is useful for collections like @@ -270,12 +266,16 @@ fn check_item(&mut self, cx: &LateContext<'hir>, item: &'hir Item<'_>) { /// ``` fn check_expr(&mut self, cx: &LateContext<'hir>, expr: &'hir hir::Expr<'_>) { if let Some(args) = match_lint_emission(cx, expr) { - if let Some((lint_name, applicability, is_multi_part)) = extract_complex_emission_info(cx, args) { + let mut emission_info = extract_complex_emission_info(cx, args); + if emission_info.is_empty() { + lint_collection_error_span(cx, expr.span, "Look, here ... I have no clue what todo with it"); + return; + } + + for (lint_name, applicability, is_multi_part) in emission_info.drain(..) { let app_info = self.applicability_into.entry(lint_name).or_default(); app_info.applicability = applicability; app_info.is_multi_suggestion = is_multi_part; - } else { - lint_collection_error_span(cx, expr.span, "Look, here ... I have no clue what todo with it"); } } } @@ -380,8 +380,8 @@ fn match_lint_emission<'hir>(cx: &LateContext<'hir>, expr: &'hir hir::Expr<'_>) fn extract_complex_emission_info<'hir>( cx: &LateContext<'hir>, args: &'hir [hir::Expr<'hir>], -) -> Option<(String, Option, bool)> { - let mut lint_name = None; +) -> Vec<(String, Option, bool)> { + let mut lints= Vec::new(); let mut applicability = None; let mut multi_part = false; @@ -390,9 +390,8 @@ fn extract_complex_emission_info<'hir>( if match_type(cx, arg_ty, &paths::LINT) { // If we found the lint arg, extract the lint name - if let ExprKind::Path(ref lint_path) = arg.kind { - lint_name = Some(last_path_segment(lint_path).ident.name); - } + let mut resolved_lints = resolve_lints(cx, arg); + lints.append(&mut resolved_lints); } else if match_type(cx, arg_ty, &paths::APPLICABILITY) { applicability = resolve_applicability(cx, arg); } else if arg_ty.is_closure() { @@ -402,7 +401,14 @@ fn extract_complex_emission_info<'hir>( } } - lint_name.map(|lint_name| (sym_to_string(lint_name).to_ascii_lowercase(), applicability, multi_part)) + lints.drain(..).map(|lint_name| (lint_name, applicability.clone(), multi_part)).collect() +} + +/// Resolves the possible lints that this expression could reference +fn resolve_lints(cx: &LateContext<'hir>, expr: &'hir hir::Expr<'hir>) -> Vec { + let mut resolver = LintResolver::new(cx); + resolver.visit_expr(expr); + resolver.lints } /// This function tries to resolve the linked applicability to the given expression. @@ -426,6 +432,50 @@ fn check_is_multi_part(cx: &LateContext<'hir>, closure_expr: &'hir hir::Expr<'hi false } +struct LintResolver<'a, 'hir> { + cx: &'a LateContext<'hir>, + lints: Vec, +} + +impl<'a, 'hir> LintResolver<'a, 'hir> { + fn new(cx: &'a LateContext<'hir>) -> Self { + Self { + cx, + lints: Vec::::default(), + } + } +} + +impl<'a, 'hir> intravisit::Visitor<'hir> for LintResolver<'a, 'hir> { + type Map = Map<'hir>; + + fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap { + intravisit::NestedVisitorMap::All(self.cx.tcx.hir()) + } + + fn visit_expr(&mut self, expr: &'hir hir::Expr<'hir>) { + if_chain! { + if let ExprKind::Path(qpath) = &expr.kind; + if let QPath::Resolved(_, path) = qpath; + + let (expr_ty, _) = walk_ptrs_ty_depth(self.cx.typeck_results().expr_ty(&expr)); + if match_type(self.cx, expr_ty, &paths::LINT); + then { + if let hir::def::Res::Def(DefKind::Static, _) = path.res { + let lint_name = last_path_segment(qpath).ident.name; + self.lints.push(sym_to_string(lint_name).to_ascii_lowercase()); + } else if let Some(local) = get_parent_local(self.cx, expr) { + if let Some(local_init) = local.init { + intravisit::walk_expr(self, local_init); + } + } + } + } + + intravisit::walk_expr(self, expr); + } +} + /// This visitor finds the highest applicability value in the visited expressions struct ApplicabilityResolver<'a, 'hir> { cx: &'a LateContext<'hir>, @@ -488,7 +538,7 @@ fn visit_expr(&mut self, expr: &'hir hir::Expr<'hir>) { } } -/// This returns the parent local node if the expression is a reference to +/// This returns the parent local node if the expression is a reference one fn get_parent_local(cx: &LateContext<'hir>, expr: &'hir hir::Expr<'hir>) -> Option<&'hir hir::Local<'hir>> { if let ExprKind::Path(QPath::Resolved(_, path)) = expr.kind { if let hir::def::Res::Local(local_hir) = path.res { diff --git a/clippy_utils/src/paths.rs b/clippy_utils/src/paths.rs index a6292b87768..1f19724ad25 100644 --- a/clippy_utils/src/paths.rs +++ b/clippy_utils/src/paths.rs @@ -83,7 +83,7 @@ #[cfg(feature = "internal-lints")] pub const LATE_CONTEXT: [&str; 2] = ["rustc_lint", "LateContext"]; pub const LINKED_LIST: [&str; 4] = ["alloc", "collections", "linked_list", "LinkedList"]; -#[cfg(feature = "internal-lints")] +#[cfg(any(feature = "internal-lints", feature = "metadata-collector-lint"))] pub const LINT: [&str; 2] = ["rustc_lint_defs", "Lint"]; pub const MEM_DISCRIMINANT: [&str; 3] = ["core", "mem", "discriminant"]; pub const MEM_FORGET: [&str; 3] = ["core", "mem", "forget"]; diff --git a/metadata_collection.json b/metadata_collection.json index 507752a782c..f6f72ffa5fa 100644 --- a/metadata_collection.json +++ b/metadata_collection.json @@ -2,7 +2,7 @@ { "id": "approx_constant", "id_span": { - "path": "clippy_lints/src/approx_const.rs", + "path": "src/approx_const.rs", "line": 34 }, "group": "clippy::correctness", @@ -15,7 +15,7 @@ { "id": "integer_arithmetic", "id_span": { - "path": "clippy_lints/src/arithmetic.rs", + "path": "src/arithmetic.rs", "line": 28 }, "group": "clippy::restriction", @@ -28,7 +28,7 @@ { "id": "float_arithmetic", "id_span": { - "path": "clippy_lints/src/arithmetic.rs", + "path": "src/arithmetic.rs", "line": 46 }, "group": "clippy::restriction", @@ -41,7 +41,7 @@ { "id": "as_conversions", "id_span": { - "path": "clippy_lints/src/as_conversions.rs", + "path": "src/as_conversions.rs", "line": 42 }, "group": "clippy::restriction", @@ -54,7 +54,7 @@ { "id": "inline_asm_x86_intel_syntax", "id_span": { - "path": "clippy_lints/src/asm_syntax.rs", + "path": "src/asm_syntax.rs", "line": 78 }, "group": "clippy::restriction", @@ -64,7 +64,7 @@ { "id": "inline_asm_x86_att_syntax", "id_span": { - "path": "clippy_lints/src/asm_syntax.rs", + "path": "src/asm_syntax.rs", "line": 114 }, "group": "clippy::restriction", @@ -74,7 +74,7 @@ { "id": "assertions_on_constants", "id_span": { - "path": "clippy_lints/src/assertions_on_constants.rs", + "path": "src/assertions_on_constants.rs", "line": 23 }, "group": "clippy::style", @@ -87,7 +87,7 @@ { "id": "assign_op_pattern", "id_span": { - "path": "clippy_lints/src/assign_ops.rs", + "path": "src/assign_ops.rs", "line": 33 }, "group": "clippy::style", @@ -100,7 +100,7 @@ { "id": "misrefactored_assign_op", "id_span": { - "path": "clippy_lints/src/assign_ops.rs", + "path": "src/assign_ops.rs", "line": 56 }, "group": "clippy::complexity", @@ -113,7 +113,7 @@ { "id": "async_yields_async", "id_span": { - "path": "clippy_lints/src/async_yields_async.rs", + "path": "src/async_yields_async.rs", "line": 36 }, "group": "clippy::correctness", @@ -126,7 +126,7 @@ { "id": "invalid_atomic_ordering", "id_span": { - "path": "clippy_lints/src/atomic_ordering.rs", + "path": "src/atomic_ordering.rs", "line": 47 }, "group": "clippy::correctness", @@ -139,7 +139,7 @@ { "id": "inline_always", "id_span": { - "path": "clippy_lints/src/attrs.rs", + "path": "src/attrs.rs", "line": 65 }, "group": "clippy::pedantic", @@ -152,7 +152,7 @@ { "id": "useless_attribute", "id_span": { - "path": "clippy_lints/src/attrs.rs", + "path": "src/attrs.rs", "line": 99 }, "group": "clippy::correctness", @@ -165,7 +165,7 @@ { "id": "deprecated_semver", "id_span": { - "path": "clippy_lints/src/attrs.rs", + "path": "src/attrs.rs", "line": 118 }, "group": "clippy::correctness", @@ -178,7 +178,7 @@ { "id": "empty_line_after_outer_attr", "id_span": { - "path": "clippy_lints/src/attrs.rs", + "path": "src/attrs.rs", "line": 153 }, "group": "clippy::nursery", @@ -191,7 +191,7 @@ { "id": "blanket_clippy_restriction_lints", "id_span": { - "path": "clippy_lints/src/attrs.rs", + "path": "src/attrs.rs", "line": 176 }, "group": "clippy::style", @@ -204,7 +204,7 @@ { "id": "deprecated_cfg_attr", "id_span": { - "path": "clippy_lints/src/attrs.rs", + "path": "src/attrs.rs", "line": 205 }, "group": "clippy::complexity", @@ -217,7 +217,7 @@ { "id": "mismatched_target_os", "id_span": { - "path": "clippy_lints/src/attrs.rs", + "path": "src/attrs.rs", "line": 238 }, "group": "clippy::correctness", @@ -230,7 +230,7 @@ { "id": "await_holding_lock", "id_span": { - "path": "clippy_lints/src/await_holding_invalid.rs", + "path": "src/await_holding_invalid.rs", "line": 47 }, "group": "clippy::pedantic", @@ -243,7 +243,7 @@ { "id": "await_holding_refcell_ref", "id_span": { - "path": "clippy_lints/src/await_holding_invalid.rs", + "path": "src/await_holding_invalid.rs", "line": 86 }, "group": "clippy::pedantic", @@ -256,7 +256,7 @@ { "id": "bad_bit_mask", "id_span": { - "path": "clippy_lints/src/bit_mask.rs", + "path": "src/bit_mask.rs", "line": 44 }, "group": "clippy::correctness", @@ -269,7 +269,7 @@ { "id": "ineffective_bit_mask", "id_span": { - "path": "clippy_lints/src/bit_mask.rs", + "path": "src/bit_mask.rs", "line": 73 }, "group": "clippy::correctness", @@ -282,7 +282,7 @@ { "id": "verbose_bit_mask", "id_span": { - "path": "clippy_lints/src/bit_mask.rs", + "path": "src/bit_mask.rs", "line": 92 }, "group": "clippy::pedantic", @@ -295,7 +295,7 @@ { "id": "blacklisted_name", "id_span": { - "path": "clippy_lints/src/blacklisted_name.rs", + "path": "src/blacklisted_name.rs", "line": 20 }, "group": "clippy::style", @@ -308,7 +308,7 @@ { "id": "blocks_in_if_conditions", "id_span": { - "path": "clippy_lints/src/blocks_in_if_conditions.rs", + "path": "src/blocks_in_if_conditions.rs", "line": 42 }, "group": "clippy::style", @@ -321,7 +321,7 @@ { "id": "nonminimal_bool", "id_span": { - "path": "clippy_lints/src/booleans.rs", + "path": "src/booleans.rs", "line": 31 }, "group": "clippy::complexity", @@ -334,7 +334,7 @@ { "id": "logic_bug", "id_span": { - "path": "clippy_lints/src/booleans.rs", + "path": "src/booleans.rs", "line": 49 }, "group": "clippy::correctness", @@ -347,10 +347,10 @@ { "id": "naive_bytecount", "id_span": { - "path": "clippy_lints/src/bytecount.rs", + "path": "src/bytecount.rs", "line": 30 }, - "group": "clippy::perf", + "group": "clippy::pedantic", "docs": " **What it does:** Checks for naive byte counts\n **Why is this bad?** The [`bytecount`](https://crates.io/crates/bytecount)\n crate has methods to count your bytes faster, especially for large slices.\n\n **Known problems:** If you have predominantly small slices, the\n `bytecount::count(..)` method may actually be slower. However, if you can\n ensure that less than 2³²-1 matches arise, the `naive_count_32(..)` can be\n faster in those cases.\n\n **Example:**\n\n ```rust\n # let vec = vec![1_u8];\n &vec.iter().filter(|x| **x == 0u8).count(); // use bytecount::count instead\n ```\n", "applicability": { "is_multi_suggestion": false, @@ -360,7 +360,7 @@ { "id": "cargo_common_metadata", "id_span": { - "path": "clippy_lints/src/cargo_common_metadata.rs", + "path": "src/cargo_common_metadata.rs", "line": 49 }, "group": "clippy::cargo", @@ -373,7 +373,7 @@ { "id": "case_sensitive_file_extension_comparisons", "id_span": { - "path": "clippy_lints/src/case_sensitive_file_extension_comparisons.rs", + "path": "src/case_sensitive_file_extension_comparisons.rs", "line": 34 }, "group": "clippy::pedantic", @@ -386,7 +386,7 @@ { "id": "checked_conversions", "id_span": { - "path": "clippy_lints/src/checked_conversions.rs", + "path": "src/checked_conversions.rs", "line": 40 }, "group": "clippy::pedantic", @@ -399,7 +399,7 @@ { "id": "cognitive_complexity", "id_span": { - "path": "clippy_lints/src/cognitive_complexity.rs", + "path": "src/cognitive_complexity.rs", "line": 24 }, "group": "clippy::nursery", @@ -412,7 +412,7 @@ { "id": "collapsible_if", "id_span": { - "path": "clippy_lints/src/collapsible_if.rs", + "path": "src/collapsible_if.rs", "line": 50 }, "group": "clippy::style", @@ -425,7 +425,7 @@ { "id": "collapsible_else_if", "id_span": { - "path": "clippy_lints/src/collapsible_if.rs", + "path": "src/collapsible_if.rs", "line": 85 }, "group": "clippy::style", @@ -438,7 +438,7 @@ { "id": "collapsible_match", "id_span": { - "path": "clippy_lints/src/collapsible_match.rs", + "path": "src/collapsible_match.rs", "line": 44 }, "group": "clippy::style", @@ -451,7 +451,7 @@ { "id": "comparison_chain", "id_span": { - "path": "clippy_lints/src/comparison_chain.rs", + "path": "src/comparison_chain.rs", "line": 49 }, "group": "clippy::style", @@ -464,7 +464,7 @@ { "id": "ifs_same_cond", "id_span": { - "path": "clippy_lints/src/copies.rs", + "path": "src/copies.rs", "line": 33 }, "group": "clippy::correctness", @@ -477,7 +477,7 @@ { "id": "same_functions_in_if_condition", "id_span": { - "path": "clippy_lints/src/copies.rs", + "path": "src/copies.rs", "line": 80 }, "group": "clippy::pedantic", @@ -490,7 +490,7 @@ { "id": "if_same_then_else", "id_span": { - "path": "clippy_lints/src/copies.rs", + "path": "src/copies.rs", "line": 101 }, "group": "clippy::correctness", @@ -503,7 +503,7 @@ { "id": "copy_iterator", "id_span": { - "path": "clippy_lints/src/copy_iterator.rs", + "path": "src/copy_iterator.rs", "line": 27 }, "group": "clippy::pedantic", @@ -516,7 +516,7 @@ { "id": "create_dir", "id_span": { - "path": "clippy_lints/src/create_dir.rs", + "path": "src/create_dir.rs", "line": 24 }, "group": "clippy::restriction", @@ -529,7 +529,7 @@ { "id": "dbg_macro", "id_span": { - "path": "clippy_lints/src/dbg_macro.rs", + "path": "src/dbg_macro.rs", "line": 25 }, "group": "clippy::restriction", @@ -542,7 +542,7 @@ { "id": "default_trait_access", "id_span": { - "path": "clippy_lints/src/default.rs", + "path": "src/default.rs", "line": 33 }, "group": "clippy::pedantic", @@ -555,7 +555,7 @@ { "id": "field_reassign_with_default", "id_span": { - "path": "clippy_lints/src/default.rs", + "path": "src/default.rs", "line": 63 }, "group": "clippy::style", @@ -568,7 +568,7 @@ { "id": "default_numeric_fallback", "id_span": { - "path": "clippy_lints/src/default_numeric_fallback.rs", + "path": "src/default_numeric_fallback.rs", "line": 44 }, "group": "clippy::restriction", @@ -581,7 +581,7 @@ { "id": "explicit_deref_methods", "id_span": { - "path": "clippy_lints/src/dereference.rs", + "path": "src/dereference.rs", "line": 32 }, "group": "clippy::pedantic", @@ -594,7 +594,7 @@ { "id": "derive_hash_xor_eq", "id_span": { - "path": "clippy_lints/src/derive.rs", + "path": "src/derive.rs", "line": 42 }, "group": "clippy::correctness", @@ -607,7 +607,7 @@ { "id": "derive_ord_xor_partial_ord", "id_span": { - "path": "clippy_lints/src/derive.rs", + "path": "src/derive.rs", "line": 93 }, "group": "clippy::correctness", @@ -620,7 +620,7 @@ { "id": "expl_impl_clone_on_copy", "id_span": { - "path": "clippy_lints/src/derive.rs", + "path": "src/derive.rs", "line": 119 }, "group": "clippy::pedantic", @@ -633,7 +633,7 @@ { "id": "unsafe_derive_deserialize", "id_span": { - "path": "clippy_lints/src/derive.rs", + "path": "src/derive.rs", "line": 153 }, "group": "clippy::pedantic", @@ -646,7 +646,7 @@ { "id": "disallowed_method", "id_span": { - "path": "clippy_lints/src/disallowed_method.rs", + "path": "src/disallowed_method.rs", "line": 46 }, "group": "clippy::nursery", @@ -659,7 +659,7 @@ { "id": "doc_markdown", "id_span": { - "path": "clippy_lints/src/doc.rs", + "path": "src/doc.rs", "line": 63 }, "group": "clippy::pedantic", @@ -672,7 +672,7 @@ { "id": "missing_safety_doc", "id_span": { - "path": "clippy_lints/src/doc.rs", + "path": "src/doc.rs", "line": 97 }, "group": "clippy::style", @@ -685,7 +685,7 @@ { "id": "missing_errors_doc", "id_span": { - "path": "clippy_lints/src/doc.rs", + "path": "src/doc.rs", "line": 126 }, "group": "clippy::pedantic", @@ -698,7 +698,7 @@ { "id": "missing_panics_doc", "id_span": { - "path": "clippy_lints/src/doc.rs", + "path": "src/doc.rs", "line": 157 }, "group": "clippy::pedantic", @@ -711,7 +711,7 @@ { "id": "needless_doctest_main", "id_span": { - "path": "clippy_lints/src/doc.rs", + "path": "src/doc.rs", "line": 185 }, "group": "clippy::style", @@ -724,7 +724,7 @@ { "id": "double_comparisons", "id_span": { - "path": "clippy_lints/src/double_comparison.rs", + "path": "src/double_comparison.rs", "line": 33 }, "group": "clippy::complexity", @@ -737,7 +737,7 @@ { "id": "double_parens", "id_span": { - "path": "clippy_lints/src/double_parens.rs", + "path": "src/double_parens.rs", "line": 35 }, "group": "clippy::complexity", @@ -750,7 +750,7 @@ { "id": "drop_ref", "id_span": { - "path": "clippy_lints/src/drop_forget_ref.rs", + "path": "src/drop_forget_ref.rs", "line": 26 }, "group": "clippy::correctness", @@ -760,7 +760,7 @@ { "id": "forget_ref", "id_span": { - "path": "clippy_lints/src/drop_forget_ref.rs", + "path": "src/drop_forget_ref.rs", "line": 47 }, "group": "clippy::correctness", @@ -770,7 +770,7 @@ { "id": "drop_copy", "id_span": { - "path": "clippy_lints/src/drop_forget_ref.rs", + "path": "src/drop_forget_ref.rs", "line": 68 }, "group": "clippy::correctness", @@ -780,7 +780,7 @@ { "id": "forget_copy", "id_span": { - "path": "clippy_lints/src/drop_forget_ref.rs", + "path": "src/drop_forget_ref.rs", "line": 95 }, "group": "clippy::correctness", @@ -790,7 +790,7 @@ { "id": "duration_subsec", "id_span": { - "path": "clippy_lints/src/duration_subsec.rs", + "path": "src/duration_subsec.rs", "line": 34 }, "group": "clippy::complexity", @@ -803,7 +803,7 @@ { "id": "else_if_without_else", "id_span": { - "path": "clippy_lints/src/else_if_without_else.rs", + "path": "src/else_if_without_else.rs", "line": 44 }, "group": "clippy::restriction", @@ -816,7 +816,7 @@ { "id": "empty_enum", "id_span": { - "path": "clippy_lints/src/empty_enum.rs", + "path": "src/empty_enum.rs", "line": 38 }, "group": "clippy::pedantic", @@ -829,7 +829,7 @@ { "id": "map_entry", "id_span": { - "path": "clippy_lints/src/entry.rs", + "path": "src/entry.rs", "line": 48 }, "group": "clippy::perf", @@ -842,7 +842,7 @@ { "id": "enum_clike_unportable_variant", "id_span": { - "path": "clippy_lints/src/enum_clike.rs", + "path": "src/enum_clike.rs", "line": 31 }, "group": "clippy::correctness", @@ -855,7 +855,7 @@ { "id": "enum_variant_names", "id_span": { - "path": "clippy_lints/src/enum_variants.rs", + "path": "src/enum_variants.rs", "line": 36 }, "group": "clippy::style", @@ -865,7 +865,7 @@ { "id": "pub_enum_variant_names", "id_span": { - "path": "clippy_lints/src/enum_variants.rs", + "path": "src/enum_variants.rs", "line": 66 }, "group": "clippy::pedantic", @@ -875,7 +875,7 @@ { "id": "module_name_repetitions", "id_span": { - "path": "clippy_lints/src/enum_variants.rs", + "path": "src/enum_variants.rs", "line": 91 }, "group": "clippy::pedantic", @@ -888,7 +888,7 @@ { "id": "module_inception", "id_span": { - "path": "clippy_lints/src/enum_variants.rs", + "path": "src/enum_variants.rs", "line": 121 }, "group": "clippy::style", @@ -901,7 +901,7 @@ { "id": "eq_op", "id_span": { - "path": "clippy_lints/src/eq_op.rs", + "path": "src/eq_op.rs", "line": 34 }, "group": "clippy::correctness", @@ -914,7 +914,7 @@ { "id": "op_ref", "id_span": { - "path": "clippy_lints/src/eq_op.rs", + "path": "src/eq_op.rs", "line": 56 }, "group": "clippy::style", @@ -927,7 +927,7 @@ { "id": "erasing_op", "id_span": { - "path": "clippy_lints/src/erasing_op.rs", + "path": "src/erasing_op.rs", "line": 25 }, "group": "clippy::correctness", @@ -940,7 +940,7 @@ { "id": "boxed_local", "id_span": { - "path": "clippy_lints/src/escape.rs", + "path": "src/escape.rs", "line": 43 }, "group": "clippy::perf", @@ -953,7 +953,7 @@ { "id": "redundant_closure", "id_span": { - "path": "clippy_lints/src/eta_reduction.rs", + "path": "src/eta_reduction.rs", "line": 37 }, "group": "clippy::style", @@ -966,7 +966,7 @@ { "id": "redundant_closure_for_method_calls", "id_span": { - "path": "clippy_lints/src/eta_reduction.rs", + "path": "src/eta_reduction.rs", "line": 61 }, "group": "clippy::pedantic", @@ -979,7 +979,7 @@ { "id": "eval_order_dependence", "id_span": { - "path": "clippy_lints/src/eval_order_dependence.rs", + "path": "src/eval_order_dependence.rs", "line": 38 }, "group": "clippy::complexity", @@ -992,7 +992,7 @@ { "id": "diverging_sub_expression", "id_span": { - "path": "clippy_lints/src/eval_order_dependence.rs", + "path": "src/eval_order_dependence.rs", "line": 62 }, "group": "clippy::complexity", @@ -1005,7 +1005,7 @@ { "id": "struct_excessive_bools", "id_span": { - "path": "clippy_lints/src/excessive_bools.rs", + "path": "src/excessive_bools.rs", "line": 40 }, "group": "clippy::pedantic", @@ -1018,7 +1018,7 @@ { "id": "fn_params_excessive_bools", "id_span": { - "path": "clippy_lints/src/excessive_bools.rs", + "path": "src/excessive_bools.rs", "line": 78 }, "group": "clippy::pedantic", @@ -1031,27 +1031,33 @@ { "id": "exhaustive_enums", "id_span": { - "path": "clippy_lints/src/exhaustive_items.rs", + "path": "src/exhaustive_items.rs", "line": 34 }, "group": "clippy::restriction", "docs": " **What it does:** Warns on any exported `enum`s that are not tagged `#[non_exhaustive]`\n **Why is this bad?** Exhaustive enums are typically fine, but a project which does\n not wish to make a stability commitment around exported enums may wish to\n disable them by default.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n enum Foo {\n Bar,\n Baz\n }\n ```\n Use instead:\n ```rust\n #[non_exhaustive]\n enum Foo {\n Bar,\n Baz\n }\n ```\n", - "applicability": null + "applicability": { + "is_multi_suggestion": false, + "applicability": "MaybeIncorrect" + } }, { "id": "exhaustive_structs", "id_span": { - "path": "clippy_lints/src/exhaustive_items.rs", + "path": "src/exhaustive_items.rs", "line": 64 }, "group": "clippy::restriction", "docs": " **What it does:** Warns on any exported `structs`s that are not tagged `#[non_exhaustive]`\n **Why is this bad?** Exhaustive structs are typically fine, but a project which does\n not wish to make a stability commitment around exported structs may wish to\n disable them by default.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n struct Foo {\n bar: u8,\n baz: String,\n }\n ```\n Use instead:\n ```rust\n #[non_exhaustive]\n struct Foo {\n bar: u8,\n baz: String,\n }\n ```\n", - "applicability": null + "applicability": { + "is_multi_suggestion": false, + "applicability": "MaybeIncorrect" + } }, { "id": "exit", "id_span": { - "path": "clippy_lints/src/exit.rs", + "path": "src/exit.rs", "line": 20 }, "group": "clippy::restriction", @@ -1064,7 +1070,7 @@ { "id": "explicit_write", "id_span": { - "path": "clippy_lints/src/explicit_write.rs", + "path": "src/explicit_write.rs", "line": 25 }, "group": "clippy::complexity", @@ -1077,7 +1083,7 @@ { "id": "fallible_impl_from", "id_span": { - "path": "clippy_lints/src/fallible_impl_from.rs", + "path": "src/fallible_impl_from.rs", "line": 45 }, "group": "clippy::nursery", @@ -1090,7 +1096,7 @@ { "id": "float_equality_without_abs", "id_span": { - "path": "clippy_lints/src/float_equality_without_abs.rs", + "path": "src/float_equality_without_abs.rs", "line": 37 }, "group": "clippy::correctness", @@ -1103,7 +1109,7 @@ { "id": "excessive_precision", "id_span": { - "path": "clippy_lints/src/float_literal.rs", + "path": "src/float_literal.rs", "line": 30 }, "group": "clippy::style", @@ -1116,7 +1122,7 @@ { "id": "lossy_float_literal", "id_span": { - "path": "clippy_lints/src/float_literal.rs", + "path": "src/float_literal.rs", "line": 54 }, "group": "clippy::restriction", @@ -1129,7 +1135,7 @@ { "id": "imprecise_flops", "id_span": { - "path": "clippy_lints/src/floating_point_arithmetic.rs", + "path": "src/floating_point_arithmetic.rs", "line": 45 }, "group": "clippy::nursery", @@ -1142,7 +1148,7 @@ { "id": "suboptimal_flops", "id_span": { - "path": "clippy_lints/src/floating_point_arithmetic.rs", + "path": "src/floating_point_arithmetic.rs", "line": 102 }, "group": "clippy::nursery", @@ -1155,7 +1161,7 @@ { "id": "useless_format", "id_span": { - "path": "clippy_lints/src/format.rs", + "path": "src/format.rs", "line": 37 }, "group": "clippy::complexity", @@ -1168,7 +1174,7 @@ { "id": "suspicious_assignment_formatting", "id_span": { - "path": "clippy_lints/src/formatting.rs", + "path": "src/formatting.rs", "line": 22 }, "group": "clippy::style", @@ -1181,7 +1187,7 @@ { "id": "suspicious_unary_op_formatting", "id_span": { - "path": "clippy_lints/src/formatting.rs", + "path": "src/formatting.rs", "line": 44 }, "group": "clippy::style", @@ -1194,7 +1200,7 @@ { "id": "suspicious_else_formatting", "id_span": { - "path": "clippy_lints/src/formatting.rs", + "path": "src/formatting.rs", "line": 80 }, "group": "clippy::style", @@ -1207,7 +1213,7 @@ { "id": "possible_missing_comma", "id_span": { - "path": "clippy_lints/src/formatting.rs", + "path": "src/formatting.rs", "line": 100 }, "group": "clippy::correctness", @@ -1220,7 +1226,7 @@ { "id": "from_over_into", "id_span": { - "path": "clippy_lints/src/from_over_into.rs", + "path": "src/from_over_into.rs", "line": 39 }, "group": "clippy::style", @@ -1233,7 +1239,7 @@ { "id": "from_str_radix_10", "id_span": { - "path": "clippy_lints/src/from_str_radix_10.rs", + "path": "src/from_str_radix_10.rs", "line": 37 }, "group": "clippy::style", @@ -1246,7 +1252,7 @@ { "id": "too_many_arguments", "id_span": { - "path": "clippy_lints/src/functions.rs", + "path": "src/functions.rs", "line": 39 }, "group": "clippy::complexity", @@ -1259,7 +1265,7 @@ { "id": "too_many_lines", "id_span": { - "path": "clippy_lints/src/functions.rs", + "path": "src/functions.rs", "line": 62 }, "group": "clippy::pedantic", @@ -1272,7 +1278,7 @@ { "id": "not_unsafe_ptr_arg_deref", "id_span": { - "path": "clippy_lints/src/functions.rs", + "path": "src/functions.rs", "line": 96 }, "group": "clippy::correctness", @@ -1285,7 +1291,7 @@ { "id": "must_use_unit", "id_span": { - "path": "clippy_lints/src/functions.rs", + "path": "src/functions.rs", "line": 117 }, "group": "clippy::style", @@ -1298,7 +1304,7 @@ { "id": "double_must_use", "id_span": { - "path": "clippy_lints/src/functions.rs", + "path": "src/functions.rs", "line": 142 }, "group": "clippy::style", @@ -1311,7 +1317,7 @@ { "id": "must_use_candidate", "id_span": { - "path": "clippy_lints/src/functions.rs", + "path": "src/functions.rs", "line": 170 }, "group": "clippy::pedantic", @@ -1324,7 +1330,7 @@ { "id": "result_unit_err", "id_span": { - "path": "clippy_lints/src/functions.rs", + "path": "src/functions.rs", "line": 216 }, "group": "clippy::style", @@ -1337,7 +1343,7 @@ { "id": "future_not_send", "id_span": { - "path": "clippy_lints/src/future_not_send.rs", + "path": "src/future_not_send.rs", "line": 44 }, "group": "clippy::nursery", @@ -1350,7 +1356,7 @@ { "id": "get_last_with_len", "id_span": { - "path": "clippy_lints/src/get_last_with_len.rs", + "path": "src/get_last_with_len.rs", "line": 40 }, "group": "clippy::complexity", @@ -1363,7 +1369,7 @@ { "id": "identity_op", "id_span": { - "path": "clippy_lints/src/identity_op.rs", + "path": "src/identity_op.rs", "line": 24 }, "group": "clippy::complexity", @@ -1376,7 +1382,7 @@ { "id": "if_let_mutex", "id_span": { - "path": "clippy_lints/src/if_let_mutex.rs", + "path": "src/if_let_mutex.rs", "line": 36 }, "group": "clippy::correctness", @@ -1389,7 +1395,7 @@ { "id": "if_let_some_result", "id_span": { - "path": "clippy_lints/src/if_let_some_result.rs", + "path": "src/if_let_some_result.rs", "line": 34 }, "group": "clippy::style", @@ -1402,7 +1408,7 @@ { "id": "if_not_else", "id_span": { - "path": "clippy_lints/src/if_not_else.rs", + "path": "src/if_not_else.rs", "line": 43 }, "group": "clippy::pedantic", @@ -1415,7 +1421,7 @@ { "id": "implicit_return", "id_span": { - "path": "clippy_lints/src/implicit_return.rs", + "path": "src/implicit_return.rs", "line": 33 }, "group": "clippy::restriction", @@ -1428,7 +1434,7 @@ { "id": "implicit_saturating_sub", "id_span": { - "path": "clippy_lints/src/implicit_saturating_sub.rs", + "path": "src/implicit_saturating_sub.rs", "line": 32 }, "group": "clippy::pedantic", @@ -1441,7 +1447,7 @@ { "id": "inconsistent_struct_constructor", "id_span": { - "path": "clippy_lints/src/inconsistent_struct_constructor.rs", + "path": "src/inconsistent_struct_constructor.rs", "line": 58 }, "group": "clippy::style", @@ -1454,7 +1460,7 @@ { "id": "out_of_bounds_indexing", "id_span": { - "path": "clippy_lints/src/indexing_slicing.rs", + "path": "src/indexing_slicing.rs", "line": 32 }, "group": "clippy::correctness", @@ -1467,7 +1473,7 @@ { "id": "indexing_slicing", "id_span": { - "path": "clippy_lints/src/indexing_slicing.rs", + "path": "src/indexing_slicing.rs", "line": 81 }, "group": "clippy::restriction", @@ -1480,27 +1486,33 @@ { "id": "infinite_iter", "id_span": { - "path": "clippy_lints/src/infinite_iter.rs", + "path": "src/infinite_iter.rs", "line": 21 }, "group": "clippy::correctness", "docs": " **What it does:** Checks for iteration that is guaranteed to be infinite.\n **Why is this bad?** While there may be places where this is acceptable\n (e.g., in event streams), in most cases this is simply an error.\n\n **Known problems:** None.\n\n **Example:**\n ```no_run\n use std::iter;\n\n iter::repeat(1_u8).collect::>();\n ```\n", - "applicability": null + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } }, { "id": "maybe_infinite_iter", "id_span": { - "path": "clippy_lints/src/infinite_iter.rs", + "path": "src/infinite_iter.rs", "line": 40 }, "group": "clippy::pedantic", "docs": " **What it does:** Checks for iteration that may be infinite.\n **Why is this bad?** While there may be places where this is acceptable\n (e.g., in event streams), in most cases this is simply an error.\n\n **Known problems:** The code may have a condition to stop iteration, but\n this lint is not clever enough to analyze it.\n\n **Example:**\n ```rust\n let infinite_iter = 0..;\n [0..].iter().zip(infinite_iter.take_while(|x| *x > 5));\n ```\n", - "applicability": null + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } }, { "id": "multiple_inherent_impl", "id_span": { - "path": "clippy_lints/src/inherent_impl.rs", + "path": "src/inherent_impl.rs", "line": 37 }, "group": "clippy::restriction", @@ -1513,7 +1525,7 @@ { "id": "inherent_to_string", "id_span": { - "path": "clippy_lints/src/inherent_to_string.rs", + "path": "src/inherent_to_string.rs", "line": 44 }, "group": "clippy::style", @@ -1526,7 +1538,7 @@ { "id": "inherent_to_string_shadow_display", "id_span": { - "path": "clippy_lints/src/inherent_to_string.rs", + "path": "src/inherent_to_string.rs", "line": 89 }, "group": "clippy::correctness", @@ -1539,7 +1551,7 @@ { "id": "inline_fn_without_body", "id_span": { - "path": "clippy_lints/src/inline_fn_without_body.rs", + "path": "src/inline_fn_without_body.rs", "line": 27 }, "group": "clippy::correctness", @@ -1552,7 +1564,7 @@ { "id": "int_plus_one", "id_span": { - "path": "clippy_lints/src/int_plus_one.rs", + "path": "src/int_plus_one.rs", "line": 31 }, "group": "clippy::complexity", @@ -1565,7 +1577,7 @@ { "id": "integer_division", "id_span": { - "path": "clippy_lints/src/integer_division.rs", + "path": "src/integer_division.rs", "line": 26 }, "group": "clippy::restriction", @@ -1578,7 +1590,7 @@ { "id": "items_after_statements", "id_span": { - "path": "clippy_lints/src/items_after_statements.rs", + "path": "src/items_after_statements.rs", "line": 48 }, "group": "clippy::pedantic", @@ -1591,7 +1603,7 @@ { "id": "large_const_arrays", "id_span": { - "path": "clippy_lints/src/large_const_arrays.rs", + "path": "src/large_const_arrays.rs", "line": 30 }, "group": "clippy::perf", @@ -1604,7 +1616,7 @@ { "id": "large_enum_variant", "id_span": { - "path": "clippy_lints/src/large_enum_variant.rs", + "path": "src/large_enum_variant.rs", "line": 39 }, "group": "clippy::perf", @@ -1617,7 +1629,7 @@ { "id": "large_stack_arrays", "id_span": { - "path": "clippy_lints/src/large_stack_arrays.rs", + "path": "src/large_stack_arrays.rs", "line": 23 }, "group": "clippy::pedantic", @@ -1630,7 +1642,7 @@ { "id": "len_zero", "id_span": { - "path": "clippy_lints/src/len_zero.rs", + "path": "src/len_zero.rs", "line": 41 }, "group": "clippy::style", @@ -1643,7 +1655,7 @@ { "id": "len_without_is_empty", "id_span": { - "path": "clippy_lints/src/len_zero.rs", + "path": "src/len_zero.rs", "line": 66 }, "group": "clippy::style", @@ -1656,7 +1668,7 @@ { "id": "comparison_to_empty", "id_span": { - "path": "clippy_lints/src/len_zero.rs", + "path": "src/len_zero.rs", "line": 103 }, "group": "clippy::style", @@ -1669,7 +1681,7 @@ { "id": "useless_let_if_seq", "id_span": { - "path": "clippy_lints/src/let_if_seq.rs", + "path": "src/let_if_seq.rs", "line": 49 }, "group": "clippy::nursery", @@ -1682,7 +1694,7 @@ { "id": "let_underscore_must_use", "id_span": { - "path": "clippy_lints/src/let_underscore.rs", + "path": "src/let_underscore.rs", "line": 29 }, "group": "clippy::restriction", @@ -1695,7 +1707,7 @@ { "id": "let_underscore_lock", "id_span": { - "path": "clippy_lints/src/let_underscore.rs", + "path": "src/let_underscore.rs", "line": 56 }, "group": "clippy::correctness", @@ -1708,7 +1720,7 @@ { "id": "let_underscore_drop", "id_span": { - "path": "clippy_lints/src/let_underscore.rs", + "path": "src/let_underscore.rs", "line": 97 }, "group": "clippy::pedantic", @@ -1721,7 +1733,7 @@ { "id": "needless_lifetimes", "id_span": { - "path": "clippy_lints/src/lifetimes.rs", + "path": "src/lifetimes.rs", "line": 46 }, "group": "clippy::complexity", @@ -1734,7 +1746,7 @@ { "id": "extra_unused_lifetimes", "id_span": { - "path": "clippy_lints/src/lifetimes.rs", + "path": "src/lifetimes.rs", "line": 74 }, "group": "clippy::complexity", @@ -1747,7 +1759,7 @@ { "id": "unreadable_literal", "id_span": { - "path": "clippy_lints/src/literal_representation.rs", + "path": "src/literal_representation.rs", "line": 33 }, "group": "clippy::pedantic", @@ -1760,7 +1772,7 @@ { "id": "mistyped_literal_suffixes", "id_span": { - "path": "clippy_lints/src/literal_representation.rs", + "path": "src/literal_representation.rs", "line": 57 }, "group": "clippy::correctness", @@ -1773,7 +1785,7 @@ { "id": "inconsistent_digit_grouping", "id_span": { - "path": "clippy_lints/src/literal_representation.rs", + "path": "src/literal_representation.rs", "line": 80 }, "group": "clippy::style", @@ -1786,7 +1798,7 @@ { "id": "unusual_byte_groupings", "id_span": { - "path": "clippy_lints/src/literal_representation.rs", + "path": "src/literal_representation.rs", "line": 99 }, "group": "clippy::style", @@ -1799,7 +1811,7 @@ { "id": "large_digit_groups", "id_span": { - "path": "clippy_lints/src/literal_representation.rs", + "path": "src/literal_representation.rs", "line": 118 }, "group": "clippy::pedantic", @@ -1812,7 +1824,7 @@ { "id": "decimal_literal_representation", "id_span": { - "path": "clippy_lints/src/literal_representation.rs", + "path": "src/literal_representation.rs", "line": 136 }, "group": "clippy::restriction", @@ -1825,8 +1837,8 @@ { "id": "manual_memcpy", "id_span": { - "path": "clippy_lints/src/loops.rs", - "line": 57 + "path": "src/loops/mod.rs", + "line": 50 }, "group": "clippy::perf", "docs": " **What it does:** Checks for for-loops that manually copy items between slices that could be optimized by having a memcpy.\n\n **Why is this bad?** It is not as fast as a memcpy.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let src = vec![1];\n # let mut dst = vec![0; 65];\n for i in 0..src.len() {\n dst[i + 64] = src[i];\n }\n ```\n Could be written as:\n ```rust\n # let src = vec![1];\n # let mut dst = vec![0; 65];\n dst[64..(src.len() + 64)].clone_from_slice(&src[..]);\n ```\n", @@ -1838,8 +1850,8 @@ { "id": "needless_range_loop", "id_span": { - "path": "clippy_lints/src/loops.rs", - "line": 85 + "path": "src/loops/mod.rs", + "line": 78 }, "group": "clippy::style", "docs": " **What it does:** Checks for looping over the range of `0..len` of some collection just to get the values by index.\n\n **Why is this bad?** Just iterating the collection itself makes the intent\n more clear and is probably faster.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let vec = vec!['a', 'b', 'c'];\n for i in 0..vec.len() {\n println!(\"{}\", vec[i]);\n }\n ```\n Could be written as:\n ```rust\n let vec = vec!['a', 'b', 'c'];\n for i in vec {\n println!(\"{}\", i);\n }\n ```\n", @@ -1851,8 +1863,8 @@ { "id": "explicit_iter_loop", "id_span": { - "path": "clippy_lints/src/loops.rs", - "line": 114 + "path": "src/loops/mod.rs", + "line": 107 }, "group": "clippy::pedantic", "docs": " **What it does:** Checks for loops on `x.iter()` where `&x` will do, and suggests the latter.\n\n **Why is this bad?** Readability.\n\n **Known problems:** False negatives. We currently only warn on some known\n types.\n\n **Example:**\n ```rust\n // with `y` a `Vec` or slice:\n # let y = vec![1];\n for x in y.iter() {\n // ..\n }\n ```\n can be rewritten to\n ```rust\n # let y = vec![1];\n for x in &y {\n // ..\n }\n ```\n", @@ -1864,8 +1876,8 @@ { "id": "explicit_into_iter_loop", "id_span": { - "path": "clippy_lints/src/loops.rs", - "line": 142 + "path": "src/loops/mod.rs", + "line": 135 }, "group": "clippy::pedantic", "docs": " **What it does:** Checks for loops on `y.into_iter()` where `y` will do, and suggests the latter.\n\n **Why is this bad?** Readability.\n\n **Known problems:** None\n\n **Example:**\n ```rust\n # let y = vec![1];\n // with `y` a `Vec` or slice:\n for x in y.into_iter() {\n // ..\n }\n ```\n can be rewritten to\n ```rust\n # let y = vec![1];\n for x in y {\n // ..\n }\n ```\n", @@ -1877,8 +1889,8 @@ { "id": "iter_next_loop", "id_span": { - "path": "clippy_lints/src/loops.rs", - "line": 165 + "path": "src/loops/mod.rs", + "line": 158 }, "group": "clippy::correctness", "docs": " **What it does:** Checks for loops on `x.next()`.\n **Why is this bad?** `next()` returns either `Some(value)` if there was a\n value, or `None` otherwise. The insidious thing is that `Option<_>`\n implements `IntoIterator`, so that possibly one value will be iterated,\n leading to some hard to find bugs. No one will want to write such code\n [except to win an Underhanded Rust\n Contest](https://www.reddit.com/r/rust/comments/3hb0wm/underhanded_rust_contest/cu5yuhr).\n\n **Known problems:** None.\n\n **Example:**\n ```ignore\n for x in y.next() {\n ..\n }\n ```\n", @@ -1890,8 +1902,8 @@ { "id": "for_loops_over_fallibles", "id_span": { - "path": "clippy_lints/src/loops.rs", - "line": 208 + "path": "src/loops/mod.rs", + "line": 201 }, "group": "clippy::correctness", "docs": " **What it does:** Checks for `for` loops over `Option` or `Result` values.\n **Why is this bad?** Readability. This is more clearly expressed as an `if\n let`.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let opt = Some(1);\n\n // Bad\n for x in opt {\n // ..\n }\n\n // Good\n if let Some(x) = opt {\n // ..\n }\n ```\n\n // or\n\n ```rust\n # let res: Result = Ok(1);\n\n // Bad\n for x in &res {\n // ..\n }\n\n // Good\n if let Ok(x) = res {\n // ..\n }\n ```\n", @@ -1903,8 +1915,8 @@ { "id": "while_let_loop", "id_span": { - "path": "clippy_lints/src/loops.rs", - "line": 237 + "path": "src/loops/mod.rs", + "line": 230 }, "group": "clippy::complexity", "docs": " **What it does:** Detects `loop + match` combinations that are easier written as a `while let` loop.\n\n **Why is this bad?** The `while let` loop is usually shorter and more\n readable.\n\n **Known problems:** Sometimes the wrong binding is displayed ([#383](https://github.com/rust-lang/rust-clippy/issues/383)).\n\n **Example:**\n ```rust,no_run\n # let y = Some(1);\n loop {\n let x = match y {\n Some(x) => x,\n None => break,\n };\n // .. do something with x\n }\n // is easier written as\n while let Some(x) = y {\n // .. do something with x\n };\n ```\n", @@ -1916,8 +1928,8 @@ { "id": "needless_collect", "id_span": { - "path": "clippy_lints/src/loops.rs", - "line": 259 + "path": "src/loops/mod.rs", + "line": 252 }, "group": "clippy::perf", "docs": " **What it does:** Checks for functions collecting an iterator when collect is not needed.\n\n **Why is this bad?** `collect` causes the allocation of a new data structure,\n when this allocation may not be needed.\n\n **Known problems:**\n None\n\n **Example:**\n ```rust\n # let iterator = vec![1].into_iter();\n let len = iterator.clone().collect::>().len();\n // should be\n let len = iterator.count();\n ```\n", @@ -1929,8 +1941,8 @@ { "id": "explicit_counter_loop", "id_span": { - "path": "clippy_lints/src/loops.rs", - "line": 289 + "path": "src/loops/mod.rs", + "line": 282 }, "group": "clippy::complexity", "docs": " **What it does:** Checks `for` loops over slices with an explicit counter and suggests the use of `.enumerate()`.\n\n **Why is it bad?** Using `.enumerate()` makes the intent more clear,\n declutters the code and may be faster in some instances.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let v = vec![1];\n # fn bar(bar: usize, baz: usize) {}\n let mut i = 0;\n for item in &v {\n bar(i, *item);\n i += 1;\n }\n ```\n Could be written as\n ```rust\n # let v = vec![1];\n # fn bar(bar: usize, baz: usize) {}\n for (i, item) in v.iter().enumerate() { bar(i, *item); }\n ```\n", @@ -1942,8 +1954,8 @@ { "id": "empty_loop", "id_span": { - "path": "clippy_lints/src/loops.rs", - "line": 322 + "path": "src/loops/mod.rs", + "line": 315 }, "group": "clippy::style", "docs": " **What it does:** Checks for empty `loop` expressions.\n **Why is this bad?** These busy loops burn CPU cycles without doing\n anything. It is _almost always_ a better idea to `panic!` than to have\n a busy loop.\n\n If panicking isn't possible, think of the environment and either:\n - block on something\n - sleep the thread for some microseconds\n - yield or pause the thread\n\n For `std` targets, this can be done with\n [`std::thread::sleep`](https://doc.rust-lang.org/std/thread/fn.sleep.html)\n or [`std::thread::yield_now`](https://doc.rust-lang.org/std/thread/fn.yield_now.html).\n\n For `no_std` targets, doing this is more complicated, especially because\n `#[panic_handler]`s can't panic. To stop/pause the thread, you will\n probably need to invoke some target-specific intrinsic. Examples include:\n - [`x86_64::instructions::hlt`](https://docs.rs/x86_64/0.12.2/x86_64/instructions/fn.hlt.html)\n - [`cortex_m::asm::wfi`](https://docs.rs/cortex-m/0.6.3/cortex_m/asm/fn.wfi.html)\n\n **Known problems:** None.\n\n **Example:**\n ```no_run\n loop {}\n ```\n", @@ -1955,8 +1967,8 @@ { "id": "while_let_on_iterator", "id_span": { - "path": "clippy_lints/src/loops.rs", - "line": 341 + "path": "src/loops/mod.rs", + "line": 334 }, "group": "clippy::style", "docs": " **What it does:** Checks for `while let` expressions on iterators.\n **Why is this bad?** Readability. A simple `for` loop is shorter and conveys\n the intent better.\n\n **Known problems:** None.\n\n **Example:**\n ```ignore\n while let Some(val) = iter() {\n ..\n }\n ```\n", @@ -1968,8 +1980,8 @@ { "id": "for_kv_map", "id_span": { - "path": "clippy_lints/src/loops.rs", - "line": 369 + "path": "src/loops/mod.rs", + "line": 362 }, "group": "clippy::style", "docs": " **What it does:** Checks for iterating a map (`HashMap` or `BTreeMap`) and ignoring either the keys or values.\n\n **Why is this bad?** Readability. There are `keys` and `values` methods that\n can be used to express that don't need the values or keys.\n\n **Known problems:** None.\n\n **Example:**\n ```ignore\n for (k, _) in &map {\n ..\n }\n ```\n\n could be replaced by\n\n ```ignore\n for k in map.keys() {\n ..\n }\n ```\n", @@ -1981,8 +1993,8 @@ { "id": "never_loop", "id_span": { - "path": "clippy_lints/src/loops.rs", - "line": 390 + "path": "src/loops/mod.rs", + "line": 383 }, "group": "clippy::correctness", "docs": " **What it does:** Checks for loops that will always `break`, `return` or `continue` an outer loop.\n\n **Why is this bad?** This loop never loops, all it does is obfuscating the\n code.\n\n **Known problems:** None\n\n **Example:**\n ```rust\n loop {\n ..;\n break;\n }\n ```\n", @@ -1994,8 +2006,8 @@ { "id": "mut_range_bound", "id_span": { - "path": "clippy_lints/src/loops.rs", - "line": 410 + "path": "src/loops/mod.rs", + "line": 403 }, "group": "clippy::complexity", "docs": " **What it does:** Checks for loops which have a range bound that is a mutable variable\n **Why is this bad?** One might think that modifying the mutable variable changes the loop bounds\n\n **Known problems:** None\n\n **Example:**\n ```rust\n let mut foo = 42;\n for i in 0..foo {\n foo -= 1;\n println!(\"{}\", i); // prints numbers from 0 to 42, not 0 to 21\n }\n ```\n", @@ -2007,8 +2019,8 @@ { "id": "while_immutable_condition", "id_span": { - "path": "clippy_lints/src/loops.rs", - "line": 433 + "path": "src/loops/mod.rs", + "line": 426 }, "group": "clippy::correctness", "docs": " **What it does:** Checks whether variables used within while loop condition can be (and are) mutated in the body.\n\n **Why is this bad?** If the condition is unchanged, entering the body of the loop\n will lead to an infinite loop.\n\n **Known problems:** If the `while`-loop is in a closure, the check for mutation of the\n condition variables in the body can cause false negatives. For example when only `Upvar` `a` is\n in the condition and only `Upvar` `b` gets mutated in the body, the lint will not trigger.\n\n **Example:**\n ```rust\n let i = 0;\n while i > 10 {\n println!(\"let me loop forever!\");\n }\n ```\n", @@ -2020,8 +2032,8 @@ { "id": "same_item_push", "id_span": { - "path": "clippy_lints/src/loops.rs", - "line": 466 + "path": "src/loops/mod.rs", + "line": 459 }, "group": "clippy::style", "docs": " **What it does:** Checks whether a for loop is being used to push a constant value into a Vec.\n\n **Why is this bad?** This kind of operation can be expressed more succinctly with\n `vec![item;SIZE]` or `vec.resize(NEW_SIZE, item)` and using these alternatives may also\n have better performance.\n **Known problems:** None\n\n **Example:**\n ```rust\n let item1 = 2;\n let item2 = 3;\n let mut vec: Vec = Vec::new();\n for _ in 0..20 {\n vec.push(item1);\n }\n for _ in 0..30 {\n vec.push(item2);\n }\n ```\n could be written as\n ```rust\n let item1 = 2;\n let item2 = 3;\n let mut vec: Vec = vec![item1; 20];\n vec.resize(20 + 30, item2);\n ```\n", @@ -2033,8 +2045,8 @@ { "id": "single_element_loop", "id_span": { - "path": "clippy_lints/src/loops.rs", - "line": 491 + "path": "src/loops/mod.rs", + "line": 484 }, "group": "clippy::complexity", "docs": " **What it does:** Checks whether a for loop has a single element.\n **Why is this bad?** There is no reason to have a loop of a\n single element.\n **Known problems:** None\n\n **Example:**\n ```rust\n let item1 = 2;\n for item in &[item1] {\n println!(\"{}\", item);\n }\n ```\n could be written as\n ```rust\n let item1 = 2;\n let item = &item1;\n println!(\"{}\", item);\n ```\n", @@ -2046,8 +2058,8 @@ { "id": "manual_flatten", "id_span": { - "path": "clippy_lints/src/loops.rs", - "line": 522 + "path": "src/loops/mod.rs", + "line": 515 }, "group": "clippy::complexity", "docs": " **What it does:** Check for unnecessary `if let` usage in a for loop where only the `Some` or `Ok` variant of the iterator element is used.\n\n **Why is this bad?** It is verbose and can be simplified\n by first calling the `flatten` method on the `Iterator`.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n let x = vec![Some(1), Some(2), Some(3)];\n for n in x {\n if let Some(n) = n {\n println!(\"{}\", n);\n }\n }\n ```\n Use instead:\n ```rust\n let x = vec![Some(1), Some(2), Some(3)];\n for n in x.into_iter().flatten() {\n println!(\"{}\", n);\n }\n ```\n", @@ -2059,7 +2071,7 @@ { "id": "macro_use_imports", "id_span": { - "path": "clippy_lints/src/macro_use.rs", + "path": "src/macro_use.rs", "line": 25 }, "group": "clippy::pedantic", @@ -2072,7 +2084,7 @@ { "id": "main_recursion", "id_span": { - "path": "clippy_lints/src/main_recursion.rs", + "path": "src/main_recursion.rs", "line": 22 }, "group": "clippy::style", @@ -2085,7 +2097,7 @@ { "id": "manual_async_fn", "id_span": { - "path": "clippy_lints/src/manual_async_fn.rs", + "path": "src/manual_async_fn.rs", "line": 32 }, "group": "clippy::style", @@ -2098,11 +2110,11 @@ { "id": "manual_map", "id_span": { - "path": "clippy_lints/src/manual_map.rs", - "line": 36 + "path": "src/manual_map.rs", + "line": 44 }, - "group": "clippy::nursery", - "docs": " **What it does:** Checks for usages of `match` which could be implemented using `map`\n **Why is this bad?** Using the `map` method is clearer and more concise.\n\n **Known problems:** `map` is not capable of representing some control flow which works fine in `match`.\n\n **Example:**\n\n ```rust\n match Some(0) {\n Some(x) => Some(x + 1),\n None => None,\n };\n ```\n Use instead:\n ```rust\n Some(0).map(|x| x + 1);\n ```\n", + "group": "clippy::style", + "docs": " **What it does:** Checks for usages of `match` which could be implemented using `map`\n **Why is this bad?** Using the `map` method is clearer and more concise.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n match Some(0) {\n Some(x) => Some(x + 1),\n None => None,\n };\n ```\n Use instead:\n ```rust\n Some(0).map(|x| x + 1);\n ```\n", "applicability": { "is_multi_suggestion": false, "applicability": "MachineApplicable" @@ -2111,7 +2123,7 @@ { "id": "manual_non_exhaustive", "id_span": { - "path": "clippy_lints/src/manual_non_exhaustive.rs", + "path": "src/manual_non_exhaustive.rs", "line": 56 }, "group": "clippy::style", @@ -2124,7 +2136,7 @@ { "id": "manual_ok_or", "id_span": { - "path": "clippy_lints/src/manual_ok_or.rs", + "path": "src/manual_ok_or.rs", "line": 34 }, "group": "clippy::pedantic", @@ -2137,7 +2149,7 @@ { "id": "manual_strip", "id_span": { - "path": "clippy_lints/src/manual_strip.rs", + "path": "src/manual_strip.rs", "line": 52 }, "group": "clippy::complexity", @@ -2150,7 +2162,7 @@ { "id": "manual_unwrap_or", "id_span": { - "path": "clippy_lints/src/manual_unwrap_or.rs", + "path": "src/manual_unwrap_or.rs", "line": 36 }, "group": "clippy::complexity", @@ -2163,7 +2175,7 @@ { "id": "map_clone", "id_span": { - "path": "clippy_lints/src/map_clone.rs", + "path": "src/map_clone.rs", "line": 40 }, "group": "clippy::style", @@ -2176,7 +2188,7 @@ { "id": "map_err_ignore", "id_span": { - "path": "clippy_lints/src/map_err_ignore.rs", + "path": "src/map_err_ignore.rs", "line": 101 }, "group": "clippy::restriction", @@ -2189,7 +2201,7 @@ { "id": "map_identity", "id_span": { - "path": "clippy_lints/src/map_identity.rs", + "path": "src/map_identity.rs", "line": 30 }, "group": "clippy::complexity", @@ -2202,27 +2214,33 @@ { "id": "option_map_unit_fn", "id_span": { - "path": "clippy_lints/src/map_unit_fn.rs", + "path": "src/map_unit_fn.rs", "line": 48 }, "group": "clippy::complexity", "docs": " **What it does:** Checks for usage of `option.map(f)` where f is a function or closure that returns the unit type `()`.\n\n **Why is this bad?** Readability, this can be written more clearly with\n an if let statement\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n # fn do_stuff() -> Option { Some(String::new()) }\n # fn log_err_msg(foo: String) -> Option { Some(foo) }\n # fn format_msg(foo: String) -> String { String::new() }\n let x: Option = do_stuff();\n x.map(log_err_msg);\n # let x: Option = do_stuff();\n x.map(|msg| log_err_msg(format_msg(msg)));\n ```\n\n The correct use would be:\n\n ```rust\n # fn do_stuff() -> Option { Some(String::new()) }\n # fn log_err_msg(foo: String) -> Option { Some(foo) }\n # fn format_msg(foo: String) -> String { String::new() }\n let x: Option = do_stuff();\n if let Some(msg) = x {\n log_err_msg(msg);\n }\n\n # let x: Option = do_stuff();\n if let Some(msg) = x {\n log_err_msg(format_msg(msg));\n }\n ```\n", - "applicability": null + "applicability": { + "is_multi_suggestion": true, + "applicability": "MachineApplicable" + } }, { "id": "result_map_unit_fn", "id_span": { - "path": "clippy_lints/src/map_unit_fn.rs", + "path": "src/map_unit_fn.rs", "line": 89 }, "group": "clippy::complexity", "docs": " **What it does:** Checks for usage of `result.map(f)` where f is a function or closure that returns the unit type `()`.\n\n **Why is this bad?** Readability, this can be written more clearly with\n an if let statement\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n # fn do_stuff() -> Result { Ok(String::new()) }\n # fn log_err_msg(foo: String) -> Result { Ok(foo) }\n # fn format_msg(foo: String) -> String { String::new() }\n let x: Result = do_stuff();\n x.map(log_err_msg);\n # let x: Result = do_stuff();\n x.map(|msg| log_err_msg(format_msg(msg)));\n ```\n\n The correct use would be:\n\n ```rust\n # fn do_stuff() -> Result { Ok(String::new()) }\n # fn log_err_msg(foo: String) -> Result { Ok(foo) }\n # fn format_msg(foo: String) -> String { String::new() }\n let x: Result = do_stuff();\n if let Ok(msg) = x {\n log_err_msg(msg);\n };\n # let x: Result = do_stuff();\n if let Ok(msg) = x {\n log_err_msg(format_msg(msg));\n };\n ```\n", - "applicability": null + "applicability": { + "is_multi_suggestion": true, + "applicability": "MachineApplicable" + } }, { "id": "match_on_vec_items", "id_span": { - "path": "clippy_lints/src/match_on_vec_items.rs", + "path": "src/match_on_vec_items.rs", "line": 41 }, "group": "clippy::pedantic", @@ -2235,27 +2253,33 @@ { "id": "single_match", "id_span": { - "path": "clippy_lints/src/matches.rs", + "path": "src/matches.rs", "line": 55 }, "group": "clippy::style", "docs": " **What it does:** Checks for matches with a single arm where an `if let` will usually suffice.\n\n **Why is this bad?** Just readability – `if let` nests less than a `match`.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # fn bar(stool: &str) {}\n # let x = Some(\"abc\");\n // Bad\n match x {\n Some(ref foo) => bar(foo),\n _ => (),\n }\n\n // Good\n if let Some(ref foo) = x {\n bar(foo);\n }\n ```\n", - "applicability": null + "applicability": { + "is_multi_suggestion": false, + "applicability": "HasPlaceholders" + } }, { "id": "single_match_else", "id_span": { - "path": "clippy_lints/src/matches.rs", + "path": "src/matches.rs", "line": 94 }, "group": "clippy::pedantic", "docs": " **What it does:** Checks for matches with two arms where an `if let else` will usually suffice.\n\n **Why is this bad?** Just readability – `if let` nests less than a `match`.\n\n **Known problems:** Personal style preferences may differ.\n\n **Example:**\n\n Using `match`:\n\n ```rust\n # fn bar(foo: &usize) {}\n # let other_ref: usize = 1;\n # let x: Option<&usize> = Some(&1);\n match x {\n Some(ref foo) => bar(foo),\n _ => bar(&other_ref),\n }\n ```\n\n Using `if let` with `else`:\n\n ```rust\n # fn bar(foo: &usize) {}\n # let other_ref: usize = 1;\n # let x: Option<&usize> = Some(&1);\n if let Some(ref foo) = x {\n bar(foo);\n } else {\n bar(&other_ref);\n }\n ```\n", - "applicability": null + "applicability": { + "is_multi_suggestion": false, + "applicability": "HasPlaceholders" + } }, { "id": "match_ref_pats", "id_span": { - "path": "clippy_lints/src/matches.rs", + "path": "src/matches.rs", "line": 125 }, "group": "clippy::style", @@ -2268,7 +2292,7 @@ { "id": "match_bool", "id_span": { - "path": "clippy_lints/src/matches.rs", + "path": "src/matches.rs", "line": 159 }, "group": "clippy::pedantic", @@ -2281,7 +2305,7 @@ { "id": "match_overlapping_arm", "id_span": { - "path": "clippy_lints/src/matches.rs", + "path": "src/matches.rs", "line": 181 }, "group": "clippy::style", @@ -2294,7 +2318,7 @@ { "id": "match_wild_err_arm", "id_span": { - "path": "clippy_lints/src/matches.rs", + "path": "src/matches.rs", "line": 203 }, "group": "clippy::pedantic", @@ -2307,7 +2331,7 @@ { "id": "match_as_ref", "id_span": { - "path": "clippy_lints/src/matches.rs", + "path": "src/matches.rs", "line": 229 }, "group": "clippy::complexity", @@ -2320,7 +2344,7 @@ { "id": "wildcard_enum_match_arm", "id_span": { - "path": "clippy_lints/src/matches.rs", + "path": "src/matches.rs", "line": 258 }, "group": "clippy::restriction", @@ -2333,7 +2357,7 @@ { "id": "match_wildcard_for_single_variants", "id_span": { - "path": "clippy_lints/src/matches.rs", + "path": "src/matches.rs", "line": 290 }, "group": "clippy::pedantic", @@ -2346,7 +2370,7 @@ { "id": "wildcard_in_or_patterns", "id_span": { - "path": "clippy_lints/src/matches.rs", + "path": "src/matches.rs", "line": 317 }, "group": "clippy::complexity", @@ -2359,7 +2383,7 @@ { "id": "infallible_destructuring_match", "id_span": { - "path": "clippy_lints/src/matches.rs", + "path": "src/matches.rs", "line": 352 }, "group": "clippy::style", @@ -2372,7 +2396,7 @@ { "id": "match_single_binding", "id_span": { - "path": "clippy_lints/src/matches.rs", + "path": "src/matches.rs", "line": 380 }, "group": "clippy::complexity", @@ -2385,7 +2409,7 @@ { "id": "rest_pat_in_fully_bound_structs", "id_span": { - "path": "clippy_lints/src/matches.rs", + "path": "src/matches.rs", "line": 410 }, "group": "clippy::restriction", @@ -2398,7 +2422,7 @@ { "id": "redundant_pattern_matching", "id_span": { - "path": "clippy_lints/src/matches.rs", + "path": "src/matches.rs", "line": 458 }, "group": "clippy::style", @@ -2411,7 +2435,7 @@ { "id": "match_like_matches_macro", "id_span": { - "path": "clippy_lints/src/matches.rs", + "path": "src/matches.rs", "line": 491 }, "group": "clippy::style", @@ -2424,7 +2448,7 @@ { "id": "match_same_arms", "id_span": { - "path": "clippy_lints/src/matches.rs", + "path": "src/matches.rs", "line": 532 }, "group": "clippy::pedantic", @@ -2437,7 +2461,7 @@ { "id": "mem_discriminant_non_enum", "id_span": { - "path": "clippy_lints/src/mem_discriminant.rs", + "path": "src/mem_discriminant.rs", "line": 25 }, "group": "clippy::correctness", @@ -2450,7 +2474,7 @@ { "id": "mem_forget", "id_span": { - "path": "clippy_lints/src/mem_forget.rs", + "path": "src/mem_forget.rs", "line": 21 }, "group": "clippy::restriction", @@ -2463,7 +2487,7 @@ { "id": "mem_replace_option_with_none", "id_span": { - "path": "clippy_lints/src/mem_replace.rs", + "path": "src/mem_replace.rs", "line": 37 }, "group": "clippy::style", @@ -2476,7 +2500,7 @@ { "id": "mem_replace_with_uninit", "id_span": { - "path": "clippy_lints/src/mem_replace.rs", + "path": "src/mem_replace.rs", "line": 69 }, "group": "clippy::correctness", @@ -2489,7 +2513,7 @@ { "id": "mem_replace_with_default", "id_span": { - "path": "clippy_lints/src/mem_replace.rs", + "path": "src/mem_replace.rs", "line": 93 }, "group": "clippy::style", @@ -2502,8 +2526,8 @@ { "id": "unwrap_used", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 82 + "path": "src/methods/mod.rs", + "line": 84 }, "group": "clippy::restriction", "docs": " **What it does:** Checks for `.unwrap()` calls on `Option`s and on `Result`s.\n **Why is this bad?** It is better to handle the `None` or `Err` case,\n or at least call `.expect(_)` with a more helpful message. Still, for a lot of\n quick-and-dirty code, `unwrap` is a good choice, which is why this lint is\n `Allow` by default.\n\n `result.unwrap()` will let the thread panic on `Err` values.\n Normally, you want to implement more sophisticated error handling,\n and propagate errors upwards with `?` operator.\n\n Even if you want to panic on errors, not all `Error`s implement good\n messages on display. Therefore, it may be beneficial to look at the places\n where they may get displayed. Activate this lint to do just that.\n\n **Known problems:** None.\n\n **Examples:**\n ```rust\n # let opt = Some(1);\n\n // Bad\n opt.unwrap();\n\n // Good\n opt.expect(\"more helpful message\");\n ```\n\n // or\n\n ```rust\n # let res: Result = Ok(1);\n\n // Bad\n res.unwrap();\n\n // Good\n res.expect(\"more helpful message\");\n ```\n", @@ -2512,8 +2536,8 @@ { "id": "expect_used", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 124 + "path": "src/methods/mod.rs", + "line": 126 }, "group": "clippy::restriction", "docs": " **What it does:** Checks for `.expect()` calls on `Option`s and `Result`s.\n **Why is this bad?** Usually it is better to handle the `None` or `Err` case.\n Still, for a lot of quick-and-dirty code, `expect` is a good choice, which is why\n this lint is `Allow` by default.\n\n `result.expect()` will let the thread panic on `Err`\n values. Normally, you want to implement more sophisticated error handling,\n and propagate errors upwards with `?` operator.\n\n **Known problems:** None.\n\n **Examples:**\n ```rust,ignore\n # let opt = Some(1);\n\n // Bad\n opt.expect(\"one\");\n\n // Good\n let opt = Some(1);\n opt?;\n ```\n\n // or\n\n ```rust\n # let res: Result = Ok(1);\n\n // Bad\n res.expect(\"one\");\n\n // Good\n res?;\n # Ok::<(), ()>(())\n ```\n", @@ -2522,8 +2546,8 @@ { "id": "should_implement_trait", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 153 + "path": "src/methods/mod.rs", + "line": 155 }, "group": "clippy::style", "docs": " **What it does:** Checks for methods that should live in a trait implementation of a `std` trait (see [llogiq's blog\n post](http://llogiq.github.io/2015/07/30/traits.html) for further\n information) instead of an inherent implementation.\n\n **Why is this bad?** Implementing the traits improve ergonomics for users of\n the code, often with very little cost. Also people seeing a `mul(...)`\n method\n may expect `*` to work equally, so you should have good reason to disappoint\n them.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n struct X;\n impl X {\n fn add(&self, other: &X) -> X {\n // ..\n # X\n }\n }\n ```\n", @@ -2535,28 +2559,34 @@ { "id": "wrong_self_convention", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 186 + "path": "src/methods/mod.rs", + "line": 188 }, "group": "clippy::style", "docs": " **What it does:** Checks for methods with certain name prefixes and which doesn't match how self is taken. The actual rules are:\n\n |Prefix |`self` taken |\n |-------|----------------------|\n |`as_` |`&self` or `&mut self`|\n |`from_`| none |\n |`into_`|`self` |\n |`is_` |`&self` or none |\n |`to_` |`&self` |\n\n **Why is this bad?** Consistency breeds readability. If you follow the\n conventions, your users won't be surprised that they, e.g., need to supply a\n mutable reference to a `as_..` function.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # struct X;\n impl X {\n fn as_str(self) -> &'static str {\n // ..\n # \"\"\n }\n }\n ```\n", - "applicability": null + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } }, { "id": "wrong_pub_self_convention", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 210 + "path": "src/methods/mod.rs", + "line": 212 }, "group": "clippy::restriction", "docs": " **What it does:** This is the same as [`wrong_self_convention`](#wrong_self_convention), but for public items.\n\n **Why is this bad?** See [`wrong_self_convention`](#wrong_self_convention).\n\n **Known problems:** Actually *renaming* the function may break clients if\n the function is part of the public interface. In that case, be mindful of\n the stability guarantees you've given your users.\n\n **Example:**\n ```rust\n # struct X;\n impl<'a> X {\n pub fn as_str(self) -> &'a str {\n \"foo\"\n }\n }\n ```\n", - "applicability": null + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } }, { "id": "ok_expect", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 233 + "path": "src/methods/mod.rs", + "line": 235 }, "group": "clippy::style", "docs": " **What it does:** Checks for usage of `ok().expect(..)`.\n **Why is this bad?** Because you usually call `expect()` on the `Result`\n directly to get a better error message.\n\n **Known problems:** The error type needs to implement `Debug`\n\n **Example:**\n ```rust\n # let x = Ok::<_, ()>(());\n\n // Bad\n x.ok().expect(\"why did I do this again?\");\n\n // Good\n x.expect(\"why did I do this again?\");\n ```\n", @@ -2568,8 +2598,8 @@ { "id": "map_unwrap_or", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 270 + "path": "src/methods/mod.rs", + "line": 272 }, "group": "clippy::pedantic", "docs": " **What it does:** Checks for usage of `option.map(_).unwrap_or(_)` or `option.map(_).unwrap_or_else(_)` or `result.map(_).unwrap_or_else(_)`.\n\n **Why is this bad?** Readability, these can be written more concisely (resp.) as\n `option.map_or(_, _)`, `option.map_or_else(_, _)` and `result.map_or_else(_, _)`.\n\n **Known problems:** The order of the arguments is not in execution order\n\n **Examples:**\n ```rust\n # let x = Some(1);\n\n // Bad\n x.map(|a| a + 1).unwrap_or(0);\n\n // Good\n x.map_or(0, |a| a + 1);\n ```\n\n // or\n\n ```rust\n # let x: Result = Ok(1);\n # fn some_function(foo: ()) -> usize { 1 }\n\n // Bad\n x.map(|a| a + 1).unwrap_or_else(some_function);\n\n // Good\n x.map_or_else(some_function, |a| a + 1);\n ```\n", @@ -2581,28 +2611,34 @@ { "id": "option_map_or_none", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 293 + "path": "src/methods/mod.rs", + "line": 295 }, "group": "clippy::style", "docs": " **What it does:** Checks for usage of `_.map_or(None, _)`.\n **Why is this bad?** Readability, this can be written more concisely as\n `_.and_then(_)`.\n\n **Known problems:** The order of the arguments is not in execution order.\n\n **Example:**\n ```rust\n # let opt = Some(1);\n\n // Bad\n opt.map_or(None, |a| Some(a + 1));\n\n // Good\n opt.and_then(|a| Some(a + 1));\n ```\n", - "applicability": null + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } }, { "id": "result_map_or_into_option", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 319 + "path": "src/methods/mod.rs", + "line": 321 }, "group": "clippy::style", "docs": " **What it does:** Checks for usage of `_.map_or(None, Some)`.\n **Why is this bad?** Readability, this can be written more concisely as\n `_.ok()`.\n\n **Known problems:** None.\n\n **Example:**\n\n Bad:\n ```rust\n # let r: Result = Ok(1);\n assert_eq!(Some(1), r.map_or(None, Some));\n ```\n\n Good:\n ```rust\n # let r: Result = Ok(1);\n assert_eq!(Some(1), r.ok());\n ```\n", - "applicability": null + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } }, { "id": "bind_instead_of_map", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 352 + "path": "src/methods/mod.rs", + "line": 354 }, "group": "clippy::complexity", "docs": " **What it does:** Checks for usage of `_.and_then(|x| Some(y))`, `_.and_then(|x| Ok(y))` or `_.or_else(|x| Err(y))`.\n\n **Why is this bad?** Readability, this can be written more concisely as\n `_.map(|x| y)` or `_.map_err(|x| y)`.\n\n **Known problems:** None\n\n **Example:**\n\n ```rust\n # fn opt() -> Option<&'static str> { Some(\"42\") }\n # fn res() -> Result<&'static str, &'static str> { Ok(\"42\") }\n let _ = opt().and_then(|s| Some(s.len()));\n let _ = res().and_then(|s| if s.len() == 42 { Ok(10) } else { Ok(20) });\n let _ = res().or_else(|s| if s.len() == 42 { Err(10) } else { Err(20) });\n ```\n\n The correct use would be:\n\n ```rust\n # fn opt() -> Option<&'static str> { Some(\"42\") }\n # fn res() -> Result<&'static str, &'static str> { Ok(\"42\") }\n let _ = opt().map(|s| s.len());\n let _ = res().map(|s| if s.len() == 42 { 10 } else { 20 });\n let _ = res().map_err(|s| if s.len() == 42 { 10 } else { 20 });\n ```\n", @@ -2614,8 +2650,8 @@ { "id": "filter_next", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 375 + "path": "src/methods/mod.rs", + "line": 377 }, "group": "clippy::complexity", "docs": " **What it does:** Checks for usage of `_.filter(_).next()`.\n **Why is this bad?** Readability, this can be written more concisely as\n `_.find(_)`.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let vec = vec![1];\n vec.iter().filter(|x| **x == 0).next();\n ```\n Could be written as\n ```rust\n # let vec = vec![1];\n vec.iter().find(|x| **x == 0);\n ```\n", @@ -2627,8 +2663,8 @@ { "id": "skip_while_next", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 398 + "path": "src/methods/mod.rs", + "line": 400 }, "group": "clippy::complexity", "docs": " **What it does:** Checks for usage of `_.skip_while(condition).next()`.\n **Why is this bad?** Readability, this can be written more concisely as\n `_.find(!condition)`.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let vec = vec![1];\n vec.iter().skip_while(|x| **x == 0).next();\n ```\n Could be written as\n ```rust\n # let vec = vec![1];\n vec.iter().find(|x| **x != 0);\n ```\n", @@ -2640,8 +2676,8 @@ { "id": "map_flatten", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 421 + "path": "src/methods/mod.rs", + "line": 423 }, "group": "clippy::pedantic", "docs": " **What it does:** Checks for usage of `_.map(_).flatten(_)`,\n **Why is this bad?** Readability, this can be written more concisely as\n `_.flat_map(_)`\n\n **Known problems:**\n\n **Example:**\n ```rust\n let vec = vec![vec![1]];\n\n // Bad\n vec.iter().map(|x| x.iter()).flatten();\n\n // Good\n vec.iter().flat_map(|x| x.iter());\n ```\n", @@ -2653,8 +2689,8 @@ { "id": "filter_map", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 450 + "path": "src/methods/mod.rs", + "line": 452 }, "group": "clippy::pedantic", "docs": " **What it does:** Checks for usage of `_.filter(_).map(_)`, `_.filter(_).flat_map(_)`, `_.filter_map(_).flat_map(_)` and similar.\n\n **Why is this bad?** Readability, this can be written more concisely as\n `_.filter_map(_)`.\n\n **Known problems:** Often requires a condition + Option/Iterator creation\n inside the closure.\n\n **Example:**\n ```rust\n let vec = vec![1];\n\n // Bad\n vec.iter().filter(|x| **x == 0).map(|x| *x * 2);\n\n // Good\n vec.iter().filter_map(|x| if *x == 0 {\n Some(*x * 2)\n } else {\n None\n });\n ```\n", @@ -2666,28 +2702,34 @@ { "id": "manual_filter_map", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 476 + "path": "src/methods/mod.rs", + "line": 478 }, "group": "clippy::complexity", "docs": " **What it does:** Checks for usage of `_.filter(_).map(_)` that can be written more simply as `filter_map(_)`.\n\n **Why is this bad?** Redundant code in the `filter` and `map` operations is poor style and\n less performant.\n\n **Known problems:** None.\n\n **Example:**\n Bad:\n ```rust\n (0_i32..10)\n .filter(|n| n.checked_add(1).is_some())\n .map(|n| n.checked_add(1).unwrap());\n ```\n\n Good:\n ```rust\n (0_i32..10).filter_map(|n| n.checked_add(1));\n ```\n", - "applicability": null + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } }, { "id": "manual_find_map", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 502 + "path": "src/methods/mod.rs", + "line": 504 }, "group": "clippy::complexity", "docs": " **What it does:** Checks for usage of `_.find(_).map(_)` that can be written more simply as `find_map(_)`.\n\n **Why is this bad?** Redundant code in the `find` and `map` operations is poor style and\n less performant.\n\n **Known problems:** None.\n\n **Example:**\n Bad:\n ```rust\n (0_i32..10)\n .find(|n| n.checked_add(1).is_some())\n .map(|n| n.checked_add(1).unwrap());\n ```\n\n Good:\n ```rust\n (0_i32..10).find_map(|n| n.checked_add(1));\n ```\n", - "applicability": null + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } }, { "id": "filter_map_next", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 524 + "path": "src/methods/mod.rs", + "line": 526 }, "group": "clippy::pedantic", "docs": " **What it does:** Checks for usage of `_.filter_map(_).next()`.\n **Why is this bad?** Readability, this can be written more concisely as\n `_.find_map(_)`.\n\n **Known problems:** None\n\n **Example:**\n ```rust\n (0..3).filter_map(|x| if x == 2 { Some(x) } else { None }).next();\n ```\n Can be written as\n\n ```rust\n (0..3).find_map(|x| if x == 2 { Some(x) } else { None });\n ```\n", @@ -2699,8 +2741,8 @@ { "id": "flat_map_identity", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 546 + "path": "src/methods/mod.rs", + "line": 548 }, "group": "clippy::complexity", "docs": " **What it does:** Checks for usage of `flat_map(|x| x)`.\n **Why is this bad?** Readability, this can be written more concisely by using `flatten`.\n\n **Known problems:** None\n\n **Example:**\n ```rust\n # let iter = vec![vec![0]].into_iter();\n iter.flat_map(|x| x);\n ```\n Can be written as\n ```rust\n # let iter = vec![vec![0]].into_iter();\n iter.flatten();\n ```\n", @@ -2712,8 +2754,8 @@ { "id": "search_is_some", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 570 + "path": "src/methods/mod.rs", + "line": 572 }, "group": "clippy::complexity", "docs": " **What it does:** Checks for an iterator or string search (such as `find()`, `position()`, or `rposition()`) followed by a call to `is_some()`.\n\n **Why is this bad?** Readability, this can be written more concisely as\n `_.any(_)` or `_.contains(_)`.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let vec = vec![1];\n vec.iter().find(|x| **x == 0).is_some();\n ```\n Could be written as\n ```rust\n # let vec = vec![1];\n vec.iter().any(|x| *x == 0);\n ```\n", @@ -2725,8 +2767,8 @@ { "id": "chars_next_cmp", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 594 + "path": "src/methods/mod.rs", + "line": 596 }, "group": "clippy::style", "docs": " **What it does:** Checks for usage of `.chars().next()` on a `str` to check if it starts with a given char.\n\n **Why is this bad?** Readability, this can be written more concisely as\n `_.starts_with(_)`.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let name = \"foo\";\n if name.chars().next() == Some('_') {};\n ```\n Could be written as\n ```rust\n let name = \"foo\";\n if name.starts_with('_') {};\n ```\n", @@ -2735,8 +2777,8 @@ { "id": "or_fun_call", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 625 + "path": "src/methods/mod.rs", + "line": 627 }, "group": "clippy::perf", "docs": " **What it does:** Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`, etc., and suggests to use `or_else`, `unwrap_or_else`, etc., or\n `unwrap_or_default` instead.\n\n **Why is this bad?** The function will always be called and potentially\n allocate an object acting as the default.\n\n **Known problems:** If the function has side-effects, not calling it will\n change the semantic of the program, but you shouldn't rely on that anyway.\n\n **Example:**\n ```rust\n # let foo = Some(String::new());\n foo.unwrap_or(String::new());\n ```\n this can instead be written:\n ```rust\n # let foo = Some(String::new());\n foo.unwrap_or_else(String::new);\n ```\n or\n ```rust\n # let foo = Some(String::new());\n foo.unwrap_or_default();\n ```\n", @@ -2748,8 +2790,8 @@ { "id": "expect_fun_call", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 660 + "path": "src/methods/mod.rs", + "line": 662 }, "group": "clippy::perf", "docs": " **What it does:** Checks for calls to `.expect(&format!(...))`, `.expect(foo(..))`, etc., and suggests to use `unwrap_or_else` instead\n\n **Why is this bad?** The function will always be called.\n\n **Known problems:** If the function has side-effects, not calling it will\n change the semantics of the program, but you shouldn't rely on that anyway.\n\n **Example:**\n ```rust\n # let foo = Some(String::new());\n # let err_code = \"418\";\n # let err_msg = \"I'm a teapot\";\n foo.expect(&format!(\"Err {}: {}\", err_code, err_msg));\n ```\n or\n ```rust\n # let foo = Some(String::new());\n # let err_code = \"418\";\n # let err_msg = \"I'm a teapot\";\n foo.expect(format!(\"Err {}: {}\", err_code, err_msg).as_str());\n ```\n this can instead be written:\n ```rust\n # let foo = Some(String::new());\n # let err_code = \"418\";\n # let err_msg = \"I'm a teapot\";\n foo.unwrap_or_else(|| panic!(\"Err {}: {}\", err_code, err_msg));\n ```\n", @@ -2761,8 +2803,8 @@ { "id": "clone_on_copy", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 677 + "path": "src/methods/mod.rs", + "line": 679 }, "group": "clippy::complexity", "docs": " **What it does:** Checks for usage of `.clone()` on a `Copy` type.\n **Why is this bad?** The only reason `Copy` types implement `Clone` is for\n generics, not for using the `clone` method on a concrete type.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n 42u64.clone();\n ```\n", @@ -2774,8 +2816,8 @@ { "id": "clone_on_ref_ptr", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 702 + "path": "src/methods/mod.rs", + "line": 704 }, "group": "clippy::restriction", "docs": " **What it does:** Checks for usage of `.clone()` on a ref-counted pointer, (`Rc`, `Arc`, `rc::Weak`, or `sync::Weak`), and suggests calling Clone via unified\n function syntax instead (e.g., `Rc::clone(foo)`).\n\n **Why is this bad?** Calling '.clone()' on an Rc, Arc, or Weak\n can obscure the fact that only the pointer is being cloned, not the underlying\n data.\n\n **Example:**\n ```rust\n # use std::rc::Rc;\n let x = Rc::new(1);\n\n // Bad\n x.clone();\n\n // Good\n Rc::clone(&x);\n ```\n", @@ -2787,8 +2829,8 @@ { "id": "clone_double_ref", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 724 + "path": "src/methods/mod.rs", + "line": 726 }, "group": "clippy::correctness", "docs": " **What it does:** Checks for usage of `.clone()` on an `&&T`.\n **Why is this bad?** Cloning an `&&T` copies the inner `&T`, instead of\n cloning the underlying `T`.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n fn main() {\n let x = vec![1];\n let y = &&x;\n let z = y.clone();\n println!(\"{:p} {:p}\", *y, z); // prints out the same pointer\n }\n ```\n", @@ -2800,8 +2842,8 @@ { "id": "inefficient_to_string", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 747 + "path": "src/methods/mod.rs", + "line": 749 }, "group": "clippy::pedantic", "docs": " **What it does:** Checks for usage of `.to_string()` on an `&&T` where `T` implements `ToString` directly (like `&&str` or `&&String`).\n\n **Why is this bad?** This bypasses the specialized implementation of\n `ToString` and instead goes through the more expensive string formatting\n facilities.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n // Generic implementation for `T: Display` is used (slow)\n [\"foo\", \"bar\"].iter().map(|s| s.to_string());\n\n // OK, the specialized impl is used\n [\"foo\", \"bar\"].iter().map(|&s| s.to_string());\n ```\n", @@ -2813,8 +2855,8 @@ { "id": "new_ret_no_self", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 808 + "path": "src/methods/mod.rs", + "line": 810 }, "group": "clippy::style", "docs": " **What it does:** Checks for `new` not returning a type that contains `Self`.\n **Why is this bad?** As a convention, `new` methods are used to make a new\n instance of a type.\n\n **Known problems:** None.\n\n **Example:**\n In an impl block:\n ```rust\n # struct Foo;\n # struct NotAFoo;\n impl Foo {\n fn new() -> NotAFoo {\n # NotAFoo\n }\n }\n ```\n\n ```rust\n # struct Foo;\n struct Bar(Foo);\n impl Foo {\n // Bad. The type name must contain `Self`\n fn new() -> Bar {\n # Bar(Foo)\n }\n }\n ```\n\n ```rust\n # struct Foo;\n # struct FooError;\n impl Foo {\n // Good. Return type contains `Self`\n fn new() -> Result {\n # Ok(Foo)\n }\n }\n ```\n\n Or in a trait definition:\n ```rust\n pub trait Trait {\n // Bad. The type name must contain `Self`\n fn new();\n }\n ```\n\n ```rust\n pub trait Trait {\n // Good. Return type contains `Self`\n fn new() -> Self;\n }\n ```\n", @@ -2826,8 +2868,8 @@ { "id": "single_char_pattern", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 829 + "path": "src/methods/mod.rs", + "line": 831 }, "group": "clippy::perf", "docs": " **What it does:** Checks for string methods that receive a single-character `str` as an argument, e.g., `_.split(\"x\")`.\n\n **Why is this bad?** Performing these methods using a `char` is faster than\n using a `str`.\n\n **Known problems:** Does not catch multi-byte unicode characters.\n\n **Example:**\n ```rust,ignore\n // Bad\n _.split(\"x\");\n\n // Good\n _.split('x');\n", @@ -2839,8 +2881,8 @@ { "id": "iterator_step_by_zero", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 848 + "path": "src/methods/mod.rs", + "line": 850 }, "group": "clippy::correctness", "docs": " **What it does:** Checks for calling `.step_by(0)` on iterators which panics.\n **Why is this bad?** This very much looks like an oversight. Use `panic!()` instead if you\n actually intend to panic.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,should_panic\n for x in (0..100).step_by(0) {\n //..\n }\n ```\n", @@ -2852,8 +2894,8 @@ { "id": "iter_nth_zero", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 876 + "path": "src/methods/mod.rs", + "line": 878 }, "group": "clippy::style", "docs": " **What it does:** Checks for the use of `iter.nth(0)`.\n **Why is this bad?** `iter.next()` is equivalent to\n `iter.nth(0)`, as they both consume the next element,\n but is more readable.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n # use std::collections::HashSet;\n // Bad\n # let mut s = HashSet::new();\n # s.insert(1);\n let x = s.iter().nth(0);\n\n // Good\n # let mut s = HashSet::new();\n # s.insert(1);\n let x = s.iter().next();\n ```\n", @@ -2865,8 +2907,8 @@ { "id": "iter_nth", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 902 + "path": "src/methods/mod.rs", + "line": 904 }, "group": "clippy::perf", "docs": " **What it does:** Checks for use of `.iter().nth()` (and the related `.iter_mut().nth()`) on standard library types with O(1) element access.\n\n **Why is this bad?** `.get()` and `.get_mut()` are more efficient and more\n readable.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let some_vec = vec![0, 1, 2, 3];\n let bad_vec = some_vec.iter().nth(3);\n let bad_slice = &some_vec[..].iter().nth(3);\n ```\n The correct use would be:\n ```rust\n let some_vec = vec![0, 1, 2, 3];\n let bad_vec = some_vec.get(3);\n let bad_slice = &some_vec[..].get(3);\n ```\n", @@ -2878,8 +2920,8 @@ { "id": "iter_skip_next", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 926 + "path": "src/methods/mod.rs", + "line": 928 }, "group": "clippy::style", "docs": " **What it does:** Checks for use of `.skip(x).next()` on iterators.\n **Why is this bad?** `.nth(x)` is cleaner\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let some_vec = vec![0, 1, 2, 3];\n let bad_vec = some_vec.iter().skip(3).next();\n let bad_slice = &some_vec[..].iter().skip(3).next();\n ```\n The correct use would be:\n ```rust\n let some_vec = vec![0, 1, 2, 3];\n let bad_vec = some_vec.iter().nth(3);\n let bad_slice = &some_vec[..].iter().nth(3);\n ```\n", @@ -2891,8 +2933,8 @@ { "id": "get_unwrap", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 959 + "path": "src/methods/mod.rs", + "line": 961 }, "group": "clippy::restriction", "docs": " **What it does:** Checks for use of `.get().unwrap()` (or `.get_mut().unwrap`) on a standard library type which implements `Index`\n\n **Why is this bad?** Using the Index trait (`[]`) is more clear and more\n concise.\n\n **Known problems:** Not a replacement for error handling: Using either\n `.unwrap()` or the Index trait (`[]`) carries the risk of causing a `panic`\n if the value being accessed is `None`. If the use of `.get().unwrap()` is a\n temporary placeholder for dealing with the `Option` type, then this does\n not mitigate the need for error handling. If there is a chance that `.get()`\n will be `None` in your program, then it is advisable that the `None` case\n is handled in a future refactor instead of using `.unwrap()` or the Index\n trait.\n\n **Example:**\n ```rust\n let mut some_vec = vec![0, 1, 2, 3];\n let last = some_vec.get(3).unwrap();\n *some_vec.get_mut(0).unwrap() = 1;\n ```\n The correct use would be:\n ```rust\n let mut some_vec = vec![0, 1, 2, 3];\n let last = some_vec[3];\n some_vec[0] = 1;\n ```\n", @@ -2904,8 +2946,8 @@ { "id": "string_extend_chars", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 988 + "path": "src/methods/mod.rs", + "line": 990 }, "group": "clippy::style", "docs": " **What it does:** Checks for the use of `.extend(s.chars())` where s is a `&str` or `String`.\n\n **Why is this bad?** `.push_str(s)` is clearer\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let abc = \"abc\";\n let def = String::from(\"def\");\n let mut s = String::new();\n s.extend(abc.chars());\n s.extend(def.chars());\n ```\n The correct use would be:\n ```rust\n let abc = \"abc\";\n let def = String::from(\"def\");\n let mut s = String::new();\n s.push_str(abc);\n s.push_str(&def);\n ```\n", @@ -2917,8 +2959,8 @@ { "id": "iter_cloned_collect", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 1011 + "path": "src/methods/mod.rs", + "line": 1013 }, "group": "clippy::style", "docs": " **What it does:** Checks for the use of `.cloned().collect()` on slice to create a `Vec`.\n\n **Why is this bad?** `.to_vec()` is clearer\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let s = [1, 2, 3, 4, 5];\n let s2: Vec = s[..].iter().cloned().collect();\n ```\n The better use would be:\n ```rust\n let s = [1, 2, 3, 4, 5];\n let s2: Vec = s.to_vec();\n ```\n", @@ -2930,8 +2972,8 @@ { "id": "chars_last_cmp", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 1035 + "path": "src/methods/mod.rs", + "line": 1037 }, "group": "clippy::style", "docs": " **What it does:** Checks for usage of `_.chars().last()` or `_.chars().next_back()` on a `str` to check if it ends with a given char.\n\n **Why is this bad?** Readability, this can be written more concisely as\n `_.ends_with(_)`.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let name = \"_\";\n\n // Bad\n name.chars().last() == Some('_') || name.chars().next_back() == Some('-');\n\n // Good\n name.ends_with('_') || name.ends_with('-');\n ```\n", @@ -2940,8 +2982,8 @@ { "id": "useless_asref", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 1060 + "path": "src/methods/mod.rs", + "line": 1062 }, "group": "clippy::complexity", "docs": " **What it does:** Checks for usage of `.as_ref()` or `.as_mut()` where the types before and after the call are the same.\n\n **Why is this bad?** The call is unnecessary.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # fn do_stuff(x: &[i32]) {}\n let x: &[i32] = &[1, 2, 3, 4, 5];\n do_stuff(x.as_ref());\n ```\n The correct use would be:\n ```rust\n # fn do_stuff(x: &[i32]) {}\n let x: &[i32] = &[1, 2, 3, 4, 5];\n do_stuff(x);\n ```\n", @@ -2953,8 +2995,8 @@ { "id": "unnecessary_fold", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 1082 + "path": "src/methods/mod.rs", + "line": 1084 }, "group": "clippy::style", "docs": " **What it does:** Checks for using `fold` when a more succinct alternative exists. Specifically, this checks for `fold`s which could be replaced by `any`, `all`,\n `sum` or `product`.\n\n **Why is this bad?** Readability.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let _ = (0..3).fold(false, |acc, x| acc || x > 2);\n ```\n This could be written as:\n ```rust\n let _ = (0..3).any(|x| x > 2);\n ```\n", @@ -2966,8 +3008,8 @@ { "id": "unnecessary_filter_map", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 1111 + "path": "src/methods/mod.rs", + "line": 1113 }, "group": "clippy::complexity", "docs": " **What it does:** Checks for `filter_map` calls which could be replaced by `filter` or `map`. More specifically it checks if the closure provided is only performing one of the\n filter or map operations and suggests the appropriate option.\n\n **Why is this bad?** Complexity. The intent is also clearer if only a single\n operation is being performed.\n\n **Known problems:** None\n\n **Example:**\n ```rust\n let _ = (0..3).filter_map(|x| if x > 2 { Some(x) } else { None });\n\n // As there is no transformation of the argument this could be written as:\n let _ = (0..3).filter(|&x| x > 2);\n ```\n\n ```rust\n let _ = (0..4).filter_map(|x| Some(x + 1));\n\n // As there is no conditional check on the argument this could be written as:\n let _ = (0..4).map(|x| x + 1);\n ```\n", @@ -2979,8 +3021,8 @@ { "id": "into_iter_on_ref", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 1135 + "path": "src/methods/mod.rs", + "line": 1137 }, "group": "clippy::style", "docs": " **What it does:** Checks for `into_iter` calls on references which should be replaced by `iter` or `iter_mut`.\n\n **Why is this bad?** Readability. Calling `into_iter` on a reference will not move out its\n content into the resulting iterator, which is confusing. It is better just call `iter` or\n `iter_mut` directly.\n\n **Known problems:** None\n\n **Example:**\n\n ```rust\n // Bad\n let _ = (&vec![3, 4, 5]).into_iter();\n\n // Good\n let _ = (&vec![3, 4, 5]).iter();\n ```\n", @@ -2992,8 +3034,8 @@ { "id": "suspicious_map", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 1154 + "path": "src/methods/mod.rs", + "line": 1156 }, "group": "clippy::complexity", "docs": " **What it does:** Checks for calls to `map` followed by a `count`.\n **Why is this bad?** It looks suspicious. Maybe `map` was confused with `filter`.\n If the `map` call is intentional, this should be rewritten. Or, if you intend to\n drive the iterator to completion, you can just use `for_each` instead.\n\n **Known problems:** None\n\n **Example:**\n\n ```rust\n let _ = (0..3).map(|x| x + 2).count();\n ```\n", @@ -3005,8 +3047,8 @@ { "id": "uninit_assumed_init", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 1186 + "path": "src/methods/mod.rs", + "line": 1188 }, "group": "clippy::correctness", "docs": " **What it does:** Checks for `MaybeUninit::uninit().assume_init()`.\n **Why is this bad?** For most types, this is undefined behavior.\n\n **Known problems:** For now, we accept empty tuples and tuples / arrays\n of `MaybeUninit`. There may be other types that allow uninitialized\n data, but those are not yet rigorously defined.\n\n **Example:**\n\n ```rust\n // Beware the UB\n use std::mem::MaybeUninit;\n\n let _: usize = unsafe { MaybeUninit::uninit().assume_init() };\n ```\n\n Note that the following is OK:\n\n ```rust\n use std::mem::MaybeUninit;\n\n let _: [MaybeUninit; 5] = unsafe {\n MaybeUninit::uninit().assume_init()\n };\n ```\n", @@ -3018,8 +3060,8 @@ { "id": "manual_saturating_arithmetic", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 1213 + "path": "src/methods/mod.rs", + "line": 1215 }, "group": "clippy::style", "docs": " **What it does:** Checks for `.checked_add/sub(x).unwrap_or(MAX/MIN)`.\n **Why is this bad?** These can be written simply with `saturating_add/sub` methods.\n\n **Example:**\n\n ```rust\n # let y: u32 = 0;\n # let x: u32 = 100;\n let add = x.checked_add(y).unwrap_or(u32::MAX);\n let sub = x.checked_sub(y).unwrap_or(u32::MIN);\n ```\n\n can be written using dedicated methods for saturating addition/subtraction as:\n\n ```rust\n # let y: u32 = 0;\n # let x: u32 = 100;\n let add = x.saturating_add(y);\n let sub = x.saturating_sub(y);\n ```\n", @@ -3031,8 +3073,8 @@ { "id": "zst_offset", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 1230 + "path": "src/methods/mod.rs", + "line": 1232 }, "group": "clippy::correctness", "docs": " **What it does:** Checks for `offset(_)`, `wrapping_`{`add`, `sub`}, etc. on raw pointers to zero-sized types\n\n **Why is this bad?** This is a no-op, and likely unintended\n\n **Known problems:** None\n\n **Example:**\n ```rust\n unsafe { (&() as *const ()).offset(1) };\n ```\n", @@ -3044,8 +3086,8 @@ { "id": "filetype_is_file", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 1270 + "path": "src/methods/mod.rs", + "line": 1272 }, "group": "clippy::restriction", "docs": " **What it does:** Checks for `FileType::is_file()`.\n **Why is this bad?** When people testing a file type with `FileType::is_file`\n they are testing whether a path is something they can get bytes from. But\n `is_file` doesn't cover special file types in unix-like systems, and doesn't cover\n symlink in windows. Using `!FileType::is_dir()` is a better way to that intention.\n\n **Example:**\n\n ```rust\n # || {\n let metadata = std::fs::metadata(\"foo.txt\")?;\n let filetype = metadata.file_type();\n\n if filetype.is_file() {\n // read file\n }\n # Ok::<_, std::io::Error>(())\n # };\n ```\n\n should be written as:\n\n ```rust\n # || {\n let metadata = std::fs::metadata(\"foo.txt\")?;\n let filetype = metadata.file_type();\n\n if !filetype.is_dir() {\n // read file\n }\n # Ok::<_, std::io::Error>(())\n # };\n ```\n", @@ -3057,8 +3099,8 @@ { "id": "option_as_ref_deref", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 1295 + "path": "src/methods/mod.rs", + "line": 1297 }, "group": "clippy::complexity", "docs": " **What it does:** Checks for usage of `_.as_ref().map(Deref::deref)` or it's aliases (such as String::as_str).\n **Why is this bad?** Readability, this can be written more concisely as\n `_.as_deref()`.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let opt = Some(\"\".to_string());\n opt.as_ref().map(String::as_str)\n # ;\n ```\n Can be written as\n ```rust\n # let opt = Some(\"\".to_string());\n opt.as_deref()\n # ;\n ```\n", @@ -3070,8 +3112,8 @@ { "id": "iter_next_slice", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 1321 + "path": "src/methods/mod.rs", + "line": 1323 }, "group": "clippy::style", "docs": " **What it does:** Checks for usage of `iter().next()` on a Slice or an Array\n **Why is this bad?** These can be shortened into `.get()`\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let a = [1, 2, 3];\n # let b = vec![1, 2, 3];\n a[2..].iter().next();\n b.iter().next();\n ```\n should be written as:\n ```rust\n # let a = [1, 2, 3];\n # let b = vec![1, 2, 3];\n a.get(2);\n b.get(0);\n ```\n", @@ -3083,8 +3125,8 @@ { "id": "single_char_add_str", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 1346 + "path": "src/methods/mod.rs", + "line": 1348 }, "group": "clippy::style", "docs": " **What it does:** Warns when using `push_str`/`insert_str` with a single-character string literal where `push`/`insert` with a `char` would work fine.\n\n **Why is this bad?** It's less clear that we are pushing a single character.\n\n **Known problems:** None\n\n **Example:**\n ```rust\n let mut string = String::new();\n string.insert_str(0, \"R\");\n string.push_str(\"R\");\n ```\n Could be written as\n ```rust\n let mut string = String::new();\n string.insert(0, 'R');\n string.push('R');\n ```\n", @@ -3096,8 +3138,8 @@ { "id": "unnecessary_lazy_evaluations", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 1382 + "path": "src/methods/mod.rs", + "line": 1384 }, "group": "clippy::style", "docs": " **What it does:** As the counterpart to `or_fun_call`, this lint looks for unnecessary lazily evaluated closures on `Option` and `Result`.\n\n This lint suggests changing the following functions, when eager evaluation results in\n simpler code:\n - `unwrap_or_else` to `unwrap_or`\n - `and_then` to `and`\n - `or_else` to `or`\n - `get_or_insert_with` to `get_or_insert`\n - `ok_or_else` to `ok_or`\n\n **Why is this bad?** Using eager evaluation is shorter and simpler in some cases.\n\n **Known problems:** It is possible, but not recommended for `Deref` and `Index` to have\n side effects. Eagerly evaluating them can change the semantics of the program.\n\n **Example:**\n\n ```rust\n // example code where clippy issues a warning\n let opt: Option = None;\n\n opt.unwrap_or_else(|| 42);\n ```\n Use instead:\n ```rust\n let opt: Option = None;\n\n opt.unwrap_or(42);\n ```\n", @@ -3109,8 +3151,8 @@ { "id": "map_collect_result_unit", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 1403 + "path": "src/methods/mod.rs", + "line": 1405 }, "group": "clippy::style", "docs": " **What it does:** Checks for usage of `_.map(_).collect::()`.\n **Why is this bad?** Using `try_for_each` instead is more readable and idiomatic.\n\n **Known problems:** None\n\n **Example:**\n\n ```rust\n (0..3).map(|t| Err(t)).collect::>();\n ```\n Use instead:\n ```rust\n (0..3).try_for_each(|t| Err(t));\n ```\n", @@ -3122,8 +3164,8 @@ { "id": "from_iter_instead_of_collect", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 1436 + "path": "src/methods/mod.rs", + "line": 1438 }, "group": "clippy::style", "docs": " **What it does:** Checks for `from_iter()` function calls on types that implement the `FromIterator` trait.\n\n **Why is this bad?** It is recommended style to use collect. See\n [FromIterator documentation](https://doc.rust-lang.org/std/iter/trait.FromIterator.html)\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n use std::iter::FromIterator;\n\n let five_fives = std::iter::repeat(5).take(5);\n\n let v = Vec::from_iter(five_fives);\n\n assert_eq!(v, vec![5, 5, 5, 5, 5]);\n ```\n Use instead:\n ```rust\n let five_fives = std::iter::repeat(5).take(5);\n\n let v: Vec = five_fives.collect();\n\n assert_eq!(v, vec![5, 5, 5, 5, 5]);\n ```\n", @@ -3135,8 +3177,8 @@ { "id": "inspect_for_each", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 1466 + "path": "src/methods/mod.rs", + "line": 1468 }, "group": "clippy::complexity", "docs": " **What it does:** Checks for usage of `inspect().for_each()`.\n **Why is this bad?** It is the same as performing the computation\n inside `inspect` at the beginning of the closure in `for_each`.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n [1,2,3,4,5].iter()\n .inspect(|&x| println!(\"inspect the number: {}\", x))\n .for_each(|&x| {\n assert!(x >= 0);\n });\n ```\n Can be written as\n ```rust\n [1,2,3,4,5].iter()\n .for_each(|&x| {\n println!(\"inspect the number: {}\", x);\n assert!(x >= 0);\n });\n ```\n", @@ -3148,8 +3190,8 @@ { "id": "filter_map_identity", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 1489 + "path": "src/methods/mod.rs", + "line": 1491 }, "group": "clippy::complexity", "docs": " **What it does:** Checks for usage of `filter_map(|x| x)`.\n **Why is this bad?** Readability, this can be written more concisely by using `flatten`.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n # let iter = vec![Some(1)].into_iter();\n iter.filter_map(|x| x);\n ```\n Use instead:\n ```rust\n # let iter = vec![Some(1)].into_iter();\n iter.flatten();\n ```\n", @@ -3161,8 +3203,8 @@ { "id": "bytes_nth", "id_span": { - "path": "clippy_lints/src/methods/mod.rs", - "line": 1511 + "path": "src/methods/mod.rs", + "line": 1513 }, "group": "clippy::style", "docs": " **What it does:** Checks for the use of `.bytes().nth()`.\n **Why is this bad?** `.as_bytes().get()` is more efficient and more\n readable.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n // Bad\n let _ = \"Hello\".bytes().nth(3);\n\n // Good\n let _ = \"Hello\".as_bytes().get(3);\n ```\n", @@ -3171,10 +3213,36 @@ "applicability": "MachineApplicable" } }, + { + "id": "implicit_clone", + "id_span": { + "path": "src/methods/mod.rs", + "line": 1539 + }, + "group": "clippy::pedantic", + "docs": " **What it does:** Checks for the usage of `_.to_owned()`, `vec.to_vec()`, or similar when calling `_.clone()` would be clearer.\n **Why is this bad?** These methods do the same thing as `_.clone()` but may be confusing as\n to why we are calling `to_vec` on something that is already a `Vec` or calling `to_owned` on something that is already owned.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n let a = vec![1, 2, 3];\n let b = a.to_vec();\n let c = a.to_owned();\n ```\n Use instead:\n ```rust\n let a = vec![1, 2, 3];\n let b = a.clone();\n let c = a.clone();\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, + { + "id": "iter_count", + "id_span": { + "path": "src/methods/mod.rs", + "line": 1565 + }, + "group": "clippy::complexity", + "docs": " **What it does:** Checks for the use of `.iter().count()`.\n **Why is this bad?** `.len()` is more efficient and more\n readable.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n // Bad\n let some_vec = vec![0, 1, 2, 3];\n let _ = some_vec.iter().count();\n let _ = &some_vec[..].iter().count();\n\n // Good\n let some_vec = vec![0, 1, 2, 3];\n let _ = some_vec.len();\n let _ = &some_vec[..].len();\n ```\n", + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } + }, { "id": "min_max", "id_span": { - "path": "clippy_lints/src/minmax.rs", + "path": "src/minmax.rs", "line": 28 }, "group": "clippy::correctness", @@ -3187,7 +3255,7 @@ { "id": "toplevel_ref_arg", "id_span": { - "path": "clippy_lints/src/misc.rs", + "path": "src/misc.rs", "line": 53 }, "group": "clippy::style", @@ -3200,7 +3268,7 @@ { "id": "cmp_nan", "id_span": { - "path": "clippy_lints/src/misc.rs", + "path": "src/misc.rs", "line": 76 }, "group": "clippy::correctness", @@ -3213,7 +3281,7 @@ { "id": "float_cmp", "id_span": { - "path": "clippy_lints/src/misc.rs", + "path": "src/misc.rs", "line": 109 }, "group": "clippy::correctness", @@ -3223,7 +3291,7 @@ { "id": "cmp_owned", "id_span": { - "path": "clippy_lints/src/misc.rs", + "path": "src/misc.rs", "line": 136 }, "group": "clippy::perf", @@ -3236,7 +3304,7 @@ { "id": "modulo_one", "id_span": { - "path": "clippy_lints/src/misc.rs", + "path": "src/misc.rs", "line": 159 }, "group": "clippy::correctness", @@ -3249,7 +3317,7 @@ { "id": "used_underscore_binding", "id_span": { - "path": "clippy_lints/src/misc.rs", + "path": "src/misc.rs", "line": 181 }, "group": "clippy::pedantic", @@ -3262,7 +3330,7 @@ { "id": "short_circuit_statement", "id_span": { - "path": "clippy_lints/src/misc.rs", + "path": "src/misc.rs", "line": 201 }, "group": "clippy::complexity", @@ -3275,7 +3343,7 @@ { "id": "zero_ptr", "id_span": { - "path": "clippy_lints/src/misc.rs", + "path": "src/misc.rs", "line": 223 }, "group": "clippy::style", @@ -3288,7 +3356,7 @@ { "id": "float_cmp_const", "id_span": { - "path": "clippy_lints/src/misc.rs", + "path": "src/misc.rs", "line": 254 }, "group": "clippy::restriction", @@ -3298,7 +3366,7 @@ { "id": "unneeded_field_pattern", "id_span": { - "path": "clippy_lints/src/misc_early.rs", + "path": "src/misc_early.rs", "line": 44 }, "group": "clippy::restriction", @@ -3311,7 +3379,7 @@ { "id": "duplicate_underscore_argument", "id_span": { - "path": "clippy_lints/src/misc_early.rs", + "path": "src/misc_early.rs", "line": 65 }, "group": "clippy::style", @@ -3324,7 +3392,7 @@ { "id": "double_neg", "id_span": { - "path": "clippy_lints/src/misc_early.rs", + "path": "src/misc_early.rs", "line": 83 }, "group": "clippy::style", @@ -3337,7 +3405,7 @@ { "id": "mixed_case_hex_literals", "id_span": { - "path": "clippy_lints/src/misc_early.rs", + "path": "src/misc_early.rs", "line": 104 }, "group": "clippy::style", @@ -3350,7 +3418,7 @@ { "id": "unseparated_literal_suffix", "id_span": { - "path": "clippy_lints/src/misc_early.rs", + "path": "src/misc_early.rs", "line": 125 }, "group": "clippy::pedantic", @@ -3363,7 +3431,7 @@ { "id": "zero_prefixed_literal", "id_span": { - "path": "clippy_lints/src/misc_early.rs", + "path": "src/misc_early.rs", "line": 163 }, "group": "clippy::complexity", @@ -3376,7 +3444,7 @@ { "id": "builtin_type_shadow", "id_span": { - "path": "clippy_lints/src/misc_early.rs", + "path": "src/misc_early.rs", "line": 184 }, "group": "clippy::style", @@ -3389,7 +3457,7 @@ { "id": "redundant_pattern", "id_span": { - "path": "clippy_lints/src/misc_early.rs", + "path": "src/misc_early.rs", "line": 213 }, "group": "clippy::style", @@ -3402,7 +3470,7 @@ { "id": "unneeded_wildcard_pattern", "id_span": { - "path": "clippy_lints/src/misc_early.rs", + "path": "src/misc_early.rs", "line": 247 }, "group": "clippy::complexity", @@ -3415,7 +3483,7 @@ { "id": "missing_const_for_fn", "id_span": { - "path": "clippy_lints/src/missing_const_for_fn.rs", + "path": "src/missing_const_for_fn.rs", "line": 72 }, "group": "clippy::nursery", @@ -3428,7 +3496,7 @@ { "id": "missing_docs_in_private_items", "id_span": { - "path": "clippy_lints/src/missing_doc.rs", + "path": "src/missing_doc.rs", "line": 29 }, "group": "clippy::restriction", @@ -3441,7 +3509,7 @@ { "id": "missing_inline_in_public_items", "id_span": { - "path": "clippy_lints/src/missing_inline.rs", + "path": "src/missing_inline.rs", "line": 55 }, "group": "clippy::restriction", @@ -3454,7 +3522,7 @@ { "id": "modulo_arithmetic", "id_span": { - "path": "clippy_lints/src/modulo_arithmetic.rs", + "path": "src/modulo_arithmetic.rs", "line": 26 }, "group": "clippy::restriction", @@ -3467,7 +3535,7 @@ { "id": "multiple_crate_versions", "id_span": { - "path": "clippy_lints/src/multiple_crate_versions.rs", + "path": "src/multiple_crate_versions.rs", "line": 32 }, "group": "clippy::cargo", @@ -3480,7 +3548,7 @@ { "id": "mutable_key_type", "id_span": { - "path": "clippy_lints/src/mut_key.rs", + "path": "src/mut_key.rs", "line": 50 }, "group": "clippy::correctness", @@ -3493,7 +3561,7 @@ { "id": "mut_mut", "id_span": { - "path": "clippy_lints/src/mut_mut.rs", + "path": "src/mut_mut.rs", "line": 24 }, "group": "clippy::pedantic", @@ -3506,7 +3574,7 @@ { "id": "mut_mutex_lock", "id_span": { - "path": "clippy_lints/src/mut_mutex_lock.rs", + "path": "src/mut_mutex_lock.rs", "line": 40 }, "group": "clippy::style", @@ -3519,7 +3587,7 @@ { "id": "unnecessary_mut_passed", "id_span": { - "path": "clippy_lints/src/mut_reference.rs", + "path": "src/mut_reference.rs", "line": 25 }, "group": "clippy::style", @@ -3532,7 +3600,7 @@ { "id": "debug_assert_with_mut_call", "id_span": { - "path": "clippy_lints/src/mutable_debug_assertion.rs", + "path": "src/mutable_debug_assertion.rs", "line": 28 }, "group": "clippy::nursery", @@ -3545,7 +3613,7 @@ { "id": "mutex_atomic", "id_span": { - "path": "clippy_lints/src/mutex_atomic.rs", + "path": "src/mutex_atomic.rs", "line": 34 }, "group": "clippy::perf", @@ -3558,7 +3626,7 @@ { "id": "mutex_integer", "id_span": { - "path": "clippy_lints/src/mutex_atomic.rs", + "path": "src/mutex_atomic.rs", "line": 59 }, "group": "clippy::nursery", @@ -3571,7 +3639,7 @@ { "id": "needless_arbitrary_self_type", "id_span": { - "path": "clippy_lints/src/needless_arbitrary_self_type.rs", + "path": "src/needless_arbitrary_self_type.rs", "line": 55 }, "group": "clippy::complexity", @@ -3584,7 +3652,7 @@ { "id": "needless_bool", "id_span": { - "path": "clippy_lints/src/needless_bool.rs", + "path": "src/needless_bool.rs", "line": 38 }, "group": "clippy::complexity", @@ -3597,7 +3665,7 @@ { "id": "bool_comparison", "id_span": { - "path": "clippy_lints/src/needless_bool.rs", + "path": "src/needless_bool.rs", "line": 62 }, "group": "clippy::complexity", @@ -3610,7 +3678,7 @@ { "id": "needless_borrow", "id_span": { - "path": "clippy_lints/src/needless_borrow.rs", + "path": "src/needless_borrow.rs", "line": 32 }, "group": "clippy::nursery", @@ -3623,7 +3691,7 @@ { "id": "needless_borrowed_reference", "id_span": { - "path": "clippy_lints/src/needless_borrowed_ref.rs", + "path": "src/needless_borrowed_ref.rs", "line": 48 }, "group": "clippy::complexity", @@ -3636,7 +3704,7 @@ { "id": "needless_continue", "id_span": { - "path": "clippy_lints/src/needless_continue.rs", + "path": "src/needless_continue.rs", "line": 114 }, "group": "clippy::pedantic", @@ -3649,7 +3717,7 @@ { "id": "needless_pass_by_value", "id_span": { - "path": "clippy_lints/src/needless_pass_by_value.rs", + "path": "src/needless_pass_by_value.rs", "line": 50 }, "group": "clippy::pedantic", @@ -3662,7 +3730,7 @@ { "id": "needless_question_mark", "id_span": { - "path": "clippy_lints/src/needless_question_mark.rs", + "path": "src/needless_question_mark.rs", "line": 57 }, "group": "clippy::complexity", @@ -3675,7 +3743,7 @@ { "id": "needless_update", "id_span": { - "path": "clippy_lints/src/needless_update.rs", + "path": "src/needless_update.rs", "line": 43 }, "group": "clippy::complexity", @@ -3688,7 +3756,7 @@ { "id": "neg_cmp_op_on_partial_ord", "id_span": { - "path": "clippy_lints/src/neg_cmp_op_on_partial_ord.rs", + "path": "src/neg_cmp_op_on_partial_ord.rs", "line": 41 }, "group": "clippy::complexity", @@ -3701,7 +3769,7 @@ { "id": "neg_multiply", "id_span": { - "path": "clippy_lints/src/neg_multiply.rs", + "path": "src/neg_multiply.rs", "line": 21 }, "group": "clippy::style", @@ -3714,7 +3782,7 @@ { "id": "new_without_default", "id_span": { - "path": "clippy_lints/src/new_without_default.rs", + "path": "src/new_without_default.rs", "line": 48 }, "group": "clippy::style", @@ -3727,7 +3795,7 @@ { "id": "no_effect", "id_span": { - "path": "clippy_lints/src/no_effect.rs", + "path": "src/no_effect.rs", "line": 22 }, "group": "clippy::complexity", @@ -3740,7 +3808,7 @@ { "id": "unnecessary_operation", "id_span": { - "path": "clippy_lints/src/no_effect.rs", + "path": "src/no_effect.rs", "line": 40 }, "group": "clippy::complexity", @@ -3753,7 +3821,7 @@ { "id": "declare_interior_mutable_const", "id_span": { - "path": "clippy_lints/src/non_copy_const.rs", + "path": "src/non_copy_const.rs", "line": 69 }, "group": "clippy::style", @@ -3763,7 +3831,7 @@ { "id": "borrow_interior_mutable_const", "id_span": { - "path": "clippy_lints/src/non_copy_const.rs", + "path": "src/non_copy_const.rs", "line": 110 }, "group": "clippy::style", @@ -3773,7 +3841,7 @@ { "id": "similar_names", "id_span": { - "path": "clippy_lints/src/non_expressive_names.rs", + "path": "src/non_expressive_names.rs", "line": 27 }, "group": "clippy::pedantic", @@ -3786,7 +3854,7 @@ { "id": "many_single_char_names", "id_span": { - "path": "clippy_lints/src/non_expressive_names.rs", + "path": "src/non_expressive_names.rs", "line": 45 }, "group": "clippy::style", @@ -3799,7 +3867,7 @@ { "id": "just_underscores_and_digits", "id_span": { - "path": "clippy_lints/src/non_expressive_names.rs", + "path": "src/non_expressive_names.rs", "line": 65 }, "group": "clippy::style", @@ -3812,7 +3880,7 @@ { "id": "nonsensical_open_options", "id_span": { - "path": "clippy_lints/src/open_options.rs", + "path": "src/open_options.rs", "line": 23 }, "group": "clippy::correctness", @@ -3825,7 +3893,7 @@ { "id": "option_env_unwrap", "id_span": { - "path": "clippy_lints/src/option_env_unwrap.rs", + "path": "src/option_env_unwrap.rs", "line": 28 }, "group": "clippy::correctness", @@ -3838,7 +3906,7 @@ { "id": "option_if_let_else", "id_span": { - "path": "clippy_lints/src/option_if_let_else.rs", + "path": "src/option_if_let_else.rs", "line": 59 }, "group": "clippy::pedantic", @@ -3851,7 +3919,7 @@ { "id": "overflow_check_conditional", "id_span": { - "path": "clippy_lints/src/overflow_check_conditional.rs", + "path": "src/overflow_check_conditional.rs", "line": 21 }, "group": "clippy::complexity", @@ -3864,7 +3932,7 @@ { "id": "panic_in_result_fn", "id_span": { - "path": "clippy_lints/src/panic_in_result_fn.rs", + "path": "src/panic_in_result_fn.rs", "line": 29 }, "group": "clippy::restriction", @@ -3877,7 +3945,7 @@ { "id": "panic", "id_span": { - "path": "clippy_lints/src/panic_unimplemented.rs", + "path": "src/panic_unimplemented.rs", "line": 19 }, "group": "clippy::restriction", @@ -3890,7 +3958,7 @@ { "id": "unimplemented", "id_span": { - "path": "clippy_lints/src/panic_unimplemented.rs", + "path": "src/panic_unimplemented.rs", "line": 35 }, "group": "clippy::restriction", @@ -3903,7 +3971,7 @@ { "id": "todo", "id_span": { - "path": "clippy_lints/src/panic_unimplemented.rs", + "path": "src/panic_unimplemented.rs", "line": 51 }, "group": "clippy::restriction", @@ -3916,7 +3984,7 @@ { "id": "unreachable", "id_span": { - "path": "clippy_lints/src/panic_unimplemented.rs", + "path": "src/panic_unimplemented.rs", "line": 67 }, "group": "clippy::restriction", @@ -3929,7 +3997,7 @@ { "id": "partialeq_ne_impl", "id_span": { - "path": "clippy_lints/src/partialeq_ne_impl.rs", + "path": "src/partialeq_ne_impl.rs", "line": 27 }, "group": "clippy::complexity", @@ -3942,7 +4010,7 @@ { "id": "trivially_copy_pass_by_ref", "id_span": { - "path": "clippy_lints/src/pass_by_ref_or_value.rs", + "path": "src/pass_by_ref_or_value.rs", "line": 52 }, "group": "clippy::pedantic", @@ -3955,7 +4023,7 @@ { "id": "large_types_passed_by_value", "id_span": { - "path": "clippy_lints/src/pass_by_ref_or_value.rs", + "path": "src/pass_by_ref_or_value.rs", "line": 84 }, "group": "clippy::pedantic", @@ -3968,7 +4036,7 @@ { "id": "path_buf_push_overwrite", "id_span": { - "path": "clippy_lints/src/path_buf_push_overwrite.rs", + "path": "src/path_buf_push_overwrite.rs", "line": 36 }, "group": "clippy::nursery", @@ -3981,7 +4049,7 @@ { "id": "pattern_type_mismatch", "id_span": { - "path": "clippy_lints/src/pattern_type_mismatch.rs", + "path": "src/pattern_type_mismatch.rs", "line": 79 }, "group": "clippy::restriction", @@ -3994,7 +4062,7 @@ { "id": "precedence", "id_span": { - "path": "clippy_lints/src/precedence.rs", + "path": "src/precedence.rs", "line": 44 }, "group": "clippy::complexity", @@ -4007,7 +4075,7 @@ { "id": "ptr_arg", "id_span": { - "path": "clippy_lints/src/ptr.rs", + "path": "src/ptr.rs", "line": 69 }, "group": "clippy::style", @@ -4020,7 +4088,7 @@ { "id": "cmp_null", "id_span": { - "path": "clippy_lints/src/ptr.rs", + "path": "src/ptr.rs", "line": 95 }, "group": "clippy::style", @@ -4033,7 +4101,7 @@ { "id": "mut_from_ref", "id_span": { - "path": "clippy_lints/src/ptr.rs", + "path": "src/ptr.rs", "line": 117 }, "group": "clippy::correctness", @@ -4046,7 +4114,7 @@ { "id": "ptr_eq", "id_span": { - "path": "clippy_lints/src/ptr_eq.rs", + "path": "src/ptr_eq.rs", "line": 32 }, "group": "clippy::style", @@ -4059,7 +4127,7 @@ { "id": "ptr_offset_with_cast", "id_span": { - "path": "clippy_lints/src/ptr_offset_with_cast.rs", + "path": "src/ptr_offset_with_cast.rs", "line": 40 }, "group": "clippy::complexity", @@ -4072,7 +4140,7 @@ { "id": "question_mark", "id_span": { - "path": "clippy_lints/src/question_mark.rs", + "path": "src/question_mark.rs", "line": 34 }, "group": "clippy::style", @@ -4085,7 +4153,7 @@ { "id": "range_zip_with_len", "id_span": { - "path": "clippy_lints/src/ranges.rs", + "path": "src/ranges.rs", "line": 40 }, "group": "clippy::complexity", @@ -4098,7 +4166,7 @@ { "id": "range_plus_one", "id_span": { - "path": "clippy_lints/src/ranges.rs", + "path": "src/ranges.rs", "line": 74 }, "group": "clippy::pedantic", @@ -4111,7 +4179,7 @@ { "id": "range_minus_one", "id_span": { - "path": "clippy_lints/src/ranges.rs", + "path": "src/ranges.rs", "line": 99 }, "group": "clippy::pedantic", @@ -4124,7 +4192,7 @@ { "id": "reversed_empty_ranges", "id_span": { - "path": "clippy_lints/src/ranges.rs", + "path": "src/ranges.rs", "line": 132 }, "group": "clippy::correctness", @@ -4137,7 +4205,7 @@ { "id": "manual_range_contains", "id_span": { - "path": "clippy_lints/src/ranges.rs", + "path": "src/ranges.rs", "line": 159 }, "group": "clippy::style", @@ -4150,7 +4218,7 @@ { "id": "redundant_clone", "id_span": { - "path": "clippy_lints/src/redundant_clone.rs", + "path": "src/redundant_clone.rs", "line": 63 }, "group": "clippy::perf", @@ -4163,7 +4231,7 @@ { "id": "redundant_closure_call", "id_span": { - "path": "clippy_lints/src/redundant_closure_call.rs", + "path": "src/redundant_closure_call.rs", "line": 32 }, "group": "clippy::complexity", @@ -4176,7 +4244,7 @@ { "id": "redundant_else", "id_span": { - "path": "clippy_lints/src/redundant_else.rs", + "path": "src/redundant_else.rs", "line": 37 }, "group": "clippy::pedantic", @@ -4189,7 +4257,7 @@ { "id": "redundant_field_names", "id_span": { - "path": "clippy_lints/src/redundant_field_names.rs", + "path": "src/redundant_field_names.rs", "line": 34 }, "group": "clippy::style", @@ -4202,7 +4270,7 @@ { "id": "redundant_pub_crate", "id_span": { - "path": "clippy_lints/src/redundant_pub_crate.rs", + "path": "src/redundant_pub_crate.rs", "line": 30 }, "group": "clippy::nursery", @@ -4215,7 +4283,7 @@ { "id": "redundant_slicing", "id_span": { - "path": "clippy_lints/src/redundant_slicing.rs", + "path": "src/redundant_slicing.rs", "line": 33 }, "group": "clippy::complexity", @@ -4228,7 +4296,7 @@ { "id": "redundant_static_lifetimes", "id_span": { - "path": "clippy_lints/src/redundant_static_lifetimes.rs", + "path": "src/redundant_static_lifetimes.rs", "line": 30 }, "group": "clippy::style", @@ -4241,7 +4309,7 @@ { "id": "ref_option_ref", "id_span": { - "path": "clippy_lints/src/ref_option_ref.rs", + "path": "src/ref_option_ref.rs", "line": 28 }, "group": "clippy::pedantic", @@ -4254,7 +4322,7 @@ { "id": "deref_addrof", "id_span": { - "path": "clippy_lints/src/reference.rs", + "path": "src/reference.rs", "line": 29 }, "group": "clippy::complexity", @@ -4267,7 +4335,7 @@ { "id": "ref_in_deref", "id_span": { - "path": "clippy_lints/src/reference.rs", + "path": "src/reference.rs", "line": 120 }, "group": "clippy::complexity", @@ -4280,7 +4348,7 @@ { "id": "invalid_regex", "id_span": { - "path": "clippy_lints/src/regex.rs", + "path": "src/regex.rs", "line": 25 }, "group": "clippy::correctness", @@ -4293,7 +4361,7 @@ { "id": "trivial_regex", "id_span": { - "path": "clippy_lints/src/regex.rs", + "path": "src/regex.rs", "line": 46 }, "group": "clippy::nursery", @@ -4306,7 +4374,7 @@ { "id": "repeat_once", "id_span": { - "path": "clippy_lints/src/repeat_once.rs", + "path": "src/repeat_once.rs", "line": 33 }, "group": "clippy::complexity", @@ -4319,7 +4387,7 @@ { "id": "let_and_return", "id_span": { - "path": "clippy_lints/src/returns.rs", + "path": "src/returns.rs", "line": 38 }, "group": "clippy::style", @@ -4332,7 +4400,7 @@ { "id": "needless_return", "id_span": { - "path": "clippy_lints/src/returns.rs", + "path": "src/returns.rs", "line": 63 }, "group": "clippy::style", @@ -4345,7 +4413,7 @@ { "id": "self_assignment", "id_span": { - "path": "clippy_lints/src/self_assignment.rs", + "path": "src/self_assignment.rs", "line": 29 }, "group": "clippy::correctness", @@ -4358,7 +4426,7 @@ { "id": "semicolon_if_nothing_returned", "id_span": { - "path": "clippy_lints/src/semicolon_if_nothing_returned.rs", + "path": "src/semicolon_if_nothing_returned.rs", "line": 30 }, "group": "clippy::restriction", @@ -4371,7 +4439,7 @@ { "id": "serde_api_misuse", "id_span": { - "path": "clippy_lints/src/serde_api.rs", + "path": "src/serde_api.rs", "line": 16 }, "group": "clippy::correctness", @@ -4384,7 +4452,7 @@ { "id": "shadow_same", "id_span": { - "path": "clippy_lints/src/shadow.rs", + "path": "src/shadow.rs", "line": 34 }, "group": "clippy::restriction", @@ -4397,7 +4465,7 @@ { "id": "shadow_reuse", "id_span": { - "path": "clippy_lints/src/shadow.rs", + "path": "src/shadow.rs", "line": 61 }, "group": "clippy::restriction", @@ -4410,7 +4478,7 @@ { "id": "shadow_unrelated", "id_span": { - "path": "clippy_lints/src/shadow.rs", + "path": "src/shadow.rs", "line": 93 }, "group": "clippy::pedantic", @@ -4423,7 +4491,7 @@ { "id": "single_component_path_imports", "id_span": { - "path": "clippy_lints/src/single_component_path_imports.rs", + "path": "src/single_component_path_imports.rs", "line": 32 }, "group": "clippy::style", @@ -4436,7 +4504,7 @@ { "id": "size_of_in_element_count", "id_span": { - "path": "clippy_lints/src/size_of_in_element_count.rs", + "path": "src/size_of_in_element_count.rs", "line": 31 }, "group": "clippy::correctness", @@ -4449,7 +4517,7 @@ { "id": "slow_vector_initialization", "id_span": { - "path": "clippy_lints/src/slow_vector_initialization.rs", + "path": "src/slow_vector_initialization.rs", "line": 37 }, "group": "clippy::perf", @@ -4462,7 +4530,7 @@ { "id": "stable_sort_primitive", "id_span": { - "path": "clippy_lints/src/stable_sort_primitive.rs", + "path": "src/stable_sort_primitive.rs", "line": 36 }, "group": "clippy::perf", @@ -4475,7 +4543,7 @@ { "id": "string_add_assign", "id_span": { - "path": "clippy_lints/src/strings.rs", + "path": "src/strings.rs", "line": 37 }, "group": "clippy::pedantic", @@ -4488,7 +4556,7 @@ { "id": "string_add", "id_span": { - "path": "clippy_lints/src/strings.rs", + "path": "src/strings.rs", "line": 65 }, "group": "clippy::restriction", @@ -4501,7 +4569,7 @@ { "id": "string_lit_as_bytes", "id_span": { - "path": "clippy_lints/src/strings.rs", + "path": "src/strings.rs", "line": 107 }, "group": "clippy::nursery", @@ -4514,7 +4582,7 @@ { "id": "string_from_utf8_as_bytes", "id_span": { - "path": "clippy_lints/src/strings.rs", + "path": "src/strings.rs", "line": 196 }, "group": "clippy::complexity", @@ -4527,7 +4595,7 @@ { "id": "str_to_string", "id_span": { - "path": "clippy_lints/src/strings.rs", + "path": "src/strings.rs", "line": 313 }, "group": "clippy::restriction", @@ -4540,7 +4608,7 @@ { "id": "string_to_string", "id_span": { - "path": "clippy_lints/src/strings.rs", + "path": "src/strings.rs", "line": 362 }, "group": "clippy::restriction", @@ -4553,7 +4621,7 @@ { "id": "suspicious_operation_groupings", "id_span": { - "path": "clippy_lints/src/suspicious_operation_groupings.rs", + "path": "src/suspicious_operation_groupings.rs", "line": 60 }, "group": "clippy::style", @@ -4566,7 +4634,7 @@ { "id": "suspicious_arithmetic_impl", "id_span": { - "path": "clippy_lints/src/suspicious_trait_impl.rs", + "path": "src/suspicious_trait_impl.rs", "line": 27 }, "group": "clippy::correctness", @@ -4579,7 +4647,7 @@ { "id": "suspicious_op_assign_impl", "id_span": { - "path": "clippy_lints/src/suspicious_trait_impl.rs", + "path": "src/suspicious_trait_impl.rs", "line": 48 }, "group": "clippy::correctness", @@ -4592,7 +4660,7 @@ { "id": "manual_swap", "id_span": { - "path": "clippy_lints/src/swap.rs", + "path": "src/swap.rs", "line": 36 }, "group": "clippy::complexity", @@ -4605,7 +4673,7 @@ { "id": "almost_swapped", "id_span": { - "path": "clippy_lints/src/swap.rs", + "path": "src/swap.rs", "line": 61 }, "group": "clippy::correctness", @@ -4618,7 +4686,7 @@ { "id": "tabs_in_doc_comments", "id_span": { - "path": "clippy_lints/src/tabs_in_doc_comments.rs", + "path": "src/tabs_in_doc_comments.rs", "line": 54 }, "group": "clippy::style", @@ -4631,7 +4699,7 @@ { "id": "temporary_assignment", "id_span": { - "path": "clippy_lints/src/temporary_assignment.rs", + "path": "src/temporary_assignment.rs", "line": 19 }, "group": "clippy::complexity", @@ -4644,7 +4712,7 @@ { "id": "to_digit_is_some", "id_span": { - "path": "clippy_lints/src/to_digit_is_some.rs", + "path": "src/to_digit_is_some.rs", "line": 27 }, "group": "clippy::style", @@ -4657,7 +4725,7 @@ { "id": "to_string_in_display", "id_span": { - "path": "clippy_lints/src/to_string_in_display.rs", + "path": "src/to_string_in_display.rs", "line": 40 }, "group": "clippy::correctness", @@ -4670,7 +4738,7 @@ { "id": "type_repetition_in_bounds", "id_span": { - "path": "clippy_lints/src/trait_bounds.rs", + "path": "src/trait_bounds.rs", "line": 28 }, "group": "clippy::pedantic", @@ -4683,7 +4751,7 @@ { "id": "trait_duplication_in_bounds", "id_span": { - "path": "clippy_lints/src/trait_bounds.rs", + "path": "src/trait_bounds.rs", "line": 57 }, "group": "clippy::pedantic", @@ -4696,8 +4764,8 @@ { "id": "wrong_transmute", "id_span": { - "path": "clippy_lints/src/transmute.rs", - "line": 29 + "path": "src/transmute/mod.rs", + "line": 34 }, "group": "clippy::correctness", "docs": " **What it does:** Checks for transmutes that can't ever be correct on any architecture.\n\n **Why is this bad?** It's basically guaranteed to be undefined behaviour.\n\n **Known problems:** When accessing C, users might want to store pointer\n sized objects in `extradata` arguments to save an allocation.\n\n **Example:**\n ```ignore\n let ptr: *const T = core::intrinsics::transmute('x')\n ```\n", @@ -4709,8 +4777,8 @@ { "id": "useless_transmute", "id_span": { - "path": "clippy_lints/src/transmute.rs", - "line": 48 + "path": "src/transmute/mod.rs", + "line": 53 }, "group": "clippy::nursery", "docs": " **What it does:** Checks for transmutes to the original type of the object and transmutes that could be a cast.\n\n **Why is this bad?** Readability. The code tricks people into thinking that\n something complex is going on.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n core::intrinsics::transmute(t); // where the result type is the same as `t`'s\n ```\n", @@ -4722,8 +4790,8 @@ { "id": "transmutes_expressible_as_ptr_casts", "id_span": { - "path": "clippy_lints/src/transmute.rs", - "line": 73 + "path": "src/transmute/mod.rs", + "line": 78 }, "group": "clippy::complexity", "docs": " **What it does:**Checks for transmutes that could be a pointer cast.\n **Why is this bad?** Readability. The code tricks people into thinking that\n something complex is going on.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n # let p: *const [i32] = &[];\n unsafe { std::mem::transmute::<*const [i32], *const [u16]>(p) };\n ```\n Use instead:\n ```rust\n # let p: *const [i32] = &[];\n p as *const [u16];\n ```\n", @@ -4735,8 +4803,8 @@ { "id": "crosspointer_transmute", "id_span": { - "path": "clippy_lints/src/transmute.rs", - "line": 91 + "path": "src/transmute/mod.rs", + "line": 96 }, "group": "clippy::complexity", "docs": " **What it does:** Checks for transmutes between a type `T` and `*T`.\n **Why is this bad?** It's easy to mistakenly transmute between a type and a\n pointer to that type.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n core::intrinsics::transmute(t) // where the result type is the same as\n // `*t` or `&t`'s\n ```\n", @@ -4748,8 +4816,8 @@ { "id": "transmute_ptr_to_ref", "id_span": { - "path": "clippy_lints/src/transmute.rs", - "line": 116 + "path": "src/transmute/mod.rs", + "line": 121 }, "group": "clippy::complexity", "docs": " **What it does:** Checks for transmutes from a pointer to a reference.\n **Why is this bad?** This can always be rewritten with `&` and `*`.\n\n **Known problems:**\n - `mem::transmute` in statics and constants is stable from Rust 1.46.0,\n while dereferencing raw pointer is not stable yet.\n If you need to do this in those places,\n you would have to use `transmute` instead.\n\n **Example:**\n ```rust,ignore\n unsafe {\n let _: &T = std::mem::transmute(p); // where p: *const T\n }\n\n // can be written:\n let _: &T = &*p;\n ```\n", @@ -4761,8 +4829,8 @@ { "id": "transmute_int_to_char", "id_span": { - "path": "clippy_lints/src/transmute.rs", - "line": 147 + "path": "src/transmute/mod.rs", + "line": 152 }, "group": "clippy::complexity", "docs": " **What it does:** Checks for transmutes from an integer to a `char`.\n **Why is this bad?** Not every integer is a Unicode scalar value.\n\n **Known problems:**\n - [`from_u32`] which this lint suggests using is slower than `transmute`\n as it needs to validate the input.\n If you are certain that the input is always a valid Unicode scalar value,\n use [`from_u32_unchecked`] which is as fast as `transmute`\n but has a semantically meaningful name.\n - You might want to handle `None` returned from [`from_u32`] instead of calling `unwrap`.\n\n [`from_u32`]: https://doc.rust-lang.org/std/char/fn.from_u32.html\n [`from_u32_unchecked`]: https://doc.rust-lang.org/std/char/fn.from_u32_unchecked.html\n\n **Example:**\n ```rust\n let x = 1_u32;\n unsafe {\n let _: char = std::mem::transmute(x); // where x: u32\n }\n\n // should be:\n let _ = std::char::from_u32(x).unwrap();\n ```\n", @@ -4774,8 +4842,8 @@ { "id": "transmute_bytes_to_str", "id_span": { - "path": "clippy_lints/src/transmute.rs", - "line": 178 + "path": "src/transmute/mod.rs", + "line": 183 }, "group": "clippy::complexity", "docs": " **What it does:** Checks for transmutes from a `&[u8]` to a `&str`.\n **Why is this bad?** Not every byte slice is a valid UTF-8 string.\n\n **Known problems:**\n - [`from_utf8`] which this lint suggests using is slower than `transmute`\n as it needs to validate the input.\n If you are certain that the input is always a valid UTF-8,\n use [`from_utf8_unchecked`] which is as fast as `transmute`\n but has a semantically meaningful name.\n - You might want to handle errors returned from [`from_utf8`] instead of calling `unwrap`.\n\n [`from_utf8`]: https://doc.rust-lang.org/std/str/fn.from_utf8.html\n [`from_utf8_unchecked`]: https://doc.rust-lang.org/std/str/fn.from_utf8_unchecked.html\n\n **Example:**\n ```rust\n let b: &[u8] = &[1_u8, 2_u8];\n unsafe {\n let _: &str = std::mem::transmute(b); // where b: &[u8]\n }\n\n // should be:\n let _ = std::str::from_utf8(b).unwrap();\n ```\n", @@ -4787,8 +4855,8 @@ { "id": "transmute_int_to_bool", "id_span": { - "path": "clippy_lints/src/transmute.rs", - "line": 200 + "path": "src/transmute/mod.rs", + "line": 205 }, "group": "clippy::complexity", "docs": " **What it does:** Checks for transmutes from an integer to a `bool`.\n **Why is this bad?** This might result in an invalid in-memory representation of a `bool`.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let x = 1_u8;\n unsafe {\n let _: bool = std::mem::transmute(x); // where x: u8\n }\n\n // should be:\n let _: bool = x != 0;\n ```\n", @@ -4800,8 +4868,8 @@ { "id": "transmute_int_to_float", "id_span": { - "path": "clippy_lints/src/transmute.rs", - "line": 222 + "path": "src/transmute/mod.rs", + "line": 227 }, "group": "clippy::complexity", "docs": " **What it does:** Checks for transmutes from an integer to a float.\n **Why is this bad?** Transmutes are dangerous and error-prone, whereas `from_bits` is intuitive\n and safe.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n unsafe {\n let _: f32 = std::mem::transmute(1_u32); // where x: u32\n }\n\n // should be:\n let _: f32 = f32::from_bits(1_u32);\n ```\n", @@ -4813,8 +4881,8 @@ { "id": "transmute_float_to_int", "id_span": { - "path": "clippy_lints/src/transmute.rs", - "line": 244 + "path": "src/transmute/mod.rs", + "line": 249 }, "group": "clippy::complexity", "docs": " **What it does:** Checks for transmutes from a float to an integer.\n **Why is this bad?** Transmutes are dangerous and error-prone, whereas `to_bits` is intuitive\n and safe.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n unsafe {\n let _: u32 = std::mem::transmute(1f32);\n }\n\n // should be:\n let _: u32 = 1f32.to_bits();\n ```\n", @@ -4826,8 +4894,8 @@ { "id": "transmute_ptr_to_ptr", "id_span": { - "path": "clippy_lints/src/transmute.rs", - "line": 271 + "path": "src/transmute/mod.rs", + "line": 276 }, "group": "clippy::complexity", "docs": " **What it does:** Checks for transmutes from a pointer to a pointer, or from a reference to a reference.\n\n **Why is this bad?** Transmutes are dangerous, and these can instead be\n written as casts.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let ptr = &1u32 as *const u32;\n unsafe {\n // pointer-to-pointer transmute\n let _: *const f32 = std::mem::transmute(ptr);\n // ref-ref transmute\n let _: &f32 = std::mem::transmute(&1u32);\n }\n // These can be respectively written:\n let _ = ptr as *const f32;\n let _ = unsafe{ &*(&1u32 as *const u32 as *const f32) };\n ```\n", @@ -4839,8 +4907,8 @@ { "id": "unsound_collection_transmute", "id_span": { - "path": "clippy_lints/src/transmute.rs", - "line": 299 + "path": "src/transmute/mod.rs", + "line": 304 }, "group": "clippy::correctness", "docs": " **What it does:** Checks for transmutes between collections whose types have different ABI, size or alignment.\n\n **Why is this bad?** This is undefined behavior.\n\n **Known problems:** Currently, we cannot know whether a type is a\n collection, so we just lint the ones that come with `std`.\n\n **Example:**\n ```rust\n // different size, therefore likely out-of-bounds memory access\n // You absolutely do not want this in your code!\n unsafe {\n std::mem::transmute::<_, Vec>(vec![2_u16])\n };\n ```\n\n You must always iterate, map and collect the values:\n\n ```rust\n vec![2_u16].into_iter().map(u32::from).collect::>();\n ```\n", @@ -4852,7 +4920,7 @@ { "id": "transmuting_null", "id_span": { - "path": "clippy_lints/src/transmuting_null.rs", + "path": "src/transmuting_null.rs", "line": 23 }, "group": "clippy::correctness", @@ -4865,7 +4933,7 @@ { "id": "try_err", "id_span": { - "path": "clippy_lints/src/try_err.rs", + "path": "src/try_err.rs", "line": 43 }, "group": "clippy::style", @@ -4878,7 +4946,7 @@ { "id": "box_vec", "id_span": { - "path": "clippy_lints/src/types.rs", + "path": "src/types.rs", "line": 66 }, "group": "clippy::perf", @@ -4891,7 +4959,7 @@ { "id": "vec_box", "id_span": { - "path": "clippy_lints/src/types.rs", + "path": "src/types.rs", "line": 95 }, "group": "clippy::complexity", @@ -4904,7 +4972,7 @@ { "id": "option_option", "id_span": { - "path": "clippy_lints/src/types.rs", + "path": "src/types.rs", "line": 133 }, "group": "clippy::pedantic", @@ -4917,7 +4985,7 @@ { "id": "linkedlist", "id_span": { - "path": "clippy_lints/src/types.rs", + "path": "src/types.rs", "line": 169 }, "group": "clippy::pedantic", @@ -4930,7 +4998,7 @@ { "id": "borrowed_box", "id_span": { - "path": "clippy_lints/src/types.rs", + "path": "src/types.rs", "line": 193 }, "group": "clippy::complexity", @@ -4943,7 +5011,7 @@ { "id": "redundant_allocation", "id_span": { - "path": "clippy_lints/src/types.rs", + "path": "src/types.rs", "line": 217 }, "group": "clippy::perf", @@ -4956,7 +5024,7 @@ { "id": "rc_buffer", "id_span": { - "path": "clippy_lints/src/types.rs", + "path": "src/types.rs", "line": 248 }, "group": "clippy::restriction", @@ -4969,7 +5037,7 @@ { "id": "let_unit_value", "id_span": { - "path": "clippy_lints/src/types.rs", + "path": "src/types.rs", "line": 768 }, "group": "clippy::pedantic", @@ -4982,7 +5050,7 @@ { "id": "unit_cmp", "id_span": { - "path": "clippy_lints/src/types.rs", + "path": "src/types.rs", "line": 849 }, "group": "clippy::correctness", @@ -4995,7 +5063,7 @@ { "id": "unit_arg", "id_span": { - "path": "clippy_lints/src/types.rs", + "path": "src/types.rs", "line": 922 }, "group": "clippy::complexity", @@ -5008,7 +5076,7 @@ { "id": "cast_precision_loss", "id_span": { - "path": "clippy_lints/src/types.rs", + "path": "src/types.rs", "line": 1158 }, "group": "clippy::pedantic", @@ -5021,7 +5089,7 @@ { "id": "cast_sign_loss", "id_span": { - "path": "clippy_lints/src/types.rs", + "path": "src/types.rs", "line": 1179 }, "group": "clippy::pedantic", @@ -5034,7 +5102,7 @@ { "id": "cast_possible_truncation", "id_span": { - "path": "clippy_lints/src/types.rs", + "path": "src/types.rs", "line": 1201 }, "group": "clippy::pedantic", @@ -5047,7 +5115,7 @@ { "id": "cast_possible_wrap", "id_span": { - "path": "clippy_lints/src/types.rs", + "path": "src/types.rs", "line": 1224 }, "group": "clippy::pedantic", @@ -5060,7 +5128,7 @@ { "id": "cast_lossless", "id_span": { - "path": "clippy_lints/src/types.rs", + "path": "src/types.rs", "line": 1256 }, "group": "clippy::pedantic", @@ -5073,7 +5141,7 @@ { "id": "unnecessary_cast", "id_span": { - "path": "clippy_lints/src/types.rs", + "path": "src/types.rs", "line": 1281 }, "group": "clippy::complexity", @@ -5086,7 +5154,7 @@ { "id": "cast_ptr_alignment", "id_span": { - "path": "clippy_lints/src/types.rs", + "path": "src/types.rs", "line": 1305 }, "group": "clippy::pedantic", @@ -5099,7 +5167,7 @@ { "id": "fn_to_numeric_cast", "id_span": { - "path": "clippy_lints/src/types.rs", + "path": "src/types.rs", "line": 1332 }, "group": "clippy::style", @@ -5112,7 +5180,7 @@ { "id": "fn_to_numeric_cast_with_truncation", "id_span": { - "path": "clippy_lints/src/types.rs", + "path": "src/types.rs", "line": 1362 }, "group": "clippy::style", @@ -5125,7 +5193,7 @@ { "id": "type_complexity", "id_span": { - "path": "clippy_lints/src/types.rs", + "path": "src/types.rs", "line": 1897 }, "group": "clippy::complexity", @@ -5138,7 +5206,7 @@ { "id": "char_lit_as_u8", "id_span": { - "path": "clippy_lints/src/types.rs", + "path": "src/types.rs", "line": 2068 }, "group": "clippy::complexity", @@ -5151,7 +5219,7 @@ { "id": "absurd_extreme_comparisons", "id_span": { - "path": "clippy_lints/src/types.rs", + "path": "src/types.rs", "line": 2133 }, "group": "clippy::correctness", @@ -5164,7 +5232,7 @@ { "id": "invalid_upcast_comparisons", "id_span": { - "path": "clippy_lints/src/types.rs", + "path": "src/types.rs", "line": 2294 }, "group": "clippy::pedantic", @@ -5177,7 +5245,7 @@ { "id": "implicit_hasher", "id_span": { - "path": "clippy_lints/src/types.rs", + "path": "src/types.rs", "line": 2515 }, "group": "clippy::pedantic", @@ -5190,7 +5258,7 @@ { "id": "cast_ref_to_mut", "id_span": { - "path": "clippy_lints/src/types.rs", + "path": "src/types.rs", "line": 2866 }, "group": "clippy::correctness", @@ -5203,7 +5271,7 @@ { "id": "ptr_as_ptr", "id_span": { - "path": "clippy_lints/src/types.rs", + "path": "src/types.rs", "line": 2922 }, "group": "clippy::pedantic", @@ -5216,7 +5284,7 @@ { "id": "undropped_manually_drops", "id_span": { - "path": "clippy_lints/src/undropped_manually_drops.rs", + "path": "src/undropped_manually_drops.rs", "line": 27 }, "group": "clippy::correctness", @@ -5229,7 +5297,7 @@ { "id": "invisible_characters", "id_span": { - "path": "clippy_lints/src/unicode.rs", + "path": "src/unicode.rs", "line": 20 }, "group": "clippy::correctness", @@ -5242,7 +5310,7 @@ { "id": "non_ascii_literal", "id_span": { - "path": "clippy_lints/src/unicode.rs", + "path": "src/unicode.rs", "line": 44 }, "group": "clippy::pedantic", @@ -5255,7 +5323,7 @@ { "id": "unicode_not_nfc", "id_span": { - "path": "clippy_lints/src/unicode.rs", + "path": "src/unicode.rs", "line": 61 }, "group": "clippy::pedantic", @@ -5268,7 +5336,7 @@ { "id": "unit_return_expecting_ord", "id_span": { - "path": "clippy_lints/src/unit_return_expecting_ord.rs", + "path": "src/unit_return_expecting_ord.rs", "line": 30 }, "group": "clippy::correctness", @@ -5281,7 +5349,7 @@ { "id": "fn_address_comparisons", "id_span": { - "path": "clippy_lints/src/unnamed_address.rs", + "path": "src/unnamed_address.rs", "line": 27 }, "group": "clippy::correctness", @@ -5294,7 +5362,7 @@ { "id": "vtable_address_comparisons", "id_span": { - "path": "clippy_lints/src/unnamed_address.rs", + "path": "src/unnamed_address.rs", "line": 51 }, "group": "clippy::correctness", @@ -5307,7 +5375,7 @@ { "id": "unnecessary_sort_by", "id_span": { - "path": "clippy_lints/src/unnecessary_sort_by.rs", + "path": "src/unnecessary_sort_by.rs", "line": 41 }, "group": "clippy::complexity", @@ -5320,7 +5388,7 @@ { "id": "unnecessary_wraps", "id_span": { - "path": "clippy_lints/src/unnecessary_wraps.rs", + "path": "src/unnecessary_wraps.rs", "line": 50 }, "group": "clippy::pedantic", @@ -5333,7 +5401,7 @@ { "id": "unnested_or_patterns", "id_span": { - "path": "clippy_lints/src/unnested_or_patterns.rs", + "path": "src/unnested_or_patterns.rs", "line": 47 }, "group": "clippy::pedantic", @@ -5346,7 +5414,7 @@ { "id": "unsafe_removed_from_name", "id_span": { - "path": "clippy_lints/src/unsafe_removed_from_name.rs", + "path": "src/unsafe_removed_from_name.rs", "line": 24 }, "group": "clippy::style", @@ -5359,7 +5427,7 @@ { "id": "unused_io_amount", "id_span": { - "path": "clippy_lints/src/unused_io_amount.rs", + "path": "src/unused_io_amount.rs", "line": 28 }, "group": "clippy::correctness", @@ -5372,7 +5440,7 @@ { "id": "unused_self", "id_span": { - "path": "clippy_lints/src/unused_self.rs", + "path": "src/unused_self.rs", "line": 33 }, "group": "clippy::pedantic", @@ -5385,7 +5453,7 @@ { "id": "unused_unit", "id_span": { - "path": "clippy_lints/src/unused_unit.rs", + "path": "src/unused_unit.rs", "line": 27 }, "group": "clippy::style", @@ -5398,7 +5466,7 @@ { "id": "unnecessary_unwrap", "id_span": { - "path": "clippy_lints/src/unwrap.rs", + "path": "src/unwrap.rs", "line": 40 }, "group": "clippy::complexity", @@ -5411,7 +5479,7 @@ { "id": "panicking_unwrap", "id_span": { - "path": "clippy_lints/src/unwrap.rs", + "path": "src/unwrap.rs", "line": 63 }, "group": "clippy::correctness", @@ -5424,7 +5492,7 @@ { "id": "unwrap_in_result", "id_span": { - "path": "clippy_lints/src/unwrap_in_result.rs", + "path": "src/unwrap_in_result.rs", "line": 47 }, "group": "clippy::restriction", @@ -5437,7 +5505,7 @@ { "id": "upper_case_acronyms", "id_span": { - "path": "clippy_lints/src/upper_case_acronyms.rs", + "path": "src/upper_case_acronyms.rs", "line": 35 }, "group": "clippy::style", @@ -5450,7 +5518,7 @@ { "id": "use_self", "id_span": { - "path": "clippy_lints/src/use_self.rs", + "path": "src/use_self.rs", "line": 53 }, "group": "clippy::nursery", @@ -5463,7 +5531,7 @@ { "id": "useless_conversion", "id_span": { - "path": "clippy_lints/src/useless_conversion.rs", + "path": "src/useless_conversion.rs", "line": 32 }, "group": "clippy::complexity", @@ -5476,7 +5544,7 @@ { "id": "useless_vec", "id_span": { - "path": "clippy_lints/src/vec.rs", + "path": "src/vec.rs", "line": 36 }, "group": "clippy::perf", @@ -5489,7 +5557,7 @@ { "id": "vec_init_then_push", "id_span": { - "path": "clippy_lints/src/vec_init_then_push.rs", + "path": "src/vec_init_then_push.rs", "line": 32 }, "group": "clippy::perf", @@ -5502,7 +5570,7 @@ { "id": "vec_resize_to_zero", "id_span": { - "path": "clippy_lints/src/vec_resize_to_zero.rs", + "path": "src/vec_resize_to_zero.rs", "line": 24 }, "group": "clippy::correctness", @@ -5515,7 +5583,7 @@ { "id": "verbose_file_reads", "id_span": { - "path": "clippy_lints/src/verbose_file_reads.rs", + "path": "src/verbose_file_reads.rs", "line": 29 }, "group": "clippy::restriction", @@ -5528,7 +5596,7 @@ { "id": "wildcard_dependencies", "id_span": { - "path": "clippy_lints/src/wildcard_dependencies.rs", + "path": "src/wildcard_dependencies.rs", "line": 24 }, "group": "clippy::cargo", @@ -5541,27 +5609,33 @@ { "id": "enum_glob_use", "id_span": { - "path": "clippy_lints/src/wildcard_imports.rs", + "path": "src/wildcard_imports.rs", "line": 32 }, "group": "clippy::pedantic", "docs": " **What it does:** Checks for `use Enum::*`.\n **Why is this bad?** It is usually better style to use the prefixed name of\n an enumeration variant, rather than importing variants.\n\n **Known problems:** Old-style enumerations that prefix the variants are\n still around.\n\n **Example:**\n ```rust,ignore\n // Bad\n use std::cmp::Ordering::*;\n foo(Less);\n\n // Good\n use std::cmp::Ordering;\n foo(Ordering::Less)\n ```\n", - "applicability": null + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } }, { "id": "wildcard_imports", "id_span": { - "path": "clippy_lints/src/wildcard_imports.rs", + "path": "src/wildcard_imports.rs", "line": 83 }, "group": "clippy::pedantic", "docs": " **What it does:** Checks for wildcard imports `use _::*`.\n **Why is this bad?** wildcard imports can pollute the namespace. This is especially bad if\n you try to import something through a wildcard, that already has been imported by name from\n a different source:\n\n ```rust,ignore\n use crate1::foo; // Imports a function named foo\n use crate2::*; // Has a function named foo\n\n foo(); // Calls crate1::foo\n ```\n\n This can lead to confusing error messages at best and to unexpected behavior at worst.\n\n **Exceptions:**\n\n Wildcard imports are allowed from modules named `prelude`. Many crates (including the standard library)\n provide modules named \"prelude\" specifically designed for wildcard import.\n\n `use super::*` is allowed in test modules. This is defined as any module with \"test\" in the name.\n\n These exceptions can be disabled using the `warn-on-all-wildcard-imports` configuration flag.\n\n **Known problems:** If macros are imported through the wildcard, this macro is not included\n by the suggestion and has to be added by hand.\n\n Applying the suggestion when explicit imports of the things imported with a glob import\n exist, may result in `unused_imports` warnings.\n\n **Example:**\n\n ```rust,ignore\n // Bad\n use crate1::*;\n\n foo();\n ```\n\n ```rust,ignore\n // Good\n use crate1::foo;\n\n foo();\n ```\n", - "applicability": null + "applicability": { + "is_multi_suggestion": false, + "applicability": "MachineApplicable" + } }, { "id": "println_empty_string", "id_span": { - "path": "clippy_lints/src/write.rs", + "path": "src/write.rs", "line": 33 }, "group": "clippy::style", @@ -5574,7 +5648,7 @@ { "id": "print_with_newline", "id_span": { - "path": "clippy_lints/src/write.rs", + "path": "src/write.rs", "line": 57 }, "group": "clippy::style", @@ -5587,7 +5661,7 @@ { "id": "print_stdout", "id_span": { - "path": "clippy_lints/src/write.rs", + "path": "src/write.rs", "line": 75 }, "group": "clippy::restriction", @@ -5600,7 +5674,7 @@ { "id": "print_stderr", "id_span": { - "path": "clippy_lints/src/write.rs", + "path": "src/write.rs", "line": 93 }, "group": "clippy::restriction", @@ -5613,7 +5687,7 @@ { "id": "use_debug", "id_span": { - "path": "clippy_lints/src/write.rs", + "path": "src/write.rs", "line": 110 }, "group": "clippy::restriction", @@ -5626,17 +5700,20 @@ { "id": "print_literal", "id_span": { - "path": "clippy_lints/src/write.rs", + "path": "src/write.rs", "line": 133 }, "group": "clippy::style", "docs": " **What it does:** This lint warns about the use of literals as `print!`/`println!` args.\n **Why is this bad?** Using literals as `println!` args is inefficient\n (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary\n (i.e., just put the literal in the format string)\n\n **Known problems:** Will also warn with macro calls as arguments that expand to literals\n -- e.g., `println!(\"{}\", env!(\"FOO\"))`.\n\n **Example:**\n ```rust\n println!(\"{}\", \"foo\");\n ```\n use the literal without formatting:\n ```rust\n println!(\"foo\");\n ```\n", - "applicability": null + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } }, { "id": "writeln_empty_string", "id_span": { - "path": "clippy_lints/src/write.rs", + "path": "src/write.rs", "line": 156 }, "group": "clippy::style", @@ -5649,7 +5726,7 @@ { "id": "write_with_newline", "id_span": { - "path": "clippy_lints/src/write.rs", + "path": "src/write.rs", "line": 182 }, "group": "clippy::style", @@ -5662,17 +5739,20 @@ { "id": "write_literal", "id_span": { - "path": "clippy_lints/src/write.rs", + "path": "src/write.rs", "line": 207 }, "group": "clippy::style", "docs": " **What it does:** This lint warns about the use of literals as `write!`/`writeln!` args.\n **Why is this bad?** Using literals as `writeln!` args is inefficient\n (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary\n (i.e., just put the literal in the format string)\n\n **Known problems:** Will also warn with macro calls as arguments that expand to literals\n -- e.g., `writeln!(buf, \"{}\", env!(\"FOO\"))`.\n\n **Example:**\n ```rust\n # use std::fmt::Write;\n # let mut buf = String::new();\n // Bad\n writeln!(buf, \"{}\", \"foo\");\n\n // Good\n writeln!(buf, \"foo\");\n ```\n", - "applicability": null + "applicability": { + "is_multi_suggestion": false, + "applicability": null + } }, { "id": "zero_divided_by_zero", "id_span": { - "path": "clippy_lints/src/zero_div_zero.rs", + "path": "src/zero_div_zero.rs", "line": 23 }, "group": "clippy::complexity", @@ -5685,7 +5765,7 @@ { "id": "zero_sized_map_values", "id_span": { - "path": "clippy_lints/src/zero_sized_map_values.rs", + "path": "src/zero_sized_map_values.rs", "line": 37 }, "group": "clippy::pedantic", From 4fc960301bcd4370bfc2238415c7ba3d2d8f9312 Mon Sep 17 00:00:00 2001 From: xFrednet Date: Wed, 10 Mar 2021 23:04:12 +0100 Subject: [PATCH 12/15] Metadata collection: Rounding up the implementation --- .gitignore | 2 +- .../internal_lints/metadata_collector.rs | 144 +- clippy_utils/src/paths.rs | 6 +- metadata_collection.json | 5778 ----------------- tests/dogfood.rs | 4 - .../track_applicability_value.rs | 50 - 6 files changed, 84 insertions(+), 5900 deletions(-) delete mode 100644 metadata_collection.json delete mode 100644 tests/ui-internal/metadata-collector/track_applicability_value.rs diff --git a/.gitignore b/.gitignore index 565327a7f83..523bab18828 100644 --- a/.gitignore +++ b/.gitignore @@ -29,7 +29,7 @@ out # gh pages docs util/gh-pages/lints.json -# **/metadata_collection.json +**/metadata_collection.json # rustfmt backups *.rs.bk diff --git a/clippy_lints/src/utils/internal_lints/metadata_collector.rs b/clippy_lints/src/utils/internal_lints/metadata_collector.rs index 0425689b0dd..37e90bf8686 100644 --- a/clippy_lints/src/utils/internal_lints/metadata_collector.rs +++ b/clippy_lints/src/utils/internal_lints/metadata_collector.rs @@ -7,34 +7,21 @@ //! The module transforms all lint names to ascii lowercase to ensure that we don't have mismatches //! during any comparison or mapping. (Please take care of this, it's not fun to spend time on such //! a simple mistake) -//! -//! The metadata currently contains: -//! - [x] TODO The lint declaration line for [#1303](https://github.com/rust-lang/rust-clippy/issues/1303) -//! and [#6492](https://github.com/rust-lang/rust-clippy/issues/6492) -//! - [ ] TODO The Applicability for each lint for [#4310](https://github.com/rust-lang/rust-clippy/issues/4310) -// # Applicability -// - TODO xFrednet 2021-01-17: Find lint emit and collect applicability -// - TODO xFrednet 2021-02-28: 4x weird emission forwarding -// - See clippy_lints/src/enum_variants.rs@EnumVariantNames::check_name -// - TODO xFrednet 2021-02-28: 6x emission forwarding with local that is initializes from -// function. -// - See clippy_lints/src/methods/mod.rs@lint_binary_expr_with_method_call -// - TODO xFrednet 2021-02-28: 2x lint from local from function call -// - See clippy_lints/src/misc.rs@check_binary -// - TODO xFrednet 2021-02-28: 2x lint from local from method call -// - See clippy_lints/src/non_copy_const.rs@lint // # NITs // - TODO xFrednet 2021-02-13: Collect depreciations and maybe renames use if_chain::if_chain; use rustc_data_structures::fx::FxHashMap; -use rustc_hir::{self as hir, intravisit, intravisit::Visitor, ExprKind, Item, ItemKind, Mutability, QPath, def::DefKind}; +use rustc_hir::{ + self as hir, def::DefKind, intravisit, intravisit::Visitor, ExprKind, Item, ItemKind, Mutability, QPath, +}; use rustc_lint::{CheckLintNameResult, LateContext, LateLintPass, LintContext, LintId}; use rustc_middle::hir::map::Map; use rustc_session::{declare_tool_lint, impl_lint_pass}; use rustc_span::{sym, Loc, Span, Symbol}; -use serde::Serialize; +use serde::{ser::SerializeStruct, Serialize, Serializer}; +use std::collections::BinaryHeap; use std::fs::{self, OpenOptions}; use std::io::prelude::*; use std::path::Path; @@ -47,7 +34,7 @@ /// This is the output file of the lint collector. const OUTPUT_FILE: &str = "../metadata_collection.json"; /// These lints are excluded from the export. -const BLACK_LISTED_LINTS: [&str; 2] = ["lint_author", "deep_code_inspection"]; +const BLACK_LISTED_LINTS: [&str; 3] = ["lint_author", "deep_code_inspection", "internal_metadata_collector"]; /// These groups will be ignored by the lint group matcher. This is useful for collections like /// `clippy::all` const IGNORED_LINT_GROUPS: [&str; 1] = ["clippy::all"]; @@ -107,7 +94,7 @@ /// } /// ``` pub INTERNAL_METADATA_COLLECTOR, - internal, + internal_warn, "A busy bee collection metadata about lints" } @@ -116,7 +103,10 @@ #[allow(clippy::module_name_repetitions)] #[derive(Debug, Clone, Default)] pub struct MetadataCollector { - lints: Vec, + /// All collected lints + /// + /// We use a Heap here to have the lints added in alphabetic order in the export + lints: BinaryHeap, applicability_into: FxHashMap, } @@ -124,6 +114,8 @@ impl Drop for MetadataCollector { /// You might ask: How hacky is this? /// My answer: YES fn drop(&mut self) { + // The metadata collector gets dropped twice, this makes sure that we only write + // when the list is full if self.lints.is_empty() { return; } @@ -131,7 +123,8 @@ fn drop(&mut self) { let mut applicability_info = std::mem::take(&mut self.applicability_into); // Mapping the final data - self.lints + let mut lints = std::mem::take(&mut self.lints).into_sorted_vec(); + lints .iter_mut() .for_each(|x| x.applicability = applicability_info.remove(&x.id)); @@ -140,11 +133,11 @@ fn drop(&mut self) { fs::remove_file(OUTPUT_FILE).unwrap(); } let mut file = OpenOptions::new().write(true).create(true).open(OUTPUT_FILE).unwrap(); - writeln!(file, "{}", serde_json::to_string_pretty(&self.lints).unwrap()).unwrap(); + writeln!(file, "{}", serde_json::to_string_pretty(&lints).unwrap()).unwrap(); } } -#[derive(Debug, Clone, Serialize)] +#[derive(Debug, Clone, Serialize, PartialEq, Eq, PartialOrd, Ord)] struct LintMetadata { id: String, id_span: SerializableSpan, @@ -155,6 +148,24 @@ struct LintMetadata { applicability: Option, } +// impl Ord for LintMetadata { +// fn cmp(&self, other: &Self) -> Ordering { +// self.id.cmp(&other.id) +// } +// } +// +// impl PartialOrd for LintMetadata { +// fn partial_cmp(&self, other: &Self) -> Option { +// Some(self.cmp(other)) +// } +// } +// +// impl PartialEq for LintMetadata { +// fn eq(&self, other: &Self) -> bool { +// self.id == other.id +// } +// } + impl LintMetadata { fn new(id: String, id_span: SerializableSpan, group: String, docs: String) -> Self { Self { @@ -167,7 +178,7 @@ fn new(id: String, id_span: SerializableSpan, group: String, docs: String) -> Se } } -#[derive(Debug, Clone, Serialize)] +#[derive(Debug, Clone, Serialize, PartialEq, Eq, PartialOrd, Ord)] struct SerializableSpan { path: String, line: usize, @@ -194,25 +205,30 @@ fn from_span(cx: &LateContext<'_>, span: Span) -> Self { } } -#[derive(Debug, Clone, Default, Serialize)] +#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord)] struct ApplicabilityInfo { /// Indicates if any of the lint emissions uses multiple spans. This is related to /// [rustfix#141](https://github.com/rust-lang/rustfix/issues/141) as such suggestions can /// currently not be applied automatically. - is_multi_suggestion: bool, - applicability: Option, + is_multi_part_suggestion: bool, + applicability: Option, } -#[allow(dead_code)] -fn log_to_file(msg: &str) { - let mut file = OpenOptions::new() - .write(true) - .append(true) - .create(true) - .open("metadata-lint.log") - .unwrap(); +impl Serialize for ApplicabilityInfo { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let index = self.applicability.unwrap_or_default(); - write!(file, "{}", msg).unwrap(); + let mut s = serializer.serialize_struct("ApplicabilityInfo", 2)?; + s.serialize_field("is_multi_part_suggestion", &self.is_multi_part_suggestion)?; + s.serialize_field( + "applicability", + &paths::APPLICABILITY_VALUES[index][APPLICABILITY_NAME_INDEX], + )?; + s.end() + } } impl<'hir> LateLintPass<'hir> for MetadataCollector { @@ -266,16 +282,20 @@ fn check_item(&mut self, cx: &LateContext<'hir>, item: &'hir Item<'_>) { /// ``` fn check_expr(&mut self, cx: &LateContext<'hir>, expr: &'hir hir::Expr<'_>) { if let Some(args) = match_lint_emission(cx, expr) { - let mut emission_info = extract_complex_emission_info(cx, args); + let mut emission_info = extract_emission_info(cx, args); if emission_info.is_empty() { - lint_collection_error_span(cx, expr.span, "Look, here ... I have no clue what todo with it"); + // See: + // - src/misc.rs:734:9 + // - src/methods/mod.rs:3545:13 + // - src/methods/mod.rs:3496:13 + // We are basically unable to resolve the lint name it self. return; } for (lint_name, applicability, is_multi_part) in emission_info.drain(..) { let app_info = self.applicability_into.entry(lint_name).or_default(); app_info.applicability = applicability; - app_info.is_multi_suggestion = is_multi_part; + app_info.is_multi_part_suggestion = is_multi_part; } } } @@ -289,7 +309,7 @@ fn sym_to_string(sym: Symbol) -> String { } fn extract_attr_docs_or_lint(cx: &LateContext<'_>, item: &Item<'_>) -> Option { - extract_attr_docs(item).or_else(|| { + extract_attr_docs(cx, item).or_else(|| { lint_collection_error_item(cx, item, "could not collect the lint documentation"); None }) @@ -305,8 +325,10 @@ fn extract_attr_docs_or_lint(cx: &LateContext<'_>, item: &Item<'_>) -> Option) -> Option { - item.attrs +fn extract_attr_docs(cx: &LateContext<'_>, item: &Item<'_>) -> Option { + cx.tcx + .hir() + .attrs(item.hir_id()) .iter() .filter_map(|ref x| x.doc_str().map(|sym| sym.as_str().to_string())) .reduce(|mut acc, sym| { @@ -357,15 +379,6 @@ fn lint_collection_error_item(cx: &LateContext<'_>, item: &Item<'_>, message: &s ); } -fn lint_collection_error_span(cx: &LateContext<'_>, span: Span, message: &str) { - span_lint( - cx, - INTERNAL_METADATA_COLLECTOR, - span, - &format!("Metadata collection error: {}", message), - ); -} - // ================================================================== // Applicability // ================================================================== @@ -377,11 +390,15 @@ fn match_lint_emission<'hir>(cx: &LateContext<'hir>, expr: &'hir hir::Expr<'_>) .find_map(|emission_fn| match_function_call(cx, expr, emission_fn)) } -fn extract_complex_emission_info<'hir>( +fn take_higher_applicability(a: Option, b: Option) -> Option { + a.map_or(b, |a| a.max(b.unwrap_or_default()).into()) +} + +fn extract_emission_info<'hir>( cx: &LateContext<'hir>, args: &'hir [hir::Expr<'hir>], -) -> Vec<(String, Option, bool)> { - let mut lints= Vec::new(); +) -> Vec<(String, Option, bool)> { + let mut lints = Vec::new(); let mut applicability = None; let mut multi_part = false; @@ -401,7 +418,10 @@ fn extract_complex_emission_info<'hir>( } } - lints.drain(..).map(|lint_name| (lint_name, applicability.clone(), multi_part)).collect() + lints + .drain(..) + .map(|lint_name| (lint_name, applicability, multi_part)) + .collect() } /// Resolves the possible lints that this expression could reference @@ -412,7 +432,7 @@ fn resolve_lints(cx: &LateContext<'hir>, expr: &'hir hir::Expr<'hir>) -> Vec, expr: &'hir hir::Expr<'hir>) -> Option { +fn resolve_applicability(cx: &LateContext<'hir>, expr: &'hir hir::Expr<'hir>) -> Option { let mut resolver = ApplicabilityResolver::new(cx); resolver.visit_expr(expr); resolver.complete() @@ -457,7 +477,7 @@ fn visit_expr(&mut self, expr: &'hir hir::Expr<'hir>) { if_chain! { if let ExprKind::Path(qpath) = &expr.kind; if let QPath::Resolved(_, path) = qpath; - + let (expr_ty, _) = walk_ptrs_ty_depth(self.cx.typeck_results().expr_ty(&expr)); if match_type(self.cx, expr_ty, &paths::LINT); then { @@ -492,15 +512,11 @@ fn new(cx: &'a LateContext<'hir>) -> Self { } fn add_new_index(&mut self, new_index: usize) { - self.applicability_index = self - .applicability_index - .map_or(new_index, |old_index| old_index.min(new_index)) - .into(); + self.applicability_index = take_higher_applicability(self.applicability_index, Some(new_index)); } - fn complete(self) -> Option { + fn complete(self) -> Option { self.applicability_index - .map(|index| paths::APPLICABILITY_VALUES[index][APPLICABILITY_NAME_INDEX].to_string()) } } diff --git a/clippy_utils/src/paths.rs b/clippy_utils/src/paths.rs index 1f19724ad25..7c7bb9b02b1 100644 --- a/clippy_utils/src/paths.rs +++ b/clippy_utils/src/paths.rs @@ -9,10 +9,10 @@ pub const APPLICABILITY: [&str; 2] = ["rustc_lint_defs", "Applicability"]; #[cfg(feature = "metadata-collector-lint")] pub const APPLICABILITY_VALUES: [[&str; 3]; 4] = [ - ["rustc_lint_defs", "Applicability", "MachineApplicable"], - ["rustc_lint_defs", "Applicability", "MaybeIncorrect"], - ["rustc_lint_defs", "Applicability", "HasPlaceholders"], ["rustc_lint_defs", "Applicability", "Unspecified"], + ["rustc_lint_defs", "Applicability", "HasPlaceholders"], + ["rustc_lint_defs", "Applicability", "MaybeIncorrect"], + ["rustc_lint_defs", "Applicability", "MachineApplicable"], ]; #[cfg(feature = "metadata-collector-lint")] pub const DIAGNOSTIC_BUILDER: [&str; 3] = ["rustc_errors", "diagnostic_builder", "DiagnosticBuilder"]; diff --git a/metadata_collection.json b/metadata_collection.json deleted file mode 100644 index f6f72ffa5fa..00000000000 --- a/metadata_collection.json +++ /dev/null @@ -1,5778 +0,0 @@ -[ - { - "id": "approx_constant", - "id_span": { - "path": "src/approx_const.rs", - "line": 34 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for floating point literals that approximate constants which are defined in\n [`std::f32::consts`](https://doc.rust-lang.org/stable/std/f32/consts/#constants)\n or\n [`std::f64::consts`](https://doc.rust-lang.org/stable/std/f64/consts/#constants),\n respectively, suggesting to use the predefined constant.\n\n **Why is this bad?** Usually, the definition in the standard library is more\n precise than what people come up with. If you find that your definition is\n actually more precise, please [file a Rust\n issue](https://github.com/rust-lang/rust/issues).\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let x = 3.14;\n let y = 1_f64 / x;\n ```\n Use predefined constants instead:\n ```rust\n let x = std::f32::consts::PI;\n let y = std::f64::consts::FRAC_1_PI;\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "integer_arithmetic", - "id_span": { - "path": "src/arithmetic.rs", - "line": 28 - }, - "group": "clippy::restriction", - "docs": " **What it does:** Checks for integer arithmetic operations which could overflow or panic.\n Specifically, checks for any operators (`+`, `-`, `*`, `<<`, etc) which are capable\n of overflowing according to the [Rust\n Reference](https://doc.rust-lang.org/reference/expressions/operator-expr.html#overflow),\n or which can panic (`/`, `%`). No bounds analysis or sophisticated reasoning is\n attempted.\n\n **Why is this bad?** Integer overflow will trigger a panic in debug builds or will wrap in\n release mode. Division by zero will cause a panic in either mode. In some applications one\n wants explicitly checked, wrapping or saturating arithmetic.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let a = 0;\n a + 1;\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "float_arithmetic", - "id_span": { - "path": "src/arithmetic.rs", - "line": 46 - }, - "group": "clippy::restriction", - "docs": " **What it does:** Checks for float arithmetic.\n **Why is this bad?** For some embedded systems or kernel development, it\n can be useful to rule out floating-point numbers.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let a = 0.0;\n a + 1.0;\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "as_conversions", - "id_span": { - "path": "src/as_conversions.rs", - "line": 42 - }, - "group": "clippy::restriction", - "docs": " **What it does:** Checks for usage of `as` conversions.\n Note that this lint is specialized in linting *every single* use of `as`\n regardless of whether good alternatives exist or not.\n If you want more precise lints for `as`, please consider using these separate lints:\n `unnecessary_cast`, `cast_lossless/possible_truncation/possible_wrap/precision_loss/sign_loss`,\n `fn_to_numeric_cast(_with_truncation)`, `char_lit_as_u8`, `ref_to_mut` and `ptr_as_ptr`.\n There is a good explanation the reason why this lint should work in this way and how it is useful\n [in this issue](https://github.com/rust-lang/rust-clippy/issues/5122).\n\n **Why is this bad?** `as` conversions will perform many kinds of\n conversions, including silently lossy conversions and dangerous coercions.\n There are cases when it makes sense to use `as`, so the lint is\n Allow by default.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n let a: u32;\n ...\n f(a as u16);\n ```\n\n Usually better represents the semantics you expect:\n ```rust,ignore\n f(a.try_into()?);\n ```\n or\n ```rust,ignore\n f(a.try_into().expect(\"Unexpected u16 overflow in f\"));\n ```\n\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "inline_asm_x86_intel_syntax", - "id_span": { - "path": "src/asm_syntax.rs", - "line": 78 - }, - "group": "clippy::restriction", - "docs": " **What it does:** Checks for usage of Intel x86 assembly syntax.\n **Why is this bad?** The lint has been enabled to indicate a preference\n for AT&T x86 assembly syntax.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust,no_run\n # #![feature(asm)]\n # unsafe { let ptr = \"\".as_ptr();\n asm!(\"lea {}, [{}]\", lateout(reg) _, in(reg) ptr);\n # }\n ```\n Use instead:\n ```rust,no_run\n # #![feature(asm)]\n # unsafe { let ptr = \"\".as_ptr();\n asm!(\"lea ({}), {}\", in(reg) ptr, lateout(reg) _, options(att_syntax));\n # }\n ```\n", - "applicability": null - }, - { - "id": "inline_asm_x86_att_syntax", - "id_span": { - "path": "src/asm_syntax.rs", - "line": 114 - }, - "group": "clippy::restriction", - "docs": " **What it does:** Checks for usage of AT&T x86 assembly syntax.\n **Why is this bad?** The lint has been enabled to indicate a preference\n for Intel x86 assembly syntax.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust,no_run\n # #![feature(asm)]\n # unsafe { let ptr = \"\".as_ptr();\n asm!(\"lea ({}), {}\", in(reg) ptr, lateout(reg) _, options(att_syntax));\n # }\n ```\n Use instead:\n ```rust,no_run\n # #![feature(asm)]\n # unsafe { let ptr = \"\".as_ptr();\n asm!(\"lea {}, [{}]\", lateout(reg) _, in(reg) ptr);\n # }\n ```\n", - "applicability": null - }, - { - "id": "assertions_on_constants", - "id_span": { - "path": "src/assertions_on_constants.rs", - "line": 23 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for `assert!(true)` and `assert!(false)` calls.\n **Why is this bad?** Will be optimized out by the compiler or should probably be replaced by a\n `panic!()` or `unreachable!()`\n\n **Known problems:** None\n\n **Example:**\n ```rust,ignore\n assert!(false)\n assert!(true)\n const B: bool = false;\n assert!(B)\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "assign_op_pattern", - "id_span": { - "path": "src/assign_ops.rs", - "line": 33 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for `a = a op b` or `a = b commutative_op a` patterns.\n\n **Why is this bad?** These can be written as the shorter `a op= b`.\n\n **Known problems:** While forbidden by the spec, `OpAssign` traits may have\n implementations that differ from the regular `Op` impl.\n\n **Example:**\n ```rust\n let mut a = 5;\n let b = 0;\n // ...\n // Bad\n a = a + b;\n\n // Good\n a += b;\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "misrefactored_assign_op", - "id_span": { - "path": "src/assign_ops.rs", - "line": 56 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for `a op= a op b` or `a op= b op a` patterns.\n **Why is this bad?** Most likely these are bugs where one meant to write `a\n op= b`.\n\n **Known problems:** Clippy cannot know for sure if `a op= a op b` should have\n been `a = a op a op b` or `a = a op b`/`a op= b`. Therefore, it suggests both.\n If `a op= a op b` is really the correct behaviour it should be\n written as `a = a op a op b` as it's less confusing.\n\n **Example:**\n ```rust\n let mut a = 5;\n let b = 2;\n // ...\n a += a + b;\n ```\n", - "applicability": { - "is_multi_suggestion": true, - "applicability": "MaybeIncorrect" - } - }, - { - "id": "async_yields_async", - "id_span": { - "path": "src/async_yields_async.rs", - "line": 36 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for async blocks that yield values of types that can themselves be awaited.\n\n **Why is this bad?** An await is likely missing.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n async fn foo() {}\n\n fn bar() {\n let x = async {\n foo()\n };\n }\n ```\n Use instead:\n ```rust\n async fn foo() {}\n\n fn bar() {\n let x = async {\n foo().await\n };\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MaybeIncorrect" - } - }, - { - "id": "invalid_atomic_ordering", - "id_span": { - "path": "src/atomic_ordering.rs", - "line": 47 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for usage of invalid atomic ordering in atomic loads/stores/exchanges/updates and\n memory fences.\n\n **Why is this bad?** Using an invalid atomic ordering\n will cause a panic at run-time.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,no_run\n # use std::sync::atomic::{self, AtomicU8, Ordering};\n\n let x = AtomicU8::new(0);\n\n // Bad: `Release` and `AcqRel` cannot be used for `load`.\n let _ = x.load(Ordering::Release);\n let _ = x.load(Ordering::AcqRel);\n\n // Bad: `Acquire` and `AcqRel` cannot be used for `store`.\n x.store(1, Ordering::Acquire);\n x.store(2, Ordering::AcqRel);\n\n // Bad: `Relaxed` cannot be used as a fence's ordering.\n atomic::fence(Ordering::Relaxed);\n atomic::compiler_fence(Ordering::Relaxed);\n\n // Bad: `Release` and `AcqRel` are both always invalid\n // for the failure ordering (the last arg).\n let _ = x.compare_exchange(1, 2, Ordering::SeqCst, Ordering::Release);\n let _ = x.compare_exchange_weak(2, 3, Ordering::AcqRel, Ordering::AcqRel);\n\n // Bad: The failure ordering is not allowed to be\n // stronger than the success order, and `SeqCst` is\n // stronger than `Relaxed`.\n let _ = x.fetch_update(Ordering::Relaxed, Ordering::SeqCst, |val| Some(val + val));\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "inline_always", - "id_span": { - "path": "src/attrs.rs", - "line": 65 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for items annotated with `#[inline(always)]`, unless the annotated function is empty or simply panics.\n\n **Why is this bad?** While there are valid uses of this annotation (and once\n you know when to use it, by all means `allow` this lint), it's a common\n newbie-mistake to pepper one's code with it.\n\n As a rule of thumb, before slapping `#[inline(always)]` on a function,\n measure if that additional function call really affects your runtime profile\n sufficiently to make up for the increase in compile time.\n\n **Known problems:** False positives, big time. This lint is meant to be\n deactivated by everyone doing serious performance work. This means having\n done the measurement.\n\n **Example:**\n ```ignore\n #[inline(always)]\n fn not_quite_hot_code(..) { ... }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "useless_attribute", - "id_span": { - "path": "src/attrs.rs", - "line": 99 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for `extern crate` and `use` items annotated with lint attributes.\n\n This lint permits `#[allow(unused_imports)]`, `#[allow(deprecated)]`,\n `#[allow(unreachable_pub)]`, `#[allow(clippy::wildcard_imports)]` and\n `#[allow(clippy::enum_glob_use)]` on `use` items and `#[allow(unused_imports)]` on\n `extern crate` items with a `#[macro_use]` attribute.\n\n **Why is this bad?** Lint attributes have no effect on crate imports. Most\n likely a `!` was forgotten.\n\n **Known problems:** None.\n\n **Example:**\n ```ignore\n // Bad\n #[deny(dead_code)]\n extern crate foo;\n #[forbid(dead_code)]\n use foo::bar;\n\n // Ok\n #[allow(unused_imports)]\n use foo::baz;\n #[allow(unused_imports)]\n #[macro_use]\n extern crate baz;\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MaybeIncorrect" - } - }, - { - "id": "deprecated_semver", - "id_span": { - "path": "src/attrs.rs", - "line": 118 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for `#[deprecated]` annotations with a `since` field that is not a valid semantic version.\n\n **Why is this bad?** For checking the version of the deprecation, it must be\n a valid semver. Failing that, the contained information is useless.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n #[deprecated(since = \"forever\")]\n fn something_else() { /* ... */ }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "empty_line_after_outer_attr", - "id_span": { - "path": "src/attrs.rs", - "line": 153 - }, - "group": "clippy::nursery", - "docs": " **What it does:** Checks for empty lines after outer attributes\n **Why is this bad?**\n Most likely the attribute was meant to be an inner attribute using a '!'.\n If it was meant to be an outer attribute, then the following item\n should not be separated by empty lines.\n\n **Known problems:** Can cause false positives.\n\n From the clippy side it's difficult to detect empty lines between an attributes and the\n following item because empty lines and comments are not part of the AST. The parsing\n currently works for basic cases but is not perfect.\n\n **Example:**\n ```rust\n // Good (as inner attribute)\n #![allow(dead_code)]\n\n fn this_is_fine() { }\n\n // Bad\n #[allow(dead_code)]\n\n fn not_quite_good_code() { }\n\n // Good (as outer attribute)\n #[allow(dead_code)]\n fn this_is_fine_too() { }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "blanket_clippy_restriction_lints", - "id_span": { - "path": "src/attrs.rs", - "line": 176 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for `warn`/`deny`/`forbid` attributes targeting the whole clippy::restriction category.\n **Why is this bad?** Restriction lints sometimes are in contrast with other lints or even go against idiomatic rust.\n These lints should only be enabled on a lint-by-lint basis and with careful consideration.\n\n **Known problems:** None.\n\n **Example:**\n Bad:\n ```rust\n #![deny(clippy::restriction)]\n ```\n\n Good:\n ```rust\n #![deny(clippy::as_conversions)]\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "deprecated_cfg_attr", - "id_span": { - "path": "src/attrs.rs", - "line": 205 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for `#[cfg_attr(rustfmt, rustfmt_skip)]` and suggests to replace it with `#[rustfmt::skip]`.\n\n **Why is this bad?** Since tool_attributes ([rust-lang/rust#44690](https://github.com/rust-lang/rust/issues/44690))\n are stable now, they should be used instead of the old `cfg_attr(rustfmt)` attributes.\n\n **Known problems:** This lint doesn't detect crate level inner attributes, because they get\n processed before the PreExpansionPass lints get executed. See\n [#3123](https://github.com/rust-lang/rust-clippy/pull/3123#issuecomment-422321765)\n\n **Example:**\n\n Bad:\n ```rust\n #[cfg_attr(rustfmt, rustfmt_skip)]\n fn main() { }\n ```\n\n Good:\n ```rust\n #[rustfmt::skip]\n fn main() { }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "mismatched_target_os", - "id_span": { - "path": "src/attrs.rs", - "line": 238 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for cfg attributes having operating systems used in target family position.\n **Why is this bad?** The configuration option will not be recognised and the related item will not be included\n by the conditional compilation engine.\n\n **Known problems:** None.\n\n **Example:**\n\n Bad:\n ```rust\n #[cfg(linux)]\n fn conditional() { }\n ```\n\n Good:\n ```rust\n #[cfg(target_os = \"linux\")]\n fn conditional() { }\n ```\n\n Or:\n ```rust\n #[cfg(unix)]\n fn conditional() { }\n ```\n Check the [Rust Reference](https://doc.rust-lang.org/reference/conditional-compilation.html#target_os) for more details.\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MaybeIncorrect" - } - }, - { - "id": "await_holding_lock", - "id_span": { - "path": "src/await_holding_invalid.rs", - "line": 47 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for calls to await while holding a non-async-aware MutexGuard.\n\n **Why is this bad?** The Mutex types found in std::sync and parking_lot\n are not designed to operate in an async context across await points.\n\n There are two potential solutions. One is to use an asynx-aware Mutex\n type. Many asynchronous foundation crates provide such a Mutex type. The\n other solution is to ensure the mutex is unlocked before calling await,\n either by introducing a scope or an explicit call to Drop::drop.\n\n **Known problems:** Will report false positive for explicitly dropped guards ([#6446](https://github.com/rust-lang/rust-clippy/issues/6446)).\n\n **Example:**\n\n ```rust,ignore\n use std::sync::Mutex;\n\n async fn foo(x: &Mutex) {\n let guard = x.lock().unwrap();\n *guard += 1;\n bar.await;\n }\n ```\n\n Use instead:\n ```rust,ignore\n use std::sync::Mutex;\n\n async fn foo(x: &Mutex) {\n {\n let guard = x.lock().unwrap();\n *guard += 1;\n }\n bar.await;\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "await_holding_refcell_ref", - "id_span": { - "path": "src/await_holding_invalid.rs", - "line": 86 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for calls to await while holding a `RefCell` `Ref` or `RefMut`.\n\n **Why is this bad?** `RefCell` refs only check for exclusive mutable access\n at runtime. Holding onto a `RefCell` ref across an `await` suspension point\n risks panics from a mutable ref shared while other refs are outstanding.\n\n **Known problems:** Will report false positive for explicitly dropped refs ([#6353](https://github.com/rust-lang/rust-clippy/issues/6353)).\n\n **Example:**\n\n ```rust,ignore\n use std::cell::RefCell;\n\n async fn foo(x: &RefCell) {\n let mut y = x.borrow_mut();\n *y += 1;\n bar.await;\n }\n ```\n\n Use instead:\n ```rust,ignore\n use std::cell::RefCell;\n\n async fn foo(x: &RefCell) {\n {\n let mut y = x.borrow_mut();\n *y += 1;\n }\n bar.await;\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "bad_bit_mask", - "id_span": { - "path": "src/bit_mask.rs", - "line": 44 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for incompatible bit masks in comparisons.\n The formula for detecting if an expression of the type `_ m\n c` (where `` is one of {`&`, `|`} and `` is one of\n {`!=`, `>=`, `>`, `!=`, `>=`, `>`}) can be determined from the following\n table:\n\n |Comparison |Bit Op|Example |is always|Formula |\n |------------|------|------------|---------|----------------------|\n |`==` or `!=`| `&` |`x & 2 == 3`|`false` |`c & m != c` |\n |`<` or `>=`| `&` |`x & 2 < 3` |`true` |`m < c` |\n |`>` or `<=`| `&` |`x & 1 > 1` |`false` |`m <= c` |\n |`==` or `!=`| `|` |`x | 1 == 0`|`false` |`c | m != c` |\n |`<` or `>=`| `|` |`x | 1 < 1` |`false` |`m >= c` |\n |`<=` or `>` | `|` |`x | 1 > 0` |`true` |`m > c` |\n\n **Why is this bad?** If the bits that the comparison cares about are always\n set to zero or one by the bit mask, the comparison is constant `true` or\n `false` (depending on mask, compared value, and operators).\n\n So the code is actively misleading, and the only reason someone would write\n this intentionally is to win an underhanded Rust contest or create a\n test-case for this lint.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let x = 1;\n if (x & 1 == 2) { }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "ineffective_bit_mask", - "id_span": { - "path": "src/bit_mask.rs", - "line": 73 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for bit masks in comparisons which can be removed without changing the outcome. The basic structure can be seen in the\n following table:\n\n |Comparison| Bit Op |Example |equals |\n |----------|---------|-----------|-------|\n |`>` / `<=`|`|` / `^`|`x | 2 > 3`|`x > 3`|\n |`<` / `>=`|`|` / `^`|`x ^ 1 < 4`|`x < 4`|\n\n **Why is this bad?** Not equally evil as [`bad_bit_mask`](#bad_bit_mask),\n but still a bit misleading, because the bit mask is ineffective.\n\n **Known problems:** False negatives: This lint will only match instances\n where we have figured out the math (which is for a power-of-two compared\n value). This means things like `x | 1 >= 7` (which would be better written\n as `x >= 6`) will not be reported (but bit masks like this are fairly\n uncommon).\n\n **Example:**\n ```rust\n # let x = 1;\n if (x | 1 > 3) { }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "verbose_bit_mask", - "id_span": { - "path": "src/bit_mask.rs", - "line": 92 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for bit masks that can be replaced by a call to `trailing_zeros`\n\n **Why is this bad?** `x.trailing_zeros() > 4` is much clearer than `x & 15\n == 0`\n\n **Known problems:** llvm generates better code for `x & 15 == 0` on x86\n\n **Example:**\n ```rust\n # let x = 1;\n if x & 0b1111 == 0 { }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MaybeIncorrect" - } - }, - { - "id": "blacklisted_name", - "id_span": { - "path": "src/blacklisted_name.rs", - "line": 20 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for usage of blacklisted names for variables, such as `foo`.\n\n **Why is this bad?** These names are usually placeholder names and should be\n avoided.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let foo = 3.14;\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "blocks_in_if_conditions", - "id_span": { - "path": "src/blocks_in_if_conditions.rs", - "line": 42 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for `if` conditions that use blocks containing an expression, statements or conditions that use closures with blocks.\n\n **Why is this bad?** Style, using blocks in the condition makes it hard to read.\n\n **Known problems:** None.\n\n **Examples:**\n ```rust\n // Bad\n if { true } { /* ... */ }\n\n // Good\n if true { /* ... */ }\n ```\n\n // or\n\n ```rust\n # fn somefunc() -> bool { true };\n // Bad\n if { let x = somefunc(); x } { /* ... */ }\n\n // Good\n let res = { let x = somefunc(); x };\n if res { /* ... */ }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "nonminimal_bool", - "id_span": { - "path": "src/booleans.rs", - "line": 31 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for boolean expressions that can be written more concisely.\n\n **Why is this bad?** Readability of boolean expressions suffers from\n unnecessary duplication.\n\n **Known problems:** Ignores short circuiting behavior of `||` and\n `&&`. Ignores `|`, `&` and `^`.\n\n **Example:**\n ```ignore\n if a && true // should be: if a\n if !(a == b) // should be: if a != b\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "logic_bug", - "id_span": { - "path": "src/booleans.rs", - "line": 49 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for boolean expressions that contain terminals that can be eliminated.\n\n **Why is this bad?** This is most likely a logic bug.\n\n **Known problems:** Ignores short circuiting behavior.\n\n **Example:**\n ```ignore\n if a && b || a { ... }\n ```\n The `b` is unnecessary, the expression is equivalent to `if a`.\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "Unspecified" - } - }, - { - "id": "naive_bytecount", - "id_span": { - "path": "src/bytecount.rs", - "line": 30 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for naive byte counts\n **Why is this bad?** The [`bytecount`](https://crates.io/crates/bytecount)\n crate has methods to count your bytes faster, especially for large slices.\n\n **Known problems:** If you have predominantly small slices, the\n `bytecount::count(..)` method may actually be slower. However, if you can\n ensure that less than 2³²-1 matches arise, the `naive_count_32(..)` can be\n faster in those cases.\n\n **Example:**\n\n ```rust\n # let vec = vec![1_u8];\n &vec.iter().filter(|x| **x == 0u8).count(); // use bytecount::count instead\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MaybeIncorrect" - } - }, - { - "id": "cargo_common_metadata", - "id_span": { - "path": "src/cargo_common_metadata.rs", - "line": 49 - }, - "group": "clippy::cargo", - "docs": " **What it does:** Checks to see if all common metadata is defined in `Cargo.toml`. See: https://rust-lang-nursery.github.io/api-guidelines/documentation.html#cargotoml-includes-all-common-metadata-c-metadata\n\n **Why is this bad?** It will be more difficult for users to discover the\n purpose of the crate, and key information related to it.\n\n **Known problems:** None.\n\n **Example:**\n ```toml\n # This `Cargo.toml` is missing an authors field:\n [package]\n name = \"clippy\"\n version = \"0.0.212\"\n description = \"A bunch of helpful lints to avoid common pitfalls in Rust\"\n repository = \"https://github.com/rust-lang/rust-clippy\"\n readme = \"README.md\"\n license = \"MIT OR Apache-2.0\"\n keywords = [\"clippy\", \"lint\", \"plugin\"]\n categories = [\"development-tools\", \"development-tools::cargo-plugins\"]\n ```\n\n Should include an authors field like:\n\n ```toml\n # This `Cargo.toml` includes all common metadata\n [package]\n name = \"clippy\"\n version = \"0.0.212\"\n authors = [\"Someone \"]\n description = \"A bunch of helpful lints to avoid common pitfalls in Rust\"\n repository = \"https://github.com/rust-lang/rust-clippy\"\n readme = \"README.md\"\n license = \"MIT OR Apache-2.0\"\n keywords = [\"clippy\", \"lint\", \"plugin\"]\n categories = [\"development-tools\", \"development-tools::cargo-plugins\"]\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "case_sensitive_file_extension_comparisons", - "id_span": { - "path": "src/case_sensitive_file_extension_comparisons.rs", - "line": 34 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for calls to `ends_with` with possible file extensions\n and suggests to use a case-insensitive approach instead.\n\n **Why is this bad?**\n `ends_with` is case-sensitive and may not detect files with a valid extension.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n fn is_rust_file(filename: &str) -> bool {\n filename.ends_with(\".rs\")\n }\n ```\n Use instead:\n ```rust\n fn is_rust_file(filename: &str) -> bool {\n filename.rsplit('.').next().map(|ext| ext.eq_ignore_ascii_case(\"rs\")) == Some(true)\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "checked_conversions", - "id_span": { - "path": "src/checked_conversions.rs", - "line": 40 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for explicit bounds checking when casting.\n **Why is this bad?** Reduces the readability of statements & is error prone.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let foo: u32 = 5;\n # let _ =\n foo <= i32::MAX as u32\n # ;\n ```\n\n Could be written:\n\n ```rust\n # use std::convert::TryFrom;\n # let foo = 1;\n # let _ =\n i32::try_from(foo).is_ok()\n # ;\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "cognitive_complexity", - "id_span": { - "path": "src/cognitive_complexity.rs", - "line": 24 - }, - "group": "clippy::nursery", - "docs": " **What it does:** Checks for methods with high cognitive complexity.\n **Why is this bad?** Methods of high cognitive complexity tend to be hard to\n both read and maintain. Also LLVM will tend to optimize small methods better.\n\n **Known problems:** Sometimes it's hard to find a way to reduce the\n complexity.\n\n **Example:** No. You'll see it when you get the warning.\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "collapsible_if", - "id_span": { - "path": "src/collapsible_if.rs", - "line": 50 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for nested `if` statements which can be collapsed by `&&`-combining their conditions.\n\n **Why is this bad?** Each `if`-statement adds one level of nesting, which\n makes code look more complex than it really is.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n if x {\n if y {\n …\n }\n }\n\n ```\n\n Should be written:\n\n ```rust.ignore\n if x && y {\n …\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "collapsible_else_if", - "id_span": { - "path": "src/collapsible_if.rs", - "line": 85 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for collapsible `else { if ... }` expressions that can be collapsed to `else if ...`.\n\n **Why is this bad?** Each `if`-statement adds one level of nesting, which\n makes code look more complex than it really is.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n\n if x {\n …\n } else {\n if y {\n …\n }\n }\n ```\n\n Should be written:\n\n ```rust.ignore\n if x {\n …\n } else if y {\n …\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "collapsible_match", - "id_span": { - "path": "src/collapsible_match.rs", - "line": 44 - }, - "group": "clippy::style", - "docs": " **What it does:** Finds nested `match` or `if let` expressions where the patterns may be \"collapsed\" together without adding any branches.\n\n Note that this lint is not intended to find _all_ cases where nested match patterns can be merged, but only\n cases where merging would most likely make the code more readable.\n\n **Why is this bad?** It is unnecessarily verbose and complex.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n fn func(opt: Option>) {\n let n = match opt {\n Some(n) => match n {\n Ok(n) => n,\n _ => return,\n }\n None => return,\n };\n }\n ```\n Use instead:\n ```rust\n fn func(opt: Option>) {\n let n = match opt {\n Some(Ok(n)) => n,\n _ => return,\n };\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "comparison_chain", - "id_span": { - "path": "src/comparison_chain.rs", - "line": 49 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks comparison chains written with `if` that can be rewritten with `match` and `cmp`.\n\n **Why is this bad?** `if` is not guaranteed to be exhaustive and conditionals can get\n repetitive\n\n **Known problems:** The match statement may be slower due to the compiler\n not inlining the call to cmp. See issue [#5354](https://github.com/rust-lang/rust-clippy/issues/5354)\n\n **Example:**\n ```rust,ignore\n # fn a() {}\n # fn b() {}\n # fn c() {}\n fn f(x: u8, y: u8) {\n if x > y {\n a()\n } else if x < y {\n b()\n } else {\n c()\n }\n }\n ```\n\n Could be written:\n\n ```rust,ignore\n use std::cmp::Ordering;\n # fn a() {}\n # fn b() {}\n # fn c() {}\n fn f(x: u8, y: u8) {\n match x.cmp(&y) {\n Ordering::Greater => a(),\n Ordering::Less => b(),\n Ordering::Equal => c()\n }\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "ifs_same_cond", - "id_span": { - "path": "src/copies.rs", - "line": 33 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for consecutive `if`s with the same condition.\n **Why is this bad?** This is probably a copy & paste error.\n\n **Known problems:** Hopefully none.\n\n **Example:**\n ```ignore\n if a == b {\n …\n } else if a == b {\n …\n }\n ```\n\n Note that this lint ignores all conditions with a function call as it could\n have side effects:\n\n ```ignore\n if foo() {\n …\n } else if foo() { // not linted\n …\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "same_functions_in_if_condition", - "id_span": { - "path": "src/copies.rs", - "line": 80 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for consecutive `if`s with the same function call.\n **Why is this bad?** This is probably a copy & paste error.\n Despite the fact that function can have side effects and `if` works as\n intended, such an approach is implicit and can be considered a \"code smell\".\n\n **Known problems:** Hopefully none.\n\n **Example:**\n ```ignore\n if foo() == bar {\n …\n } else if foo() == bar {\n …\n }\n ```\n\n This probably should be:\n ```ignore\n if foo() == bar {\n …\n } else if foo() == baz {\n …\n }\n ```\n\n or if the original code was not a typo and called function mutates a state,\n consider move the mutation out of the `if` condition to avoid similarity to\n a copy & paste error:\n\n ```ignore\n let first = foo();\n if first == bar {\n …\n } else {\n let second = foo();\n if second == bar {\n …\n }\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "if_same_then_else", - "id_span": { - "path": "src/copies.rs", - "line": 101 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for `if/else` with the same body as the *then* part and the *else* part.\n\n **Why is this bad?** This is probably a copy & paste error.\n\n **Known problems:** Hopefully none.\n\n **Example:**\n ```ignore\n let foo = if … {\n 42\n } else {\n 42\n };\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "copy_iterator", - "id_span": { - "path": "src/copy_iterator.rs", - "line": 27 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for types that implement `Copy` as well as `Iterator`.\n\n **Why is this bad?** Implicit copies can be confusing when working with\n iterator combinators.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n #[derive(Copy, Clone)]\n struct Countdown(u8);\n\n impl Iterator for Countdown {\n // ...\n }\n\n let a: Vec<_> = my_iterator.take(1).collect();\n let b: Vec<_> = my_iterator.collect();\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "create_dir", - "id_span": { - "path": "src/create_dir.rs", - "line": 24 - }, - "group": "clippy::restriction", - "docs": " **What it does:** Checks usage of `std::fs::create_dir` and suggest using `std::fs::create_dir_all` instead.\n **Why is this bad?** Sometimes `std::fs::create_dir` is mistakenly chosen over `std::fs::create_dir_all`.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n std::fs::create_dir(\"foo\");\n ```\n Use instead:\n ```rust\n std::fs::create_dir_all(\"foo\");\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MaybeIncorrect" - } - }, - { - "id": "dbg_macro", - "id_span": { - "path": "src/dbg_macro.rs", - "line": 25 - }, - "group": "clippy::restriction", - "docs": " **What it does:** Checks for usage of dbg!() macro.\n **Why is this bad?** `dbg!` macro is intended as a debugging tool. It\n should not be in version control.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n // Bad\n dbg!(true)\n\n // Good\n true\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "default_trait_access", - "id_span": { - "path": "src/default.rs", - "line": 33 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for literal calls to `Default::default()`.\n **Why is this bad?** It's more clear to the reader to use the name of the type whose default is\n being gotten than the generic `Default`.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n // Bad\n let s: String = Default::default();\n\n // Good\n let s = String::default();\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "Unspecified" - } - }, - { - "id": "field_reassign_with_default", - "id_span": { - "path": "src/default.rs", - "line": 63 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for immediate reassignment of fields initialized with Default::default().\n\n **Why is this bad?**It's more idiomatic to use the [functional update syntax](https://doc.rust-lang.org/reference/expressions/struct-expr.html#functional-update-syntax).\n\n **Known problems:** Assignments to patterns that are of tuple type are not linted.\n\n **Example:**\n Bad:\n ```\n # #[derive(Default)]\n # struct A { i: i32 }\n let mut a: A = Default::default();\n a.i = 42;\n ```\n Use instead:\n ```\n # #[derive(Default)]\n # struct A { i: i32 }\n let a = A {\n i: 42,\n .. Default::default()\n };\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "default_numeric_fallback", - "id_span": { - "path": "src/default_numeric_fallback.rs", - "line": 44 - }, - "group": "clippy::restriction", - "docs": " **What it does:** Checks for usage of unconstrained numeric literals which may cause default numeric fallback in type inference.\n\n Default numeric fallback means that if numeric types have not yet been bound to concrete\n types at the end of type inference, then integer type is bound to `i32`, and similarly\n floating type is bound to `f64`.\n\n See [RFC0212](https://github.com/rust-lang/rfcs/blob/master/text/0212-restore-int-fallback.md) for more information about the fallback.\n\n **Why is this bad?** For those who are very careful about types, default numeric fallback\n can be a pitfall that cause unexpected runtime behavior.\n\n **Known problems:** This lint can only be allowed at the function level or above.\n\n **Example:**\n ```rust\n let i = 10;\n let f = 1.23;\n ```\n\n Use instead:\n ```rust\n let i = 10i32;\n let f = 1.23f64;\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MaybeIncorrect" - } - }, - { - "id": "explicit_deref_methods", - "id_span": { - "path": "src/dereference.rs", - "line": 32 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for explicit `deref()` or `deref_mut()` method calls.\n **Why is this bad?** Dereferencing by `&*x` or `&mut *x` is clearer and more concise,\n when not part of a method chain.\n\n **Example:**\n ```rust\n use std::ops::Deref;\n let a: &mut String = &mut String::from(\"foo\");\n let b: &str = a.deref();\n ```\n Could be written as:\n ```rust\n let a: &mut String = &mut String::from(\"foo\");\n let b = &*a;\n ```\n\n This lint excludes\n ```rust,ignore\n let _ = d.unwrap().deref();\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "derive_hash_xor_eq", - "id_span": { - "path": "src/derive.rs", - "line": 42 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for deriving `Hash` but implementing `PartialEq` explicitly or vice versa.\n\n **Why is this bad?** The implementation of these traits must agree (for\n example for use with `HashMap`) so it’s probably a bad idea to use a\n default-generated `Hash` implementation with an explicitly defined\n `PartialEq`. In particular, the following must hold for any type:\n\n ```text\n k1 == k2 ⇒ hash(k1) == hash(k2)\n ```\n\n **Known problems:** None.\n\n **Example:**\n ```ignore\n #[derive(Hash)]\n struct Foo;\n\n impl PartialEq for Foo {\n ...\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "derive_ord_xor_partial_ord", - "id_span": { - "path": "src/derive.rs", - "line": 93 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for deriving `Ord` but implementing `PartialOrd` explicitly or vice versa.\n\n **Why is this bad?** The implementation of these traits must agree (for\n example for use with `sort`) so it’s probably a bad idea to use a\n default-generated `Ord` implementation with an explicitly defined\n `PartialOrd`. In particular, the following must hold for any type\n implementing `Ord`:\n\n ```text\n k1.cmp(&k2) == k1.partial_cmp(&k2).unwrap()\n ```\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust,ignore\n #[derive(Ord, PartialEq, Eq)]\n struct Foo;\n\n impl PartialOrd for Foo {\n ...\n }\n ```\n Use instead:\n ```rust,ignore\n #[derive(PartialEq, Eq)]\n struct Foo;\n\n impl PartialOrd for Foo {\n fn partial_cmp(&self, other: &Foo) -> Option {\n Some(self.cmp(other))\n }\n }\n\n impl Ord for Foo {\n ...\n }\n ```\n or, if you don't need a custom ordering:\n ```rust,ignore\n #[derive(Ord, PartialOrd, PartialEq, Eq)]\n struct Foo;\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "expl_impl_clone_on_copy", - "id_span": { - "path": "src/derive.rs", - "line": 119 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for explicit `Clone` implementations for `Copy` types.\n\n **Why is this bad?** To avoid surprising behaviour, these traits should\n agree and the behaviour of `Copy` cannot be overridden. In almost all\n situations a `Copy` type should have a `Clone` implementation that does\n nothing more than copy the object, which is what `#[derive(Copy, Clone)]`\n gets you.\n\n **Known problems:** Bounds of generic types are sometimes wrong: https://github.com/rust-lang/rust/issues/26925\n\n **Example:**\n ```rust,ignore\n #[derive(Copy)]\n struct Foo;\n\n impl Clone for Foo {\n // ..\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "unsafe_derive_deserialize", - "id_span": { - "path": "src/derive.rs", - "line": 153 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for deriving `serde::Deserialize` on a type that has methods using `unsafe`.\n\n **Why is this bad?** Deriving `serde::Deserialize` will create a constructor\n that may violate invariants hold by another constructor.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust,ignore\n use serde::Deserialize;\n\n #[derive(Deserialize)]\n pub struct Foo {\n // ..\n }\n\n impl Foo {\n pub fn new() -> Self {\n // setup here ..\n }\n\n pub unsafe fn parts() -> (&str, &str) {\n // assumes invariants hold\n }\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "disallowed_method", - "id_span": { - "path": "src/disallowed_method.rs", - "line": 46 - }, - "group": "clippy::nursery", - "docs": " **What it does:** Denies the configured methods and functions in clippy.toml\n **Why is this bad?** Some methods are undesirable in certain contexts,\n and it's beneficial to lint for them as needed.\n\n **Known problems:** Currently, you must write each function as a\n fully-qualified path. This lint doesn't support aliases or reexported\n names; be aware that many types in `std` are actually reexports.\n\n For example, if you want to disallow `Duration::as_secs`, your clippy.toml\n configuration would look like\n `disallowed-methods = [\"core::time::Duration::as_secs\"]` and not\n `disallowed-methods = [\"std::time::Duration::as_secs\"]` as you might expect.\n\n **Example:**\n\n An example clippy.toml configuration:\n ```toml\n # clippy.toml\n disallowed-methods = [\"alloc::vec::Vec::leak\", \"std::time::Instant::now\"]\n ```\n\n ```rust,ignore\n // Example code where clippy issues a warning\n let xs = vec![1, 2, 3, 4];\n xs.leak(); // Vec::leak is disallowed in the config.\n\n let _now = Instant::now(); // Instant::now is disallowed in the config.\n ```\n\n Use instead:\n ```rust,ignore\n // Example code which does not raise clippy warning\n let mut xs = Vec::new(); // Vec::new is _not_ disallowed in the config.\n xs.push(123); // Vec::push is _not_ disallowed in the config.\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "doc_markdown", - "id_span": { - "path": "src/doc.rs", - "line": 63 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for the presence of `_`, `::` or camel-case words outside ticks in documentation.\n\n **Why is this bad?** *Rustdoc* supports markdown formatting, `_`, `::` and\n camel-case probably indicates some code which should be included between\n ticks. `_` can also be used for emphasis in markdown, this lint tries to\n consider that.\n\n **Known problems:** Lots of bad docs won’t be fixed, what the lint checks\n for is limited, and there are still false positives.\n\n In addition, when writing documentation comments, including `[]` brackets\n inside a link text would trip the parser. Therfore, documenting link with\n `[`SmallVec<[T; INLINE_CAPACITY]>`]` and then [`SmallVec<[T; INLINE_CAPACITY]>`]: SmallVec\n would fail.\n\n **Examples:**\n ```rust\n /// Do something with the foo_bar parameter. See also\n /// that::other::module::foo.\n // ^ `foo_bar` and `that::other::module::foo` should be ticked.\n fn doit(foo_bar: usize) {}\n ```\n\n ```rust\n // Link text with `[]` brackets should be written as following:\n /// Consume the array and return the inner\n /// [`SmallVec<[T; INLINE_CAPACITY]>`][SmallVec].\n /// [SmallVec]: SmallVec\n fn main() {}\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "missing_safety_doc", - "id_span": { - "path": "src/doc.rs", - "line": 97 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for the doc comments of publicly visible unsafe functions and warns if there is no `# Safety` section.\n\n **Why is this bad?** Unsafe functions should document their safety\n preconditions, so that users can be sure they are using them safely.\n\n **Known problems:** None.\n\n **Examples:**\n ```rust\n# type Universe = ();\n /// This function should really be documented\n pub unsafe fn start_apocalypse(u: &mut Universe) {\n unimplemented!();\n }\n ```\n\n At least write a line about safety:\n\n ```rust\n# type Universe = ();\n /// # Safety\n ///\n /// This function should not be called before the horsemen are ready.\n pub unsafe fn start_apocalypse(u: &mut Universe) {\n unimplemented!();\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "missing_errors_doc", - "id_span": { - "path": "src/doc.rs", - "line": 126 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks the doc comments of publicly visible functions that return a `Result` type and warns if there is no `# Errors` section.\n\n **Why is this bad?** Documenting the type of errors that can be returned from a\n function can help callers write code to handle the errors appropriately.\n\n **Known problems:** None.\n\n **Examples:**\n\n Since the following function returns a `Result` it has an `# Errors` section in\n its doc comment:\n\n ```rust\n# use std::io;\n /// # Errors\n ///\n /// Will return `Err` if `filename` does not exist or the user does not have\n /// permission to read it.\n pub fn read(filename: String) -> io::Result {\n unimplemented!();\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "missing_panics_doc", - "id_span": { - "path": "src/doc.rs", - "line": 157 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks the doc comments of publicly visible functions that may panic and warns if there is no `# Panics` section.\n\n **Why is this bad?** Documenting the scenarios in which panicking occurs\n can help callers who do not want to panic to avoid those situations.\n\n **Known problems:** None.\n\n **Examples:**\n\n Since the following function may panic it has a `# Panics` section in\n its doc comment:\n\n ```rust\n /// # Panics\n ///\n /// Will panic if y is 0\n pub fn divide_by(x: i32, y: i32) -> i32 {\n if y == 0 {\n panic!(\"Cannot divide by 0\")\n } else {\n x / y\n }\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "needless_doctest_main", - "id_span": { - "path": "src/doc.rs", - "line": 185 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for `fn main() { .. }` in doctests\n **Why is this bad?** The test can be shorter (and likely more readable)\n if the `fn main()` is left implicit.\n\n **Known problems:** None.\n\n **Examples:**\n ``````rust\n /// An example of a doctest with a `main()` function\n ///\n /// # Examples\n ///\n /// ```\n /// fn main() {\n /// // this needs not be in an `fn`\n /// }\n /// ```\n fn needless_main() {\n unimplemented!();\n }\n ``````\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "double_comparisons", - "id_span": { - "path": "src/double_comparison.rs", - "line": 33 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for double comparisons that could be simplified to a single expression.\n\n **Why is this bad?** Readability.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let x = 1;\n # let y = 2;\n if x == y || x < y {}\n ```\n\n Could be written as:\n\n ```rust\n # let x = 1;\n # let y = 2;\n if x <= y {}\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "double_parens", - "id_span": { - "path": "src/double_parens.rs", - "line": 35 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for unnecessary double parentheses.\n **Why is this bad?** This makes code harder to read and might indicate a\n mistake.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n // Bad\n fn simple_double_parens() -> i32 {\n ((0))\n }\n\n // Good\n fn simple_no_parens() -> i32 {\n 0\n }\n\n // or\n\n # fn foo(bar: usize) {}\n // Bad\n foo((0));\n\n // Good\n foo(0);\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "drop_ref", - "id_span": { - "path": "src/drop_forget_ref.rs", - "line": 26 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for calls to `std::mem::drop` with a reference instead of an owned value.\n\n **Why is this bad?** Calling `drop` on a reference will only drop the\n reference itself, which is a no-op. It will not call the `drop` method (from\n the `Drop` trait implementation) on the underlying referenced value, which\n is likely what was intended.\n\n **Known problems:** None.\n\n **Example:**\n ```ignore\n let mut lock_guard = mutex.lock();\n std::mem::drop(&lock_guard) // Should have been drop(lock_guard), mutex\n // still locked\n operation_that_requires_mutex_to_be_unlocked();\n ```\n", - "applicability": null - }, - { - "id": "forget_ref", - "id_span": { - "path": "src/drop_forget_ref.rs", - "line": 47 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for calls to `std::mem::forget` with a reference instead of an owned value.\n\n **Why is this bad?** Calling `forget` on a reference will only forget the\n reference itself, which is a no-op. It will not forget the underlying\n referenced\n value, which is likely what was intended.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let x = Box::new(1);\n std::mem::forget(&x) // Should have been forget(x), x will still be dropped\n ```\n", - "applicability": null - }, - { - "id": "drop_copy", - "id_span": { - "path": "src/drop_forget_ref.rs", - "line": 68 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for calls to `std::mem::drop` with a value that derives the Copy trait\n\n **Why is this bad?** Calling `std::mem::drop` [does nothing for types that\n implement Copy](https://doc.rust-lang.org/std/mem/fn.drop.html), since the\n value will be copied and moved into the function on invocation.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let x: i32 = 42; // i32 implements Copy\n std::mem::drop(x) // A copy of x is passed to the function, leaving the\n // original unaffected\n ```\n", - "applicability": null - }, - { - "id": "forget_copy", - "id_span": { - "path": "src/drop_forget_ref.rs", - "line": 95 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for calls to `std::mem::forget` with a value that derives the Copy trait\n\n **Why is this bad?** Calling `std::mem::forget` [does nothing for types that\n implement Copy](https://doc.rust-lang.org/std/mem/fn.drop.html) since the\n value will be copied and moved into the function on invocation.\n\n An alternative, but also valid, explanation is that Copy types do not\n implement\n the Drop trait, which means they have no destructors. Without a destructor,\n there\n is nothing for `std::mem::forget` to ignore.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let x: i32 = 42; // i32 implements Copy\n std::mem::forget(x) // A copy of x is passed to the function, leaving the\n // original unaffected\n ```\n", - "applicability": null - }, - { - "id": "duration_subsec", - "id_span": { - "path": "src/duration_subsec.rs", - "line": 34 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for calculation of subsecond microseconds or milliseconds from other `Duration` methods.\n\n **Why is this bad?** It's more concise to call `Duration::subsec_micros()` or\n `Duration::subsec_millis()` than to calculate them.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # use std::time::Duration;\n let dur = Duration::new(5, 0);\n\n // Bad\n let _micros = dur.subsec_nanos() / 1_000;\n let _millis = dur.subsec_nanos() / 1_000_000;\n\n // Good\n let _micros = dur.subsec_micros();\n let _millis = dur.subsec_millis();\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "else_if_without_else", - "id_span": { - "path": "src/else_if_without_else.rs", - "line": 44 - }, - "group": "clippy::restriction", - "docs": " **What it does:** Checks for usage of if expressions with an `else if` branch, but without a final `else` branch.\n\n **Why is this bad?** Some coding guidelines require this (e.g., MISRA-C:2004 Rule 14.10).\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # fn a() {}\n # fn b() {}\n # let x: i32 = 1;\n if x.is_positive() {\n a();\n } else if x.is_negative() {\n b();\n }\n ```\n\n Could be written:\n\n ```rust\n # fn a() {}\n # fn b() {}\n # let x: i32 = 1;\n if x.is_positive() {\n a();\n } else if x.is_negative() {\n b();\n } else {\n // We don't care about zero.\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "empty_enum", - "id_span": { - "path": "src/empty_enum.rs", - "line": 38 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for `enum`s with no variants.\n As of this writing, the `never_type` is still a\n nightly-only experimental API. Therefore, this lint is only triggered\n if the `never_type` is enabled.\n\n **Why is this bad?** If you want to introduce a type which\n can't be instantiated, you should use `!` (the primitive type \"never\"),\n or a wrapper around it, because `!` has more extensive\n compiler support (type inference, etc...) and wrappers\n around it are the conventional way to define an uninhabited type.\n For further information visit [never type documentation](https://doc.rust-lang.org/std/primitive.never.html)\n\n\n **Known problems:** None.\n\n **Example:**\n\n Bad:\n ```rust\n enum Test {}\n ```\n\n Good:\n ```rust\n #![feature(never_type)]\n\n struct Test(!);\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "map_entry", - "id_span": { - "path": "src/entry.rs", - "line": 48 - }, - "group": "clippy::perf", - "docs": " **What it does:** Checks for uses of `contains_key` + `insert` on `HashMap` or `BTreeMap`.\n\n **Why is this bad?** Using `entry` is more efficient.\n\n **Known problems:** Some false negatives, eg.:\n ```rust\n # use std::collections::HashMap;\n # let mut map = HashMap::new();\n # let v = 1;\n # let k = 1;\n if !map.contains_key(&k) {\n map.insert(k.clone(), v);\n }\n ```\n\n **Example:**\n ```rust\n # use std::collections::HashMap;\n # let mut map = HashMap::new();\n # let k = 1;\n # let v = 1;\n if !map.contains_key(&k) {\n map.insert(k, v);\n }\n ```\n can both be rewritten as:\n ```rust\n # use std::collections::HashMap;\n # let mut map = HashMap::new();\n # let k = 1;\n # let v = 1;\n map.entry(k).or_insert(v);\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "enum_clike_unportable_variant", - "id_span": { - "path": "src/enum_clike.rs", - "line": 31 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for C-like enumerations that are `repr(isize/usize)` and have values that don't fit into an `i32`.\n\n **Why is this bad?** This will truncate the variant value on 32 bit\n architectures, but works fine on 64 bit.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # #[cfg(target_pointer_width = \"64\")]\n #[repr(usize)]\n enum NonPortable {\n X = 0x1_0000_0000,\n Y = 0,\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "enum_variant_names", - "id_span": { - "path": "src/enum_variants.rs", - "line": 36 - }, - "group": "clippy::style", - "docs": " **What it does:** Detects enumeration variants that are prefixed or suffixed by the same characters.\n\n **Why is this bad?** Enumeration variant names should specify their variant,\n not repeat the enumeration name.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n enum Cake {\n BlackForestCake,\n HummingbirdCake,\n BattenbergCake,\n }\n ```\n Could be written as:\n ```rust\n enum Cake {\n BlackForest,\n Hummingbird,\n Battenberg,\n }\n ```\n", - "applicability": null - }, - { - "id": "pub_enum_variant_names", - "id_span": { - "path": "src/enum_variants.rs", - "line": 66 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Detects public enumeration variants that are prefixed or suffixed by the same characters.\n\n **Why is this bad?** Public enumeration variant names should specify their variant,\n not repeat the enumeration name.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n pub enum Cake {\n BlackForestCake,\n HummingbirdCake,\n BattenbergCake,\n }\n ```\n Could be written as:\n ```rust\n pub enum Cake {\n BlackForest,\n Hummingbird,\n Battenberg,\n }\n ```\n", - "applicability": null - }, - { - "id": "module_name_repetitions", - "id_span": { - "path": "src/enum_variants.rs", - "line": 91 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Detects type names that are prefixed or suffixed by the containing module's name.\n\n **Why is this bad?** It requires the user to type the module name twice.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n mod cake {\n struct BlackForestCake;\n }\n ```\n Could be written as:\n ```rust\n mod cake {\n struct BlackForest;\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "module_inception", - "id_span": { - "path": "src/enum_variants.rs", - "line": 121 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for modules that have the same name as their parent module\n\n **Why is this bad?** A typical beginner mistake is to have `mod foo;` and\n again `mod foo { ..\n }` in `foo.rs`.\n The expectation is that items inside the inner `mod foo { .. }` are then\n available\n through `foo::x`, but they are only available through\n `foo::foo::x`.\n If this is done on purpose, it would be better to choose a more\n representative module name.\n\n **Known problems:** None.\n\n **Example:**\n ```ignore\n // lib.rs\n mod foo;\n // foo.rs\n mod foo {\n ...\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "eq_op", - "id_span": { - "path": "src/eq_op.rs", - "line": 34 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for equal operands to comparison, logical and bitwise, difference and division binary operators (`==`, `>`, etc., `&&`,\n `||`, `&`, `|`, `^`, `-` and `/`).\n\n **Why is this bad?** This is usually just a typo or a copy and paste error.\n\n **Known problems:** False negatives: We had some false positives regarding\n calls (notably [racer](https://github.com/phildawes/racer) had one instance\n of `x.pop() && x.pop()`), so we removed matching any function or method\n calls. We may introduce a list of known pure functions in the future.\n\n **Example:**\n ```rust\n # let x = 1;\n if x + 1 == x + 1 {}\n ```\n or\n ```rust\n # let a = 3;\n # let b = 4;\n assert_eq!(a, a);\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "op_ref", - "id_span": { - "path": "src/eq_op.rs", - "line": 56 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for arguments to `==` which have their address taken to satisfy a bound\n and suggests to dereference the other argument instead\n\n **Why is this bad?** It is more idiomatic to dereference the other argument.\n\n **Known problems:** None\n\n **Example:**\n ```ignore\n // Bad\n &x == y\n\n // Good\n x == *y\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MaybeIncorrect" - } - }, - { - "id": "erasing_op", - "id_span": { - "path": "src/erasing_op.rs", - "line": 25 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for erasing operations, e.g., `x * 0`.\n **Why is this bad?** The whole expression can be replaced by zero.\n This is most likely not the intended outcome and should probably be\n corrected\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let x = 1;\n 0 / x;\n 0 * x;\n x & 0;\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "boxed_local", - "id_span": { - "path": "src/escape.rs", - "line": 43 - }, - "group": "clippy::perf", - "docs": " **What it does:** Checks for usage of `Box` where an unboxed `T` would work fine.\n\n **Why is this bad?** This is an unnecessary allocation, and bad for\n performance. It is only necessary to allocate if you wish to move the box\n into something.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # fn foo(bar: usize) {}\n // Bad\n let x = Box::new(1);\n foo(*x);\n println!(\"{}\", *x);\n\n // Good\n let x = 1;\n foo(x);\n println!(\"{}\", x);\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "redundant_closure", - "id_span": { - "path": "src/eta_reduction.rs", - "line": 37 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for closures which just call another function where the function can be called directly. `unsafe` functions or calls where types\n get adjusted are ignored.\n\n **Why is this bad?** Needlessly creating a closure adds code for no benefit\n and gives the optimizer more work.\n\n **Known problems:** If creating the closure inside the closure has a side-\n effect then moving the closure creation out will change when that side-\n effect runs.\n See [#1439](https://github.com/rust-lang/rust-clippy/issues/1439) for more details.\n\n **Example:**\n ```rust,ignore\n // Bad\n xs.map(|x| foo(x))\n\n // Good\n xs.map(foo)\n ```\n where `foo(_)` is a plain function that takes the exact argument type of\n `x`.\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "redundant_closure_for_method_calls", - "id_span": { - "path": "src/eta_reduction.rs", - "line": 61 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for closures which only invoke a method on the closure argument and can be replaced by referencing the method directly.\n\n **Why is this bad?** It's unnecessary to create the closure.\n\n **Known problems:** [#3071](https://github.com/rust-lang/rust-clippy/issues/3071),\n [#3942](https://github.com/rust-lang/rust-clippy/issues/3942),\n [#4002](https://github.com/rust-lang/rust-clippy/issues/4002)\n\n\n **Example:**\n ```rust,ignore\n Some('a').map(|s| s.to_uppercase());\n ```\n may be rewritten as\n ```rust,ignore\n Some('a').map(char::to_uppercase);\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "eval_order_dependence", - "id_span": { - "path": "src/eval_order_dependence.rs", - "line": 38 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for a read and a write to the same variable where whether the read occurs before or after the write depends on the evaluation\n order of sub-expressions.\n\n **Why is this bad?** It is often confusing to read. In addition, the\n sub-expression evaluation order for Rust is not well documented.\n\n **Known problems:** Code which intentionally depends on the evaluation\n order, or which is correct for any evaluation order.\n\n **Example:**\n ```rust\n let mut x = 0;\n\n // Bad\n let a = {\n x = 1;\n 1\n } + x;\n // Unclear whether a is 1 or 2.\n\n // Good\n let tmp = {\n x = 1;\n 1\n };\n let a = tmp + x;\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "diverging_sub_expression", - "id_span": { - "path": "src/eval_order_dependence.rs", - "line": 62 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for diverging calls that are not match arms or statements.\n\n **Why is this bad?** It is often confusing to read. In addition, the\n sub-expression evaluation order for Rust is not well documented.\n\n **Known problems:** Someone might want to use `some_bool || panic!()` as a\n shorthand.\n\n **Example:**\n ```rust,no_run\n # fn b() -> bool { true }\n # fn c() -> bool { true }\n let a = b() || panic!() || c();\n // `c()` is dead, `panic!()` is only called if `b()` returns `false`\n let x = (a, b, c, panic!());\n // can simply be replaced by `panic!()`\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "struct_excessive_bools", - "id_span": { - "path": "src/excessive_bools.rs", - "line": 40 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for excessive use of bools in structs.\n\n **Why is this bad?** Excessive bools in a struct\n is often a sign that it's used as a state machine,\n which is much better implemented as an enum.\n If it's not the case, excessive bools usually benefit\n from refactoring into two-variant enums for better\n readability and API.\n\n **Known problems:** None.\n\n **Example:**\n Bad:\n ```rust\n struct S {\n is_pending: bool,\n is_processing: bool,\n is_finished: bool,\n }\n ```\n\n Good:\n ```rust\n enum S {\n Pending,\n Processing,\n Finished,\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "fn_params_excessive_bools", - "id_span": { - "path": "src/excessive_bools.rs", - "line": 78 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for excessive use of bools in function definitions.\n\n **Why is this bad?** Calls to such functions\n are confusing and error prone, because it's\n hard to remember argument order and you have\n no type system support to back you up. Using\n two-variant enums instead of bools often makes\n API easier to use.\n\n **Known problems:** None.\n\n **Example:**\n Bad:\n ```rust,ignore\n fn f(is_round: bool, is_hot: bool) { ... }\n ```\n\n Good:\n ```rust,ignore\n enum Shape {\n Round,\n Spiky,\n }\n\n enum Temperature {\n Hot,\n IceCold,\n }\n\n fn f(shape: Shape, temperature: Temperature) { ... }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "exhaustive_enums", - "id_span": { - "path": "src/exhaustive_items.rs", - "line": 34 - }, - "group": "clippy::restriction", - "docs": " **What it does:** Warns on any exported `enum`s that are not tagged `#[non_exhaustive]`\n **Why is this bad?** Exhaustive enums are typically fine, but a project which does\n not wish to make a stability commitment around exported enums may wish to\n disable them by default.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n enum Foo {\n Bar,\n Baz\n }\n ```\n Use instead:\n ```rust\n #[non_exhaustive]\n enum Foo {\n Bar,\n Baz\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MaybeIncorrect" - } - }, - { - "id": "exhaustive_structs", - "id_span": { - "path": "src/exhaustive_items.rs", - "line": 64 - }, - "group": "clippy::restriction", - "docs": " **What it does:** Warns on any exported `structs`s that are not tagged `#[non_exhaustive]`\n **Why is this bad?** Exhaustive structs are typically fine, but a project which does\n not wish to make a stability commitment around exported structs may wish to\n disable them by default.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n struct Foo {\n bar: u8,\n baz: String,\n }\n ```\n Use instead:\n ```rust\n #[non_exhaustive]\n struct Foo {\n bar: u8,\n baz: String,\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MaybeIncorrect" - } - }, - { - "id": "exit", - "id_span": { - "path": "src/exit.rs", - "line": 20 - }, - "group": "clippy::restriction", - "docs": " **What it does:** `exit()` terminates the program and doesn't provide a stack trace.\n\n **Why is this bad?** Ideally a program is terminated by finishing\n the main function.\n\n **Known problems:** None.\n\n **Example:**\n ```ignore\n std::process::exit(0)\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "explicit_write", - "id_span": { - "path": "src/explicit_write.rs", - "line": 25 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for usage of `write!()` / `writeln()!` which can be replaced with `(e)print!()` / `(e)println!()`\n\n **Why is this bad?** Using `(e)println! is clearer and more concise\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # use std::io::Write;\n # let bar = \"furchtbar\";\n // this would be clearer as `eprintln!(\"foo: {:?}\", bar);`\n writeln!(&mut std::io::stderr(), \"foo: {:?}\", bar).unwrap();\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "fallible_impl_from", - "id_span": { - "path": "src/fallible_impl_from.rs", - "line": 45 - }, - "group": "clippy::nursery", - "docs": " **What it does:** Checks for impls of `From<..>` that contain `panic!()` or `unwrap()`\n **Why is this bad?** `TryFrom` should be used if there's a possibility of failure.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n struct Foo(i32);\n\n // Bad\n impl From for Foo {\n fn from(s: String) -> Self {\n Foo(s.parse().unwrap())\n }\n }\n ```\n\n ```rust\n // Good\n struct Foo(i32);\n\n use std::convert::TryFrom;\n impl TryFrom for Foo {\n type Error = ();\n fn try_from(s: String) -> Result {\n if let Ok(parsed) = s.parse() {\n Ok(Foo(parsed))\n } else {\n Err(())\n }\n }\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "float_equality_without_abs", - "id_span": { - "path": "src/float_equality_without_abs.rs", - "line": 37 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for statements of the form `(a - b) < f32::EPSILON` or `(a - b) < f64::EPSILON`. Notes the missing `.abs()`.\n\n **Why is this bad?** The code without `.abs()` is more likely to have a bug.\n\n **Known problems:** If the user can ensure that b is larger than a, the `.abs()` is\n technically unneccessary. However, it will make the code more robust and doesn't have any\n large performance implications. If the abs call was deliberately left out for performance\n reasons, it is probably better to state this explicitly in the code, which then can be done\n with an allow.\n\n **Example:**\n\n ```rust\n pub fn is_roughly_equal(a: f32, b: f32) -> bool {\n (a - b) < f32::EPSILON\n }\n ```\n Use instead:\n ```rust\n pub fn is_roughly_equal(a: f32, b: f32) -> bool {\n (a - b).abs() < f32::EPSILON\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MaybeIncorrect" - } - }, - { - "id": "excessive_precision", - "id_span": { - "path": "src/float_literal.rs", - "line": 30 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for float literals with a precision greater than that supported by the underlying type.\n\n **Why is this bad?** Rust will truncate the literal silently.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n // Bad\n let v: f32 = 0.123_456_789_9;\n println!(\"{}\", v); // 0.123_456_789\n\n // Good\n let v: f64 = 0.123_456_789_9;\n println!(\"{}\", v); // 0.123_456_789_9\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "lossy_float_literal", - "id_span": { - "path": "src/float_literal.rs", - "line": 54 - }, - "group": "clippy::restriction", - "docs": " **What it does:** Checks for whole number float literals that cannot be represented as the underlying type without loss.\n\n **Why is this bad?** Rust will silently lose precision during\n conversion to a float.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n // Bad\n let _: f32 = 16_777_217.0; // 16_777_216.0\n\n // Good\n let _: f32 = 16_777_216.0;\n let _: f64 = 16_777_217.0;\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "imprecise_flops", - "id_span": { - "path": "src/floating_point_arithmetic.rs", - "line": 45 - }, - "group": "clippy::nursery", - "docs": " **What it does:** Looks for floating-point expressions that can be expressed using built-in methods to improve accuracy\n at the cost of performance.\n\n **Why is this bad?** Negatively impacts accuracy.\n\n **Known problems:** None\n\n **Example:**\n\n ```rust\n let a = 3f32;\n let _ = a.powf(1.0 / 3.0);\n let _ = (1.0 + a).ln();\n let _ = a.exp() - 1.0;\n ```\n\n is better expressed as\n\n ```rust\n let a = 3f32;\n let _ = a.cbrt();\n let _ = a.ln_1p();\n let _ = a.exp_m1();\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "suboptimal_flops", - "id_span": { - "path": "src/floating_point_arithmetic.rs", - "line": 102 - }, - "group": "clippy::nursery", - "docs": " **What it does:** Looks for floating-point expressions that can be expressed using built-in methods to improve both\n accuracy and performance.\n\n **Why is this bad?** Negatively impacts accuracy and performance.\n\n **Known problems:** None\n\n **Example:**\n\n ```rust\n use std::f32::consts::E;\n\n let a = 3f32;\n let _ = (2f32).powf(a);\n let _ = E.powf(a);\n let _ = a.powf(1.0 / 2.0);\n let _ = a.log(2.0);\n let _ = a.log(10.0);\n let _ = a.log(E);\n let _ = a.powf(2.0);\n let _ = a * 2.0 + 4.0;\n let _ = if a < 0.0 {\n -a\n } else {\n a\n };\n let _ = if a < 0.0 {\n a\n } else {\n -a\n };\n ```\n\n is better expressed as\n\n ```rust\n use std::f32::consts::E;\n\n let a = 3f32;\n let _ = a.exp2();\n let _ = a.exp();\n let _ = a.sqrt();\n let _ = a.log2();\n let _ = a.log10();\n let _ = a.ln();\n let _ = a.powi(2);\n let _ = a.mul_add(2.0, 4.0);\n let _ = a.abs();\n let _ = -a.abs();\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "useless_format", - "id_span": { - "path": "src/format.rs", - "line": 37 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for the use of `format!(\"string literal with no argument\")` and `format!(\"{}\", foo)` where `foo` is a string.\n\n **Why is this bad?** There is no point of doing that. `format!(\"foo\")` can\n be replaced by `\"foo\".to_owned()` if you really need a `String`. The even\n worse `&format!(\"foo\")` is often encountered in the wild. `format!(\"{}\",\n foo)` can be replaced by `foo.clone()` if `foo: String` or `foo.to_owned()`\n if `foo: &str`.\n\n **Known problems:** None.\n\n **Examples:**\n ```rust\n\n // Bad\n # let foo = \"foo\";\n format!(\"{}\", foo);\n\n // Good\n format!(\"foo\");\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "suspicious_assignment_formatting", - "id_span": { - "path": "src/formatting.rs", - "line": 22 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for use of the non-existent `=*`, `=!` and `=-` operators.\n\n **Why is this bad?** This is either a typo of `*=`, `!=` or `-=` or\n confusing.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n a =- 42; // confusing, should it be `a -= 42` or `a = -42`?\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "suspicious_unary_op_formatting", - "id_span": { - "path": "src/formatting.rs", - "line": 44 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks the formatting of a unary operator on the right hand side of a binary operator. It lints if there is no space between the binary and unary operators,\n but there is a space between the unary and its operand.\n\n **Why is this bad?** This is either a typo in the binary operator or confusing.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n if foo <- 30 { // this should be `foo < -30` but looks like a different operator\n }\n\n if foo &&! bar { // this should be `foo && !bar` but looks like a different operator\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "suspicious_else_formatting", - "id_span": { - "path": "src/formatting.rs", - "line": 80 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for formatting of `else`. It lints if the `else` is followed immediately by a newline or the `else` seems to be missing.\n\n **Why is this bad?** This is probably some refactoring remnant, even if the\n code is correct, it might look confusing.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n if foo {\n } { // looks like an `else` is missing here\n }\n\n if foo {\n } if bar { // looks like an `else` is missing here\n }\n\n if foo {\n } else\n\n { // this is the `else` block of the previous `if`, but should it be?\n }\n\n if foo {\n } else\n\n if bar { // this is the `else` block of the previous `if`, but should it be?\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "possible_missing_comma", - "id_span": { - "path": "src/formatting.rs", - "line": 100 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for possible missing comma in an array. It lints if an array element is a binary operator expression and it lies on two lines.\n\n **Why is this bad?** This could lead to unexpected results.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n let a = &[\n -1, -2, -3 // <= no comma here\n -4, -5, -6\n ];\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "from_over_into", - "id_span": { - "path": "src/from_over_into.rs", - "line": 39 - }, - "group": "clippy::style", - "docs": " **What it does:** Searches for implementations of the `Into<..>` trait and suggests to implement `From<..>` instead.\n **Why is this bad?** According the std docs implementing `From<..>` is preferred since it gives you `Into<..>` for free where the reverse isn't true.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n struct StringWrapper(String);\n\n impl Into for String {\n fn into(self) -> StringWrapper {\n StringWrapper(self)\n }\n }\n ```\n Use instead:\n ```rust\n struct StringWrapper(String);\n\n impl From for StringWrapper {\n fn from(s: String) -> StringWrapper {\n StringWrapper(s)\n }\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "from_str_radix_10", - "id_span": { - "path": "src/from_str_radix_10.rs", - "line": 37 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for function invocations of the form `primitive::from_str_radix(s, 10)`\n\n **Why is this bad?**\n This specific common use case can be rewritten as `s.parse::()`\n (and in most cases, the turbofish can be removed), which reduces code length\n and complexity.\n\n **Known problems:**\n This lint may suggest using (&).parse() instead of .parse() directly\n in some cases, which is correct but adds unnecessary complexity to the code.\n\n **Example:**\n\n ```ignore\n let input: &str = get_input();\n let num = u16::from_str_radix(input, 10)?;\n ```\n Use instead:\n ```ignore\n let input: &str = get_input();\n let num: u16 = input.parse()?;\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MaybeIncorrect" - } - }, - { - "id": "too_many_arguments", - "id_span": { - "path": "src/functions.rs", - "line": 39 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for functions with too many parameters.\n **Why is this bad?** Functions with lots of parameters are considered bad\n style and reduce readability (“what does the 5th parameter mean?”). Consider\n grouping some parameters into a new type.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # struct Color;\n fn foo(x: u32, y: u32, name: &str, c: Color, w: f32, h: f32, a: f32, b: f32) {\n // ..\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "too_many_lines", - "id_span": { - "path": "src/functions.rs", - "line": 62 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for functions with a large amount of lines.\n **Why is this bad?** Functions with a lot of lines are harder to understand\n due to having to look at a larger amount of code to understand what the\n function is doing. Consider splitting the body of the function into\n multiple functions.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n fn im_too_long() {\n println!(\"\");\n // ... 100 more LoC\n println!(\"\");\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "not_unsafe_ptr_arg_deref", - "id_span": { - "path": "src/functions.rs", - "line": 96 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for public functions that dereference raw pointer arguments but are not marked unsafe.\n\n **Why is this bad?** The function should probably be marked `unsafe`, since\n for an arbitrary raw pointer, there is no way of telling for sure if it is\n valid.\n\n **Known problems:**\n\n * It does not check functions recursively so if the pointer is passed to a\n private non-`unsafe` function which does the dereferencing, the lint won't\n trigger.\n * It only checks for arguments whose type are raw pointers, not raw pointers\n got from an argument in some other way (`fn foo(bar: &[*const u8])` or\n `some_argument.get_raw_ptr()`).\n\n **Example:**\n ```rust,ignore\n // Bad\n pub fn foo(x: *const u8) {\n println!(\"{}\", unsafe { *x });\n }\n\n // Good\n pub unsafe fn foo(x: *const u8) {\n println!(\"{}\", unsafe { *x });\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "must_use_unit", - "id_span": { - "path": "src/functions.rs", - "line": 117 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for a [`#[must_use]`] attribute on unit-returning functions and methods.\n\n [`#[must_use]`]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute\n\n **Why is this bad?** Unit values are useless. The attribute is likely\n a remnant of a refactoring that removed the return type.\n\n **Known problems:** None.\n\n **Examples:**\n ```rust\n #[must_use]\n fn useless() { }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "double_must_use", - "id_span": { - "path": "src/functions.rs", - "line": 142 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for a [`#[must_use]`] attribute without further information on functions and methods that return a type already\n marked as `#[must_use]`.\n\n [`#[must_use]`]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute\n\n **Why is this bad?** The attribute isn't needed. Not using the result\n will already be reported. Alternatively, one can add some text to the\n attribute to improve the lint message.\n\n **Known problems:** None.\n\n **Examples:**\n ```rust\n #[must_use]\n fn double_must_use() -> Result<(), ()> {\n unimplemented!();\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "must_use_candidate", - "id_span": { - "path": "src/functions.rs", - "line": 170 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for public functions that have no [`#[must_use]`] attribute, but return something not already marked\n must-use, have no mutable arg and mutate no statics.\n\n [`#[must_use]`]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute\n\n **Why is this bad?** Not bad at all, this lint just shows places where\n you could add the attribute.\n\n **Known problems:** The lint only checks the arguments for mutable\n types without looking if they are actually changed. On the other hand,\n it also ignores a broad range of potentially interesting side effects,\n because we cannot decide whether the programmer intends the function to\n be called for the side effect or the result. Expect many false\n positives. At least we don't lint if the result type is unit or already\n `#[must_use]`.\n\n **Examples:**\n ```rust\n // this could be annotated with `#[must_use]`.\n fn id(t: T) -> T { t }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "result_unit_err", - "id_span": { - "path": "src/functions.rs", - "line": 216 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for public functions that return a `Result` with an `Err` type of `()`. It suggests using a custom type that\n implements [`std::error::Error`].\n\n **Why is this bad?** Unit does not implement `Error` and carries no\n further information about what went wrong.\n\n **Known problems:** Of course, this lint assumes that `Result` is used\n for a fallible operation (which is after all the intended use). However\n code may opt to (mis)use it as a basic two-variant-enum. In that case,\n the suggestion is misguided, and the code should use a custom enum\n instead.\n\n **Examples:**\n ```rust\n pub fn read_u8() -> Result { Err(()) }\n ```\n should become\n ```rust,should_panic\n use std::fmt;\n\n #[derive(Debug)]\n pub struct EndOfStream;\n\n impl fmt::Display for EndOfStream {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"End of Stream\")\n }\n }\n\n impl std::error::Error for EndOfStream { }\n\n pub fn read_u8() -> Result { Err(EndOfStream) }\n# fn main() {\n# read_u8().unwrap();\n# }\n ```\n\n Note that there are crates that simplify creating the error type, e.g.\n [`thiserror`](https://docs.rs/thiserror).\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "future_not_send", - "id_span": { - "path": "src/future_not_send.rs", - "line": 44 - }, - "group": "clippy::nursery", - "docs": " **What it does:** This lint requires Future implementations returned from functions and methods to implement the `Send` marker trait. It is mostly\n used by library authors (public and internal) that target an audience where\n multithreaded executors are likely to be used for running these Futures.\n\n **Why is this bad?** A Future implementation captures some state that it\n needs to eventually produce its final value. When targeting a multithreaded\n executor (which is the norm on non-embedded devices) this means that this\n state may need to be transported to other threads, in other words the\n whole Future needs to implement the `Send` marker trait. If it does not,\n then the resulting Future cannot be submitted to a thread pool in the\n end user’s code.\n\n Especially for generic functions it can be confusing to leave the\n discovery of this problem to the end user: the reported error location\n will be far from its cause and can in many cases not even be fixed without\n modifying the library where the offending Future implementation is\n produced.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n async fn not_send(bytes: std::rc::Rc<[u8]>) {}\n ```\n Use instead:\n ```rust\n async fn is_send(bytes: std::sync::Arc<[u8]>) {}\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "get_last_with_len", - "id_span": { - "path": "src/get_last_with_len.rs", - "line": 40 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for using `x.get(x.len() - 1)` instead of `x.last()`.\n\n **Why is this bad?** Using `x.last()` is easier to read and has the same\n result.\n\n Note that using `x[x.len() - 1]` is semantically different from\n `x.last()`. Indexing into the array will panic on out-of-bounds\n accesses, while `x.get()` and `x.last()` will return `None`.\n\n There is another lint (get_unwrap) that covers the case of using\n `x.get(index).unwrap()` instead of `x[index]`.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n // Bad\n let x = vec![2, 3, 5];\n let last_element = x.get(x.len() - 1);\n\n // Good\n let x = vec![2, 3, 5];\n let last_element = x.last();\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "identity_op", - "id_span": { - "path": "src/identity_op.rs", - "line": 24 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for identity operations, e.g., `x + 0`.\n **Why is this bad?** This code can be removed without changing the\n meaning. So it just obscures what's going on. Delete it mercilessly.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let x = 1;\n x / 1 + 0 * 1 - 0 | 0;\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "if_let_mutex", - "id_span": { - "path": "src/if_let_mutex.rs", - "line": 36 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for `Mutex::lock` calls in `if let` expression with lock calls in any of the else blocks.\n\n **Why is this bad?** The Mutex lock remains held for the whole\n `if let ... else` block and deadlocks.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust,ignore\n if let Ok(thing) = mutex.lock() {\n do_thing();\n } else {\n mutex.lock();\n }\n ```\n Should be written\n ```rust,ignore\n let locked = mutex.lock();\n if let Ok(thing) = locked {\n do_thing(thing);\n } else {\n use_locked(locked);\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "if_let_some_result", - "id_span": { - "path": "src/if_let_some_result.rs", - "line": 34 - }, - "group": "clippy::style", - "docs": " **What it does:*** Checks for unnecessary `ok()` in if let.\n **Why is this bad?** Calling `ok()` in if let is unnecessary, instead match\n on `Ok(pat)`\n\n **Known problems:** None.\n\n **Example:**\n ```ignore\n for i in iter {\n if let Some(value) = i.parse().ok() {\n vec.push(value)\n }\n }\n ```\n Could be written:\n\n ```ignore\n for i in iter {\n if let Ok(value) = i.parse() {\n vec.push(value)\n }\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "if_not_else", - "id_span": { - "path": "src/if_not_else.rs", - "line": 43 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for usage of `!` or `!=` in an if condition with an else branch.\n\n **Why is this bad?** Negations reduce the readability of statements.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let v: Vec = vec![];\n # fn a() {}\n # fn b() {}\n if !v.is_empty() {\n a()\n } else {\n b()\n }\n ```\n\n Could be written:\n\n ```rust\n # let v: Vec = vec![];\n # fn a() {}\n # fn b() {}\n if v.is_empty() {\n b()\n } else {\n a()\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "implicit_return", - "id_span": { - "path": "src/implicit_return.rs", - "line": 33 - }, - "group": "clippy::restriction", - "docs": " **What it does:** Checks for missing return statements at the end of a block.\n **Why is this bad?** Actually omitting the return keyword is idiomatic Rust code. Programmers\n coming from other languages might prefer the expressiveness of `return`. It's possible to miss\n the last returning statement because the only difference is a missing `;`. Especially in bigger\n code with multiple return paths having a `return` keyword makes it easier to find the\n corresponding statements.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n fn foo(x: usize) -> usize {\n x\n }\n ```\n add return\n ```rust\n fn foo(x: usize) -> usize {\n return x;\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "implicit_saturating_sub", - "id_span": { - "path": "src/implicit_saturating_sub.rs", - "line": 32 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for implicit saturating subtraction.\n **Why is this bad?** Simplicity and readability. Instead we can easily use an builtin function.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n let end: u32 = 10;\n let start: u32 = 5;\n\n let mut i: u32 = end - start;\n\n // Bad\n if i != 0 {\n i -= 1;\n }\n\n // Good\n i = i.saturating_sub(1);\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "inconsistent_struct_constructor", - "id_span": { - "path": "src/inconsistent_struct_constructor.rs", - "line": 58 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for struct constructors where the order of the field init shorthand in the constructor is inconsistent with the order in the struct definition.\n\n **Why is this bad?** Since the order of fields in a constructor doesn't affect the\n resulted instance as the below example indicates,\n\n ```rust\n #[derive(Debug, PartialEq, Eq)]\n struct Foo {\n x: i32,\n y: i32,\n }\n let x = 1;\n let y = 2;\n\n // This assertion never fails.\n assert_eq!(Foo { x, y }, Foo { y, x });\n ```\n\n inconsistent order means nothing and just decreases readability and consistency.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n struct Foo {\n x: i32,\n y: i32,\n }\n let x = 1;\n let y = 2;\n Foo { y, x };\n ```\n\n Use instead:\n ```rust\n # struct Foo {\n # x: i32,\n # y: i32,\n # }\n # let x = 1;\n # let y = 2;\n Foo { x, y };\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "out_of_bounds_indexing", - "id_span": { - "path": "src/indexing_slicing.rs", - "line": 32 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for out of bounds array indexing with a constant index.\n\n **Why is this bad?** This will always panic at runtime.\n\n **Known problems:** Hopefully none.\n\n **Example:**\n ```no_run\n # #![allow(const_err)]\n let x = [1, 2, 3, 4];\n\n // Bad\n x[9];\n &x[2..9];\n\n // Good\n x[0];\n x[3];\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "indexing_slicing", - "id_span": { - "path": "src/indexing_slicing.rs", - "line": 81 - }, - "group": "clippy::restriction", - "docs": " **What it does:** Checks for usage of indexing or slicing. Arrays are special cases, this lint does report on arrays if we can tell that slicing operations are in bounds and does not\n lint on constant `usize` indexing on arrays because that is handled by rustc's `const_err` lint.\n\n **Why is this bad?** Indexing and slicing can panic at runtime and there are\n safe alternatives.\n\n **Known problems:** Hopefully none.\n\n **Example:**\n ```rust,no_run\n // Vector\n let x = vec![0; 5];\n\n // Bad\n x[2];\n &x[2..100];\n &x[2..];\n &x[..100];\n\n // Good\n x.get(2);\n x.get(2..100);\n x.get(2..);\n x.get(..100);\n\n // Array\n let y = [0, 1, 2, 3];\n\n // Bad\n &y[10..100];\n &y[10..];\n &y[..100];\n\n // Good\n &y[2..];\n &y[..2];\n &y[0..3];\n y.get(10);\n y.get(10..100);\n y.get(10..);\n y.get(..100);\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "infinite_iter", - "id_span": { - "path": "src/infinite_iter.rs", - "line": 21 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for iteration that is guaranteed to be infinite.\n **Why is this bad?** While there may be places where this is acceptable\n (e.g., in event streams), in most cases this is simply an error.\n\n **Known problems:** None.\n\n **Example:**\n ```no_run\n use std::iter;\n\n iter::repeat(1_u8).collect::>();\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "maybe_infinite_iter", - "id_span": { - "path": "src/infinite_iter.rs", - "line": 40 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for iteration that may be infinite.\n **Why is this bad?** While there may be places where this is acceptable\n (e.g., in event streams), in most cases this is simply an error.\n\n **Known problems:** The code may have a condition to stop iteration, but\n this lint is not clever enough to analyze it.\n\n **Example:**\n ```rust\n let infinite_iter = 0..;\n [0..].iter().zip(infinite_iter.take_while(|x| *x > 5));\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "multiple_inherent_impl", - "id_span": { - "path": "src/inherent_impl.rs", - "line": 37 - }, - "group": "clippy::restriction", - "docs": " **What it does:** Checks for multiple inherent implementations of a struct\n **Why is this bad?** Splitting the implementation of a type makes the code harder to navigate.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n struct X;\n impl X {\n fn one() {}\n }\n impl X {\n fn other() {}\n }\n ```\n\n Could be written:\n\n ```rust\n struct X;\n impl X {\n fn one() {}\n fn other() {}\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "inherent_to_string", - "id_span": { - "path": "src/inherent_to_string.rs", - "line": 44 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for the definition of inherent methods with a signature of `to_string(&self) -> String`.\n **Why is this bad?** This method is also implicitly defined if a type implements the `Display` trait. As the functionality of `Display` is much more versatile, it should be preferred.\n\n **Known problems:** None\n\n ** Example:**\n\n ```rust\n // Bad\n pub struct A;\n\n impl A {\n pub fn to_string(&self) -> String {\n \"I am A\".to_string()\n }\n }\n ```\n\n ```rust\n // Good\n use std::fmt;\n\n pub struct A;\n\n impl fmt::Display for A {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n write!(f, \"I am A\")\n }\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "inherent_to_string_shadow_display", - "id_span": { - "path": "src/inherent_to_string.rs", - "line": 89 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for the definition of inherent methods with a signature of `to_string(&self) -> String` and if the type implementing this method also implements the `Display` trait.\n **Why is this bad?** This method is also implicitly defined if a type implements the `Display` trait. The less versatile inherent method will then shadow the implementation introduced by `Display`.\n\n **Known problems:** None\n\n ** Example:**\n\n ```rust\n // Bad\n use std::fmt;\n\n pub struct A;\n\n impl A {\n pub fn to_string(&self) -> String {\n \"I am A\".to_string()\n }\n }\n\n impl fmt::Display for A {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n write!(f, \"I am A, too\")\n }\n }\n ```\n\n ```rust\n // Good\n use std::fmt;\n\n pub struct A;\n\n impl fmt::Display for A {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n write!(f, \"I am A\")\n }\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "inline_fn_without_body", - "id_span": { - "path": "src/inline_fn_without_body.rs", - "line": 27 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for `#[inline]` on trait methods without bodies\n **Why is this bad?** Only implementations of trait methods may be inlined.\n The inline attribute is ignored for trait methods without bodies.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n trait Animal {\n #[inline]\n fn name(&self) -> &'static str;\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "int_plus_one", - "id_span": { - "path": "src/int_plus_one.rs", - "line": 31 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for usage of `x >= y + 1` or `x - 1 >= y` (and `<=`) in a block\n **Why is this bad?** Readability -- better to use `> y` instead of `>= y + 1`.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let x = 1;\n # let y = 1;\n if x >= y + 1 {}\n ```\n\n Could be written as:\n\n ```rust\n # let x = 1;\n # let y = 1;\n if x > y {}\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "integer_division", - "id_span": { - "path": "src/integer_division.rs", - "line": 26 - }, - "group": "clippy::restriction", - "docs": " **What it does:** Checks for division of integers\n **Why is this bad?** When outside of some very specific algorithms,\n integer division is very often a mistake because it discards the\n remainder.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n // Bad\n let x = 3 / 2;\n println!(\"{}\", x);\n\n // Good\n let x = 3f32 / 2f32;\n println!(\"{}\", x);\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "items_after_statements", - "id_span": { - "path": "src/items_after_statements.rs", - "line": 48 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for items declared after some statement in a block.\n **Why is this bad?** Items live for the entire scope they are declared\n in. But statements are processed in order. This might cause confusion as\n it's hard to figure out which item is meant in a statement.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n // Bad\n fn foo() {\n println!(\"cake\");\n }\n\n fn main() {\n foo(); // prints \"foo\"\n fn foo() {\n println!(\"foo\");\n }\n foo(); // prints \"foo\"\n }\n ```\n\n ```rust\n // Good\n fn foo() {\n println!(\"cake\");\n }\n\n fn main() {\n fn foo() {\n println!(\"foo\");\n }\n foo(); // prints \"foo\"\n foo(); // prints \"foo\"\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "large_const_arrays", - "id_span": { - "path": "src/large_const_arrays.rs", - "line": 30 - }, - "group": "clippy::perf", - "docs": " **What it does:** Checks for large `const` arrays that should be defined as `static` instead.\n\n **Why is this bad?** Performance: const variables are inlined upon use.\n Static items result in only one instance and has a fixed location in memory.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n // Bad\n pub const a = [0u32; 1_000_000];\n\n // Good\n pub static a = [0u32; 1_000_000];\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "large_enum_variant", - "id_span": { - "path": "src/large_enum_variant.rs", - "line": 39 - }, - "group": "clippy::perf", - "docs": " **What it does:** Checks for large size differences between variants on `enum`s.\n\n **Why is this bad?** Enum size is bounded by the largest variant. Having a\n large variant can penalize the memory layout of that enum.\n\n **Known problems:** This lint obviously cannot take the distribution of\n variants in your running program into account. It is possible that the\n smaller variants make up less than 1% of all instances, in which case\n the overhead is negligible and the boxing is counter-productive. Always\n measure the change this lint suggests.\n\n **Example:**\n\n ```rust\n // Bad\n enum Test {\n A(i32),\n B([i32; 8000]),\n }\n\n // Possibly better\n enum Test2 {\n A(i32),\n B(Box<[i32; 8000]>),\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MaybeIncorrect" - } - }, - { - "id": "large_stack_arrays", - "id_span": { - "path": "src/large_stack_arrays.rs", - "line": 23 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for local arrays that may be too large.\n **Why is this bad?** Large local arrays may cause stack overflow.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n let a = [0u32; 1_000_000];\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "len_zero", - "id_span": { - "path": "src/len_zero.rs", - "line": 41 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for getting the length of something via `.len()` just to compare to zero, and suggests using `.is_empty()` where applicable.\n\n **Why is this bad?** Some structures can answer `.is_empty()` much faster\n than calculating their length. So it is good to get into the habit of using\n `.is_empty()`, and having it is cheap.\n Besides, it makes the intent clearer than a manual comparison in some contexts.\n\n **Known problems:** None.\n\n **Example:**\n ```ignore\n if x.len() == 0 {\n ..\n }\n if y.len() != 0 {\n ..\n }\n ```\n instead use\n ```ignore\n if x.is_empty() {\n ..\n }\n if !y.is_empty() {\n ..\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "len_without_is_empty", - "id_span": { - "path": "src/len_zero.rs", - "line": 66 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for items that implement `.len()` but not `.is_empty()`.\n\n **Why is this bad?** It is good custom to have both methods, because for\n some data structures, asking about the length will be a costly operation,\n whereas `.is_empty()` can usually answer in constant time. Also it used to\n lead to false positives on the [`len_zero`](#len_zero) lint – currently that\n lint will ignore such entities.\n\n **Known problems:** None.\n\n **Example:**\n ```ignore\n impl X {\n pub fn len(&self) -> usize {\n ..\n }\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "comparison_to_empty", - "id_span": { - "path": "src/len_zero.rs", - "line": 103 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for comparing to an empty slice such as `\"\"` or `[]`, and suggests using `.is_empty()` where applicable.\n\n **Why is this bad?** Some structures can answer `.is_empty()` much faster\n than checking for equality. So it is good to get into the habit of using\n `.is_empty()`, and having it is cheap.\n Besides, it makes the intent clearer than a manual comparison in some contexts.\n\n **Known problems:** None.\n\n **Example:**\n\n ```ignore\n if s == \"\" {\n ..\n }\n\n if arr == [] {\n ..\n }\n ```\n Use instead:\n ```ignore\n if s.is_empty() {\n ..\n }\n\n if arr.is_empty() {\n ..\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "useless_let_if_seq", - "id_span": { - "path": "src/let_if_seq.rs", - "line": 49 - }, - "group": "clippy::nursery", - "docs": " **What it does:** Checks for variable declarations immediately followed by a conditional affectation.\n\n **Why is this bad?** This is not idiomatic Rust.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n let foo;\n\n if bar() {\n foo = 42;\n } else {\n foo = 0;\n }\n\n let mut baz = None;\n\n if bar() {\n baz = Some(42);\n }\n ```\n\n should be written\n\n ```rust,ignore\n let foo = if bar() {\n 42\n } else {\n 0\n };\n\n let baz = if bar() {\n Some(42)\n } else {\n None\n };\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "HasPlaceholders" - } - }, - { - "id": "let_underscore_must_use", - "id_span": { - "path": "src/let_underscore.rs", - "line": 29 - }, - "group": "clippy::restriction", - "docs": " **What it does:** Checks for `let _ = ` where expr is #[must_use]\n\n **Why is this bad?** It's better to explicitly\n handle the value of a #[must_use] expr\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n fn f() -> Result {\n Ok(0)\n }\n\n let _ = f();\n // is_ok() is marked #[must_use]\n let _ = f().is_ok();\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "let_underscore_lock", - "id_span": { - "path": "src/let_underscore.rs", - "line": 56 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for `let _ = sync_lock`\n **Why is this bad?** This statement immediately drops the lock instead of\n extending its lifetime to the end of the scope, which is often not intended.\n To extend lock lifetime to the end of the scope, use an underscore-prefixed\n name instead (i.e. _lock). If you want to explicitly drop the lock,\n `std::mem::drop` conveys your intention better and is less error-prone.\n\n **Known problems:** None.\n\n **Example:**\n\n Bad:\n ```rust,ignore\n let _ = mutex.lock();\n ```\n\n Good:\n ```rust,ignore\n let _lock = mutex.lock();\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "let_underscore_drop", - "id_span": { - "path": "src/let_underscore.rs", - "line": 97 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for `let _ = ` where expr has a type that implements `Drop`\n\n **Why is this bad?** This statement immediately drops the initializer\n expression instead of extending its lifetime to the end of the scope, which\n is often not intended. To extend the expression's lifetime to the end of the\n scope, use an underscore-prefixed name instead (i.e. _var). If you want to\n explicitly drop the expression, `std::mem::drop` conveys your intention\n better and is less error-prone.\n\n **Known problems:** None.\n\n **Example:**\n\n Bad:\n ```rust,ignore\n struct Droppable;\n impl Drop for Droppable {\n fn drop(&mut self) {}\n }\n {\n let _ = Droppable;\n // ^ dropped here\n /* more code */\n }\n ```\n\n Good:\n ```rust,ignore\n {\n let _droppable = Droppable;\n /* more code */\n // dropped at end of scope\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "needless_lifetimes", - "id_span": { - "path": "src/lifetimes.rs", - "line": 46 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for lifetime annotations which can be removed by relying on lifetime elision.\n\n **Why is this bad?** The additional lifetimes make the code look more\n complicated, while there is nothing out of the ordinary going on. Removing\n them leads to more readable code.\n\n **Known problems:**\n - We bail out if the function has a `where` clause where lifetimes\n are mentioned due to potenial false positives.\n - Lifetime bounds such as `impl Foo + 'a` and `T: 'a` must be elided with the\n placeholder notation `'_` because the fully elided notation leaves the type bound to `'static`.\n\n **Example:**\n ```rust\n // Bad: unnecessary lifetime annotations\n fn in_and_out<'a>(x: &'a u8, y: u8) -> &'a u8 {\n x\n }\n\n // Good\n fn elided(x: &u8, y: u8) -> &u8 {\n x\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "extra_unused_lifetimes", - "id_span": { - "path": "src/lifetimes.rs", - "line": 74 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for lifetimes in generics that are never used anywhere else.\n\n **Why is this bad?** The additional lifetimes make the code look more\n complicated, while there is nothing out of the ordinary going on. Removing\n them leads to more readable code.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n // Bad: unnecessary lifetimes\n fn unused_lifetime<'a>(x: u8) {\n // ..\n }\n\n // Good\n fn no_lifetime(x: u8) {\n // ...\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "unreadable_literal", - "id_span": { - "path": "src/literal_representation.rs", - "line": 33 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Warns if a long integral or floating-point constant does not contain underscores.\n\n **Why is this bad?** Reading long numbers is difficult without separators.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n // Bad\n let x: u64 = 61864918973511;\n\n // Good\n let x: u64 = 61_864_918_973_511;\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "mistyped_literal_suffixes", - "id_span": { - "path": "src/literal_representation.rs", - "line": 57 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Warns for mistyped suffix in literals\n **Why is this bad?** This is most probably a typo\n\n **Known problems:**\n - Recommends a signed suffix, even though the number might be too big and an unsigned\n suffix is required\n - Does not match on `_127` since that is a valid grouping for decimal and octal numbers\n\n **Example:**\n\n ```rust\n // Probably mistyped\n 2_32;\n\n // Good\n 2_i32;\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MaybeIncorrect" - } - }, - { - "id": "inconsistent_digit_grouping", - "id_span": { - "path": "src/literal_representation.rs", - "line": 80 - }, - "group": "clippy::style", - "docs": " **What it does:** Warns if an integral or floating-point constant is grouped inconsistently with underscores.\n\n **Why is this bad?** Readers may incorrectly interpret inconsistently\n grouped digits.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n // Bad\n let x: u64 = 618_64_9189_73_511;\n\n // Good\n let x: u64 = 61_864_918_973_511;\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "unusual_byte_groupings", - "id_span": { - "path": "src/literal_representation.rs", - "line": 99 - }, - "group": "clippy::style", - "docs": " **What it does:** Warns if hexadecimal or binary literals are not grouped by nibble or byte.\n\n **Why is this bad?** Negatively impacts readability.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n let x: u32 = 0xFFF_FFF;\n let y: u8 = 0b01_011_101;\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "large_digit_groups", - "id_span": { - "path": "src/literal_representation.rs", - "line": 118 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Warns if the digits of an integral or floating-point constant are grouped into groups that\n are too large.\n\n **Why is this bad?** Negatively impacts readability.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n let x: u64 = 6186491_8973511;\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "decimal_literal_representation", - "id_span": { - "path": "src/literal_representation.rs", - "line": 136 - }, - "group": "clippy::restriction", - "docs": " **What it does:** Warns if there is a better representation for a numeric literal.\n **Why is this bad?** Especially for big powers of 2 a hexadecimal representation is more\n readable than a decimal representation.\n\n **Known problems:** None.\n\n **Example:**\n\n `255` => `0xFF`\n `65_535` => `0xFFFF`\n `4_042_322_160` => `0xF0F0_F0F0`\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "manual_memcpy", - "id_span": { - "path": "src/loops/mod.rs", - "line": 50 - }, - "group": "clippy::perf", - "docs": " **What it does:** Checks for for-loops that manually copy items between slices that could be optimized by having a memcpy.\n\n **Why is this bad?** It is not as fast as a memcpy.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let src = vec![1];\n # let mut dst = vec![0; 65];\n for i in 0..src.len() {\n dst[i + 64] = src[i];\n }\n ```\n Could be written as:\n ```rust\n # let src = vec![1];\n # let mut dst = vec![0; 65];\n dst[64..(src.len() + 64)].clone_from_slice(&src[..]);\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "Unspecified" - } - }, - { - "id": "needless_range_loop", - "id_span": { - "path": "src/loops/mod.rs", - "line": 78 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for looping over the range of `0..len` of some collection just to get the values by index.\n\n **Why is this bad?** Just iterating the collection itself makes the intent\n more clear and is probably faster.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let vec = vec!['a', 'b', 'c'];\n for i in 0..vec.len() {\n println!(\"{}\", vec[i]);\n }\n ```\n Could be written as:\n ```rust\n let vec = vec!['a', 'b', 'c'];\n for i in vec {\n println!(\"{}\", i);\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "explicit_iter_loop", - "id_span": { - "path": "src/loops/mod.rs", - "line": 107 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for loops on `x.iter()` where `&x` will do, and suggests the latter.\n\n **Why is this bad?** Readability.\n\n **Known problems:** False negatives. We currently only warn on some known\n types.\n\n **Example:**\n ```rust\n // with `y` a `Vec` or slice:\n # let y = vec![1];\n for x in y.iter() {\n // ..\n }\n ```\n can be rewritten to\n ```rust\n # let y = vec![1];\n for x in &y {\n // ..\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "explicit_into_iter_loop", - "id_span": { - "path": "src/loops/mod.rs", - "line": 135 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for loops on `y.into_iter()` where `y` will do, and suggests the latter.\n\n **Why is this bad?** Readability.\n\n **Known problems:** None\n\n **Example:**\n ```rust\n # let y = vec![1];\n // with `y` a `Vec` or slice:\n for x in y.into_iter() {\n // ..\n }\n ```\n can be rewritten to\n ```rust\n # let y = vec![1];\n for x in y {\n // ..\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "iter_next_loop", - "id_span": { - "path": "src/loops/mod.rs", - "line": 158 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for loops on `x.next()`.\n **Why is this bad?** `next()` returns either `Some(value)` if there was a\n value, or `None` otherwise. The insidious thing is that `Option<_>`\n implements `IntoIterator`, so that possibly one value will be iterated,\n leading to some hard to find bugs. No one will want to write such code\n [except to win an Underhanded Rust\n Contest](https://www.reddit.com/r/rust/comments/3hb0wm/underhanded_rust_contest/cu5yuhr).\n\n **Known problems:** None.\n\n **Example:**\n ```ignore\n for x in y.next() {\n ..\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "for_loops_over_fallibles", - "id_span": { - "path": "src/loops/mod.rs", - "line": 201 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for `for` loops over `Option` or `Result` values.\n **Why is this bad?** Readability. This is more clearly expressed as an `if\n let`.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let opt = Some(1);\n\n // Bad\n for x in opt {\n // ..\n }\n\n // Good\n if let Some(x) = opt {\n // ..\n }\n ```\n\n // or\n\n ```rust\n # let res: Result = Ok(1);\n\n // Bad\n for x in &res {\n // ..\n }\n\n // Good\n if let Ok(x) = res {\n // ..\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "while_let_loop", - "id_span": { - "path": "src/loops/mod.rs", - "line": 230 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Detects `loop + match` combinations that are easier written as a `while let` loop.\n\n **Why is this bad?** The `while let` loop is usually shorter and more\n readable.\n\n **Known problems:** Sometimes the wrong binding is displayed ([#383](https://github.com/rust-lang/rust-clippy/issues/383)).\n\n **Example:**\n ```rust,no_run\n # let y = Some(1);\n loop {\n let x = match y {\n Some(x) => x,\n None => break,\n };\n // .. do something with x\n }\n // is easier written as\n while let Some(x) = y {\n // .. do something with x\n };\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "HasPlaceholders" - } - }, - { - "id": "needless_collect", - "id_span": { - "path": "src/loops/mod.rs", - "line": 252 - }, - "group": "clippy::perf", - "docs": " **What it does:** Checks for functions collecting an iterator when collect is not needed.\n\n **Why is this bad?** `collect` causes the allocation of a new data structure,\n when this allocation may not be needed.\n\n **Known problems:**\n None\n\n **Example:**\n ```rust\n # let iterator = vec![1].into_iter();\n let len = iterator.clone().collect::>().len();\n // should be\n let len = iterator.count();\n ```\n", - "applicability": { - "is_multi_suggestion": true, - "applicability": "MachineApplicable" - } - }, - { - "id": "explicit_counter_loop", - "id_span": { - "path": "src/loops/mod.rs", - "line": 282 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks `for` loops over slices with an explicit counter and suggests the use of `.enumerate()`.\n\n **Why is it bad?** Using `.enumerate()` makes the intent more clear,\n declutters the code and may be faster in some instances.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let v = vec![1];\n # fn bar(bar: usize, baz: usize) {}\n let mut i = 0;\n for item in &v {\n bar(i, *item);\n i += 1;\n }\n ```\n Could be written as\n ```rust\n # let v = vec![1];\n # fn bar(bar: usize, baz: usize) {}\n for (i, item) in v.iter().enumerate() { bar(i, *item); }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "empty_loop", - "id_span": { - "path": "src/loops/mod.rs", - "line": 315 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for empty `loop` expressions.\n **Why is this bad?** These busy loops burn CPU cycles without doing\n anything. It is _almost always_ a better idea to `panic!` than to have\n a busy loop.\n\n If panicking isn't possible, think of the environment and either:\n - block on something\n - sleep the thread for some microseconds\n - yield or pause the thread\n\n For `std` targets, this can be done with\n [`std::thread::sleep`](https://doc.rust-lang.org/std/thread/fn.sleep.html)\n or [`std::thread::yield_now`](https://doc.rust-lang.org/std/thread/fn.yield_now.html).\n\n For `no_std` targets, doing this is more complicated, especially because\n `#[panic_handler]`s can't panic. To stop/pause the thread, you will\n probably need to invoke some target-specific intrinsic. Examples include:\n - [`x86_64::instructions::hlt`](https://docs.rs/x86_64/0.12.2/x86_64/instructions/fn.hlt.html)\n - [`cortex_m::asm::wfi`](https://docs.rs/cortex-m/0.6.3/cortex_m/asm/fn.wfi.html)\n\n **Known problems:** None.\n\n **Example:**\n ```no_run\n loop {}\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "while_let_on_iterator", - "id_span": { - "path": "src/loops/mod.rs", - "line": 334 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for `while let` expressions on iterators.\n **Why is this bad?** Readability. A simple `for` loop is shorter and conveys\n the intent better.\n\n **Known problems:** None.\n\n **Example:**\n ```ignore\n while let Some(val) = iter() {\n ..\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "for_kv_map", - "id_span": { - "path": "src/loops/mod.rs", - "line": 362 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for iterating a map (`HashMap` or `BTreeMap`) and ignoring either the keys or values.\n\n **Why is this bad?** Readability. There are `keys` and `values` methods that\n can be used to express that don't need the values or keys.\n\n **Known problems:** None.\n\n **Example:**\n ```ignore\n for (k, _) in &map {\n ..\n }\n ```\n\n could be replaced by\n\n ```ignore\n for k in map.keys() {\n ..\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "never_loop", - "id_span": { - "path": "src/loops/mod.rs", - "line": 383 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for loops that will always `break`, `return` or `continue` an outer loop.\n\n **Why is this bad?** This loop never loops, all it does is obfuscating the\n code.\n\n **Known problems:** None\n\n **Example:**\n ```rust\n loop {\n ..;\n break;\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "mut_range_bound", - "id_span": { - "path": "src/loops/mod.rs", - "line": 403 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for loops which have a range bound that is a mutable variable\n **Why is this bad?** One might think that modifying the mutable variable changes the loop bounds\n\n **Known problems:** None\n\n **Example:**\n ```rust\n let mut foo = 42;\n for i in 0..foo {\n foo -= 1;\n println!(\"{}\", i); // prints numbers from 0 to 42, not 0 to 21\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "while_immutable_condition", - "id_span": { - "path": "src/loops/mod.rs", - "line": 426 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks whether variables used within while loop condition can be (and are) mutated in the body.\n\n **Why is this bad?** If the condition is unchanged, entering the body of the loop\n will lead to an infinite loop.\n\n **Known problems:** If the `while`-loop is in a closure, the check for mutation of the\n condition variables in the body can cause false negatives. For example when only `Upvar` `a` is\n in the condition and only `Upvar` `b` gets mutated in the body, the lint will not trigger.\n\n **Example:**\n ```rust\n let i = 0;\n while i > 10 {\n println!(\"let me loop forever!\");\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "same_item_push", - "id_span": { - "path": "src/loops/mod.rs", - "line": 459 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks whether a for loop is being used to push a constant value into a Vec.\n\n **Why is this bad?** This kind of operation can be expressed more succinctly with\n `vec![item;SIZE]` or `vec.resize(NEW_SIZE, item)` and using these alternatives may also\n have better performance.\n **Known problems:** None\n\n **Example:**\n ```rust\n let item1 = 2;\n let item2 = 3;\n let mut vec: Vec = Vec::new();\n for _ in 0..20 {\n vec.push(item1);\n }\n for _ in 0..30 {\n vec.push(item2);\n }\n ```\n could be written as\n ```rust\n let item1 = 2;\n let item2 = 3;\n let mut vec: Vec = vec![item1; 20];\n vec.resize(20 + 30, item2);\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "single_element_loop", - "id_span": { - "path": "src/loops/mod.rs", - "line": 484 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks whether a for loop has a single element.\n **Why is this bad?** There is no reason to have a loop of a\n single element.\n **Known problems:** None\n\n **Example:**\n ```rust\n let item1 = 2;\n for item in &[item1] {\n println!(\"{}\", item);\n }\n ```\n could be written as\n ```rust\n let item1 = 2;\n let item = &item1;\n println!(\"{}\", item);\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "manual_flatten", - "id_span": { - "path": "src/loops/mod.rs", - "line": 515 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Check for unnecessary `if let` usage in a for loop where only the `Some` or `Ok` variant of the iterator element is used.\n\n **Why is this bad?** It is verbose and can be simplified\n by first calling the `flatten` method on the `Iterator`.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n let x = vec![Some(1), Some(2), Some(3)];\n for n in x {\n if let Some(n) = n {\n println!(\"{}\", n);\n }\n }\n ```\n Use instead:\n ```rust\n let x = vec![Some(1), Some(2), Some(3)];\n for n in x.into_iter().flatten() {\n println!(\"{}\", n);\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MaybeIncorrect" - } - }, - { - "id": "macro_use_imports", - "id_span": { - "path": "src/macro_use.rs", - "line": 25 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for `#[macro_use] use...`.\n **Why is this bad?** Since the Rust 2018 edition you can import\n macro's directly, this is considered idiomatic.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n #[macro_use]\n use some_macro;\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MaybeIncorrect" - } - }, - { - "id": "main_recursion", - "id_span": { - "path": "src/main_recursion.rs", - "line": 22 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for recursion using the entrypoint.\n **Why is this bad?** Apart from special setups (which we could detect following attributes like #![no_std]),\n recursing into main() seems like an unintuitive antipattern we should be able to detect.\n\n **Known problems:** None.\n\n **Example:**\n ```no_run\n fn main() {\n main();\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "manual_async_fn", - "id_span": { - "path": "src/manual_async_fn.rs", - "line": 32 - }, - "group": "clippy::style", - "docs": " **What it does:** It checks for manual implementations of `async` functions.\n **Why is this bad?** It's more idiomatic to use the dedicated syntax.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n use std::future::Future;\n\n fn foo() -> impl Future { async { 42 } }\n ```\n Use instead:\n ```rust\n async fn foo() -> i32 { 42 }\n ```\n", - "applicability": { - "is_multi_suggestion": true, - "applicability": "MachineApplicable" - } - }, - { - "id": "manual_map", - "id_span": { - "path": "src/manual_map.rs", - "line": 44 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for usages of `match` which could be implemented using `map`\n **Why is this bad?** Using the `map` method is clearer and more concise.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n match Some(0) {\n Some(x) => Some(x + 1),\n None => None,\n };\n ```\n Use instead:\n ```rust\n Some(0).map(|x| x + 1);\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "manual_non_exhaustive", - "id_span": { - "path": "src/manual_non_exhaustive.rs", - "line": 56 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for manual implementations of the non-exhaustive pattern.\n **Why is this bad?** Using the #[non_exhaustive] attribute expresses better the intent\n and allows possible optimizations when applied to enums.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n struct S {\n pub a: i32,\n pub b: i32,\n _c: (),\n }\n\n enum E {\n A,\n B,\n #[doc(hidden)]\n _C,\n }\n\n struct T(pub i32, pub i32, ());\n ```\n Use instead:\n ```rust\n #[non_exhaustive]\n struct S {\n pub a: i32,\n pub b: i32,\n }\n\n #[non_exhaustive]\n enum E {\n A,\n B,\n }\n\n #[non_exhaustive]\n struct T(pub i32, pub i32);\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "Unspecified" - } - }, - { - "id": "manual_ok_or", - "id_span": { - "path": "src/manual_ok_or.rs", - "line": 34 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Finds patterns that reimplement `Option::ok_or`.\n\n **Why is this bad?**\n Concise code helps focusing on behavior instead of boilerplate.\n\n **Known problems:** None.\n\n **Examples:**\n ```rust\n let foo: Option = None;\n foo.map_or(Err(\"error\"), |v| Ok(v));\n ```\n\n Use instead:\n ```rust\n let foo: Option = None;\n foo.ok_or(\"error\");\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "manual_strip", - "id_span": { - "path": "src/manual_strip.rs", - "line": 52 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Suggests using `strip_{prefix,suffix}` over `str::{starts,ends}_with` and slicing using\n the pattern's length.\n\n **Why is this bad?**\n Using `str:strip_{prefix,suffix}` is safer and may have better performance as there is no\n slicing which may panic and the compiler does not need to insert this panic code. It is\n also sometimes more readable as it removes the need for duplicating or storing the pattern\n used by `str::{starts,ends}_with` and in the slicing.\n\n **Known problems:**\n None.\n\n **Example:**\n\n ```rust\n let s = \"hello, world!\";\n if s.starts_with(\"hello, \") {\n assert_eq!(s[\"hello, \".len()..].to_uppercase(), \"WORLD!\");\n }\n ```\n Use instead:\n ```rust\n let s = \"hello, world!\";\n if let Some(end) = s.strip_prefix(\"hello, \") {\n assert_eq!(end.to_uppercase(), \"WORLD!\");\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "manual_unwrap_or", - "id_span": { - "path": "src/manual_unwrap_or.rs", - "line": 36 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Finds patterns that reimplement `Option::unwrap_or` or `Result::unwrap_or`.\n\n **Why is this bad?**\n Concise code helps focusing on behavior instead of boilerplate.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let foo: Option = None;\n match foo {\n Some(v) => v,\n None => 1,\n };\n ```\n\n Use instead:\n ```rust\n let foo: Option = None;\n foo.unwrap_or(1);\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "map_clone", - "id_span": { - "path": "src/map_clone.rs", - "line": 40 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for usage of `map(|x| x.clone())` or dereferencing closures for `Copy` types, on `Iterator` or `Option`,\n and suggests `cloned()` or `copied()` instead\n\n **Why is this bad?** Readability, this can be written more concisely\n\n **Known problems:** None\n\n **Example:**\n\n ```rust\n let x = vec![42, 43];\n let y = x.iter();\n let z = y.map(|i| *i);\n ```\n\n The correct use would be:\n\n ```rust\n let x = vec![42, 43];\n let y = x.iter();\n let z = y.cloned();\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "map_err_ignore", - "id_span": { - "path": "src/map_err_ignore.rs", - "line": 101 - }, - "group": "clippy::restriction", - "docs": " **What it does:** Checks for instances of `map_err(|_| Some::Enum)`\n **Why is this bad?** This `map_err` throws away the original error rather than allowing the enum to contain and report the cause of the error\n\n **Known problems:** None.\n\n **Example:**\n Before:\n ```rust\n use std::fmt;\n\n #[derive(Debug)]\n enum Error {\n Indivisible,\n Remainder(u8),\n }\n\n impl fmt::Display for Error {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n match self {\n Error::Indivisible => write!(f, \"could not divide input by three\"),\n Error::Remainder(remainder) => write!(\n f,\n \"input is not divisible by three, remainder = {}\",\n remainder\n ),\n }\n }\n }\n\n impl std::error::Error for Error {}\n\n fn divisible_by_3(input: &str) -> Result<(), Error> {\n input\n .parse::()\n .map_err(|_| Error::Indivisible)\n .map(|v| v % 3)\n .and_then(|remainder| {\n if remainder == 0 {\n Ok(())\n } else {\n Err(Error::Remainder(remainder as u8))\n }\n })\n }\n ```\n\n After:\n ```rust\n use std::{fmt, num::ParseIntError};\n\n #[derive(Debug)]\n enum Error {\n Indivisible(ParseIntError),\n Remainder(u8),\n }\n\n impl fmt::Display for Error {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n match self {\n Error::Indivisible(_) => write!(f, \"could not divide input by three\"),\n Error::Remainder(remainder) => write!(\n f,\n \"input is not divisible by three, remainder = {}\",\n remainder\n ),\n }\n }\n }\n\n impl std::error::Error for Error {\n fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {\n match self {\n Error::Indivisible(source) => Some(source),\n _ => None,\n }\n }\n }\n\n fn divisible_by_3(input: &str) -> Result<(), Error> {\n input\n .parse::()\n .map_err(Error::Indivisible)\n .map(|v| v % 3)\n .and_then(|remainder| {\n if remainder == 0 {\n Ok(())\n } else {\n Err(Error::Remainder(remainder as u8))\n }\n })\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "map_identity", - "id_span": { - "path": "src/map_identity.rs", - "line": 30 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for instances of `map(f)` where `f` is the identity function.\n **Why is this bad?** It can be written more concisely without the call to `map`.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n let x = [1, 2, 3];\n let y: Vec<_> = x.iter().map(|x| x).map(|x| 2*x).collect();\n ```\n Use instead:\n ```rust\n let x = [1, 2, 3];\n let y: Vec<_> = x.iter().map(|x| 2*x).collect();\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "option_map_unit_fn", - "id_span": { - "path": "src/map_unit_fn.rs", - "line": 48 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for usage of `option.map(f)` where f is a function or closure that returns the unit type `()`.\n\n **Why is this bad?** Readability, this can be written more clearly with\n an if let statement\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n # fn do_stuff() -> Option { Some(String::new()) }\n # fn log_err_msg(foo: String) -> Option { Some(foo) }\n # fn format_msg(foo: String) -> String { String::new() }\n let x: Option = do_stuff();\n x.map(log_err_msg);\n # let x: Option = do_stuff();\n x.map(|msg| log_err_msg(format_msg(msg)));\n ```\n\n The correct use would be:\n\n ```rust\n # fn do_stuff() -> Option { Some(String::new()) }\n # fn log_err_msg(foo: String) -> Option { Some(foo) }\n # fn format_msg(foo: String) -> String { String::new() }\n let x: Option = do_stuff();\n if let Some(msg) = x {\n log_err_msg(msg);\n }\n\n # let x: Option = do_stuff();\n if let Some(msg) = x {\n log_err_msg(format_msg(msg));\n }\n ```\n", - "applicability": { - "is_multi_suggestion": true, - "applicability": "MachineApplicable" - } - }, - { - "id": "result_map_unit_fn", - "id_span": { - "path": "src/map_unit_fn.rs", - "line": 89 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for usage of `result.map(f)` where f is a function or closure that returns the unit type `()`.\n\n **Why is this bad?** Readability, this can be written more clearly with\n an if let statement\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n # fn do_stuff() -> Result { Ok(String::new()) }\n # fn log_err_msg(foo: String) -> Result { Ok(foo) }\n # fn format_msg(foo: String) -> String { String::new() }\n let x: Result = do_stuff();\n x.map(log_err_msg);\n # let x: Result = do_stuff();\n x.map(|msg| log_err_msg(format_msg(msg)));\n ```\n\n The correct use would be:\n\n ```rust\n # fn do_stuff() -> Result { Ok(String::new()) }\n # fn log_err_msg(foo: String) -> Result { Ok(foo) }\n # fn format_msg(foo: String) -> String { String::new() }\n let x: Result = do_stuff();\n if let Ok(msg) = x {\n log_err_msg(msg);\n };\n # let x: Result = do_stuff();\n if let Ok(msg) = x {\n log_err_msg(format_msg(msg));\n };\n ```\n", - "applicability": { - "is_multi_suggestion": true, - "applicability": "MachineApplicable" - } - }, - { - "id": "match_on_vec_items", - "id_span": { - "path": "src/match_on_vec_items.rs", - "line": 41 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for `match vec[idx]` or `match vec[n..m]`.\n **Why is this bad?** This can panic at runtime.\n\n **Known problems:** None.\n\n **Example:**\n ```rust, no_run\n let arr = vec![0, 1, 2, 3];\n let idx = 1;\n\n // Bad\n match arr[idx] {\n 0 => println!(\"{}\", 0),\n 1 => println!(\"{}\", 3),\n _ => {},\n }\n ```\n Use instead:\n ```rust, no_run\n let arr = vec![0, 1, 2, 3];\n let idx = 1;\n\n // Good\n match arr.get(idx) {\n Some(0) => println!(\"{}\", 0),\n Some(1) => println!(\"{}\", 3),\n _ => {},\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MaybeIncorrect" - } - }, - { - "id": "single_match", - "id_span": { - "path": "src/matches.rs", - "line": 55 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for matches with a single arm where an `if let` will usually suffice.\n\n **Why is this bad?** Just readability – `if let` nests less than a `match`.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # fn bar(stool: &str) {}\n # let x = Some(\"abc\");\n // Bad\n match x {\n Some(ref foo) => bar(foo),\n _ => (),\n }\n\n // Good\n if let Some(ref foo) = x {\n bar(foo);\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "HasPlaceholders" - } - }, - { - "id": "single_match_else", - "id_span": { - "path": "src/matches.rs", - "line": 94 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for matches with two arms where an `if let else` will usually suffice.\n\n **Why is this bad?** Just readability – `if let` nests less than a `match`.\n\n **Known problems:** Personal style preferences may differ.\n\n **Example:**\n\n Using `match`:\n\n ```rust\n # fn bar(foo: &usize) {}\n # let other_ref: usize = 1;\n # let x: Option<&usize> = Some(&1);\n match x {\n Some(ref foo) => bar(foo),\n _ => bar(&other_ref),\n }\n ```\n\n Using `if let` with `else`:\n\n ```rust\n # fn bar(foo: &usize) {}\n # let other_ref: usize = 1;\n # let x: Option<&usize> = Some(&1);\n if let Some(ref foo) = x {\n bar(foo);\n } else {\n bar(&other_ref);\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "HasPlaceholders" - } - }, - { - "id": "match_ref_pats", - "id_span": { - "path": "src/matches.rs", - "line": 125 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for matches where all arms match a reference, suggesting to remove the reference and deref the matched expression\n instead. It also checks for `if let &foo = bar` blocks.\n\n **Why is this bad?** It just makes the code less readable. That reference\n destructuring adds nothing to the code.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n // Bad\n match x {\n &A(ref y) => foo(y),\n &B => bar(),\n _ => frob(&x),\n }\n\n // Good\n match *x {\n A(ref y) => foo(y),\n B => bar(),\n _ => frob(x),\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "match_bool", - "id_span": { - "path": "src/matches.rs", - "line": 159 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for matches where match expression is a `bool`. It suggests to replace the expression with an `if...else` block.\n\n **Why is this bad?** It makes the code less readable.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # fn foo() {}\n # fn bar() {}\n let condition: bool = true;\n match condition {\n true => foo(),\n false => bar(),\n }\n ```\n Use if/else instead:\n ```rust\n # fn foo() {}\n # fn bar() {}\n let condition: bool = true;\n if condition {\n foo();\n } else {\n bar();\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "HasPlaceholders" - } - }, - { - "id": "match_overlapping_arm", - "id_span": { - "path": "src/matches.rs", - "line": 181 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for overlapping match arms.\n **Why is this bad?** It is likely to be an error and if not, makes the code\n less obvious.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let x = 5;\n match x {\n 1...10 => println!(\"1 ... 10\"),\n 5...15 => println!(\"5 ... 15\"),\n _ => (),\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "match_wild_err_arm", - "id_span": { - "path": "src/matches.rs", - "line": 203 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for arm which matches all errors with `Err(_)` and take drastic actions like `panic!`.\n\n **Why is this bad?** It is generally a bad practice, similar to\n catching all exceptions in java with `catch(Exception)`\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let x: Result = Ok(3);\n match x {\n Ok(_) => println!(\"ok\"),\n Err(_) => panic!(\"err\"),\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "match_as_ref", - "id_span": { - "path": "src/matches.rs", - "line": 229 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for match which is used to add a reference to an `Option` value.\n\n **Why is this bad?** Using `as_ref()` or `as_mut()` instead is shorter.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let x: Option<()> = None;\n\n // Bad\n let r: Option<&()> = match x {\n None => None,\n Some(ref v) => Some(v),\n };\n\n // Good\n let r: Option<&()> = x.as_ref();\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "wildcard_enum_match_arm", - "id_span": { - "path": "src/matches.rs", - "line": 258 - }, - "group": "clippy::restriction", - "docs": " **What it does:** Checks for wildcard enum matches using `_`.\n **Why is this bad?** New enum variants added by library updates can be missed.\n\n **Known problems:** Suggested replacements may be incorrect if guards exhaustively cover some\n variants, and also may not use correct path to enum if it's not present in the current scope.\n\n **Example:**\n ```rust\n # enum Foo { A(usize), B(usize) }\n # let x = Foo::B(1);\n // Bad\n match x {\n Foo::A(_) => {},\n _ => {},\n }\n\n // Good\n match x {\n Foo::A(_) => {},\n Foo::B(_) => {},\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MaybeIncorrect" - } - }, - { - "id": "match_wildcard_for_single_variants", - "id_span": { - "path": "src/matches.rs", - "line": 290 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for wildcard enum matches for a single variant.\n **Why is this bad?** New enum variants added by library updates can be missed.\n\n **Known problems:** Suggested replacements may not use correct path to enum\n if it's not present in the current scope.\n\n **Example:**\n\n ```rust\n # enum Foo { A, B, C }\n # let x = Foo::B;\n // Bad\n match x {\n Foo::A => {},\n Foo::B => {},\n _ => {},\n }\n\n // Good\n match x {\n Foo::A => {},\n Foo::B => {},\n Foo::C => {},\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MaybeIncorrect" - } - }, - { - "id": "wildcard_in_or_patterns", - "id_span": { - "path": "src/matches.rs", - "line": 317 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for wildcard pattern used with others patterns in same match arm.\n **Why is this bad?** Wildcard pattern already covers any other pattern as it will match anyway.\n It makes the code less readable, especially to spot wildcard pattern use in match arm.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n // Bad\n match \"foo\" {\n \"a\" => {},\n \"bar\" | _ => {},\n }\n\n // Good\n match \"foo\" {\n \"a\" => {},\n _ => {},\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "infallible_destructuring_match", - "id_span": { - "path": "src/matches.rs", - "line": 352 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for matches being used to destructure a single-variant enum or tuple struct where a `let` will suffice.\n\n **Why is this bad?** Just readability – `let` doesn't nest, whereas a `match` does.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n enum Wrapper {\n Data(i32),\n }\n\n let wrapper = Wrapper::Data(42);\n\n let data = match wrapper {\n Wrapper::Data(i) => i,\n };\n ```\n\n The correct use would be:\n ```rust\n enum Wrapper {\n Data(i32),\n }\n\n let wrapper = Wrapper::Data(42);\n let Wrapper::Data(data) = wrapper;\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "match_single_binding", - "id_span": { - "path": "src/matches.rs", - "line": 380 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for useless match that binds to only one value.\n **Why is this bad?** Readability and needless complexity.\n\n **Known problems:** Suggested replacements may be incorrect when `match`\n is actually binding temporary value, bringing a 'dropped while borrowed' error.\n\n **Example:**\n ```rust\n # let a = 1;\n # let b = 2;\n\n // Bad\n match (a, b) {\n (c, d) => {\n // useless match\n }\n }\n\n // Good\n let (c, d) = (a, b);\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "rest_pat_in_fully_bound_structs", - "id_span": { - "path": "src/matches.rs", - "line": 410 - }, - "group": "clippy::restriction", - "docs": " **What it does:** Checks for unnecessary '..' pattern binding on struct when all fields are explicitly matched.\n **Why is this bad?** Correctness and readability. It's like having a wildcard pattern after\n matching all enum variants explicitly.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # struct A { a: i32 }\n let a = A { a: 5 };\n\n // Bad\n match a {\n A { a: 5, .. } => {},\n _ => {},\n }\n\n // Good\n match a {\n A { a: 5 } => {},\n _ => {},\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "redundant_pattern_matching", - "id_span": { - "path": "src/matches.rs", - "line": 458 - }, - "group": "clippy::style", - "docs": " **What it does:** Lint for redundant pattern matching over `Result`, `Option`, `std::task::Poll` or `std::net::IpAddr`\n\n **Why is this bad?** It's more concise and clear to just use the proper\n utility function\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n # use std::task::Poll;\n # use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};\n if let Ok(_) = Ok::(42) {}\n if let Err(_) = Err::(42) {}\n if let None = None::<()> {}\n if let Some(_) = Some(42) {}\n if let Poll::Pending = Poll::Pending::<()> {}\n if let Poll::Ready(_) = Poll::Ready(42) {}\n if let IpAddr::V4(_) = IpAddr::V4(Ipv4Addr::LOCALHOST) {}\n if let IpAddr::V6(_) = IpAddr::V6(Ipv6Addr::LOCALHOST) {}\n match Ok::(42) {\n Ok(_) => true,\n Err(_) => false,\n };\n ```\n\n The more idiomatic use would be:\n\n ```rust\n # use std::task::Poll;\n # use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};\n if Ok::(42).is_ok() {}\n if Err::(42).is_err() {}\n if None::<()>.is_none() {}\n if Some(42).is_some() {}\n if Poll::Pending::<()>.is_pending() {}\n if Poll::Ready(42).is_ready() {}\n if IpAddr::V4(Ipv4Addr::LOCALHOST).is_ipv4() {}\n if IpAddr::V6(Ipv6Addr::LOCALHOST).is_ipv6() {}\n Ok::(42).is_ok();\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MaybeIncorrect" - } - }, - { - "id": "match_like_matches_macro", - "id_span": { - "path": "src/matches.rs", - "line": 491 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for `match` or `if let` expressions producing a `bool` that could be written using `matches!`\n\n **Why is this bad?** Readability and needless complexity.\n\n **Known problems:** This lint falsely triggers, if there are arms with\n `cfg` attributes that remove an arm evaluating to `false`.\n\n **Example:**\n ```rust\n let x = Some(5);\n\n // Bad\n let a = match x {\n Some(0) => true,\n _ => false,\n };\n\n let a = if let Some(0) = x {\n true\n } else {\n false\n };\n\n // Good\n let a = matches!(x, Some(0));\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MaybeIncorrect" - } - }, - { - "id": "match_same_arms", - "id_span": { - "path": "src/matches.rs", - "line": 532 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for `match` with identical arm bodies.\n **Why is this bad?** This is probably a copy & paste error. If arm bodies\n are the same on purpose, you can factor them\n [using `|`](https://doc.rust-lang.org/book/patterns.html#multiple-patterns).\n\n **Known problems:** False positive possible with order dependent `match`\n (see issue\n [#860](https://github.com/rust-lang/rust-clippy/issues/860)).\n\n **Example:**\n ```rust,ignore\n match foo {\n Bar => bar(),\n Quz => quz(),\n Baz => bar(), // <= oops\n }\n ```\n\n This should probably be\n ```rust,ignore\n match foo {\n Bar => bar(),\n Quz => quz(),\n Baz => baz(), // <= fixed\n }\n ```\n\n or if the original code was not a typo:\n ```rust,ignore\n match foo {\n Bar | Baz => bar(), // <= shows the intent better\n Quz => quz(),\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "mem_discriminant_non_enum", - "id_span": { - "path": "src/mem_discriminant.rs", - "line": 25 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for calls of `mem::discriminant()` on a non-enum type.\n **Why is this bad?** The value of `mem::discriminant()` on non-enum types\n is unspecified.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n use std::mem;\n\n mem::discriminant(&\"hello\");\n mem::discriminant(&&Some(2));\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "mem_forget", - "id_span": { - "path": "src/mem_forget.rs", - "line": 21 - }, - "group": "clippy::restriction", - "docs": " **What it does:** Checks for usage of `std::mem::forget(t)` where `t` is `Drop`.\n\n **Why is this bad?** `std::mem::forget(t)` prevents `t` from running its\n destructor, possibly causing leaks.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # use std::mem;\n # use std::rc::Rc;\n mem::forget(Rc::new(55))\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "mem_replace_option_with_none", - "id_span": { - "path": "src/mem_replace.rs", - "line": 37 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for `mem::replace()` on an `Option` with `None`.\n\n **Why is this bad?** `Option` already has the method `take()` for\n taking its current value (Some(..) or None) and replacing it with\n `None`.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n use std::mem;\n\n let mut an_option = Some(0);\n let replaced = mem::replace(&mut an_option, None);\n ```\n Is better expressed with:\n ```rust\n let mut an_option = Some(0);\n let taken = an_option.take();\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "mem_replace_with_uninit", - "id_span": { - "path": "src/mem_replace.rs", - "line": 69 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for `mem::replace(&mut _, mem::uninitialized())` and `mem::replace(&mut _, mem::zeroed())`.\n\n **Why is this bad?** This will lead to undefined behavior even if the\n value is overwritten later, because the uninitialized value may be\n observed in the case of a panic.\n\n **Known problems:** None.\n\n **Example:**\n\n ```\n use std::mem;\n# fn may_panic(v: Vec) -> Vec { v }\n\n #[allow(deprecated, invalid_value)]\n fn myfunc (v: &mut Vec) {\n let taken_v = unsafe { mem::replace(v, mem::uninitialized()) };\n let new_v = may_panic(taken_v); // undefined behavior on panic\n mem::forget(mem::replace(v, new_v));\n }\n ```\n\n The [take_mut](https://docs.rs/take_mut) crate offers a sound solution,\n at the cost of either lazily creating a replacement value or aborting\n on panic, to ensure that the uninitialized value cannot be observed.\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "mem_replace_with_default", - "id_span": { - "path": "src/mem_replace.rs", - "line": 93 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for `std::mem::replace` on a value of type `T` with `T::default()`.\n\n **Why is this bad?** `std::mem` module already has the method `take` to\n take the current value and replace it with the default value of that type.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let mut text = String::from(\"foo\");\n let replaced = std::mem::replace(&mut text, String::default());\n ```\n Is better expressed with:\n ```rust\n let mut text = String::from(\"foo\");\n let taken = std::mem::take(&mut text);\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "unwrap_used", - "id_span": { - "path": "src/methods/mod.rs", - "line": 84 - }, - "group": "clippy::restriction", - "docs": " **What it does:** Checks for `.unwrap()` calls on `Option`s and on `Result`s.\n **Why is this bad?** It is better to handle the `None` or `Err` case,\n or at least call `.expect(_)` with a more helpful message. Still, for a lot of\n quick-and-dirty code, `unwrap` is a good choice, which is why this lint is\n `Allow` by default.\n\n `result.unwrap()` will let the thread panic on `Err` values.\n Normally, you want to implement more sophisticated error handling,\n and propagate errors upwards with `?` operator.\n\n Even if you want to panic on errors, not all `Error`s implement good\n messages on display. Therefore, it may be beneficial to look at the places\n where they may get displayed. Activate this lint to do just that.\n\n **Known problems:** None.\n\n **Examples:**\n ```rust\n # let opt = Some(1);\n\n // Bad\n opt.unwrap();\n\n // Good\n opt.expect(\"more helpful message\");\n ```\n\n // or\n\n ```rust\n # let res: Result = Ok(1);\n\n // Bad\n res.unwrap();\n\n // Good\n res.expect(\"more helpful message\");\n ```\n", - "applicability": null - }, - { - "id": "expect_used", - "id_span": { - "path": "src/methods/mod.rs", - "line": 126 - }, - "group": "clippy::restriction", - "docs": " **What it does:** Checks for `.expect()` calls on `Option`s and `Result`s.\n **Why is this bad?** Usually it is better to handle the `None` or `Err` case.\n Still, for a lot of quick-and-dirty code, `expect` is a good choice, which is why\n this lint is `Allow` by default.\n\n `result.expect()` will let the thread panic on `Err`\n values. Normally, you want to implement more sophisticated error handling,\n and propagate errors upwards with `?` operator.\n\n **Known problems:** None.\n\n **Examples:**\n ```rust,ignore\n # let opt = Some(1);\n\n // Bad\n opt.expect(\"one\");\n\n // Good\n let opt = Some(1);\n opt?;\n ```\n\n // or\n\n ```rust\n # let res: Result = Ok(1);\n\n // Bad\n res.expect(\"one\");\n\n // Good\n res?;\n # Ok::<(), ()>(())\n ```\n", - "applicability": null - }, - { - "id": "should_implement_trait", - "id_span": { - "path": "src/methods/mod.rs", - "line": 155 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for methods that should live in a trait implementation of a `std` trait (see [llogiq's blog\n post](http://llogiq.github.io/2015/07/30/traits.html) for further\n information) instead of an inherent implementation.\n\n **Why is this bad?** Implementing the traits improve ergonomics for users of\n the code, often with very little cost. Also people seeing a `mul(...)`\n method\n may expect `*` to work equally, so you should have good reason to disappoint\n them.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n struct X;\n impl X {\n fn add(&self, other: &X) -> X {\n // ..\n # X\n }\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "wrong_self_convention", - "id_span": { - "path": "src/methods/mod.rs", - "line": 188 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for methods with certain name prefixes and which doesn't match how self is taken. The actual rules are:\n\n |Prefix |`self` taken |\n |-------|----------------------|\n |`as_` |`&self` or `&mut self`|\n |`from_`| none |\n |`into_`|`self` |\n |`is_` |`&self` or none |\n |`to_` |`&self` |\n\n **Why is this bad?** Consistency breeds readability. If you follow the\n conventions, your users won't be surprised that they, e.g., need to supply a\n mutable reference to a `as_..` function.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # struct X;\n impl X {\n fn as_str(self) -> &'static str {\n // ..\n # \"\"\n }\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "wrong_pub_self_convention", - "id_span": { - "path": "src/methods/mod.rs", - "line": 212 - }, - "group": "clippy::restriction", - "docs": " **What it does:** This is the same as [`wrong_self_convention`](#wrong_self_convention), but for public items.\n\n **Why is this bad?** See [`wrong_self_convention`](#wrong_self_convention).\n\n **Known problems:** Actually *renaming* the function may break clients if\n the function is part of the public interface. In that case, be mindful of\n the stability guarantees you've given your users.\n\n **Example:**\n ```rust\n # struct X;\n impl<'a> X {\n pub fn as_str(self) -> &'a str {\n \"foo\"\n }\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "ok_expect", - "id_span": { - "path": "src/methods/mod.rs", - "line": 235 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for usage of `ok().expect(..)`.\n **Why is this bad?** Because you usually call `expect()` on the `Result`\n directly to get a better error message.\n\n **Known problems:** The error type needs to implement `Debug`\n\n **Example:**\n ```rust\n # let x = Ok::<_, ()>(());\n\n // Bad\n x.ok().expect(\"why did I do this again?\");\n\n // Good\n x.expect(\"why did I do this again?\");\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "map_unwrap_or", - "id_span": { - "path": "src/methods/mod.rs", - "line": 272 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for usage of `option.map(_).unwrap_or(_)` or `option.map(_).unwrap_or_else(_)` or `result.map(_).unwrap_or_else(_)`.\n\n **Why is this bad?** Readability, these can be written more concisely (resp.) as\n `option.map_or(_, _)`, `option.map_or_else(_, _)` and `result.map_or_else(_, _)`.\n\n **Known problems:** The order of the arguments is not in execution order\n\n **Examples:**\n ```rust\n # let x = Some(1);\n\n // Bad\n x.map(|a| a + 1).unwrap_or(0);\n\n // Good\n x.map_or(0, |a| a + 1);\n ```\n\n // or\n\n ```rust\n # let x: Result = Ok(1);\n # fn some_function(foo: ()) -> usize { 1 }\n\n // Bad\n x.map(|a| a + 1).unwrap_or_else(some_function);\n\n // Good\n x.map_or_else(some_function, |a| a + 1);\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "option_map_or_none", - "id_span": { - "path": "src/methods/mod.rs", - "line": 295 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for usage of `_.map_or(None, _)`.\n **Why is this bad?** Readability, this can be written more concisely as\n `_.and_then(_)`.\n\n **Known problems:** The order of the arguments is not in execution order.\n\n **Example:**\n ```rust\n # let opt = Some(1);\n\n // Bad\n opt.map_or(None, |a| Some(a + 1));\n\n // Good\n opt.and_then(|a| Some(a + 1));\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "result_map_or_into_option", - "id_span": { - "path": "src/methods/mod.rs", - "line": 321 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for usage of `_.map_or(None, Some)`.\n **Why is this bad?** Readability, this can be written more concisely as\n `_.ok()`.\n\n **Known problems:** None.\n\n **Example:**\n\n Bad:\n ```rust\n # let r: Result = Ok(1);\n assert_eq!(Some(1), r.map_or(None, Some));\n ```\n\n Good:\n ```rust\n # let r: Result = Ok(1);\n assert_eq!(Some(1), r.ok());\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "bind_instead_of_map", - "id_span": { - "path": "src/methods/mod.rs", - "line": 354 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for usage of `_.and_then(|x| Some(y))`, `_.and_then(|x| Ok(y))` or `_.or_else(|x| Err(y))`.\n\n **Why is this bad?** Readability, this can be written more concisely as\n `_.map(|x| y)` or `_.map_err(|x| y)`.\n\n **Known problems:** None\n\n **Example:**\n\n ```rust\n # fn opt() -> Option<&'static str> { Some(\"42\") }\n # fn res() -> Result<&'static str, &'static str> { Ok(\"42\") }\n let _ = opt().and_then(|s| Some(s.len()));\n let _ = res().and_then(|s| if s.len() == 42 { Ok(10) } else { Ok(20) });\n let _ = res().or_else(|s| if s.len() == 42 { Err(10) } else { Err(20) });\n ```\n\n The correct use would be:\n\n ```rust\n # fn opt() -> Option<&'static str> { Some(\"42\") }\n # fn res() -> Result<&'static str, &'static str> { Ok(\"42\") }\n let _ = opt().map(|s| s.len());\n let _ = res().map(|s| if s.len() == 42 { 10 } else { 20 });\n let _ = res().map_err(|s| if s.len() == 42 { 10 } else { 20 });\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "filter_next", - "id_span": { - "path": "src/methods/mod.rs", - "line": 377 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for usage of `_.filter(_).next()`.\n **Why is this bad?** Readability, this can be written more concisely as\n `_.find(_)`.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let vec = vec![1];\n vec.iter().filter(|x| **x == 0).next();\n ```\n Could be written as\n ```rust\n # let vec = vec![1];\n vec.iter().find(|x| **x == 0);\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "skip_while_next", - "id_span": { - "path": "src/methods/mod.rs", - "line": 400 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for usage of `_.skip_while(condition).next()`.\n **Why is this bad?** Readability, this can be written more concisely as\n `_.find(!condition)`.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let vec = vec![1];\n vec.iter().skip_while(|x| **x == 0).next();\n ```\n Could be written as\n ```rust\n # let vec = vec![1];\n vec.iter().find(|x| **x != 0);\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "map_flatten", - "id_span": { - "path": "src/methods/mod.rs", - "line": 423 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for usage of `_.map(_).flatten(_)`,\n **Why is this bad?** Readability, this can be written more concisely as\n `_.flat_map(_)`\n\n **Known problems:**\n\n **Example:**\n ```rust\n let vec = vec![vec![1]];\n\n // Bad\n vec.iter().map(|x| x.iter()).flatten();\n\n // Good\n vec.iter().flat_map(|x| x.iter());\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "filter_map", - "id_span": { - "path": "src/methods/mod.rs", - "line": 452 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for usage of `_.filter(_).map(_)`, `_.filter(_).flat_map(_)`, `_.filter_map(_).flat_map(_)` and similar.\n\n **Why is this bad?** Readability, this can be written more concisely as\n `_.filter_map(_)`.\n\n **Known problems:** Often requires a condition + Option/Iterator creation\n inside the closure.\n\n **Example:**\n ```rust\n let vec = vec![1];\n\n // Bad\n vec.iter().filter(|x| **x == 0).map(|x| *x * 2);\n\n // Good\n vec.iter().filter_map(|x| if *x == 0 {\n Some(*x * 2)\n } else {\n None\n });\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "manual_filter_map", - "id_span": { - "path": "src/methods/mod.rs", - "line": 478 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for usage of `_.filter(_).map(_)` that can be written more simply as `filter_map(_)`.\n\n **Why is this bad?** Redundant code in the `filter` and `map` operations is poor style and\n less performant.\n\n **Known problems:** None.\n\n **Example:**\n Bad:\n ```rust\n (0_i32..10)\n .filter(|n| n.checked_add(1).is_some())\n .map(|n| n.checked_add(1).unwrap());\n ```\n\n Good:\n ```rust\n (0_i32..10).filter_map(|n| n.checked_add(1));\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "manual_find_map", - "id_span": { - "path": "src/methods/mod.rs", - "line": 504 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for usage of `_.find(_).map(_)` that can be written more simply as `find_map(_)`.\n\n **Why is this bad?** Redundant code in the `find` and `map` operations is poor style and\n less performant.\n\n **Known problems:** None.\n\n **Example:**\n Bad:\n ```rust\n (0_i32..10)\n .find(|n| n.checked_add(1).is_some())\n .map(|n| n.checked_add(1).unwrap());\n ```\n\n Good:\n ```rust\n (0_i32..10).find_map(|n| n.checked_add(1));\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "filter_map_next", - "id_span": { - "path": "src/methods/mod.rs", - "line": 526 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for usage of `_.filter_map(_).next()`.\n **Why is this bad?** Readability, this can be written more concisely as\n `_.find_map(_)`.\n\n **Known problems:** None\n\n **Example:**\n ```rust\n (0..3).filter_map(|x| if x == 2 { Some(x) } else { None }).next();\n ```\n Can be written as\n\n ```rust\n (0..3).find_map(|x| if x == 2 { Some(x) } else { None });\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "flat_map_identity", - "id_span": { - "path": "src/methods/mod.rs", - "line": 548 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for usage of `flat_map(|x| x)`.\n **Why is this bad?** Readability, this can be written more concisely by using `flatten`.\n\n **Known problems:** None\n\n **Example:**\n ```rust\n # let iter = vec![vec![0]].into_iter();\n iter.flat_map(|x| x);\n ```\n Can be written as\n ```rust\n # let iter = vec![vec![0]].into_iter();\n iter.flatten();\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "search_is_some", - "id_span": { - "path": "src/methods/mod.rs", - "line": 572 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for an iterator or string search (such as `find()`, `position()`, or `rposition()`) followed by a call to `is_some()`.\n\n **Why is this bad?** Readability, this can be written more concisely as\n `_.any(_)` or `_.contains(_)`.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let vec = vec![1];\n vec.iter().find(|x| **x == 0).is_some();\n ```\n Could be written as\n ```rust\n # let vec = vec![1];\n vec.iter().any(|x| *x == 0);\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "chars_next_cmp", - "id_span": { - "path": "src/methods/mod.rs", - "line": 596 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for usage of `.chars().next()` on a `str` to check if it starts with a given char.\n\n **Why is this bad?** Readability, this can be written more concisely as\n `_.starts_with(_)`.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let name = \"foo\";\n if name.chars().next() == Some('_') {};\n ```\n Could be written as\n ```rust\n let name = \"foo\";\n if name.starts_with('_') {};\n ```\n", - "applicability": null - }, - { - "id": "or_fun_call", - "id_span": { - "path": "src/methods/mod.rs", - "line": 627 - }, - "group": "clippy::perf", - "docs": " **What it does:** Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`, etc., and suggests to use `or_else`, `unwrap_or_else`, etc., or\n `unwrap_or_default` instead.\n\n **Why is this bad?** The function will always be called and potentially\n allocate an object acting as the default.\n\n **Known problems:** If the function has side-effects, not calling it will\n change the semantic of the program, but you shouldn't rely on that anyway.\n\n **Example:**\n ```rust\n # let foo = Some(String::new());\n foo.unwrap_or(String::new());\n ```\n this can instead be written:\n ```rust\n # let foo = Some(String::new());\n foo.unwrap_or_else(String::new);\n ```\n or\n ```rust\n # let foo = Some(String::new());\n foo.unwrap_or_default();\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "HasPlaceholders" - } - }, - { - "id": "expect_fun_call", - "id_span": { - "path": "src/methods/mod.rs", - "line": 662 - }, - "group": "clippy::perf", - "docs": " **What it does:** Checks for calls to `.expect(&format!(...))`, `.expect(foo(..))`, etc., and suggests to use `unwrap_or_else` instead\n\n **Why is this bad?** The function will always be called.\n\n **Known problems:** If the function has side-effects, not calling it will\n change the semantics of the program, but you shouldn't rely on that anyway.\n\n **Example:**\n ```rust\n # let foo = Some(String::new());\n # let err_code = \"418\";\n # let err_msg = \"I'm a teapot\";\n foo.expect(&format!(\"Err {}: {}\", err_code, err_msg));\n ```\n or\n ```rust\n # let foo = Some(String::new());\n # let err_code = \"418\";\n # let err_msg = \"I'm a teapot\";\n foo.expect(format!(\"Err {}: {}\", err_code, err_msg).as_str());\n ```\n this can instead be written:\n ```rust\n # let foo = Some(String::new());\n # let err_code = \"418\";\n # let err_msg = \"I'm a teapot\";\n foo.unwrap_or_else(|| panic!(\"Err {}: {}\", err_code, err_msg));\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "clone_on_copy", - "id_span": { - "path": "src/methods/mod.rs", - "line": 679 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for usage of `.clone()` on a `Copy` type.\n **Why is this bad?** The only reason `Copy` types implement `Clone` is for\n generics, not for using the `clone` method on a concrete type.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n 42u64.clone();\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "clone_on_ref_ptr", - "id_span": { - "path": "src/methods/mod.rs", - "line": 704 - }, - "group": "clippy::restriction", - "docs": " **What it does:** Checks for usage of `.clone()` on a ref-counted pointer, (`Rc`, `Arc`, `rc::Weak`, or `sync::Weak`), and suggests calling Clone via unified\n function syntax instead (e.g., `Rc::clone(foo)`).\n\n **Why is this bad?** Calling '.clone()' on an Rc, Arc, or Weak\n can obscure the fact that only the pointer is being cloned, not the underlying\n data.\n\n **Example:**\n ```rust\n # use std::rc::Rc;\n let x = Rc::new(1);\n\n // Bad\n x.clone();\n\n // Good\n Rc::clone(&x);\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "Unspecified" - } - }, - { - "id": "clone_double_ref", - "id_span": { - "path": "src/methods/mod.rs", - "line": 726 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for usage of `.clone()` on an `&&T`.\n **Why is this bad?** Cloning an `&&T` copies the inner `&T`, instead of\n cloning the underlying `T`.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n fn main() {\n let x = vec![1];\n let y = &&x;\n let z = y.clone();\n println!(\"{:p} {:p}\", *y, z); // prints out the same pointer\n }\n ```\n", - "applicability": { - "is_multi_suggestion": true, - "applicability": "MaybeIncorrect" - } - }, - { - "id": "inefficient_to_string", - "id_span": { - "path": "src/methods/mod.rs", - "line": 749 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for usage of `.to_string()` on an `&&T` where `T` implements `ToString` directly (like `&&str` or `&&String`).\n\n **Why is this bad?** This bypasses the specialized implementation of\n `ToString` and instead goes through the more expensive string formatting\n facilities.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n // Generic implementation for `T: Display` is used (slow)\n [\"foo\", \"bar\"].iter().map(|s| s.to_string());\n\n // OK, the specialized impl is used\n [\"foo\", \"bar\"].iter().map(|&s| s.to_string());\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "new_ret_no_self", - "id_span": { - "path": "src/methods/mod.rs", - "line": 810 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for `new` not returning a type that contains `Self`.\n **Why is this bad?** As a convention, `new` methods are used to make a new\n instance of a type.\n\n **Known problems:** None.\n\n **Example:**\n In an impl block:\n ```rust\n # struct Foo;\n # struct NotAFoo;\n impl Foo {\n fn new() -> NotAFoo {\n # NotAFoo\n }\n }\n ```\n\n ```rust\n # struct Foo;\n struct Bar(Foo);\n impl Foo {\n // Bad. The type name must contain `Self`\n fn new() -> Bar {\n # Bar(Foo)\n }\n }\n ```\n\n ```rust\n # struct Foo;\n # struct FooError;\n impl Foo {\n // Good. Return type contains `Self`\n fn new() -> Result {\n # Ok(Foo)\n }\n }\n ```\n\n Or in a trait definition:\n ```rust\n pub trait Trait {\n // Bad. The type name must contain `Self`\n fn new();\n }\n ```\n\n ```rust\n pub trait Trait {\n // Good. Return type contains `Self`\n fn new() -> Self;\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "single_char_pattern", - "id_span": { - "path": "src/methods/mod.rs", - "line": 831 - }, - "group": "clippy::perf", - "docs": " **What it does:** Checks for string methods that receive a single-character `str` as an argument, e.g., `_.split(\"x\")`.\n\n **Why is this bad?** Performing these methods using a `char` is faster than\n using a `str`.\n\n **Known problems:** Does not catch multi-byte unicode characters.\n\n **Example:**\n ```rust,ignore\n // Bad\n _.split(\"x\");\n\n // Good\n _.split('x');\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "iterator_step_by_zero", - "id_span": { - "path": "src/methods/mod.rs", - "line": 850 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for calling `.step_by(0)` on iterators which panics.\n **Why is this bad?** This very much looks like an oversight. Use `panic!()` instead if you\n actually intend to panic.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,should_panic\n for x in (0..100).step_by(0) {\n //..\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "iter_nth_zero", - "id_span": { - "path": "src/methods/mod.rs", - "line": 878 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for the use of `iter.nth(0)`.\n **Why is this bad?** `iter.next()` is equivalent to\n `iter.nth(0)`, as they both consume the next element,\n but is more readable.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n # use std::collections::HashSet;\n // Bad\n # let mut s = HashSet::new();\n # s.insert(1);\n let x = s.iter().nth(0);\n\n // Good\n # let mut s = HashSet::new();\n # s.insert(1);\n let x = s.iter().next();\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "iter_nth", - "id_span": { - "path": "src/methods/mod.rs", - "line": 904 - }, - "group": "clippy::perf", - "docs": " **What it does:** Checks for use of `.iter().nth()` (and the related `.iter_mut().nth()`) on standard library types with O(1) element access.\n\n **Why is this bad?** `.get()` and `.get_mut()` are more efficient and more\n readable.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let some_vec = vec![0, 1, 2, 3];\n let bad_vec = some_vec.iter().nth(3);\n let bad_slice = &some_vec[..].iter().nth(3);\n ```\n The correct use would be:\n ```rust\n let some_vec = vec![0, 1, 2, 3];\n let bad_vec = some_vec.get(3);\n let bad_slice = &some_vec[..].get(3);\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "iter_skip_next", - "id_span": { - "path": "src/methods/mod.rs", - "line": 928 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for use of `.skip(x).next()` on iterators.\n **Why is this bad?** `.nth(x)` is cleaner\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let some_vec = vec![0, 1, 2, 3];\n let bad_vec = some_vec.iter().skip(3).next();\n let bad_slice = &some_vec[..].iter().skip(3).next();\n ```\n The correct use would be:\n ```rust\n let some_vec = vec![0, 1, 2, 3];\n let bad_vec = some_vec.iter().nth(3);\n let bad_slice = &some_vec[..].iter().nth(3);\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "get_unwrap", - "id_span": { - "path": "src/methods/mod.rs", - "line": 961 - }, - "group": "clippy::restriction", - "docs": " **What it does:** Checks for use of `.get().unwrap()` (or `.get_mut().unwrap`) on a standard library type which implements `Index`\n\n **Why is this bad?** Using the Index trait (`[]`) is more clear and more\n concise.\n\n **Known problems:** Not a replacement for error handling: Using either\n `.unwrap()` or the Index trait (`[]`) carries the risk of causing a `panic`\n if the value being accessed is `None`. If the use of `.get().unwrap()` is a\n temporary placeholder for dealing with the `Option` type, then this does\n not mitigate the need for error handling. If there is a chance that `.get()`\n will be `None` in your program, then it is advisable that the `None` case\n is handled in a future refactor instead of using `.unwrap()` or the Index\n trait.\n\n **Example:**\n ```rust\n let mut some_vec = vec![0, 1, 2, 3];\n let last = some_vec.get(3).unwrap();\n *some_vec.get_mut(0).unwrap() = 1;\n ```\n The correct use would be:\n ```rust\n let mut some_vec = vec![0, 1, 2, 3];\n let last = some_vec[3];\n some_vec[0] = 1;\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "string_extend_chars", - "id_span": { - "path": "src/methods/mod.rs", - "line": 990 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for the use of `.extend(s.chars())` where s is a `&str` or `String`.\n\n **Why is this bad?** `.push_str(s)` is clearer\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let abc = \"abc\";\n let def = String::from(\"def\");\n let mut s = String::new();\n s.extend(abc.chars());\n s.extend(def.chars());\n ```\n The correct use would be:\n ```rust\n let abc = \"abc\";\n let def = String::from(\"def\");\n let mut s = String::new();\n s.push_str(abc);\n s.push_str(&def);\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "iter_cloned_collect", - "id_span": { - "path": "src/methods/mod.rs", - "line": 1013 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for the use of `.cloned().collect()` on slice to create a `Vec`.\n\n **Why is this bad?** `.to_vec()` is clearer\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let s = [1, 2, 3, 4, 5];\n let s2: Vec = s[..].iter().cloned().collect();\n ```\n The better use would be:\n ```rust\n let s = [1, 2, 3, 4, 5];\n let s2: Vec = s.to_vec();\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "chars_last_cmp", - "id_span": { - "path": "src/methods/mod.rs", - "line": 1037 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for usage of `_.chars().last()` or `_.chars().next_back()` on a `str` to check if it ends with a given char.\n\n **Why is this bad?** Readability, this can be written more concisely as\n `_.ends_with(_)`.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let name = \"_\";\n\n // Bad\n name.chars().last() == Some('_') || name.chars().next_back() == Some('-');\n\n // Good\n name.ends_with('_') || name.ends_with('-');\n ```\n", - "applicability": null - }, - { - "id": "useless_asref", - "id_span": { - "path": "src/methods/mod.rs", - "line": 1062 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for usage of `.as_ref()` or `.as_mut()` where the types before and after the call are the same.\n\n **Why is this bad?** The call is unnecessary.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # fn do_stuff(x: &[i32]) {}\n let x: &[i32] = &[1, 2, 3, 4, 5];\n do_stuff(x.as_ref());\n ```\n The correct use would be:\n ```rust\n # fn do_stuff(x: &[i32]) {}\n let x: &[i32] = &[1, 2, 3, 4, 5];\n do_stuff(x);\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "unnecessary_fold", - "id_span": { - "path": "src/methods/mod.rs", - "line": 1084 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for using `fold` when a more succinct alternative exists. Specifically, this checks for `fold`s which could be replaced by `any`, `all`,\n `sum` or `product`.\n\n **Why is this bad?** Readability.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let _ = (0..3).fold(false, |acc, x| acc || x > 2);\n ```\n This could be written as:\n ```rust\n let _ = (0..3).any(|x| x > 2);\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "unnecessary_filter_map", - "id_span": { - "path": "src/methods/mod.rs", - "line": 1113 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for `filter_map` calls which could be replaced by `filter` or `map`. More specifically it checks if the closure provided is only performing one of the\n filter or map operations and suggests the appropriate option.\n\n **Why is this bad?** Complexity. The intent is also clearer if only a single\n operation is being performed.\n\n **Known problems:** None\n\n **Example:**\n ```rust\n let _ = (0..3).filter_map(|x| if x > 2 { Some(x) } else { None });\n\n // As there is no transformation of the argument this could be written as:\n let _ = (0..3).filter(|&x| x > 2);\n ```\n\n ```rust\n let _ = (0..4).filter_map(|x| Some(x + 1));\n\n // As there is no conditional check on the argument this could be written as:\n let _ = (0..4).map(|x| x + 1);\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "into_iter_on_ref", - "id_span": { - "path": "src/methods/mod.rs", - "line": 1137 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for `into_iter` calls on references which should be replaced by `iter` or `iter_mut`.\n\n **Why is this bad?** Readability. Calling `into_iter` on a reference will not move out its\n content into the resulting iterator, which is confusing. It is better just call `iter` or\n `iter_mut` directly.\n\n **Known problems:** None\n\n **Example:**\n\n ```rust\n // Bad\n let _ = (&vec![3, 4, 5]).into_iter();\n\n // Good\n let _ = (&vec![3, 4, 5]).iter();\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "suspicious_map", - "id_span": { - "path": "src/methods/mod.rs", - "line": 1156 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for calls to `map` followed by a `count`.\n **Why is this bad?** It looks suspicious. Maybe `map` was confused with `filter`.\n If the `map` call is intentional, this should be rewritten. Or, if you intend to\n drive the iterator to completion, you can just use `for_each` instead.\n\n **Known problems:** None\n\n **Example:**\n\n ```rust\n let _ = (0..3).map(|x| x + 2).count();\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "uninit_assumed_init", - "id_span": { - "path": "src/methods/mod.rs", - "line": 1188 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for `MaybeUninit::uninit().assume_init()`.\n **Why is this bad?** For most types, this is undefined behavior.\n\n **Known problems:** For now, we accept empty tuples and tuples / arrays\n of `MaybeUninit`. There may be other types that allow uninitialized\n data, but those are not yet rigorously defined.\n\n **Example:**\n\n ```rust\n // Beware the UB\n use std::mem::MaybeUninit;\n\n let _: usize = unsafe { MaybeUninit::uninit().assume_init() };\n ```\n\n Note that the following is OK:\n\n ```rust\n use std::mem::MaybeUninit;\n\n let _: [MaybeUninit; 5] = unsafe {\n MaybeUninit::uninit().assume_init()\n };\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "manual_saturating_arithmetic", - "id_span": { - "path": "src/methods/mod.rs", - "line": 1215 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for `.checked_add/sub(x).unwrap_or(MAX/MIN)`.\n **Why is this bad?** These can be written simply with `saturating_add/sub` methods.\n\n **Example:**\n\n ```rust\n # let y: u32 = 0;\n # let x: u32 = 100;\n let add = x.checked_add(y).unwrap_or(u32::MAX);\n let sub = x.checked_sub(y).unwrap_or(u32::MIN);\n ```\n\n can be written using dedicated methods for saturating addition/subtraction as:\n\n ```rust\n # let y: u32 = 0;\n # let x: u32 = 100;\n let add = x.saturating_add(y);\n let sub = x.saturating_sub(y);\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "zst_offset", - "id_span": { - "path": "src/methods/mod.rs", - "line": 1232 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for `offset(_)`, `wrapping_`{`add`, `sub`}, etc. on raw pointers to zero-sized types\n\n **Why is this bad?** This is a no-op, and likely unintended\n\n **Known problems:** None\n\n **Example:**\n ```rust\n unsafe { (&() as *const ()).offset(1) };\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "filetype_is_file", - "id_span": { - "path": "src/methods/mod.rs", - "line": 1272 - }, - "group": "clippy::restriction", - "docs": " **What it does:** Checks for `FileType::is_file()`.\n **Why is this bad?** When people testing a file type with `FileType::is_file`\n they are testing whether a path is something they can get bytes from. But\n `is_file` doesn't cover special file types in unix-like systems, and doesn't cover\n symlink in windows. Using `!FileType::is_dir()` is a better way to that intention.\n\n **Example:**\n\n ```rust\n # || {\n let metadata = std::fs::metadata(\"foo.txt\")?;\n let filetype = metadata.file_type();\n\n if filetype.is_file() {\n // read file\n }\n # Ok::<_, std::io::Error>(())\n # };\n ```\n\n should be written as:\n\n ```rust\n # || {\n let metadata = std::fs::metadata(\"foo.txt\")?;\n let filetype = metadata.file_type();\n\n if !filetype.is_dir() {\n // read file\n }\n # Ok::<_, std::io::Error>(())\n # };\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "option_as_ref_deref", - "id_span": { - "path": "src/methods/mod.rs", - "line": 1297 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for usage of `_.as_ref().map(Deref::deref)` or it's aliases (such as String::as_str).\n **Why is this bad?** Readability, this can be written more concisely as\n `_.as_deref()`.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let opt = Some(\"\".to_string());\n opt.as_ref().map(String::as_str)\n # ;\n ```\n Can be written as\n ```rust\n # let opt = Some(\"\".to_string());\n opt.as_deref()\n # ;\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "iter_next_slice", - "id_span": { - "path": "src/methods/mod.rs", - "line": 1323 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for usage of `iter().next()` on a Slice or an Array\n **Why is this bad?** These can be shortened into `.get()`\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let a = [1, 2, 3];\n # let b = vec![1, 2, 3];\n a[2..].iter().next();\n b.iter().next();\n ```\n should be written as:\n ```rust\n # let a = [1, 2, 3];\n # let b = vec![1, 2, 3];\n a.get(2);\n b.get(0);\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "single_char_add_str", - "id_span": { - "path": "src/methods/mod.rs", - "line": 1348 - }, - "group": "clippy::style", - "docs": " **What it does:** Warns when using `push_str`/`insert_str` with a single-character string literal where `push`/`insert` with a `char` would work fine.\n\n **Why is this bad?** It's less clear that we are pushing a single character.\n\n **Known problems:** None\n\n **Example:**\n ```rust\n let mut string = String::new();\n string.insert_str(0, \"R\");\n string.push_str(\"R\");\n ```\n Could be written as\n ```rust\n let mut string = String::new();\n string.insert(0, 'R');\n string.push('R');\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "unnecessary_lazy_evaluations", - "id_span": { - "path": "src/methods/mod.rs", - "line": 1384 - }, - "group": "clippy::style", - "docs": " **What it does:** As the counterpart to `or_fun_call`, this lint looks for unnecessary lazily evaluated closures on `Option` and `Result`.\n\n This lint suggests changing the following functions, when eager evaluation results in\n simpler code:\n - `unwrap_or_else` to `unwrap_or`\n - `and_then` to `and`\n - `or_else` to `or`\n - `get_or_insert_with` to `get_or_insert`\n - `ok_or_else` to `ok_or`\n\n **Why is this bad?** Using eager evaluation is shorter and simpler in some cases.\n\n **Known problems:** It is possible, but not recommended for `Deref` and `Index` to have\n side effects. Eagerly evaluating them can change the semantics of the program.\n\n **Example:**\n\n ```rust\n // example code where clippy issues a warning\n let opt: Option = None;\n\n opt.unwrap_or_else(|| 42);\n ```\n Use instead:\n ```rust\n let opt: Option = None;\n\n opt.unwrap_or(42);\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "map_collect_result_unit", - "id_span": { - "path": "src/methods/mod.rs", - "line": 1405 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for usage of `_.map(_).collect::()`.\n **Why is this bad?** Using `try_for_each` instead is more readable and idiomatic.\n\n **Known problems:** None\n\n **Example:**\n\n ```rust\n (0..3).map(|t| Err(t)).collect::>();\n ```\n Use instead:\n ```rust\n (0..3).try_for_each(|t| Err(t));\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "from_iter_instead_of_collect", - "id_span": { - "path": "src/methods/mod.rs", - "line": 1438 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for `from_iter()` function calls on types that implement the `FromIterator` trait.\n\n **Why is this bad?** It is recommended style to use collect. See\n [FromIterator documentation](https://doc.rust-lang.org/std/iter/trait.FromIterator.html)\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n use std::iter::FromIterator;\n\n let five_fives = std::iter::repeat(5).take(5);\n\n let v = Vec::from_iter(five_fives);\n\n assert_eq!(v, vec![5, 5, 5, 5, 5]);\n ```\n Use instead:\n ```rust\n let five_fives = std::iter::repeat(5).take(5);\n\n let v: Vec = five_fives.collect();\n\n assert_eq!(v, vec![5, 5, 5, 5, 5]);\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MaybeIncorrect" - } - }, - { - "id": "inspect_for_each", - "id_span": { - "path": "src/methods/mod.rs", - "line": 1468 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for usage of `inspect().for_each()`.\n **Why is this bad?** It is the same as performing the computation\n inside `inspect` at the beginning of the closure in `for_each`.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n [1,2,3,4,5].iter()\n .inspect(|&x| println!(\"inspect the number: {}\", x))\n .for_each(|&x| {\n assert!(x >= 0);\n });\n ```\n Can be written as\n ```rust\n [1,2,3,4,5].iter()\n .for_each(|&x| {\n println!(\"inspect the number: {}\", x);\n assert!(x >= 0);\n });\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "filter_map_identity", - "id_span": { - "path": "src/methods/mod.rs", - "line": 1491 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for usage of `filter_map(|x| x)`.\n **Why is this bad?** Readability, this can be written more concisely by using `flatten`.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n # let iter = vec![Some(1)].into_iter();\n iter.filter_map(|x| x);\n ```\n Use instead:\n ```rust\n # let iter = vec![Some(1)].into_iter();\n iter.flatten();\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "bytes_nth", - "id_span": { - "path": "src/methods/mod.rs", - "line": 1513 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for the use of `.bytes().nth()`.\n **Why is this bad?** `.as_bytes().get()` is more efficient and more\n readable.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n // Bad\n let _ = \"Hello\".bytes().nth(3);\n\n // Good\n let _ = \"Hello\".as_bytes().get(3);\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "implicit_clone", - "id_span": { - "path": "src/methods/mod.rs", - "line": 1539 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for the usage of `_.to_owned()`, `vec.to_vec()`, or similar when calling `_.clone()` would be clearer.\n **Why is this bad?** These methods do the same thing as `_.clone()` but may be confusing as\n to why we are calling `to_vec` on something that is already a `Vec` or calling `to_owned` on something that is already owned.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n let a = vec![1, 2, 3];\n let b = a.to_vec();\n let c = a.to_owned();\n ```\n Use instead:\n ```rust\n let a = vec![1, 2, 3];\n let b = a.clone();\n let c = a.clone();\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "iter_count", - "id_span": { - "path": "src/methods/mod.rs", - "line": 1565 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for the use of `.iter().count()`.\n **Why is this bad?** `.len()` is more efficient and more\n readable.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n // Bad\n let some_vec = vec![0, 1, 2, 3];\n let _ = some_vec.iter().count();\n let _ = &some_vec[..].iter().count();\n\n // Good\n let some_vec = vec![0, 1, 2, 3];\n let _ = some_vec.len();\n let _ = &some_vec[..].len();\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "min_max", - "id_span": { - "path": "src/minmax.rs", - "line": 28 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for expressions where `std::cmp::min` and `max` are used to clamp values, but switched so that the result is constant.\n\n **Why is this bad?** This is in all probability not the intended outcome. At\n the least it hurts readability of the code.\n\n **Known problems:** None\n\n **Example:**\n ```ignore\n min(0, max(100, x))\n ```\n or\n ```ignore\n x.max(100).min(0)\n ```\n It will always be equal to `0`. Probably the author meant to clamp the value\n between 0 and 100, but has erroneously swapped `min` and `max`.\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "toplevel_ref_arg", - "id_span": { - "path": "src/misc.rs", - "line": 53 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for function arguments and let bindings denoted as `ref`.\n\n **Why is this bad?** The `ref` declaration makes the function take an owned\n value, but turns the argument into a reference (which means that the value\n is destroyed when exiting the function). This adds not much value: either\n take a reference type, or take an owned value and create references in the\n body.\n\n For let bindings, `let x = &foo;` is preferred over `let ref x = foo`. The\n type of `x` is more obvious with the former.\n\n **Known problems:** If the argument is dereferenced within the function,\n removing the `ref` will lead to errors. This can be fixed by removing the\n dereferences, e.g., changing `*x` to `x` within the function.\n\n **Example:**\n ```rust,ignore\n // Bad\n fn foo(ref x: u8) -> bool {\n true\n }\n\n // Good\n fn foo(x: &u8) -> bool {\n true\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "cmp_nan", - "id_span": { - "path": "src/misc.rs", - "line": 76 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for comparisons to NaN.\n **Why is this bad?** NaN does not compare meaningfully to anything – not\n even itself – so those comparisons are simply wrong.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let x = 1.0;\n\n // Bad\n if x == f32::NAN { }\n\n // Good\n if x.is_nan() { }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "float_cmp", - "id_span": { - "path": "src/misc.rs", - "line": 109 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for (in-)equality comparisons on floating-point values (apart from zero), except in functions called `*eq*` (which probably\n implement equality for a type involving floats).\n\n **Why is this bad?** Floating point calculations are usually imprecise, so\n asking if two values are *exactly* equal is asking for trouble. For a good\n guide on what to do, see [the floating point\n guide](http://www.floating-point-gui.de/errors/comparison).\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let x = 1.2331f64;\n let y = 1.2332f64;\n\n // Bad\n if y == 1.23f64 { }\n if y != x {} // where both are floats\n\n // Good\n let error_margin = f64::EPSILON; // Use an epsilon for comparison\n // Or, if Rust <= 1.42, use `std::f64::EPSILON` constant instead.\n // let error_margin = std::f64::EPSILON;\n if (y - 1.23f64).abs() < error_margin { }\n if (y - x).abs() > error_margin { }\n ```\n", - "applicability": null - }, - { - "id": "cmp_owned", - "id_span": { - "path": "src/misc.rs", - "line": 136 - }, - "group": "clippy::perf", - "docs": " **What it does:** Checks for conversions to owned values just for the sake of a comparison.\n\n **Why is this bad?** The comparison can operate on a reference, so creating\n an owned value effectively throws it away directly afterwards, which is\n needlessly consuming code and heap space.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let x = \"foo\";\n # let y = String::from(\"foo\");\n if x.to_owned() == y {}\n ```\n Could be written as\n ```rust\n # let x = \"foo\";\n # let y = String::from(\"foo\");\n if x == y {}\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "modulo_one", - "id_span": { - "path": "src/misc.rs", - "line": 159 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for getting the remainder of a division by one or minus one.\n\n **Why is this bad?** The result for a divisor of one can only ever be zero; for\n minus one it can cause panic/overflow (if the left operand is the minimal value of\n the respective integer type) or results in zero. No one will write such code\n deliberately, unless trying to win an Underhanded Rust Contest. Even for that\n contest, it's probably a bad idea. Use something more underhanded.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let x = 1;\n let a = x % 1;\n let a = x % -1;\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "used_underscore_binding", - "id_span": { - "path": "src/misc.rs", - "line": 181 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for the use of bindings with a single leading underscore.\n\n **Why is this bad?** A single leading underscore is usually used to indicate\n that a binding will not be used. Using such a binding breaks this\n expectation.\n\n **Known problems:** The lint does not work properly with desugaring and\n macro, it has been allowed in the mean time.\n\n **Example:**\n ```rust\n let _x = 0;\n let y = _x + 1; // Here we are using `_x`, even though it has a leading\n // underscore. We should rename `_x` to `x`\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "short_circuit_statement", - "id_span": { - "path": "src/misc.rs", - "line": 201 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for the use of short circuit boolean conditions as a\n statement.\n\n **Why is this bad?** Using a short circuit boolean condition as a statement\n may hide the fact that the second part is executed or not depending on the\n outcome of the first part.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n f() && g(); // We should write `if f() { g(); }`.\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "zero_ptr", - "id_span": { - "path": "src/misc.rs", - "line": 223 - }, - "group": "clippy::style", - "docs": " **What it does:** Catch casts from `0` to some pointer type\n **Why is this bad?** This generally means `null` and is better expressed as\n {`std`, `core`}`::ptr::`{`null`, `null_mut`}.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n // Bad\n let a = 0 as *const u32;\n\n // Good\n let a = std::ptr::null::();\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "float_cmp_const", - "id_span": { - "path": "src/misc.rs", - "line": 254 - }, - "group": "clippy::restriction", - "docs": " **What it does:** Checks for (in-)equality comparisons on floating-point value and constant, except in functions called `*eq*` (which probably\n implement equality for a type involving floats).\n\n **Why is this bad?** Floating point calculations are usually imprecise, so\n asking if two values are *exactly* equal is asking for trouble. For a good\n guide on what to do, see [the floating point\n guide](http://www.floating-point-gui.de/errors/comparison).\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let x: f64 = 1.0;\n const ONE: f64 = 1.00;\n\n // Bad\n if x == ONE { } // where both are floats\n\n // Good\n let error_margin = f64::EPSILON; // Use an epsilon for comparison\n // Or, if Rust <= 1.42, use `std::f64::EPSILON` constant instead.\n // let error_margin = std::f64::EPSILON;\n if (x - ONE).abs() < error_margin { }\n ```\n", - "applicability": null - }, - { - "id": "unneeded_field_pattern", - "id_span": { - "path": "src/misc_early.rs", - "line": 44 - }, - "group": "clippy::restriction", - "docs": " **What it does:** Checks for structure field patterns bound to wildcards.\n **Why is this bad?** Using `..` instead is shorter and leaves the focus on\n the fields that are actually bound.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # struct Foo {\n # a: i32,\n # b: i32,\n # c: i32,\n # }\n let f = Foo { a: 0, b: 0, c: 0 };\n\n // Bad\n match f {\n Foo { a: _, b: 0, .. } => {},\n Foo { a: _, b: _, c: _ } => {},\n }\n\n // Good\n match f {\n Foo { b: 0, .. } => {},\n Foo { .. } => {},\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "duplicate_underscore_argument", - "id_span": { - "path": "src/misc_early.rs", - "line": 65 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for function arguments having the similar names differing by an underscore.\n\n **Why is this bad?** It affects code readability.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n // Bad\n fn foo(a: i32, _a: i32) {}\n\n // Good\n fn bar(a: i32, _b: i32) {}\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "double_neg", - "id_span": { - "path": "src/misc_early.rs", - "line": 83 - }, - "group": "clippy::style", - "docs": " **What it does:** Detects expressions of the form `--x`.\n **Why is this bad?** It can mislead C/C++ programmers to think `x` was\n decremented.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let mut x = 3;\n --x;\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "mixed_case_hex_literals", - "id_span": { - "path": "src/misc_early.rs", - "line": 104 - }, - "group": "clippy::style", - "docs": " **What it does:** Warns on hexadecimal literals with mixed-case letter digits.\n\n **Why is this bad?** It looks confusing.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n // Bad\n let y = 0x1a9BAcD;\n\n // Good\n let y = 0x1A9BACD;\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "unseparated_literal_suffix", - "id_span": { - "path": "src/misc_early.rs", - "line": 125 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Warns if literal suffixes are not separated by an underscore.\n\n **Why is this bad?** It is much less readable.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n // Bad\n let y = 123832i32;\n\n // Good\n let y = 123832_i32;\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "zero_prefixed_literal", - "id_span": { - "path": "src/misc_early.rs", - "line": 163 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Warns if an integral constant literal starts with `0`.\n **Why is this bad?** In some languages (including the infamous C language\n and most of its\n family), this marks an octal constant. In Rust however, this is a decimal\n constant. This could\n be confusing for both the writer and a reader of the constant.\n\n **Known problems:** None.\n\n **Example:**\n\n In Rust:\n ```rust\n fn main() {\n let a = 0123;\n println!(\"{}\", a);\n }\n ```\n\n prints `123`, while in C:\n\n ```c\n #include \n\n int main() {\n int a = 0123;\n printf(\"%d\\n\", a);\n }\n ```\n\n prints `83` (as `83 == 0o123` while `123 == 0o173`).\n", - "applicability": { - "is_multi_suggestion": true, - "applicability": "MaybeIncorrect" - } - }, - { - "id": "builtin_type_shadow", - "id_span": { - "path": "src/misc_early.rs", - "line": 184 - }, - "group": "clippy::style", - "docs": " **What it does:** Warns if a generic shadows a built-in type.\n **Why is this bad?** This gives surprising type errors.\n\n **Known problems:** None.\n\n **Example:**\n\n ```ignore\n impl Foo {\n fn impl_func(&self) -> u32 {\n 42\n }\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "redundant_pattern", - "id_span": { - "path": "src/misc_early.rs", - "line": 213 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for patterns in the form `name @ _`.\n **Why is this bad?** It's almost always more readable to just use direct\n bindings.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let v = Some(\"abc\");\n\n // Bad\n match v {\n Some(x) => (),\n y @ _ => (),\n }\n\n // Good\n match v {\n Some(x) => (),\n y => (),\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "unneeded_wildcard_pattern", - "id_span": { - "path": "src/misc_early.rs", - "line": 247 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for tuple patterns with a wildcard pattern (`_`) is next to a rest pattern (`..`).\n\n _NOTE_: While `_, ..` means there is at least one element left, `..`\n means there are 0 or more elements left. This can make a difference\n when refactoring, but shouldn't result in errors in the refactored code,\n since the wildcard pattern isn't used anyway.\n **Why is this bad?** The wildcard pattern is unneeded as the rest pattern\n can match that element as well.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # struct TupleStruct(u32, u32, u32);\n # let t = TupleStruct(1, 2, 3);\n // Bad\n match t {\n TupleStruct(0, .., _) => (),\n _ => (),\n }\n\n // Good\n match t {\n TupleStruct(0, ..) => (),\n _ => (),\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "missing_const_for_fn", - "id_span": { - "path": "src/missing_const_for_fn.rs", - "line": 72 - }, - "group": "clippy::nursery", - "docs": " **What it does:**\n Suggests the use of `const` in functions and methods where possible.\n\n **Why is this bad?**\n\n Not having the function const prevents callers of the function from being const as well.\n\n **Known problems:**\n\n Const functions are currently still being worked on, with some features only being available\n on nightly. This lint does not consider all edge cases currently and the suggestions may be\n incorrect if you are using this lint on stable.\n\n Also, the lint only runs one pass over the code. Consider these two non-const functions:\n\n ```rust\n fn a() -> i32 {\n 0\n }\n fn b() -> i32 {\n a()\n }\n ```\n\n When running Clippy, the lint will only suggest to make `a` const, because `b` at this time\n can't be const as it calls a non-const function. Making `a` const and running Clippy again,\n will suggest to make `b` const, too.\n\n **Example:**\n\n ```rust\n # struct Foo {\n # random_number: usize,\n # }\n # impl Foo {\n fn new() -> Self {\n Self { random_number: 42 }\n }\n # }\n ```\n\n Could be a const fn:\n\n ```rust\n # struct Foo {\n # random_number: usize,\n # }\n # impl Foo {\n const fn new() -> Self {\n Self { random_number: 42 }\n }\n # }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "missing_docs_in_private_items", - "id_span": { - "path": "src/missing_doc.rs", - "line": 29 - }, - "group": "clippy::restriction", - "docs": " **What it does:** Warns if there is missing doc for any documentable item (public or private).\n\n **Why is this bad?** Doc is good. *rustc* has a `MISSING_DOCS`\n allowed-by-default lint for\n public members, but has no way to enforce documentation of private items.\n This lint fixes that.\n\n **Known problems:** None.\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "missing_inline_in_public_items", - "id_span": { - "path": "src/missing_inline.rs", - "line": 55 - }, - "group": "clippy::restriction", - "docs": " **What it does:** it lints if an exported function, method, trait method with default impl, or trait method impl is not `#[inline]`.\n\n **Why is this bad?** In general, it is not. Functions can be inlined across\n crates when that's profitable as long as any form of LTO is used. When LTO is disabled,\n functions that are not `#[inline]` cannot be inlined across crates. Certain types of crates\n might intend for most of the methods in their public API to be able to be inlined across\n crates even when LTO is disabled. For these types of crates, enabling this lint might make\n sense. It allows the crate to require all exported methods to be `#[inline]` by default, and\n then opt out for specific methods where this might not make sense.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n pub fn foo() {} // missing #[inline]\n fn ok() {} // ok\n #[inline] pub fn bar() {} // ok\n #[inline(always)] pub fn baz() {} // ok\n\n pub trait Bar {\n fn bar(); // ok\n fn def_bar() {} // missing #[inline]\n }\n\n struct Baz;\n impl Baz {\n fn private() {} // ok\n }\n\n impl Bar for Baz {\n fn bar() {} // ok - Baz is not exported\n }\n\n pub struct PubBaz;\n impl PubBaz {\n fn private() {} // ok\n pub fn not_ptrivate() {} // missing #[inline]\n }\n\n impl Bar for PubBaz {\n fn bar() {} // missing #[inline]\n fn def_bar() {} // missing #[inline]\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "modulo_arithmetic", - "id_span": { - "path": "src/modulo_arithmetic.rs", - "line": 26 - }, - "group": "clippy::restriction", - "docs": " **What it does:** Checks for modulo arithmetic.\n **Why is this bad?** The results of modulo (%) operation might differ\n depending on the language, when negative numbers are involved.\n If you interop with different languages it might be beneficial\n to double check all places that use modulo arithmetic.\n\n For example, in Rust `17 % -3 = 2`, but in Python `17 % -3 = -1`.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let x = -17 % 3;\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "multiple_crate_versions", - "id_span": { - "path": "src/multiple_crate_versions.rs", - "line": 32 - }, - "group": "clippy::cargo", - "docs": " **What it does:** Checks to see if multiple versions of a crate are being used.\n\n **Why is this bad?** This bloats the size of targets, and can lead to\n confusing error messages when structs or traits are used interchangeably\n between different versions of a crate.\n\n **Known problems:** Because this can be caused purely by the dependencies\n themselves, it's not always possible to fix this issue.\n\n **Example:**\n ```toml\n # This will pull in both winapi v0.3.x and v0.2.x, triggering a warning.\n [dependencies]\n ctrlc = \"=3.1.0\"\n ansi_term = \"=0.11.0\"\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "mutable_key_type", - "id_span": { - "path": "src/mut_key.rs", - "line": 50 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for sets/maps with mutable key types.\n **Why is this bad?** All of `HashMap`, `HashSet`, `BTreeMap` and\n `BtreeSet` rely on either the hash or the order of keys be unchanging,\n so having types with interior mutability is a bad idea.\n\n **Known problems:** It's correct to use a struct, that contains interior mutability\n as a key, when its `Hash` implementation doesn't access any of the interior mutable types.\n However, this lint is unable to recognize this, so it causes a false positive in theses cases.\n The `bytes` crate is a great example of this.\n\n **Example:**\n ```rust\n use std::cmp::{PartialEq, Eq};\n use std::collections::HashSet;\n use std::hash::{Hash, Hasher};\n use std::sync::atomic::AtomicUsize;\n# #[allow(unused)]\n\n struct Bad(AtomicUsize);\n impl PartialEq for Bad {\n fn eq(&self, rhs: &Self) -> bool {\n ..\n ; unimplemented!();\n }\n }\n\n impl Eq for Bad {}\n\n impl Hash for Bad {\n fn hash(&self, h: &mut H) {\n ..\n ; unimplemented!();\n }\n }\n\n fn main() {\n let _: HashSet = HashSet::new();\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "mut_mut", - "id_span": { - "path": "src/mut_mut.rs", - "line": 24 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for instances of `mut mut` references.\n **Why is this bad?** Multiple `mut`s don't add anything meaningful to the\n source. This is either a copy'n'paste error, or it shows a fundamental\n misunderstanding of references.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let mut y = 1;\n let x = &mut &mut y;\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "mut_mutex_lock", - "id_span": { - "path": "src/mut_mutex_lock.rs", - "line": 40 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for `&mut Mutex::lock` calls\n **Why is this bad?** `Mutex::lock` is less efficient than\n calling `Mutex::get_mut`. In addition you also have a statically\n guarantee that the mutex isn't locked, instead of just a runtime\n guarantee.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n use std::sync::{Arc, Mutex};\n\n let mut value_rc = Arc::new(Mutex::new(42_u8));\n let value_mutex = Arc::get_mut(&mut value_rc).unwrap();\n\n let mut value = value_mutex.lock().unwrap();\n *value += 1;\n ```\n Use instead:\n ```rust\n use std::sync::{Arc, Mutex};\n\n let mut value_rc = Arc::new(Mutex::new(42_u8));\n let value_mutex = Arc::get_mut(&mut value_rc).unwrap();\n\n let value = value_mutex.get_mut().unwrap();\n *value += 1;\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MaybeIncorrect" - } - }, - { - "id": "unnecessary_mut_passed", - "id_span": { - "path": "src/mut_reference.rs", - "line": 25 - }, - "group": "clippy::style", - "docs": " **What it does:** Detects passing a mutable reference to a function that only requires an immutable reference.\n\n **Why is this bad?** The mutable reference rules out all other references to\n the value. Also the code misleads about the intent of the call site.\n\n **Known problems:** None.\n\n **Example:**\n ```ignore\n // Bad\n my_vec.push(&mut value)\n\n // Good\n my_vec.push(&value)\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "debug_assert_with_mut_call", - "id_span": { - "path": "src/mutable_debug_assertion.rs", - "line": 28 - }, - "group": "clippy::nursery", - "docs": " **What it does:** Checks for function/method calls with a mutable parameter in `debug_assert!`, `debug_assert_eq!` and `debug_assert_ne!` macros.\n\n **Why is this bad?** In release builds `debug_assert!` macros are optimized out by the\n compiler.\n Therefore mutating something in a `debug_assert!` macro results in different behaviour\n between a release and debug build.\n\n **Known problems:** None\n\n **Example:**\n ```rust,ignore\n debug_assert_eq!(vec![3].pop(), Some(3));\n // or\n fn take_a_mut_parameter(_: &mut u32) -> bool { unimplemented!() }\n debug_assert!(take_a_mut_parameter(&mut 5));\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "mutex_atomic", - "id_span": { - "path": "src/mutex_atomic.rs", - "line": 34 - }, - "group": "clippy::perf", - "docs": " **What it does:** Checks for usages of `Mutex` where an atomic will do.\n **Why is this bad?** Using a mutex just to make access to a plain bool or\n reference sequential is shooting flies with cannons.\n `std::sync::atomic::AtomicBool` and `std::sync::atomic::AtomicPtr` are leaner and\n faster.\n\n **Known problems:** This lint cannot detect if the mutex is actually used\n for waiting before a critical section.\n\n **Example:**\n ```rust\n # let y = true;\n\n // Bad\n # use std::sync::Mutex;\n let x = Mutex::new(&y);\n\n // Good\n # use std::sync::atomic::AtomicBool;\n let x = AtomicBool::new(y);\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "mutex_integer", - "id_span": { - "path": "src/mutex_atomic.rs", - "line": 59 - }, - "group": "clippy::nursery", - "docs": " **What it does:** Checks for usages of `Mutex` where `X` is an integral type.\n\n **Why is this bad?** Using a mutex just to make access to a plain integer\n sequential is\n shooting flies with cannons. `std::sync::atomic::AtomicUsize` is leaner and faster.\n\n **Known problems:** This lint cannot detect if the mutex is actually used\n for waiting before a critical section.\n\n **Example:**\n ```rust\n # use std::sync::Mutex;\n let x = Mutex::new(0usize);\n\n // Good\n # use std::sync::atomic::AtomicUsize;\n let x = AtomicUsize::new(0usize);\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "needless_arbitrary_self_type", - "id_span": { - "path": "src/needless_arbitrary_self_type.rs", - "line": 55 - }, - "group": "clippy::complexity", - "docs": " **What it does:** The lint checks for `self` in fn parameters that specify the `Self`-type explicitly\n **Why is this bad?** Increases the amount and decreases the readability of code\n\n **Known problems:** None\n\n **Example:**\n ```rust\n enum ValType {\n I32,\n I64,\n F32,\n F64,\n }\n\n impl ValType {\n pub fn bytes(self: Self) -> usize {\n match self {\n Self::I32 | Self::F32 => 4,\n Self::I64 | Self::F64 => 8,\n }\n }\n }\n ```\n\n Could be rewritten as\n\n ```rust\n enum ValType {\n I32,\n I64,\n F32,\n F64,\n }\n\n impl ValType {\n pub fn bytes(self) -> usize {\n match self {\n Self::I32 | Self::F32 => 4,\n Self::I64 | Self::F64 => 8,\n }\n }\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "needless_bool", - "id_span": { - "path": "src/needless_bool.rs", - "line": 38 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for expressions of the form `if c { true } else { false }` (or vice versa) and suggests using the condition directly.\n\n **Why is this bad?** Redundant code.\n\n **Known problems:** Maybe false positives: Sometimes, the two branches are\n painstakingly documented (which we, of course, do not detect), so they *may*\n have some value. Even then, the documentation can be rewritten to match the\n shorter code.\n\n **Example:**\n ```rust,ignore\n if x {\n false\n } else {\n true\n }\n ```\n Could be written as\n ```rust,ignore\n !x\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "bool_comparison", - "id_span": { - "path": "src/needless_bool.rs", - "line": 62 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for expressions of the form `x == true`, `x != true` and order comparisons such as `x < true` (or vice versa) and\n suggest using the variable directly.\n\n **Why is this bad?** Unnecessary code.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n if x == true {}\n if y == false {}\n ```\n use `x` directly:\n ```rust,ignore\n if x {}\n if !y {}\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "needless_borrow", - "id_span": { - "path": "src/needless_borrow.rs", - "line": 32 - }, - "group": "clippy::nursery", - "docs": " **What it does:** Checks for address of operations (`&`) that are going to be dereferenced immediately by the compiler.\n\n **Why is this bad?** Suggests that the receiver of the expression borrows\n the expression.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n // Bad\n let x: &i32 = &&&&&&5;\n\n // Good\n let x: &i32 = &5;\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "needless_borrowed_reference", - "id_span": { - "path": "src/needless_borrowed_ref.rs", - "line": 48 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for useless borrowed references.\n **Why is this bad?** It is mostly useless and make the code look more\n complex than it\n actually is.\n\n **Known problems:** It seems that the `&ref` pattern is sometimes useful.\n For instance in the following snippet:\n ```rust,ignore\n enum Animal {\n Cat(u64),\n Dog(u64),\n }\n\n fn foo(a: &Animal, b: &Animal) {\n match (a, b) {\n (&Animal::Cat(v), k) | (k, &Animal::Cat(v)) => (), // lifetime mismatch error\n (&Animal::Dog(ref c), &Animal::Dog(_)) => ()\n }\n }\n ```\n There is a lifetime mismatch error for `k` (indeed a and b have distinct\n lifetime).\n This can be fixed by using the `&ref` pattern.\n However, the code can also be fixed by much cleaner ways\n\n **Example:**\n ```rust\n let mut v = Vec::::new();\n let _ = v.iter_mut().filter(|&ref a| a.is_empty());\n ```\n This closure takes a reference on something that has been matched as a\n reference and\n de-referenced.\n As such, it could just be |a| a.is_empty()\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "needless_continue", - "id_span": { - "path": "src/needless_continue.rs", - "line": 114 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** The lint checks for `if`-statements appearing in loops that contain a `continue` statement in either their main blocks or their\n `else`-blocks, when omitting the `else`-block possibly with some\n rearrangement of code can make the code easier to understand.\n\n **Why is this bad?** Having explicit `else` blocks for `if` statements\n containing `continue` in their THEN branch adds unnecessary branching and\n nesting to the code. Having an else block containing just `continue` can\n also be better written by grouping the statements following the whole `if`\n statement within the THEN block and omitting the else block completely.\n\n **Known problems:** None\n\n **Example:**\n ```rust\n # fn condition() -> bool { false }\n # fn update_condition() {}\n # let x = false;\n while condition() {\n update_condition();\n if x {\n // ...\n } else {\n continue;\n }\n println!(\"Hello, world\");\n }\n ```\n\n Could be rewritten as\n\n ```rust\n # fn condition() -> bool { false }\n # fn update_condition() {}\n # let x = false;\n while condition() {\n update_condition();\n if x {\n // ...\n println!(\"Hello, world\");\n }\n }\n ```\n\n As another example, the following code\n\n ```rust\n # fn waiting() -> bool { false }\n loop {\n if waiting() {\n continue;\n } else {\n // Do something useful\n }\n # break;\n }\n ```\n Could be rewritten as\n\n ```rust\n # fn waiting() -> bool { false }\n loop {\n if waiting() {\n continue;\n }\n // Do something useful\n # break;\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "needless_pass_by_value", - "id_span": { - "path": "src/needless_pass_by_value.rs", - "line": 50 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for functions taking arguments by value, but not consuming them in its\n body.\n\n **Why is this bad?** Taking arguments by reference is more flexible and can\n sometimes avoid\n unnecessary allocations.\n\n **Known problems:**\n * This lint suggests taking an argument by reference,\n however sometimes it is better to let users decide the argument type\n (by using `Borrow` trait, for example), depending on how the function is used.\n\n **Example:**\n ```rust\n fn foo(v: Vec) {\n assert_eq!(v.len(), 42);\n }\n ```\n should be\n ```rust\n fn foo(v: &[i32]) {\n assert_eq!(v.len(), 42);\n }\n ```\n", - "applicability": { - "is_multi_suggestion": true, - "applicability": null - } - }, - { - "id": "needless_question_mark", - "id_span": { - "path": "src/needless_question_mark.rs", - "line": 57 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Suggests alternatives for useless applications of `?` in terminating expressions\n\n **Why is this bad?** There's no reason to use `?` to short-circuit when execution of the body will end there anyway.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n struct TO {\n magic: Option,\n }\n\n fn f(to: TO) -> Option {\n Some(to.magic?)\n }\n\n struct TR {\n magic: Result,\n }\n\n fn g(tr: Result) -> Result {\n tr.and_then(|t| Ok(t.magic?))\n }\n\n ```\n Use instead:\n ```rust\n struct TO {\n magic: Option,\n }\n\n fn f(to: TO) -> Option {\n to.magic\n }\n\n struct TR {\n magic: Result,\n }\n\n fn g(tr: Result) -> Result {\n tr.and_then(|t| t.magic)\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "needless_update", - "id_span": { - "path": "src/needless_update.rs", - "line": 43 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for needlessly including a base struct on update when all fields are changed anyway.\n\n This lint is not applied to structs marked with\n [non_exhaustive](https://doc.rust-lang.org/reference/attributes/type_system.html).\n\n **Why is this bad?** This will cost resources (because the base has to be\n somewhere), and make the code less readable.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # struct Point {\n # x: i32,\n # y: i32,\n # z: i32,\n # }\n # let zero_point = Point { x: 0, y: 0, z: 0 };\n\n // Bad\n Point {\n x: 1,\n y: 1,\n z: 1,\n ..zero_point\n };\n\n // Ok\n Point {\n x: 1,\n y: 1,\n ..zero_point\n };\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "neg_cmp_op_on_partial_ord", - "id_span": { - "path": "src/neg_cmp_op_on_partial_ord.rs", - "line": 41 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for the usage of negated comparison operators on types which only implement\n `PartialOrd` (e.g., `f64`).\n\n **Why is this bad?**\n These operators make it easy to forget that the underlying types actually allow not only three\n potential Orderings (Less, Equal, Greater) but also a fourth one (Uncomparable). This is\n especially easy to miss if the operator based comparison result is negated.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n use std::cmp::Ordering;\n\n // Bad\n let a = 1.0;\n let b = f64::NAN;\n\n let _not_less_or_equal = !(a <= b);\n\n // Good\n let a = 1.0;\n let b = f64::NAN;\n\n let _not_less_or_equal = match a.partial_cmp(&b) {\n None | Some(Ordering::Greater) => true,\n _ => false,\n };\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "neg_multiply", - "id_span": { - "path": "src/neg_multiply.rs", - "line": 21 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for multiplication by -1 as a form of negation.\n **Why is this bad?** It's more readable to just negate.\n\n **Known problems:** This only catches integers (for now).\n\n **Example:**\n ```ignore\n x * -1\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "new_without_default", - "id_span": { - "path": "src/new_without_default.rs", - "line": 48 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for types with a `fn new() -> Self` method and no implementation of\n [`Default`](https://doc.rust-lang.org/std/default/trait.Default.html).\n\n **Why is this bad?** The user might expect to be able to use\n [`Default`](https://doc.rust-lang.org/std/default/trait.Default.html) as the\n type can be constructed without arguments.\n\n **Known problems:** Hopefully none.\n\n **Example:**\n\n ```ignore\n struct Foo(Bar);\n\n impl Foo {\n fn new() -> Self {\n Foo(Bar::new())\n }\n }\n ```\n\n To fix the lint, add a `Default` implementation that delegates to `new`:\n\n ```ignore\n struct Foo(Bar);\n\n impl Default for Foo {\n fn default() -> Self {\n Foo::new()\n }\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MaybeIncorrect" - } - }, - { - "id": "no_effect", - "id_span": { - "path": "src/no_effect.rs", - "line": 22 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for statements which have no effect.\n **Why is this bad?** Similar to dead code, these statements are actually\n executed. However, as they have no effect, all they do is make the code less\n readable.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n 0;\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "unnecessary_operation", - "id_span": { - "path": "src/no_effect.rs", - "line": 40 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for expression statements that can be reduced to a sub-expression.\n\n **Why is this bad?** Expressions by themselves often have no side-effects.\n Having such expressions reduces readability.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n compute_array()[0];\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "declare_interior_mutable_const", - "id_span": { - "path": "src/non_copy_const.rs", - "line": 69 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for declaration of `const` items which is interior mutable (e.g., contains a `Cell`, `Mutex`, `AtomicXxxx`, etc.).\n\n **Why is this bad?** Consts are copied everywhere they are referenced, i.e.,\n every time you refer to the const a fresh instance of the `Cell` or `Mutex`\n or `AtomicXxxx` will be created, which defeats the whole purpose of using\n these types in the first place.\n\n The `const` should better be replaced by a `static` item if a global\n variable is wanted, or replaced by a `const fn` if a constructor is wanted.\n\n **Known problems:** A \"non-constant\" const item is a legacy way to supply an\n initialized value to downstream `static` items (e.g., the\n `std::sync::ONCE_INIT` constant). In this case the use of `const` is legit,\n and this lint should be suppressed.\n\n Even though the lint avoids triggering on a constant whose type has enums that have variants\n with interior mutability, and its value uses non interior mutable variants (see\n [#3962](https://github.com/rust-lang/rust-clippy/issues/3962) and\n [#3825](https://github.com/rust-lang/rust-clippy/issues/3825) for examples);\n it complains about associated constants without default values only based on its types;\n which might not be preferable.\n There're other enums plus associated constants cases that the lint cannot handle.\n\n Types that have underlying or potential interior mutability trigger the lint whether\n the interior mutable field is used or not. See issues\n [#5812](https://github.com/rust-lang/rust-clippy/issues/5812) and\n\n **Example:**\n ```rust\n use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};\n\n // Bad.\n const CONST_ATOM: AtomicUsize = AtomicUsize::new(12);\n CONST_ATOM.store(6, SeqCst); // the content of the atomic is unchanged\n assert_eq!(CONST_ATOM.load(SeqCst), 12); // because the CONST_ATOM in these lines are distinct\n\n // Good.\n static STATIC_ATOM: AtomicUsize = AtomicUsize::new(15);\n STATIC_ATOM.store(9, SeqCst);\n assert_eq!(STATIC_ATOM.load(SeqCst), 9); // use a `static` item to refer to the same instance\n ```\n", - "applicability": null - }, - { - "id": "borrow_interior_mutable_const", - "id_span": { - "path": "src/non_copy_const.rs", - "line": 110 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks if `const` items which is interior mutable (e.g., contains a `Cell`, `Mutex`, `AtomicXxxx`, etc.) has been borrowed directly.\n\n **Why is this bad?** Consts are copied everywhere they are referenced, i.e.,\n every time you refer to the const a fresh instance of the `Cell` or `Mutex`\n or `AtomicXxxx` will be created, which defeats the whole purpose of using\n these types in the first place.\n\n The `const` value should be stored inside a `static` item.\n\n **Known problems:** When an enum has variants with interior mutability, use of its non\n interior mutable variants can generate false positives. See issue\n [#3962](https://github.com/rust-lang/rust-clippy/issues/3962)\n\n Types that have underlying or potential interior mutability trigger the lint whether\n the interior mutable field is used or not. See issues\n [#5812](https://github.com/rust-lang/rust-clippy/issues/5812) and\n [#3825](https://github.com/rust-lang/rust-clippy/issues/3825)\n\n **Example:**\n ```rust\n use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};\n const CONST_ATOM: AtomicUsize = AtomicUsize::new(12);\n\n // Bad.\n CONST_ATOM.store(6, SeqCst); // the content of the atomic is unchanged\n assert_eq!(CONST_ATOM.load(SeqCst), 12); // because the CONST_ATOM in these lines are distinct\n\n // Good.\n static STATIC_ATOM: AtomicUsize = CONST_ATOM;\n STATIC_ATOM.store(9, SeqCst);\n assert_eq!(STATIC_ATOM.load(SeqCst), 9); // use a `static` item to refer to the same instance\n ```\n", - "applicability": null - }, - { - "id": "similar_names", - "id_span": { - "path": "src/non_expressive_names.rs", - "line": 27 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for names that are very similar and thus confusing.\n **Why is this bad?** It's hard to distinguish between names that differ only\n by a single character.\n\n **Known problems:** None?\n\n **Example:**\n ```ignore\n let checked_exp = something;\n let checked_expr = something_else;\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "many_single_char_names", - "id_span": { - "path": "src/non_expressive_names.rs", - "line": 45 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for too many variables whose name consists of a single character.\n\n **Why is this bad?** It's hard to memorize what a variable means without a\n descriptive name.\n\n **Known problems:** None?\n\n **Example:**\n ```ignore\n let (a, b, c, d, e, f, g) = (...);\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "just_underscores_and_digits", - "id_span": { - "path": "src/non_expressive_names.rs", - "line": 65 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks if you have variables whose name consists of just underscores and digits.\n\n **Why is this bad?** It's hard to memorize what a variable means without a\n descriptive name.\n\n **Known problems:** None?\n\n **Example:**\n ```rust\n let _1 = 1;\n let ___1 = 1;\n let __1___2 = 11;\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "nonsensical_open_options", - "id_span": { - "path": "src/open_options.rs", - "line": 23 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for duplicate open options as well as combinations that make no sense.\n\n **Why is this bad?** In the best case, the code will be harder to read than\n necessary. I don't know the worst case.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n use std::fs::OpenOptions;\n\n OpenOptions::new().read(true).truncate(true);\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "option_env_unwrap", - "id_span": { - "path": "src/option_env_unwrap.rs", - "line": 28 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for usage of `option_env!(...).unwrap()` and suggests usage of the `env!` macro.\n\n **Why is this bad?** Unwrapping the result of `option_env!` will panic\n at run-time if the environment variable doesn't exist, whereas `env!`\n catches it at compile-time.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust,no_run\n let _ = option_env!(\"HOME\").unwrap();\n ```\n\n Is better expressed as:\n\n ```rust,no_run\n let _ = env!(\"HOME\");\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "option_if_let_else", - "id_span": { - "path": "src/option_if_let_else.rs", - "line": 59 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Lints usage of `if let Some(v) = ... { y } else { x }` which is more\n idiomatically done with `Option::map_or` (if the else bit is a pure\n expression) or `Option::map_or_else` (if the else bit is an impure\n expression).\n\n **Why is this bad?**\n Using the dedicated functions of the Option type is clearer and\n more concise than an `if let` expression.\n\n **Known problems:**\n This lint uses a deliberately conservative metric for checking\n if the inside of either body contains breaks or continues which will\n cause it to not suggest a fix if either block contains a loop with\n continues or breaks contained within the loop.\n\n **Example:**\n\n ```rust\n # let optional: Option = Some(0);\n # fn do_complicated_function() -> u32 { 5 };\n let _ = if let Some(foo) = optional {\n foo\n } else {\n 5\n };\n let _ = if let Some(foo) = optional {\n foo\n } else {\n let y = do_complicated_function();\n y*y\n };\n ```\n\n should be\n\n ```rust\n # let optional: Option = Some(0);\n # fn do_complicated_function() -> u32 { 5 };\n let _ = optional.map_or(5, |foo| foo);\n let _ = optional.map_or_else(||{\n let y = do_complicated_function();\n y*y\n }, |foo| foo);\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MaybeIncorrect" - } - }, - { - "id": "overflow_check_conditional", - "id_span": { - "path": "src/overflow_check_conditional.rs", - "line": 21 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Detects classic underflow/overflow checks.\n **Why is this bad?** Most classic C underflow/overflow checks will fail in\n Rust. Users can use functions like `overflowing_*` and `wrapping_*` instead.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let a = 1;\n # let b = 2;\n a + b < a;\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "panic_in_result_fn", - "id_span": { - "path": "src/panic_in_result_fn.rs", - "line": 29 - }, - "group": "clippy::restriction", - "docs": " **What it does:** Checks for usage of `panic!`, `unimplemented!`, `todo!`, `unreachable!` or assertions in a function of type result.\n **Why is this bad?** For some codebases, it is desirable for functions of type result to return an error instead of crashing. Hence panicking macros should be avoided.\n\n **Known problems:** Functions called from a function returning a `Result` may invoke a panicking macro. This is not checked.\n\n **Example:**\n\n ```rust\n fn result_with_panic() -> Result\n {\n panic!(\"error\");\n }\n ```\n Use instead:\n ```rust\n fn result_without_panic() -> Result {\n Err(String::from(\"error\"))\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "panic", - "id_span": { - "path": "src/panic_unimplemented.rs", - "line": 19 - }, - "group": "clippy::restriction", - "docs": " **What it does:** Checks for usage of `panic!`.\n **Why is this bad?** `panic!` will stop the execution of the executable\n\n **Known problems:** None.\n\n **Example:**\n ```no_run\n panic!(\"even with a good reason\");\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "unimplemented", - "id_span": { - "path": "src/panic_unimplemented.rs", - "line": 35 - }, - "group": "clippy::restriction", - "docs": " **What it does:** Checks for usage of `unimplemented!`.\n **Why is this bad?** This macro should not be present in production code\n\n **Known problems:** None.\n\n **Example:**\n ```no_run\n unimplemented!();\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "todo", - "id_span": { - "path": "src/panic_unimplemented.rs", - "line": 51 - }, - "group": "clippy::restriction", - "docs": " **What it does:** Checks for usage of `todo!`.\n **Why is this bad?** This macro should not be present in production code\n\n **Known problems:** None.\n\n **Example:**\n ```no_run\n todo!();\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "unreachable", - "id_span": { - "path": "src/panic_unimplemented.rs", - "line": 67 - }, - "group": "clippy::restriction", - "docs": " **What it does:** Checks for usage of `unreachable!`.\n **Why is this bad?** This macro can cause code to panic\n\n **Known problems:** None.\n\n **Example:**\n ```no_run\n unreachable!();\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "partialeq_ne_impl", - "id_span": { - "path": "src/partialeq_ne_impl.rs", - "line": 27 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for manual re-implementations of `PartialEq::ne`.\n **Why is this bad?** `PartialEq::ne` is required to always return the\n negated result of `PartialEq::eq`, which is exactly what the default\n implementation does. Therefore, there should never be any need to\n re-implement it.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n struct Foo;\n\n impl PartialEq for Foo {\n fn eq(&self, other: &Foo) -> bool { true }\n fn ne(&self, other: &Foo) -> bool { !(self == other) }\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "trivially_copy_pass_by_ref", - "id_span": { - "path": "src/pass_by_ref_or_value.rs", - "line": 52 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for functions taking arguments by reference, where the argument type is `Copy` and small enough to be more efficient to always\n pass by value.\n\n **Why is this bad?** In many calling conventions instances of structs will\n be passed through registers if they fit into two or less general purpose\n registers.\n\n **Known problems:** This lint is target register size dependent, it is\n limited to 32-bit to try and reduce portability problems between 32 and\n 64-bit, but if you are compiling for 8 or 16-bit targets then the limit\n will be different.\n\n The configuration option `trivial_copy_size_limit` can be set to override\n this limit for a project.\n\n This lint attempts to allow passing arguments by reference if a reference\n to that argument is returned. This is implemented by comparing the lifetime\n of the argument and return value for equality. However, this can cause\n false positives in cases involving multiple lifetimes that are bounded by\n each other.\n\n **Example:**\n\n ```rust\n // Bad\n fn foo(v: &u32) {}\n ```\n\n ```rust\n // Better\n fn foo(v: u32) {}\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "Unspecified" - } - }, - { - "id": "large_types_passed_by_value", - "id_span": { - "path": "src/pass_by_ref_or_value.rs", - "line": 84 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for functions taking arguments by value, where the argument type is `Copy` and large enough to be worth considering\n passing by reference. Does not trigger if the function is being exported,\n because that might induce API breakage, if the parameter is declared as mutable,\n or if the argument is a `self`.\n\n **Why is this bad?** Arguments passed by value might result in an unnecessary\n shallow copy, taking up more space in the stack and requiring a call to\n `memcpy`, which can be expensive.\n\n **Example:**\n\n ```rust\n #[derive(Clone, Copy)]\n struct TooLarge([u8; 2048]);\n\n // Bad\n fn foo(v: TooLarge) {}\n ```\n ```rust\n #[derive(Clone, Copy)]\n struct TooLarge([u8; 2048]);\n\n // Good\n fn foo(v: &TooLarge) {}\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MaybeIncorrect" - } - }, - { - "id": "path_buf_push_overwrite", - "id_span": { - "path": "src/path_buf_push_overwrite.rs", - "line": 36 - }, - "group": "clippy::nursery", - "docs": " **What it does:*** Checks for [push](https://doc.rust-lang.org/std/path/struct.PathBuf.html#method.push) calls on `PathBuf` that can cause overwrites.\n\n **Why is this bad?** Calling `push` with a root path at the start can overwrite the\n previous defined path.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n use std::path::PathBuf;\n\n let mut x = PathBuf::from(\"/foo\");\n x.push(\"/bar\");\n assert_eq!(x, PathBuf::from(\"/bar\"));\n ```\n Could be written:\n\n ```rust\n use std::path::PathBuf;\n\n let mut x = PathBuf::from(\"/foo\");\n x.push(\"bar\");\n assert_eq!(x, PathBuf::from(\"/foo/bar\"));\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "pattern_type_mismatch", - "id_span": { - "path": "src/pattern_type_mismatch.rs", - "line": 79 - }, - "group": "clippy::restriction", - "docs": " **What it does:** Checks for patterns that aren't exact representations of the types they are applied to.\n\n To satisfy this lint, you will have to adjust either the expression that is matched\n against or the pattern itself, as well as the bindings that are introduced by the\n adjusted patterns. For matching you will have to either dereference the expression\n with the `*` operator, or amend the patterns to explicitly match against `&`\n or `&mut ` depending on the reference mutability. For the bindings you need\n to use the inverse. You can leave them as plain bindings if you wish for the value\n to be copied, but you must use `ref mut ` or `ref ` to construct\n a reference into the matched structure.\n\n If you are looking for a way to learn about ownership semantics in more detail, it\n is recommended to look at IDE options available to you to highlight types, lifetimes\n and reference semantics in your code. The available tooling would expose these things\n in a general way even outside of the various pattern matching mechanics. Of course\n this lint can still be used to highlight areas of interest and ensure a good understanding\n of ownership semantics.\n\n **Why is this bad?** It isn't bad in general. But in some contexts it can be desirable\n because it increases ownership hints in the code, and will guard against some changes\n in ownership.\n\n **Known problems:** None.\n\n **Example:**\n\n This example shows the basic adjustments necessary to satisfy the lint. Note how\n the matched expression is explicitly dereferenced with `*` and the `inner` variable\n is bound to a shared borrow via `ref inner`.\n\n ```rust,ignore\n // Bad\n let value = &Some(Box::new(23));\n match value {\n Some(inner) => println!(\"{}\", inner),\n None => println!(\"none\"),\n }\n\n // Good\n let value = &Some(Box::new(23));\n match *value {\n Some(ref inner) => println!(\"{}\", inner),\n None => println!(\"none\"),\n }\n ```\n\n The following example demonstrates one of the advantages of the more verbose style.\n Note how the second version uses `ref mut a` to explicitly declare `a` a shared mutable\n borrow, while `b` is simply taken by value. This ensures that the loop body cannot\n accidentally modify the wrong part of the structure.\n\n ```rust,ignore\n // Bad\n let mut values = vec![(2, 3), (3, 4)];\n for (a, b) in &mut values {\n *a += *b;\n }\n\n // Good\n let mut values = vec![(2, 3), (3, 4)];\n for &mut (ref mut a, b) in &mut values {\n *a += b;\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "precedence", - "id_span": { - "path": "src/precedence.rs", - "line": 44 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for operations where precedence may be unclear and suggests to add parentheses. Currently it catches the following:\n * mixed usage of arithmetic and bit shifting/combining operators without\n parentheses\n * a \"negative\" numeric literal (which is really a unary `-` followed by a\n numeric literal)\n followed by a method call\n\n **Why is this bad?** Not everyone knows the precedence of those operators by\n heart, so expressions like these may trip others trying to reason about the\n code.\n\n **Known problems:** None.\n\n **Example:**\n * `1 << 2 + 3` equals 32, while `(1 << 2) + 3` equals 7\n * `-1i32.abs()` equals -1, while `(-1i32).abs()` equals 1\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "ptr_arg", - "id_span": { - "path": "src/ptr.rs", - "line": 69 - }, - "group": "clippy::style", - "docs": " **What it does:** This lint checks for function arguments of type `&String` or `&Vec` unless the references are mutable. It will also suggest you\n replace `.clone()` calls with the appropriate `.to_owned()`/`to_string()`\n calls.\n\n **Why is this bad?** Requiring the argument to be of the specific size\n makes the function less useful for no benefit; slices in the form of `&[T]`\n or `&str` usually suffice and can be obtained from other types, too.\n\n **Known problems:** The lint does not follow data. So if you have an\n argument `x` and write `let y = x; y.clone()` the lint will not suggest\n changing that `.clone()` to `.to_owned()`.\n\n Other functions called from this function taking a `&String` or `&Vec`\n argument may also fail to compile if you change the argument. Applying\n this lint on them will fix the problem, but they may be in other crates.\n\n One notable example of a function that may cause issues, and which cannot\n easily be changed due to being in the standard library is `Vec::contains`.\n when called on a `Vec>`. If a `&Vec` is passed to that method then\n it will compile, but if a `&[T]` is passed then it will not compile.\n\n ```ignore\n fn cannot_take_a_slice(v: &Vec) -> bool {\n let vec_of_vecs: Vec> = some_other_fn();\n\n vec_of_vecs.contains(v)\n }\n ```\n\n Also there may be `fn(&Vec)`-typed references pointing to your function.\n If you have them, you will get a compiler error after applying this lint's\n suggestions. You then have the choice to undo your changes or change the\n type of the reference.\n\n Note that if the function is part of your public interface, there may be\n other crates referencing it, of which you may not be aware. Carefully\n deprecate the function before applying the lint suggestions in this case.\n\n **Example:**\n ```ignore\n // Bad\n fn foo(&Vec) { .. }\n\n // Good\n fn foo(&[u32]) { .. }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "Unspecified" - } - }, - { - "id": "cmp_null", - "id_span": { - "path": "src/ptr.rs", - "line": 95 - }, - "group": "clippy::style", - "docs": " **What it does:** This lint checks for equality comparisons with `ptr::null`\n **Why is this bad?** It's easier and more readable to use the inherent\n `.is_null()`\n method instead\n\n **Known problems:** None.\n\n **Example:**\n ```ignore\n // Bad\n if x == ptr::null {\n ..\n }\n\n // Good\n if x.is_null() {\n ..\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "mut_from_ref", - "id_span": { - "path": "src/ptr.rs", - "line": 117 - }, - "group": "clippy::correctness", - "docs": " **What it does:** This lint checks for functions that take immutable references and return mutable ones.\n\n **Why is this bad?** This is trivially unsound, as one can create two\n mutable references from the same (immutable!) source.\n This [error](https://github.com/rust-lang/rust/issues/39465)\n actually lead to an interim Rust release 1.15.1.\n\n **Known problems:** To be on the conservative side, if there's at least one\n mutable reference with the output lifetime, this lint will not trigger.\n In practice, this case is unlikely anyway.\n\n **Example:**\n ```ignore\n fn foo(&Foo) -> &mut Bar { .. }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "ptr_eq", - "id_span": { - "path": "src/ptr_eq.rs", - "line": 32 - }, - "group": "clippy::style", - "docs": " **What it does:** Use `std::ptr::eq` when applicable\n **Why is this bad?** `ptr::eq` can be used to compare `&T` references\n (which coerce to `*const T` implicitly) by their address rather than\n comparing the values they point to.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n let a = &[1, 2, 3];\n let b = &[1, 2, 3];\n\n assert!(a as *const _ as usize == b as *const _ as usize);\n ```\n Use instead:\n ```rust\n let a = &[1, 2, 3];\n let b = &[1, 2, 3];\n\n assert!(std::ptr::eq(a, b));\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "ptr_offset_with_cast", - "id_span": { - "path": "src/ptr_offset_with_cast.rs", - "line": 40 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for usage of the `offset` pointer method with a `usize` casted to an `isize`.\n\n **Why is this bad?** If we’re always increasing the pointer address, we can avoid the numeric\n cast by using the `add` method instead.\n\n **Known problems:** None\n\n **Example:**\n ```rust\n let vec = vec![b'a', b'b', b'c'];\n let ptr = vec.as_ptr();\n let offset = 1_usize;\n\n unsafe {\n ptr.offset(offset as isize);\n }\n ```\n\n Could be written:\n\n ```rust\n let vec = vec![b'a', b'b', b'c'];\n let ptr = vec.as_ptr();\n let offset = 1_usize;\n\n unsafe {\n ptr.add(offset);\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "question_mark", - "id_span": { - "path": "src/question_mark.rs", - "line": 34 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for expressions that could be replaced by the question mark operator.\n **Why is this bad?** Question mark usage is more idiomatic.\n\n **Known problems:** None\n\n **Example:**\n ```ignore\n if option.is_none() {\n return None;\n }\n ```\n\n Could be written:\n\n ```ignore\n option?;\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "range_zip_with_len", - "id_span": { - "path": "src/ranges.rs", - "line": 40 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for zipping a collection with the range of `0.._.len()`.\n\n **Why is this bad?** The code is better expressed with `.enumerate()`.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let x = vec![1];\n x.iter().zip(0..x.len());\n ```\n Could be written as\n ```rust\n # let x = vec![1];\n x.iter().enumerate();\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "range_plus_one", - "id_span": { - "path": "src/ranges.rs", - "line": 74 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for exclusive ranges where 1 is added to the upper bound, e.g., `x..(y+1)`.\n\n **Why is this bad?** The code is more readable with an inclusive range\n like `x..=y`.\n\n **Known problems:** Will add unnecessary pair of parentheses when the\n expression is not wrapped in a pair but starts with a opening parenthesis\n and ends with a closing one.\n I.e., `let _ = (f()+1)..(f()+1)` results in `let _ = ((f()+1)..=f())`.\n\n Also in many cases, inclusive ranges are still slower to run than\n exclusive ranges, because they essentially add an extra branch that\n LLVM may fail to hoist out of the loop.\n\n This will cause a warning that cannot be fixed if the consumer of the\n range only accepts a specific range type, instead of the generic\n `RangeBounds` trait\n ([#3307](https://github.com/rust-lang/rust-clippy/issues/3307)).\n\n **Example:**\n ```rust,ignore\n for x..(y+1) { .. }\n ```\n Could be written as\n ```rust,ignore\n for x..=y { .. }\n ```\n", - "applicability": { - "is_multi_suggestion": true, - "applicability": "MachineApplicable" - } - }, - { - "id": "range_minus_one", - "id_span": { - "path": "src/ranges.rs", - "line": 99 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for inclusive ranges where 1 is subtracted from the upper bound, e.g., `x..=(y-1)`.\n\n **Why is this bad?** The code is more readable with an exclusive range\n like `x..y`.\n\n **Known problems:** This will cause a warning that cannot be fixed if\n the consumer of the range only accepts a specific range type, instead of\n the generic `RangeBounds` trait\n ([#3307](https://github.com/rust-lang/rust-clippy/issues/3307)).\n\n **Example:**\n ```rust,ignore\n for x..=(y-1) { .. }\n ```\n Could be written as\n ```rust,ignore\n for x..y { .. }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "reversed_empty_ranges", - "id_span": { - "path": "src/ranges.rs", - "line": 132 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for range expressions `x..y` where both `x` and `y` are constant and `x` is greater or equal to `y`.\n\n **Why is this bad?** Empty ranges yield no values so iterating them is a no-op.\n Moreover, trying to use a reversed range to index a slice will panic at run-time.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust,no_run\n fn main() {\n (10..=0).for_each(|x| println!(\"{}\", x));\n\n let arr = [1, 2, 3, 4, 5];\n let sub = &arr[3..1];\n }\n ```\n Use instead:\n ```rust\n fn main() {\n (0..=10).rev().for_each(|x| println!(\"{}\", x));\n\n let arr = [1, 2, 3, 4, 5];\n let sub = &arr[1..3];\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MaybeIncorrect" - } - }, - { - "id": "manual_range_contains", - "id_span": { - "path": "src/ranges.rs", - "line": 159 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for expressions like `x >= 3 && x < 8` that could be more readably expressed as `(3..8).contains(x)`.\n\n **Why is this bad?** `contains` expresses the intent better and has less\n failure modes (such as fencepost errors or using `||` instead of `&&`).\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n // given\n let x = 6;\n\n assert!(x >= 3 && x < 8);\n ```\n Use instead:\n ```rust\n# let x = 6;\n assert!((3..8).contains(&x));\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "redundant_clone", - "id_span": { - "path": "src/redundant_clone.rs", - "line": 63 - }, - "group": "clippy::perf", - "docs": " **What it does:** Checks for a redundant `clone()` (and its relatives) which clones an owned value that is going to be dropped without further use.\n\n **Why is this bad?** It is not always possible for the compiler to eliminate useless\n allocations and deallocations generated by redundant `clone()`s.\n\n **Known problems:**\n\n False-negatives: analysis performed by this lint is conservative and limited.\n\n **Example:**\n ```rust\n # use std::path::Path;\n # #[derive(Clone)]\n # struct Foo;\n # impl Foo {\n # fn new() -> Self { Foo {} }\n # }\n # fn call(x: Foo) {}\n {\n let x = Foo::new();\n call(x.clone());\n call(x.clone()); // this can just pass `x`\n }\n\n [\"lorem\", \"ipsum\"].join(\" \").to_string();\n\n Path::new(\"/a/b\").join(\"c\").to_path_buf();\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "redundant_closure_call", - "id_span": { - "path": "src/redundant_closure_call.rs", - "line": 32 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Detects closures called in the same expression where they are defined.\n\n **Why is this bad?** It is unnecessarily adding to the expression's\n complexity.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n // Bad\n let a = (|| 42)()\n\n // Good\n let a = 42\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "redundant_else", - "id_span": { - "path": "src/redundant_else.rs", - "line": 37 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for `else` blocks that can be removed without changing semantics.\n **Why is this bad?** The `else` block adds unnecessary indentation and verbosity.\n\n **Known problems:** Some may prefer to keep the `else` block for clarity.\n\n **Example:**\n\n ```rust\n fn my_func(count: u32) {\n if count == 0 {\n print!(\"Nothing to do\");\n return;\n } else {\n print!(\"Moving on...\");\n }\n }\n ```\n Use instead:\n ```rust\n fn my_func(count: u32) {\n if count == 0 {\n print!(\"Nothing to do\");\n return;\n }\n print!(\"Moving on...\");\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "redundant_field_names", - "id_span": { - "path": "src/redundant_field_names.rs", - "line": 34 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for fields in struct literals where shorthands could be used.\n\n **Why is this bad?** If the field and variable names are the same,\n the field name is redundant.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let bar: u8 = 123;\n\n struct Foo {\n bar: u8,\n }\n\n let foo = Foo { bar: bar };\n ```\n the last line can be simplified to\n ```ignore\n let foo = Foo { bar };\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "redundant_pub_crate", - "id_span": { - "path": "src/redundant_pub_crate.rs", - "line": 30 - }, - "group": "clippy::nursery", - "docs": " **What it does:** Checks for items declared `pub(crate)` that are not crate visible because they are inside a private module.\n\n **Why is this bad?** Writing `pub(crate)` is misleading when it's redundant due to the parent\n module's visibility.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n mod internal {\n pub(crate) fn internal_fn() { }\n }\n ```\n This function is not visible outside the module and it can be declared with `pub` or\n private visibility\n ```rust\n mod internal {\n pub fn internal_fn() { }\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "redundant_slicing", - "id_span": { - "path": "src/redundant_slicing.rs", - "line": 33 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for redundant slicing expressions which use the full range, and do not change the type.\n\n **Why is this bad?** It unnecessarily adds complexity to the expression.\n\n **Known problems:** If the type being sliced has an implementation of `Index`\n that actually changes anything then it can't be removed. However, this would be surprising\n to people reading the code and should have a note with it.\n\n **Example:**\n\n ```ignore\n fn get_slice(x: &[u32]) -> &[u32] {\n &x[..]\n }\n ```\n Use instead:\n ```ignore\n fn get_slice(x: &[u32]) -> &[u32] {\n x\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "redundant_static_lifetimes", - "id_span": { - "path": "src/redundant_static_lifetimes.rs", - "line": 30 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for constants and statics with an explicit `'static` lifetime.\n **Why is this bad?** Adding `'static` to every reference can create very\n complicated types.\n\n **Known problems:** None.\n\n **Example:**\n ```ignore\n const FOO: &'static [(&'static str, &'static str, fn(&Bar) -> bool)] =\n &[...]\n static FOO: &'static [(&'static str, &'static str, fn(&Bar) -> bool)] =\n &[...]\n ```\n This code can be rewritten as\n ```ignore\n const FOO: &[(&str, &str, fn(&Bar) -> bool)] = &[...]\n static FOO: &[(&str, &str, fn(&Bar) -> bool)] = &[...]\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "ref_option_ref", - "id_span": { - "path": "src/ref_option_ref.rs", - "line": 28 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for usage of `&Option<&T>`.\n **Why is this bad?** Since `&` is Copy, it's useless to have a\n reference on `Option<&T>`.\n\n **Known problems:** It may be irrelevant to use this lint on\n public API code as it will make a breaking change to apply it.\n\n **Example:**\n\n ```rust,ignore\n let x: &Option<&u32> = &Some(&0u32);\n ```\n Use instead:\n ```rust,ignore\n let x: Option<&u32> = Some(&0u32);\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MaybeIncorrect" - } - }, - { - "id": "deref_addrof", - "id_span": { - "path": "src/reference.rs", - "line": 29 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for usage of `*&` and `*&mut` in expressions.\n **Why is this bad?** Immediately dereferencing a reference is no-op and\n makes the code less clear.\n\n **Known problems:** Multiple dereference/addrof pairs are not handled so\n the suggested fix for `x = **&&y` is `x = *&y`, which is still incorrect.\n\n **Example:**\n ```rust,ignore\n // Bad\n let a = f(*&mut b);\n let c = *&d;\n\n // Good\n let a = f(b);\n let c = d;\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "ref_in_deref", - "id_span": { - "path": "src/reference.rs", - "line": 120 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for references in expressions that use auto dereference.\n\n **Why is this bad?** The reference is a no-op and is automatically\n dereferenced by the compiler and makes the code less clear.\n\n **Example:**\n ```rust\n struct Point(u32, u32);\n let point = Point(30, 20);\n let x = (&point).0;\n ```\n Use instead:\n ```rust\n # struct Point(u32, u32);\n # let point = Point(30, 20);\n let x = point.0;\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "invalid_regex", - "id_span": { - "path": "src/regex.rs", - "line": 25 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks [regex](https://crates.io/crates/regex) creation (with `Regex::new`, `RegexBuilder::new`, or `RegexSet::new`) for correct\n regex syntax.\n\n **Why is this bad?** This will lead to a runtime panic.\n\n **Known problems:** None.\n\n **Example:**\n ```ignore\n Regex::new(\"|\")\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "trivial_regex", - "id_span": { - "path": "src/regex.rs", - "line": 46 - }, - "group": "clippy::nursery", - "docs": " **What it does:** Checks for trivial [regex](https://crates.io/crates/regex) creation (with `Regex::new`, `RegexBuilder::new`, or `RegexSet::new`).\n\n **Why is this bad?** Matching the regex can likely be replaced by `==` or\n `str::starts_with`, `str::ends_with` or `std::contains` or other `str`\n methods.\n\n **Known problems:** If the same regex is going to be applied to multiple\n inputs, the precomputations done by `Regex` construction can give\n significantly better performance than any of the `str`-based methods.\n\n **Example:**\n ```ignore\n Regex::new(\"^foobar\")\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "repeat_once", - "id_span": { - "path": "src/repeat_once.rs", - "line": 33 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for usage of `.repeat(1)` and suggest the following method for each types. - `.to_string()` for `str`\n - `.clone()` for `String`\n - `.to_vec()` for `slice`\n\n **Why is this bad?** For example, `String.repeat(1)` is equivalent to `.clone()`. If cloning the string is the intention behind this, `clone()` should be used.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n fn main() {\n let x = String::from(\"hello world\").repeat(1);\n }\n ```\n Use instead:\n ```rust\n fn main() {\n let x = String::from(\"hello world\").clone();\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "let_and_return", - "id_span": { - "path": "src/returns.rs", - "line": 38 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for `let`-bindings, which are subsequently returned.\n\n **Why is this bad?** It is just extraneous code. Remove it to make your code\n more rusty.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n fn foo() -> String {\n let x = String::new();\n x\n }\n ```\n instead, use\n ```\n fn foo() -> String {\n String::new()\n }\n ```\n", - "applicability": { - "is_multi_suggestion": true, - "applicability": "MachineApplicable" - } - }, - { - "id": "needless_return", - "id_span": { - "path": "src/returns.rs", - "line": 63 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for return statements at the end of a block.\n **Why is this bad?** Removing the `return` and semicolon will make the code\n more rusty.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n fn foo(x: usize) -> usize {\n return x;\n }\n ```\n simplify to\n ```rust\n fn foo(x: usize) -> usize {\n x\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "self_assignment", - "id_span": { - "path": "src/self_assignment.rs", - "line": 29 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for explicit self-assignments.\n **Why is this bad?** Self-assignments are redundant and unlikely to be\n intentional.\n\n **Known problems:** If expression contains any deref coercions or\n indexing operations they are assumed not to have any side effects.\n\n **Example:**\n\n ```rust\n struct Event {\n id: usize,\n x: i32,\n y: i32,\n }\n\n fn copy_position(a: &mut Event, b: &Event) {\n a.x = b.x;\n a.y = a.y;\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "semicolon_if_nothing_returned", - "id_span": { - "path": "src/semicolon_if_nothing_returned.rs", - "line": 30 - }, - "group": "clippy::restriction", - "docs": " **What it does:** Looks for blocks of expressions and fires if the last expression returns `()` but is not followed by a semicolon.\n\n **Why is this bad?** The semicolon might be optional but when\n extending the block with new code, it doesn't require a change in previous last line.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n fn main() {\n println!(\"Hello world\")\n }\n ```\n Use instead:\n ```rust\n fn main() {\n println!(\"Hello world\");\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MaybeIncorrect" - } - }, - { - "id": "serde_api_misuse", - "id_span": { - "path": "src/serde_api.rs", - "line": 16 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for mis-uses of the serde API.\n **Why is this bad?** Serde is very finnicky about how its API should be\n used, but the type system can't be used to enforce it (yet?).\n\n **Known problems:** None.\n\n **Example:** Implementing `Visitor::visit_string` but not\n `Visitor::visit_str`.\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "shadow_same", - "id_span": { - "path": "src/shadow.rs", - "line": 34 - }, - "group": "clippy::restriction", - "docs": " **What it does:** Checks for bindings that shadow other bindings already in scope, while just changing reference level or mutability.\n\n **Why is this bad?** Not much, in fact it's a very common pattern in Rust\n code. Still, some may opt to avoid it in their code base, they can set this\n lint to `Warn`.\n\n **Known problems:** This lint, as the other shadowing related lints,\n currently only catches very simple patterns.\n\n **Example:**\n ```rust\n # let x = 1;\n // Bad\n let x = &x;\n\n // Good\n let y = &x; // use different variable name\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "shadow_reuse", - "id_span": { - "path": "src/shadow.rs", - "line": 61 - }, - "group": "clippy::restriction", - "docs": " **What it does:** Checks for bindings that shadow other bindings already in scope, while reusing the original value.\n\n **Why is this bad?** Not too much, in fact it's a common pattern in Rust\n code. Still, some argue that name shadowing like this hurts readability,\n because a value may be bound to different things depending on position in\n the code.\n\n **Known problems:** This lint, as the other shadowing related lints,\n currently only catches very simple patterns.\n\n **Example:**\n ```rust\n let x = 2;\n let x = x + 1;\n ```\n use different variable name:\n ```rust\n let x = 2;\n let y = x + 1;\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "shadow_unrelated", - "id_span": { - "path": "src/shadow.rs", - "line": 93 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for bindings that shadow other bindings already in scope, either without a initialization or with one that does not even use\n the original value.\n\n **Why is this bad?** Name shadowing can hurt readability, especially in\n large code bases, because it is easy to lose track of the active binding at\n any place in the code. This can be alleviated by either giving more specific\n names to bindings or introducing more scopes to contain the bindings.\n\n **Known problems:** This lint, as the other shadowing related lints,\n currently only catches very simple patterns. Note that\n `allow`/`warn`/`deny`/`forbid` attributes only work on the function level\n for this lint.\n\n **Example:**\n ```rust\n # let y = 1;\n # let z = 2;\n let x = y;\n\n // Bad\n let x = z; // shadows the earlier binding\n\n // Good\n let w = z; // use different variable name\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "single_component_path_imports", - "id_span": { - "path": "src/single_component_path_imports.rs", - "line": 32 - }, - "group": "clippy::style", - "docs": " **What it does:** Checking for imports with single component use path.\n **Why is this bad?** Import with single component use path such as `use cratename;`\n is not necessary, and thus should be removed.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust,ignore\n use regex;\n\n fn main() {\n regex::Regex::new(r\"^\\d{4}-\\d{2}-\\d{2}$\").unwrap();\n }\n ```\n Better as\n ```rust,ignore\n fn main() {\n regex::Regex::new(r\"^\\d{4}-\\d{2}-\\d{2}$\").unwrap();\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "size_of_in_element_count", - "id_span": { - "path": "src/size_of_in_element_count.rs", - "line": 31 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Detects expressions where `size_of::` or `size_of_val::` is used as a\n count of elements of type `T`\n\n **Why is this bad?** These functions expect a count\n of `T` and not a number of bytes\n\n **Known problems:** None.\n\n **Example:**\n ```rust,no_run\n # use std::ptr::copy_nonoverlapping;\n # use std::mem::size_of;\n const SIZE: usize = 128;\n let x = [2u8; SIZE];\n let mut y = [2u8; SIZE];\n unsafe { copy_nonoverlapping(x.as_ptr(), y.as_mut_ptr(), size_of::() * SIZE) };\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "slow_vector_initialization", - "id_span": { - "path": "src/slow_vector_initialization.rs", - "line": 37 - }, - "group": "clippy::perf", - "docs": " **What it does:** Checks slow zero-filled vector initialization\n **Why is this bad?** These structures are non-idiomatic and less efficient than simply using\n `vec![0; len]`.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # use core::iter::repeat;\n # let len = 4;\n\n // Bad\n let mut vec1 = Vec::with_capacity(len);\n vec1.resize(len, 0);\n\n let mut vec2 = Vec::with_capacity(len);\n vec2.extend(repeat(0).take(len));\n\n // Good\n let mut vec1 = vec![0; len];\n let mut vec2 = vec![0; len];\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "Unspecified" - } - }, - { - "id": "stable_sort_primitive", - "id_span": { - "path": "src/stable_sort_primitive.rs", - "line": 36 - }, - "group": "clippy::perf", - "docs": " **What it does:** When sorting primitive values (integers, bools, chars, as well\n as arrays, slices, and tuples of such items), it is better to\n use an unstable sort than a stable sort.\n\n **Why is this bad?**\n Using a stable sort consumes more memory and cpu cycles. Because\n values which compare equal are identical, preserving their\n relative order (the guarantee that a stable sort provides) means\n nothing, while the extra costs still apply.\n\n **Known problems:**\n None\n\n **Example:**\n\n ```rust\n let mut vec = vec![2, 1, 3];\n vec.sort();\n ```\n Use instead:\n ```rust\n let mut vec = vec![2, 1, 3];\n vec.sort_unstable();\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "string_add_assign", - "id_span": { - "path": "src/strings.rs", - "line": 37 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for string appends of the form `x = x + y` (without `let`!).\n\n **Why is this bad?** It's not really bad, but some people think that the\n `.push_str(_)` method is more readable.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n let mut x = \"Hello\".to_owned();\n x = x + \", World\";\n\n // More readable\n x += \", World\";\n x.push_str(\", World\");\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "string_add", - "id_span": { - "path": "src/strings.rs", - "line": 65 - }, - "group": "clippy::restriction", - "docs": " **What it does:** Checks for all instances of `x + _` where `x` is of type `String`, but only if [`string_add_assign`](#string_add_assign) does *not*\n match.\n\n **Why is this bad?** It's not bad in and of itself. However, this particular\n `Add` implementation is asymmetric (the other operand need not be `String`,\n but `x` does), while addition as mathematically defined is symmetric, also\n the `String::push_str(_)` function is a perfectly good replacement.\n Therefore, some dislike it and wish not to have it in their code.\n\n That said, other people think that string addition, having a long tradition\n in other languages is actually fine, which is why we decided to make this\n particular lint `allow` by default.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n let x = \"Hello\".to_owned();\n x + \", World\";\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "string_lit_as_bytes", - "id_span": { - "path": "src/strings.rs", - "line": 107 - }, - "group": "clippy::nursery", - "docs": " **What it does:** Checks for the `as_bytes` method called on string literals that contain only ASCII characters.\n\n **Why is this bad?** Byte string literals (e.g., `b\"foo\"`) can be used\n instead. They are shorter but less discoverable than `as_bytes()`.\n\n **Known Problems:**\n `\"str\".as_bytes()` and the suggested replacement of `b\"str\"` are not\n equivalent because they have different types. The former is `&[u8]`\n while the latter is `&[u8; 3]`. That means in general they will have a\n different set of methods and different trait implementations.\n\n ```compile_fail\n fn f(v: Vec) {}\n\n f(\"...\".as_bytes().to_owned()); // works\n f(b\"...\".to_owned()); // does not work, because arg is [u8; 3] not Vec\n\n fn g(r: impl std::io::Read) {}\n\n g(\"...\".as_bytes()); // works\n g(b\"...\"); // does not work\n ```\n\n The actual equivalent of `\"str\".as_bytes()` with the same type is not\n `b\"str\"` but `&b\"str\"[..]`, which is a great deal of punctuation and not\n more readable than a function call.\n\n **Example:**\n ```rust\n // Bad\n let bs = \"a byte string\".as_bytes();\n\n // Good\n let bs = b\"a byte string\";\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "string_from_utf8_as_bytes", - "id_span": { - "path": "src/strings.rs", - "line": 196 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Check if the string is transformed to byte array and casted back to string.\n **Why is this bad?** It's unnecessary, the string can be used directly.\n\n **Known problems:** None\n\n **Example:**\n ```rust\n let _ = std::str::from_utf8(&\"Hello World!\".as_bytes()[6..11]).unwrap();\n ```\n could be written as\n ```rust\n let _ = &\"Hello World!\"[6..11];\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "str_to_string", - "id_span": { - "path": "src/strings.rs", - "line": 313 - }, - "group": "clippy::restriction", - "docs": " **What it does:** This lint checks for `.to_string()` method calls on values of type `&str`.\n **Why is this bad?** The `to_string` method is also used on other types to convert them to a string.\n When called on a `&str` it turns the `&str` into the owned variant `String`, which can be better\n expressed with `.to_owned()`.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n // example code where clippy issues a warning\n let _ = \"str\".to_string();\n ```\n Use instead:\n ```rust\n // example code which does not raise clippy warning\n let _ = \"str\".to_owned();\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "string_to_string", - "id_span": { - "path": "src/strings.rs", - "line": 362 - }, - "group": "clippy::restriction", - "docs": " **What it does:** This lint checks for `.to_string()` method calls on values of type `String`.\n **Why is this bad?** The `to_string` method is also used on other types to convert them to a string.\n When called on a `String` it only clones the `String`, which can be better expressed with `.clone()`.\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n // example code where clippy issues a warning\n let msg = String::from(\"Hello World\");\n let _ = msg.to_string();\n ```\n Use instead:\n ```rust\n // example code which does not raise clippy warning\n let msg = String::from(\"Hello World\");\n let _ = msg.clone();\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "suspicious_operation_groupings", - "id_span": { - "path": "src/suspicious_operation_groupings.rs", - "line": 60 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for unlikely usages of binary operators that are almost\n certainly typos and/or copy/paste errors, given the other usages\n of binary operators nearby.\n **Why is this bad?**\n They are probably bugs and if they aren't then they look like bugs\n and you should add a comment explaining why you are doing such an\n odd set of operations.\n **Known problems:**\n There may be some false positives if you are trying to do something\n unusual that happens to look like a typo.\n\n **Example:**\n\n ```rust\n struct Vec3 {\n x: f64,\n y: f64,\n z: f64,\n }\n\n impl Eq for Vec3 {}\n\n impl PartialEq for Vec3 {\n fn eq(&self, other: &Self) -> bool {\n // This should trigger the lint because `self.x` is compared to `other.y`\n self.x == other.y && self.y == other.y && self.z == other.z\n }\n }\n ```\n Use instead:\n ```rust\n # struct Vec3 {\n # x: f64,\n # y: f64,\n # z: f64,\n # }\n // same as above except:\n impl PartialEq for Vec3 {\n fn eq(&self, other: &Self) -> bool {\n // Note we now compare other.x to self.x\n self.x == other.x && self.y == other.y && self.z == other.z\n }\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "suspicious_arithmetic_impl", - "id_span": { - "path": "src/suspicious_trait_impl.rs", - "line": 27 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Lints for suspicious operations in impls of arithmetic operators, e.g. subtracting elements in an Add impl.\n\n **Why this is bad?** This is probably a typo or copy-and-paste error and not intended.\n\n **Known problems:** None.\n\n **Example:**\n ```ignore\n impl Add for Foo {\n type Output = Foo;\n\n fn add(self, other: Foo) -> Foo {\n Foo(self.0 - other.0)\n }\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "suspicious_op_assign_impl", - "id_span": { - "path": "src/suspicious_trait_impl.rs", - "line": 48 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Lints for suspicious operations in impls of OpAssign, e.g. subtracting elements in an AddAssign impl.\n\n **Why this is bad?** This is probably a typo or copy-and-paste error and not intended.\n\n **Known problems:** None.\n\n **Example:**\n ```ignore\n impl AddAssign for Foo {\n fn add_assign(&mut self, other: Foo) {\n *self = *self - other;\n }\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "manual_swap", - "id_span": { - "path": "src/swap.rs", - "line": 36 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for manual swapping.\n **Why is this bad?** The `std::mem::swap` function exposes the intent better\n without deinitializing or copying either variable.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let mut a = 42;\n let mut b = 1337;\n\n let t = b;\n b = a;\n a = t;\n ```\n Use std::mem::swap():\n ```rust\n let mut a = 1;\n let mut b = 2;\n std::mem::swap(&mut a, &mut b);\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "almost_swapped", - "id_span": { - "path": "src/swap.rs", - "line": 61 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for `foo = bar; bar = foo` sequences.\n **Why is this bad?** This looks like a failed attempt to swap.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let mut a = 1;\n # let mut b = 2;\n a = b;\n b = a;\n ```\n If swapping is intended, use `swap()` instead:\n ```rust\n # let mut a = 1;\n # let mut b = 2;\n std::mem::swap(&mut a, &mut b);\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MaybeIncorrect" - } - }, - { - "id": "tabs_in_doc_comments", - "id_span": { - "path": "src/tabs_in_doc_comments.rs", - "line": 54 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks doc comments for usage of tab characters.\n **Why is this bad?** The rust style-guide promotes spaces instead of tabs for indentation.\n To keep a consistent view on the source, also doc comments should not have tabs.\n Also, explaining ascii-diagrams containing tabs can get displayed incorrectly when the\n display settings of the author and reader differ.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n ///\n /// Struct to hold two strings:\n /// \t- first\t\tone\n /// \t- second\tone\n pub struct DoubleString {\n ///\n /// \t- First String:\n /// \t\t- needs to be inside here\n first_string: String,\n ///\n /// \t- Second String:\n /// \t\t- needs to be inside here\n second_string: String,\n}\n ```\n\n Will be converted to:\n ```rust\n ///\n /// Struct to hold two strings:\n /// - first one\n /// - second one\n pub struct DoubleString {\n ///\n /// - First String:\n /// - needs to be inside here\n first_string: String,\n ///\n /// - Second String:\n /// - needs to be inside here\n second_string: String,\n}\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MaybeIncorrect" - } - }, - { - "id": "temporary_assignment", - "id_span": { - "path": "src/temporary_assignment.rs", - "line": 19 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for construction of a structure or tuple just to assign a value in it.\n\n **Why is this bad?** Readability. If the structure is only created to be\n updated, why not write the structure you want in the first place?\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n (0, 0).0 = 1\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "to_digit_is_some", - "id_span": { - "path": "src/to_digit_is_some.rs", - "line": 27 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for `.to_digit(..).is_some()` on `char`s.\n **Why is this bad?** This is a convoluted way of checking if a `char` is a digit. It's\n more straight forward to use the dedicated `is_digit` method.\n\n **Example:**\n ```rust\n # let c = 'c';\n # let radix = 10;\n let is_digit = c.to_digit(radix).is_some();\n ```\n can be written as:\n ```\n # let c = 'c';\n # let radix = 10;\n let is_digit = c.is_digit(radix);\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "to_string_in_display", - "id_span": { - "path": "src/to_string_in_display.rs", - "line": 40 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for uses of `to_string()` in `Display` traits.\n **Why is this bad?** Usually `to_string` is implemented indirectly\n via `Display`. Hence using it while implementing `Display` would\n lead to infinite recursion.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n use std::fmt;\n\n struct Structure(i32);\n impl fmt::Display for Structure {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n write!(f, \"{}\", self.to_string())\n }\n }\n\n ```\n Use instead:\n ```rust\n use std::fmt;\n\n struct Structure(i32);\n impl fmt::Display for Structure {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n write!(f, \"{}\", self.0)\n }\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "type_repetition_in_bounds", - "id_span": { - "path": "src/trait_bounds.rs", - "line": 28 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** This lint warns about unnecessary type repetitions in trait bounds\n **Why is this bad?** Repeating the type for every bound makes the code\n less readable than combining the bounds\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n pub fn foo(t: T) where T: Copy, T: Clone {}\n ```\n\n Could be written as:\n\n ```rust\n pub fn foo(t: T) where T: Copy + Clone {}\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "trait_duplication_in_bounds", - "id_span": { - "path": "src/trait_bounds.rs", - "line": 57 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for cases where generics are being used and multiple syntax specifications for trait bounds are used simultaneously.\n\n **Why is this bad?** Duplicate bounds makes the code\n less readable than specifing them only once.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n fn func(arg: T) where T: Clone + Default {}\n ```\n\n Could be written as:\n\n ```rust\n fn func(arg: T) {}\n ```\n or\n\n ```rust\n fn func(arg: T) where T: Clone + Default {}\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "wrong_transmute", - "id_span": { - "path": "src/transmute/mod.rs", - "line": 34 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for transmutes that can't ever be correct on any architecture.\n\n **Why is this bad?** It's basically guaranteed to be undefined behaviour.\n\n **Known problems:** When accessing C, users might want to store pointer\n sized objects in `extradata` arguments to save an allocation.\n\n **Example:**\n ```ignore\n let ptr: *const T = core::intrinsics::transmute('x')\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "useless_transmute", - "id_span": { - "path": "src/transmute/mod.rs", - "line": 53 - }, - "group": "clippy::nursery", - "docs": " **What it does:** Checks for transmutes to the original type of the object and transmutes that could be a cast.\n\n **Why is this bad?** Readability. The code tricks people into thinking that\n something complex is going on.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n core::intrinsics::transmute(t); // where the result type is the same as `t`'s\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "Unspecified" - } - }, - { - "id": "transmutes_expressible_as_ptr_casts", - "id_span": { - "path": "src/transmute/mod.rs", - "line": 78 - }, - "group": "clippy::complexity", - "docs": " **What it does:**Checks for transmutes that could be a pointer cast.\n **Why is this bad?** Readability. The code tricks people into thinking that\n something complex is going on.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n # let p: *const [i32] = &[];\n unsafe { std::mem::transmute::<*const [i32], *const [u16]>(p) };\n ```\n Use instead:\n ```rust\n # let p: *const [i32] = &[];\n p as *const [u16];\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "crosspointer_transmute", - "id_span": { - "path": "src/transmute/mod.rs", - "line": 96 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for transmutes between a type `T` and `*T`.\n **Why is this bad?** It's easy to mistakenly transmute between a type and a\n pointer to that type.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n core::intrinsics::transmute(t) // where the result type is the same as\n // `*t` or `&t`'s\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "transmute_ptr_to_ref", - "id_span": { - "path": "src/transmute/mod.rs", - "line": 121 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for transmutes from a pointer to a reference.\n **Why is this bad?** This can always be rewritten with `&` and `*`.\n\n **Known problems:**\n - `mem::transmute` in statics and constants is stable from Rust 1.46.0,\n while dereferencing raw pointer is not stable yet.\n If you need to do this in those places,\n you would have to use `transmute` instead.\n\n **Example:**\n ```rust,ignore\n unsafe {\n let _: &T = std::mem::transmute(p); // where p: *const T\n }\n\n // can be written:\n let _: &T = &*p;\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "Unspecified" - } - }, - { - "id": "transmute_int_to_char", - "id_span": { - "path": "src/transmute/mod.rs", - "line": 152 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for transmutes from an integer to a `char`.\n **Why is this bad?** Not every integer is a Unicode scalar value.\n\n **Known problems:**\n - [`from_u32`] which this lint suggests using is slower than `transmute`\n as it needs to validate the input.\n If you are certain that the input is always a valid Unicode scalar value,\n use [`from_u32_unchecked`] which is as fast as `transmute`\n but has a semantically meaningful name.\n - You might want to handle `None` returned from [`from_u32`] instead of calling `unwrap`.\n\n [`from_u32`]: https://doc.rust-lang.org/std/char/fn.from_u32.html\n [`from_u32_unchecked`]: https://doc.rust-lang.org/std/char/fn.from_u32_unchecked.html\n\n **Example:**\n ```rust\n let x = 1_u32;\n unsafe {\n let _: char = std::mem::transmute(x); // where x: u32\n }\n\n // should be:\n let _ = std::char::from_u32(x).unwrap();\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "Unspecified" - } - }, - { - "id": "transmute_bytes_to_str", - "id_span": { - "path": "src/transmute/mod.rs", - "line": 183 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for transmutes from a `&[u8]` to a `&str`.\n **Why is this bad?** Not every byte slice is a valid UTF-8 string.\n\n **Known problems:**\n - [`from_utf8`] which this lint suggests using is slower than `transmute`\n as it needs to validate the input.\n If you are certain that the input is always a valid UTF-8,\n use [`from_utf8_unchecked`] which is as fast as `transmute`\n but has a semantically meaningful name.\n - You might want to handle errors returned from [`from_utf8`] instead of calling `unwrap`.\n\n [`from_utf8`]: https://doc.rust-lang.org/std/str/fn.from_utf8.html\n [`from_utf8_unchecked`]: https://doc.rust-lang.org/std/str/fn.from_utf8_unchecked.html\n\n **Example:**\n ```rust\n let b: &[u8] = &[1_u8, 2_u8];\n unsafe {\n let _: &str = std::mem::transmute(b); // where b: &[u8]\n }\n\n // should be:\n let _ = std::str::from_utf8(b).unwrap();\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "Unspecified" - } - }, - { - "id": "transmute_int_to_bool", - "id_span": { - "path": "src/transmute/mod.rs", - "line": 205 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for transmutes from an integer to a `bool`.\n **Why is this bad?** This might result in an invalid in-memory representation of a `bool`.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let x = 1_u8;\n unsafe {\n let _: bool = std::mem::transmute(x); // where x: u8\n }\n\n // should be:\n let _: bool = x != 0;\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "Unspecified" - } - }, - { - "id": "transmute_int_to_float", - "id_span": { - "path": "src/transmute/mod.rs", - "line": 227 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for transmutes from an integer to a float.\n **Why is this bad?** Transmutes are dangerous and error-prone, whereas `from_bits` is intuitive\n and safe.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n unsafe {\n let _: f32 = std::mem::transmute(1_u32); // where x: u32\n }\n\n // should be:\n let _: f32 = f32::from_bits(1_u32);\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "Unspecified" - } - }, - { - "id": "transmute_float_to_int", - "id_span": { - "path": "src/transmute/mod.rs", - "line": 249 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for transmutes from a float to an integer.\n **Why is this bad?** Transmutes are dangerous and error-prone, whereas `to_bits` is intuitive\n and safe.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n unsafe {\n let _: u32 = std::mem::transmute(1f32);\n }\n\n // should be:\n let _: u32 = 1f32.to_bits();\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "Unspecified" - } - }, - { - "id": "transmute_ptr_to_ptr", - "id_span": { - "path": "src/transmute/mod.rs", - "line": 276 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for transmutes from a pointer to a pointer, or from a reference to a reference.\n\n **Why is this bad?** Transmutes are dangerous, and these can instead be\n written as casts.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let ptr = &1u32 as *const u32;\n unsafe {\n // pointer-to-pointer transmute\n let _: *const f32 = std::mem::transmute(ptr);\n // ref-ref transmute\n let _: &f32 = std::mem::transmute(&1u32);\n }\n // These can be respectively written:\n let _ = ptr as *const f32;\n let _ = unsafe{ &*(&1u32 as *const u32 as *const f32) };\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "Unspecified" - } - }, - { - "id": "unsound_collection_transmute", - "id_span": { - "path": "src/transmute/mod.rs", - "line": 304 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for transmutes between collections whose types have different ABI, size or alignment.\n\n **Why is this bad?** This is undefined behavior.\n\n **Known problems:** Currently, we cannot know whether a type is a\n collection, so we just lint the ones that come with `std`.\n\n **Example:**\n ```rust\n // different size, therefore likely out-of-bounds memory access\n // You absolutely do not want this in your code!\n unsafe {\n std::mem::transmute::<_, Vec>(vec![2_u16])\n };\n ```\n\n You must always iterate, map and collect the values:\n\n ```rust\n vec![2_u16].into_iter().map(u32::from).collect::>();\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "transmuting_null", - "id_span": { - "path": "src/transmuting_null.rs", - "line": 23 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for transmute calls which would receive a null pointer.\n **Why is this bad?** Transmuting a null pointer is undefined behavior.\n\n **Known problems:** Not all cases can be detected at the moment of this writing.\n For example, variables which hold a null pointer and are then fed to a `transmute`\n call, aren't detectable yet.\n\n **Example:**\n ```rust\n let null_ref: &u64 = unsafe { std::mem::transmute(0 as *const u64) };\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "try_err", - "id_span": { - "path": "src/try_err.rs", - "line": 43 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for usages of `Err(x)?`.\n **Why is this bad?** The `?` operator is designed to allow calls that\n can fail to be easily chained. For example, `foo()?.bar()` or\n `foo(bar()?)`. Because `Err(x)?` can't be used that way (it will\n always return), it is more clear to write `return Err(x)`.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n fn foo(fail: bool) -> Result {\n if fail {\n Err(\"failed\")?;\n }\n Ok(0)\n }\n ```\n Could be written:\n\n ```rust\n fn foo(fail: bool) -> Result {\n if fail {\n return Err(\"failed\".into());\n }\n Ok(0)\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "box_vec", - "id_span": { - "path": "src/types.rs", - "line": 66 - }, - "group": "clippy::perf", - "docs": " **What it does:** Checks for use of `Box>` anywhere in the code. Check the [Box documentation](https://doc.rust-lang.org/std/boxed/index.html) for more information.\n\n **Why is this bad?** `Vec` already keeps its contents in a separate area on\n the heap. So if you `Box` it, you just add another level of indirection\n without any benefit whatsoever.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n struct X {\n values: Box>,\n }\n ```\n\n Better:\n\n ```rust,ignore\n struct X {\n values: Vec,\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "vec_box", - "id_span": { - "path": "src/types.rs", - "line": 95 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for use of `Vec>` where T: Sized anywhere in the code. Check the [Box documentation](https://doc.rust-lang.org/std/boxed/index.html) for more information.\n\n **Why is this bad?** `Vec` already keeps its contents in a separate area on\n the heap. So if you `Box` its contents, you just add another level of indirection.\n\n **Known problems:** Vec> makes sense if T is a large type (see [#3530](https://github.com/rust-lang/rust-clippy/issues/3530),\n 1st comment).\n\n **Example:**\n ```rust\n struct X {\n values: Vec>,\n }\n ```\n\n Better:\n\n ```rust\n struct X {\n values: Vec,\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "option_option", - "id_span": { - "path": "src/types.rs", - "line": 133 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for use of `Option>` in function signatures and type definitions\n\n **Why is this bad?** `Option<_>` represents an optional value. `Option>`\n represents an optional optional value which is logically the same thing as an optional\n value but has an unneeded extra level of wrapping.\n\n If you have a case where `Some(Some(_))`, `Some(None)` and `None` are distinct cases,\n consider a custom `enum` instead, with clear names for each case.\n\n **Known problems:** None.\n\n **Example**\n ```rust\n fn get_data() -> Option> {\n None\n }\n ```\n\n Better:\n\n ```rust\n pub enum Contents {\n Data(Vec), // Was Some(Some(Vec))\n NotYetFetched, // Was Some(None)\n None, // Was None\n }\n\n fn get_data() -> Contents {\n Contents::None\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "linkedlist", - "id_span": { - "path": "src/types.rs", - "line": 169 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for usage of any `LinkedList`, suggesting to use a `Vec` or a `VecDeque` (formerly called `RingBuf`).\n\n **Why is this bad?** Gankro says:\n\n > The TL;DR of `LinkedList` is that it's built on a massive amount of\n pointers and indirection.\n > It wastes memory, it has terrible cache locality, and is all-around slow.\n `RingBuf`, while\n > \"only\" amortized for push/pop, should be faster in the general case for\n almost every possible\n > workload, and isn't even amortized at all if you can predict the capacity\n you need.\n >\n > `LinkedList`s are only really good if you're doing a lot of merging or\n splitting of lists.\n > This is because they can just mangle some pointers instead of actually\n copying the data. Even\n > if you're doing a lot of insertion in the middle of the list, `RingBuf`\n can still be better\n > because of how expensive it is to seek to the middle of a `LinkedList`.\n\n **Known problems:** False positives – the instances where using a\n `LinkedList` makes sense are few and far between, but they can still happen.\n\n **Example:**\n ```rust\n # use std::collections::LinkedList;\n let x: LinkedList = LinkedList::new();\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "borrowed_box", - "id_span": { - "path": "src/types.rs", - "line": 193 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for use of `&Box` anywhere in the code. Check the [Box documentation](https://doc.rust-lang.org/std/boxed/index.html) for more information.\n\n **Why is this bad?** Any `&Box` can also be a `&T`, which is more\n general.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n fn foo(bar: &Box) { ... }\n ```\n\n Better:\n\n ```rust,ignore\n fn foo(bar: &T) { ... }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "Unspecified" - } - }, - { - "id": "redundant_allocation", - "id_span": { - "path": "src/types.rs", - "line": 217 - }, - "group": "clippy::perf", - "docs": " **What it does:** Checks for use of redundant allocations anywhere in the code.\n **Why is this bad?** Expressions such as `Rc<&T>`, `Rc>`, `Rc>`, `Box<&T>`\n add an unnecessary level of indirection.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # use std::rc::Rc;\n fn foo(bar: Rc<&usize>) {}\n ```\n\n Better:\n\n ```rust\n fn foo(bar: &usize) {}\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "rc_buffer", - "id_span": { - "path": "src/types.rs", - "line": 248 - }, - "group": "clippy::restriction", - "docs": " **What it does:** Checks for `Rc` and `Arc` when `T` is a mutable buffer type such as `String` or `Vec`.\n **Why is this bad?** Expressions such as `Rc` usually have no advantage over `Rc`, since\n it is larger and involves an extra level of indirection, and doesn't implement `Borrow`.\n\n While mutating a buffer type would still be possible with `Rc::get_mut()`, it only\n works if there are no additional references yet, which usually defeats the purpose of\n enclosing it in a shared ownership type. Instead, additionally wrapping the inner\n type with an interior mutable container (such as `RefCell` or `Mutex`) would normally\n be used.\n\n **Known problems:** This pattern can be desirable to avoid the overhead of a `RefCell` or `Mutex` for\n cases where mutation only happens before there are any additional references.\n\n **Example:**\n ```rust,ignore\n # use std::rc::Rc;\n fn foo(interned: Rc) { ... }\n ```\n\n Better:\n\n ```rust,ignore\n fn foo(interned: Rc) { ... }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "let_unit_value", - "id_span": { - "path": "src/types.rs", - "line": 768 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for binding a unit value.\n **Why is this bad?** A unit value cannot usefully be used anywhere. So\n binding one is kind of pointless.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let x = {\n 1;\n };\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "unit_cmp", - "id_span": { - "path": "src/types.rs", - "line": 849 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for comparisons to unit. This includes all binary comparisons (like `==` and `<`) and asserts.\n\n **Why is this bad?** Unit is always equal to itself, and thus is just a\n clumsily written constant. Mostly this happens when someone accidentally\n adds semicolons at the end of the operands.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # fn foo() {};\n # fn bar() {};\n # fn baz() {};\n if {\n foo();\n } == {\n bar();\n } {\n baz();\n }\n ```\n is equal to\n ```rust\n # fn foo() {};\n # fn bar() {};\n # fn baz() {};\n {\n foo();\n bar();\n baz();\n }\n ```\n\n For asserts:\n ```rust\n # fn foo() {};\n # fn bar() {};\n assert_eq!({ foo(); }, { bar(); });\n ```\n will always succeed\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "unit_arg", - "id_span": { - "path": "src/types.rs", - "line": 922 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for passing a unit value as an argument to a function without using a unit literal (`()`).\n\n **Why is this bad?** This is likely the result of an accidental semicolon.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n foo({\n let a = bar();\n baz(a);\n })\n ```\n", - "applicability": { - "is_multi_suggestion": true, - "applicability": "MachineApplicable" - } - }, - { - "id": "cast_precision_loss", - "id_span": { - "path": "src/types.rs", - "line": 1158 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for casts from any numerical to a float type where the receiving type cannot store all values from the original type without\n rounding errors. This possible rounding is to be expected, so this lint is\n `Allow` by default.\n\n Basically, this warns on casting any integer with 32 or more bits to `f32`\n or any 64-bit integer to `f64`.\n\n **Why is this bad?** It's not bad at all. But in some applications it can be\n helpful to know where precision loss can take place. This lint can help find\n those places in the code.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let x = u64::MAX;\n x as f64;\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "cast_sign_loss", - "id_span": { - "path": "src/types.rs", - "line": 1179 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for casts from a signed to an unsigned numerical type. In this case, negative values wrap around to large positive values,\n which can be quite surprising in practice. However, as the cast works as\n defined, this lint is `Allow` by default.\n\n **Why is this bad?** Possibly surprising results. You can activate this lint\n as a one-time check to see where numerical wrapping can arise.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let y: i8 = -1;\n y as u128; // will return 18446744073709551615\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "cast_possible_truncation", - "id_span": { - "path": "src/types.rs", - "line": 1201 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for casts between numerical types that may truncate large values. This is expected behavior, so the cast is `Allow` by\n default.\n\n **Why is this bad?** In some problem domains, it is good practice to avoid\n truncation. This lint can be activated to help assess where additional\n checks could be beneficial.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n fn as_u8(x: u64) -> u8 {\n x as u8\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "cast_possible_wrap", - "id_span": { - "path": "src/types.rs", - "line": 1224 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for casts from an unsigned type to a signed type of the same size. Performing such a cast is a 'no-op' for the compiler,\n i.e., nothing is changed at the bit level, and the binary representation of\n the value is reinterpreted. This can cause wrapping if the value is too big\n for the target signed type. However, the cast works as defined, so this lint\n is `Allow` by default.\n\n **Why is this bad?** While such a cast is not bad in itself, the results can\n be surprising when this is not the intended behavior, as demonstrated by the\n example below.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n u32::MAX as i32; // will yield a value of `-1`\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "cast_lossless", - "id_span": { - "path": "src/types.rs", - "line": 1256 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for casts between numerical types that may be replaced by safe conversion functions.\n\n **Why is this bad?** Rust's `as` keyword will perform many kinds of\n conversions, including silently lossy conversions. Conversion functions such\n as `i32::from` will only perform lossless conversions. Using the conversion\n functions prevents conversions from turning into silent lossy conversions if\n the types of the input expressions ever change, and make it easier for\n people reading the code to know that the conversion is lossless.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n fn as_u64(x: u8) -> u64 {\n x as u64\n }\n ```\n\n Using `::from` would look like this:\n\n ```rust\n fn as_u64(x: u8) -> u64 {\n u64::from(x)\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "unnecessary_cast", - "id_span": { - "path": "src/types.rs", - "line": 1281 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for casts to the same type, casts of int literals to integer types and casts of float literals to float types.\n\n **Why is this bad?** It's just unnecessary.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let _ = 2i32 as i32;\n let _ = 0.5 as f32;\n ```\n\n Better:\n\n ```rust\n let _ = 2_i32;\n let _ = 0.5_f32;\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "cast_ptr_alignment", - "id_span": { - "path": "src/types.rs", - "line": 1305 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for casts, using `as` or `pointer::cast`, from a less-strictly-aligned pointer to a more-strictly-aligned pointer\n\n **Why is this bad?** Dereferencing the resulting pointer may be undefined\n behavior.\n\n **Known problems:** Using `std::ptr::read_unaligned` and `std::ptr::write_unaligned` or similar\n on the resulting pointer is fine. Is over-zealous: Casts with manual alignment checks or casts like\n u64-> u8 -> u16 can be fine. Miri is able to do a more in-depth analysis.\n\n **Example:**\n ```rust\n let _ = (&1u8 as *const u8) as *const u16;\n let _ = (&mut 1u8 as *mut u8) as *mut u16;\n\n (&1u8 as *const u8).cast::();\n (&mut 1u8 as *mut u8).cast::();\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "fn_to_numeric_cast", - "id_span": { - "path": "src/types.rs", - "line": 1332 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for casts of function pointers to something other than usize\n **Why is this bad?**\n Casting a function pointer to anything other than usize/isize is not portable across\n architectures, because you end up losing bits if the target type is too small or end up with a\n bunch of extra bits that waste space and add more instructions to the final binary than\n strictly necessary for the problem\n\n Casting to isize also doesn't make sense since there are no signed addresses.\n\n **Example**\n\n ```rust\n // Bad\n fn fun() -> i32 { 1 }\n let a = fun as i64;\n\n // Good\n fn fun2() -> i32 { 1 }\n let a = fun2 as usize;\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MaybeIncorrect" - } - }, - { - "id": "fn_to_numeric_cast_with_truncation", - "id_span": { - "path": "src/types.rs", - "line": 1362 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for casts of a function pointer to a numeric type not wide enough to store address.\n\n **Why is this bad?**\n Such a cast discards some bits of the function's address. If this is intended, it would be more\n clearly expressed by casting to usize first, then casting the usize to the intended type (with\n a comment) to perform the truncation.\n\n **Example**\n\n ```rust\n // Bad\n fn fn1() -> i16 {\n 1\n };\n let _ = fn1 as i32;\n\n // Better: Cast to usize first, then comment with the reason for the truncation\n fn fn2() -> i16 {\n 1\n };\n let fn_ptr = fn2 as usize;\n let fn_ptr_truncated = fn_ptr as i32;\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MaybeIncorrect" - } - }, - { - "id": "type_complexity", - "id_span": { - "path": "src/types.rs", - "line": 1897 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for types used in structs, parameters and `let` declarations above a certain complexity threshold.\n\n **Why is this bad?** Too complex types make the code less readable. Consider\n using a `type` definition to simplify them.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # use std::rc::Rc;\n struct Foo {\n inner: Rc>>>,\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "char_lit_as_u8", - "id_span": { - "path": "src/types.rs", - "line": 2068 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for expressions where a character literal is cast to `u8` and suggests using a byte literal instead.\n\n **Why is this bad?** In general, casting values to smaller types is\n error-prone and should be avoided where possible. In the particular case of\n converting a character literal to u8, it is easy to avoid by just using a\n byte literal instead. As an added bonus, `b'a'` is even slightly shorter\n than `'a' as u8`.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n 'x' as u8\n ```\n\n A better version, using the byte literal:\n\n ```rust,ignore\n b'x'\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "absurd_extreme_comparisons", - "id_span": { - "path": "src/types.rs", - "line": 2133 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for comparisons where one side of the relation is either the minimum or maximum value for its type and warns if it involves a\n case that is always true or always false. Only integer and boolean types are\n checked.\n\n **Why is this bad?** An expression like `min <= x` may misleadingly imply\n that it is possible for `x` to be less than the minimum. Expressions like\n `max < x` are probably mistakes.\n\n **Known problems:** For `usize` the size of the current compile target will\n be assumed (e.g., 64 bits on 64 bit systems). This means code that uses such\n a comparison to detect target pointer width will trigger this lint. One can\n use `mem::sizeof` and compare its value or conditional compilation\n attributes\n like `#[cfg(target_pointer_width = \"64\")] ..` instead.\n\n **Example:**\n\n ```rust\n let vec: Vec = Vec::new();\n if vec.len() <= 0 {}\n if 100 > i32::MAX {}\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "invalid_upcast_comparisons", - "id_span": { - "path": "src/types.rs", - "line": 2294 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for comparisons where the relation is always either true or false, but where one side has been upcast so that the comparison is\n necessary. Only integer types are checked.\n\n **Why is this bad?** An expression like `let x : u8 = ...; (x as u32) > 300`\n will mistakenly imply that it is possible for `x` to be outside the range of\n `u8`.\n\n **Known problems:**\n https://github.com/rust-lang/rust-clippy/issues/886\n\n **Example:**\n ```rust\n let x: u8 = 1;\n (x as u32) > 300;\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "implicit_hasher", - "id_span": { - "path": "src/types.rs", - "line": 2515 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for public `impl` or `fn` missing generalization over different hashers and implicitly defaulting to the default hashing\n algorithm (`SipHash`).\n\n **Why is this bad?** `HashMap` or `HashSet` with custom hashers cannot be\n used with them.\n\n **Known problems:** Suggestions for replacing constructors can contain\n false-positives. Also applying suggestions can require modification of other\n pieces of code, possibly including external crates.\n\n **Example:**\n ```rust\n # use std::collections::HashMap;\n # use std::hash::{Hash, BuildHasher};\n # trait Serialize {};\n impl Serialize for HashMap { }\n\n pub fn foo(map: &mut HashMap) { }\n ```\n could be rewritten as\n ```rust\n # use std::collections::HashMap;\n # use std::hash::{Hash, BuildHasher};\n # trait Serialize {};\n impl Serialize for HashMap { }\n\n pub fn foo(map: &mut HashMap) { }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "cast_ref_to_mut", - "id_span": { - "path": "src/types.rs", - "line": 2866 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for casts of `&T` to `&mut T` anywhere in the code.\n **Why is this bad?** It’s basically guaranteed to be undefined behaviour.\n `UnsafeCell` is the only way to obtain aliasable data that is considered\n mutable.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n fn x(r: &i32) {\n unsafe {\n *(r as *const _ as *mut _) += 1;\n }\n }\n ```\n\n Instead consider using interior mutability types.\n\n ```rust\n use std::cell::UnsafeCell;\n\n fn x(r: &UnsafeCell) {\n unsafe {\n *r.get() += 1;\n }\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "ptr_as_ptr", - "id_span": { - "path": "src/types.rs", - "line": 2922 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for `as` casts between raw pointers without changing its mutability,\n namely `*const T` to `*const U` and `*mut T` to `*mut U`.\n\n **Why is this bad?**\n Though `as` casts between raw pointers is not terrible, `pointer::cast` is safer because\n it cannot accidentally change the pointer's mutability nor cast the pointer to other types like `usize`.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n let ptr: *const u32 = &42_u32;\n let mut_ptr: *mut u32 = &mut 42_u32;\n let _ = ptr as *const i32;\n let _ = mut_ptr as *mut i32;\n ```\n Use instead:\n ```rust\n let ptr: *const u32 = &42_u32;\n let mut_ptr: *mut u32 = &mut 42_u32;\n let _ = ptr.cast::();\n let _ = mut_ptr.cast::();\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "undropped_manually_drops", - "id_span": { - "path": "src/undropped_manually_drops.rs", - "line": 27 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Prevents the safe `std::mem::drop` function from being called on `std::mem::ManuallyDrop`.\n **Why is this bad?** The safe `drop` function does not drop the inner value of a `ManuallyDrop`.\n\n **Known problems:** Does not catch cases if the user binds `std::mem::drop`\n to a different name and calls it that way.\n\n **Example:**\n\n ```rust\n struct S;\n drop(std::mem::ManuallyDrop::new(S));\n ```\n Use instead:\n ```rust\n struct S;\n unsafe {\n std::mem::ManuallyDrop::drop(&mut std::mem::ManuallyDrop::new(S));\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "invisible_characters", - "id_span": { - "path": "src/unicode.rs", - "line": 20 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for invisible Unicode characters in the code.\n **Why is this bad?** Having an invisible character in the code makes for all\n sorts of April fools, but otherwise is very much frowned upon.\n\n **Known problems:** None.\n\n **Example:** You don't see it, but there may be a zero-width space or soft hyphen\n some­where in this text.\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "non_ascii_literal", - "id_span": { - "path": "src/unicode.rs", - "line": 44 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for non-ASCII characters in string literals.\n **Why is this bad?** Yeah, we know, the 90's called and wanted their charset\n back. Even so, there still are editors and other programs out there that\n don't work well with Unicode. So if the code is meant to be used\n internationally, on multiple operating systems, or has other portability\n requirements, activating this lint could be useful.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n let x = String::from(\"€\");\n ```\n Could be written as:\n ```rust\n let x = String::from(\"\\u{20ac}\");\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "unicode_not_nfc", - "id_span": { - "path": "src/unicode.rs", - "line": 61 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for string literals that contain Unicode in a form that is not equal to its\n [NFC-recomposition](http://www.unicode.org/reports/tr15/#Norm_Forms).\n\n **Why is this bad?** If such a string is compared to another, the results\n may be surprising.\n\n **Known problems** None.\n\n **Example:** You may not see it, but \"à\"\" and \"à\"\" aren't the same string. The\n former when escaped is actually `\"a\\u{300}\"` while the latter is `\"\\u{e0}\"`.\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "unit_return_expecting_ord", - "id_span": { - "path": "src/unit_return_expecting_ord.rs", - "line": 30 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for functions that expect closures of type Fn(...) -> Ord where the implemented closure returns the unit type.\n The lint also suggests to remove the semi-colon at the end of the statement if present.\n\n **Why is this bad?** Likely, returning the unit type is unintentional, and\n could simply be caused by an extra semi-colon. Since () implements Ord\n it doesn't cause a compilation error.\n This is the same reasoning behind the unit_cmp lint.\n\n **Known problems:** If returning unit is intentional, then there is no\n way of specifying this without triggering needless_return lint\n\n **Example:**\n\n ```rust\n let mut twins = vec!((1, 1), (2, 2));\n twins.sort_by_key(|x| { x.1; });\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "fn_address_comparisons", - "id_span": { - "path": "src/unnamed_address.rs", - "line": 27 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for comparisons with an address of a function item.\n **Why is this bad?** Function item address is not guaranteed to be unique and could vary\n between different code generation units. Furthermore different function items could have\n the same address after being merged together.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n type F = fn();\n fn a() {}\n let f: F = a;\n if f == a {\n // ...\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "vtable_address_comparisons", - "id_span": { - "path": "src/unnamed_address.rs", - "line": 51 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for comparisons with an address of a trait vtable.\n **Why is this bad?** Comparing trait objects pointers compares an vtable addresses which\n are not guaranteed to be unique and could vary between different code generation units.\n Furthermore vtables for different types could have the same address after being merged\n together.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust,ignore\n let a: Rc = ...\n let b: Rc = ...\n if Rc::ptr_eq(&a, &b) {\n ...\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "unnecessary_sort_by", - "id_span": { - "path": "src/unnecessary_sort_by.rs", - "line": 41 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Detects uses of `Vec::sort_by` passing in a closure\n which compares the two arguments, either directly or indirectly.\n\n **Why is this bad?**\n It is more clear to use `Vec::sort_by_key` (or `Vec::sort` if\n possible) than to use `Vec::sort_by` and a more complicated\n closure.\n\n **Known problems:**\n If the suggested `Vec::sort_by_key` uses Reverse and it isn't already\n imported by a use statement, then it will need to be added manually.\n\n **Example:**\n\n ```rust\n # struct A;\n # impl A { fn foo(&self) {} }\n # let mut vec: Vec = Vec::new();\n vec.sort_by(|a, b| a.foo().cmp(&b.foo()));\n ```\n Use instead:\n ```rust\n # struct A;\n # impl A { fn foo(&self) {} }\n # let mut vec: Vec = Vec::new();\n vec.sort_by_key(|a| a.foo());\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "unnecessary_wraps", - "id_span": { - "path": "src/unnecessary_wraps.rs", - "line": 50 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for private functions that only return `Ok` or `Some`.\n **Why is this bad?** It is not meaningful to wrap values when no `None` or `Err` is returned.\n\n **Known problems:** There can be false positives if the function signature is designed to\n fit some external requirement.\n\n **Example:**\n\n ```rust\n fn get_cool_number(a: bool, b: bool) -> Option {\n if a && b {\n return Some(50);\n }\n if a {\n Some(0)\n } else {\n Some(10)\n }\n }\n ```\n Use instead:\n ```rust\n fn get_cool_number(a: bool, b: bool) -> i32 {\n if a && b {\n return 50;\n }\n if a {\n 0\n } else {\n 10\n }\n }\n ```\n", - "applicability": { - "is_multi_suggestion": true, - "applicability": "MaybeIncorrect" - } - }, - { - "id": "unnested_or_patterns", - "id_span": { - "path": "src/unnested_or_patterns.rs", - "line": 47 - }, - "group": "clippy::pedantic", - "docs": " **What it does:**\n Checks for unnested or-patterns, e.g., `Some(0) | Some(2)` and\n suggests replacing the pattern with a nested one, `Some(0 | 2)`.\n\n Another way to think of this is that it rewrites patterns in\n *disjunctive normal form (DNF)* into *conjunctive normal form (CNF)*.\n\n **Why is this bad?**\n\n In the example above, `Some` is repeated, which unncessarily complicates the pattern.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n fn main() {\n if let Some(0) | Some(2) = Some(0) {}\n }\n ```\n Use instead:\n ```rust\n #![feature(or_patterns)]\n\n fn main() {\n if let Some(0 | 2) = Some(0) {}\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "unsafe_removed_from_name", - "id_span": { - "path": "src/unsafe_removed_from_name.rs", - "line": 24 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for imports that remove \"unsafe\" from an item's name.\n\n **Why is this bad?** Renaming makes it less clear which traits and\n structures are unsafe.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n use std::cell::{UnsafeCell as TotallySafeCell};\n\n extern crate crossbeam;\n use crossbeam::{spawn_unsafe as spawn};\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "unused_io_amount", - "id_span": { - "path": "src/unused_io_amount.rs", - "line": 28 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for unused written/read amount.\n **Why is this bad?** `io::Write::write(_vectored)` and\n `io::Read::read(_vectored)` are not guaranteed to\n process the entire buffer. They return how many bytes were processed, which\n might be smaller\n than a given buffer's length. If you don't need to deal with\n partial-write/read, use\n `write_all`/`read_exact` instead.\n\n **Known problems:** Detects only common patterns.\n\n **Example:**\n ```rust,ignore\n use std::io;\n fn foo(w: &mut W) -> io::Result<()> {\n // must be `w.write_all(b\"foo\")?;`\n w.write(b\"foo\")?;\n Ok(())\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "unused_self", - "id_span": { - "path": "src/unused_self.rs", - "line": 33 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks methods that contain a `self` argument but don't use it\n **Why is this bad?** It may be clearer to define the method as an associated function instead\n of an instance method if it doesn't require `self`.\n\n **Known problems:** None.\n\n **Example:**\n ```rust,ignore\n struct A;\n impl A {\n fn method(&self) {}\n }\n ```\n\n Could be written:\n\n ```rust,ignore\n struct A;\n impl A {\n fn method() {}\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "unused_unit", - "id_span": { - "path": "src/unused_unit.rs", - "line": 27 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for unit (`()`) expressions that can be removed.\n **Why is this bad?** Such expressions add no value, but can make the code\n less readable. Depending on formatting they can make a `break` or `return`\n statement look like a function call.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n fn return_unit() -> () {\n ()\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "unnecessary_unwrap", - "id_span": { - "path": "src/unwrap.rs", - "line": 40 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for calls of `unwrap[_err]()` that cannot fail.\n **Why is this bad?** Using `if let` or `match` is more idiomatic.\n\n **Known problems:** None\n\n **Example:**\n ```rust\n # let option = Some(0);\n # fn do_something_with(_x: usize) {}\n if option.is_some() {\n do_something_with(option.unwrap())\n }\n ```\n\n Could be written:\n\n ```rust\n # let option = Some(0);\n # fn do_something_with(_x: usize) {}\n if let Some(value) = option {\n do_something_with(value)\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "panicking_unwrap", - "id_span": { - "path": "src/unwrap.rs", - "line": 63 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Checks for calls of `unwrap[_err]()` that will always fail.\n **Why is this bad?** If panicking is desired, an explicit `panic!()` should be used.\n\n **Known problems:** This lint only checks `if` conditions not assignments.\n So something like `let x: Option<()> = None; x.unwrap();` will not be recognized.\n\n **Example:**\n ```rust\n # let option = Some(0);\n # fn do_something_with(_x: usize) {}\n if option.is_none() {\n do_something_with(option.unwrap())\n }\n ```\n\n This code will always panic. The if condition should probably be inverted.\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "unwrap_in_result", - "id_span": { - "path": "src/unwrap_in_result.rs", - "line": 47 - }, - "group": "clippy::restriction", - "docs": " **What it does:** Checks for functions of type Result that contain `expect()` or `unwrap()`\n **Why is this bad?** These functions promote recoverable errors to non-recoverable errors which may be undesirable in code bases which wish to avoid panics.\n\n **Known problems:** This can cause false positives in functions that handle both recoverable and non recoverable errors.\n\n **Example:**\n Before:\n ```rust\n fn divisible_by_3(i_str: String) -> Result<(), String> {\n let i = i_str\n .parse::()\n .expect(\"cannot divide the input by three\");\n\n if i % 3 != 0 {\n Err(\"Number is not divisible by 3\")?\n }\n\n Ok(())\n }\n ```\n\n After:\n ```rust\n fn divisible_by_3(i_str: String) -> Result<(), String> {\n let i = i_str\n .parse::()\n .map_err(|e| format!(\"cannot divide the input by three: {}\", e))?;\n\n if i % 3 != 0 {\n Err(\"Number is not divisible by 3\")?\n }\n\n Ok(())\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "upper_case_acronyms", - "id_span": { - "path": "src/upper_case_acronyms.rs", - "line": 35 - }, - "group": "clippy::style", - "docs": " **What it does:** Checks for fully capitalized names and optionally names containing a capitalized acronym.\n **Why is this bad?** In CamelCase, acronyms count as one word.\n See [naming conventions](https://rust-lang.github.io/api-guidelines/naming.html#casing-conforms-to-rfc-430-c-case)\n for more.\n\n By default, the lint only triggers on fully-capitalized names.\n You can use the `upper-case-acronyms-aggressive: true` config option to enable linting\n on all camel case names\n\n **Known problems:** When two acronyms are contiguous, the lint can't tell where\n the first acronym ends and the second starts, so it suggests to lowercase all of\n the letters in the second acronym.\n\n **Example:**\n\n ```rust\n struct HTTPResponse;\n ```\n Use instead:\n ```rust\n struct HttpResponse;\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MaybeIncorrect" - } - }, - { - "id": "use_self", - "id_span": { - "path": "src/use_self.rs", - "line": 53 - }, - "group": "clippy::nursery", - "docs": " **What it does:** Checks for unnecessary repetition of structure name when a replacement with `Self` is applicable.\n\n **Why is this bad?** Unnecessary repetition. Mixed use of `Self` and struct\n name\n feels inconsistent.\n\n **Known problems:**\n - Unaddressed false negative in fn bodies of trait implementations\n - False positive with assotiated types in traits (#4140)\n\n **Example:**\n\n ```rust\n struct Foo {}\n impl Foo {\n fn new() -> Foo {\n Foo {}\n }\n }\n ```\n could be\n ```rust\n struct Foo {}\n impl Foo {\n fn new() -> Self {\n Self {}\n }\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "useless_conversion", - "id_span": { - "path": "src/useless_conversion.rs", - "line": 32 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for `Into`, `TryInto`, `From`, `TryFrom`, or `IntoIter` calls which uselessly convert to the same type.\n\n **Why is this bad?** Redundant code.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n // Bad\n // format!() returns a `String`\n let s: String = format!(\"hello\").into();\n\n // Good\n let s: String = format!(\"hello\");\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "useless_vec", - "id_span": { - "path": "src/vec.rs", - "line": 36 - }, - "group": "clippy::perf", - "docs": " **What it does:** Checks for usage of `&vec![..]` when using `&[..]` would be possible.\n\n **Why is this bad?** This is less efficient.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # fn foo(my_vec: &[u8]) {}\n\n // Bad\n foo(&vec![1, 2]);\n\n // Good\n foo(&[1, 2]);\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "vec_init_then_push", - "id_span": { - "path": "src/vec_init_then_push.rs", - "line": 32 - }, - "group": "clippy::perf", - "docs": " **What it does:** Checks for calls to `push` immediately after creating a new `Vec`.\n **Why is this bad?** The `vec![]` macro is both more performant and easier to read than\n multiple `push` calls.\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust\n let mut v = Vec::new();\n v.push(0);\n ```\n Use instead:\n ```rust\n let v = vec![0];\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "HasPlaceholders" - } - }, - { - "id": "vec_resize_to_zero", - "id_span": { - "path": "src/vec_resize_to_zero.rs", - "line": 24 - }, - "group": "clippy::correctness", - "docs": " **What it does:** Finds occurrences of `Vec::resize(0, an_int)`\n **Why is this bad?** This is probably an argument inversion mistake.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n vec!(1, 2, 3, 4, 5).resize(0, 5)\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MaybeIncorrect" - } - }, - { - "id": "verbose_file_reads", - "id_span": { - "path": "src/verbose_file_reads.rs", - "line": 29 - }, - "group": "clippy::restriction", - "docs": " **What it does:** Checks for use of File::read_to_end and File::read_to_string.\n **Why is this bad?** `fs::{read, read_to_string}` provide the same functionality when `buf` is empty with fewer imports and no intermediate values.\n See also: [fs::read docs](https://doc.rust-lang.org/std/fs/fn.read.html), [fs::read_to_string docs](https://doc.rust-lang.org/std/fs/fn.read_to_string.html)\n\n **Known problems:** None.\n\n **Example:**\n\n ```rust,no_run\n # use std::io::Read;\n # use std::fs::File;\n let mut f = File::open(\"foo.txt\").unwrap();\n let mut bytes = Vec::new();\n f.read_to_end(&mut bytes).unwrap();\n ```\n Can be written more concisely as\n ```rust,no_run\n # use std::fs;\n let mut bytes = fs::read(\"foo.txt\").unwrap();\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "wildcard_dependencies", - "id_span": { - "path": "src/wildcard_dependencies.rs", - "line": 24 - }, - "group": "clippy::cargo", - "docs": " **What it does:** Checks for wildcard dependencies in the `Cargo.toml`.\n **Why is this bad?** [As the edition guide says](https://rust-lang-nursery.github.io/edition-guide/rust-2018/cargo-and-crates-io/crates-io-disallows-wildcard-dependencies.html),\n it is highly unlikely that you work with any possible version of your dependency,\n and wildcard dependencies would cause unnecessary breakage in the ecosystem.\n\n **Known problems:** None.\n\n **Example:**\n\n ```toml\n [dependencies]\n regex = \"*\"\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "enum_glob_use", - "id_span": { - "path": "src/wildcard_imports.rs", - "line": 32 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for `use Enum::*`.\n **Why is this bad?** It is usually better style to use the prefixed name of\n an enumeration variant, rather than importing variants.\n\n **Known problems:** Old-style enumerations that prefix the variants are\n still around.\n\n **Example:**\n ```rust,ignore\n // Bad\n use std::cmp::Ordering::*;\n foo(Less);\n\n // Good\n use std::cmp::Ordering;\n foo(Ordering::Less)\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "wildcard_imports", - "id_span": { - "path": "src/wildcard_imports.rs", - "line": 83 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for wildcard imports `use _::*`.\n **Why is this bad?** wildcard imports can pollute the namespace. This is especially bad if\n you try to import something through a wildcard, that already has been imported by name from\n a different source:\n\n ```rust,ignore\n use crate1::foo; // Imports a function named foo\n use crate2::*; // Has a function named foo\n\n foo(); // Calls crate1::foo\n ```\n\n This can lead to confusing error messages at best and to unexpected behavior at worst.\n\n **Exceptions:**\n\n Wildcard imports are allowed from modules named `prelude`. Many crates (including the standard library)\n provide modules named \"prelude\" specifically designed for wildcard import.\n\n `use super::*` is allowed in test modules. This is defined as any module with \"test\" in the name.\n\n These exceptions can be disabled using the `warn-on-all-wildcard-imports` configuration flag.\n\n **Known problems:** If macros are imported through the wildcard, this macro is not included\n by the suggestion and has to be added by hand.\n\n Applying the suggestion when explicit imports of the things imported with a glob import\n exist, may result in `unused_imports` warnings.\n\n **Example:**\n\n ```rust,ignore\n // Bad\n use crate1::*;\n\n foo();\n ```\n\n ```rust,ignore\n // Good\n use crate1::foo;\n\n foo();\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "println_empty_string", - "id_span": { - "path": "src/write.rs", - "line": 33 - }, - "group": "clippy::style", - "docs": " **What it does:** This lint warns when you use `println!(\"\")` to print a newline.\n\n **Why is this bad?** You should use `println!()`, which is simpler.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n // Bad\n println!(\"\");\n\n // Good\n println!();\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "print_with_newline", - "id_span": { - "path": "src/write.rs", - "line": 57 - }, - "group": "clippy::style", - "docs": " **What it does:** This lint warns when you use `print!()` with a format string that ends in a newline.\n\n **Why is this bad?** You should use `println!()` instead, which appends the\n newline.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # let name = \"World\";\n print!(\"Hello {}!\\n\", name);\n ```\n use println!() instead\n ```rust\n # let name = \"World\";\n println!(\"Hello {}!\", name);\n ```\n", - "applicability": { - "is_multi_suggestion": true, - "applicability": "MachineApplicable" - } - }, - { - "id": "print_stdout", - "id_span": { - "path": "src/write.rs", - "line": 75 - }, - "group": "clippy::restriction", - "docs": " **What it does:** Checks for printing on *stdout*. The purpose of this lint is to catch debugging remnants.\n\n **Why is this bad?** People often print on *stdout* while debugging an\n application and might forget to remove those prints afterward.\n\n **Known problems:** Only catches `print!` and `println!` calls.\n\n **Example:**\n ```rust\n println!(\"Hello world!\");\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "print_stderr", - "id_span": { - "path": "src/write.rs", - "line": 93 - }, - "group": "clippy::restriction", - "docs": " **What it does:** Checks for printing on *stderr*. The purpose of this lint is to catch debugging remnants.\n\n **Why is this bad?** People often print on *stderr* while debugging an\n application and might forget to remove those prints afterward.\n\n **Known problems:** Only catches `eprint!` and `eprintln!` calls.\n\n **Example:**\n ```rust\n eprintln!(\"Hello world!\");\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "use_debug", - "id_span": { - "path": "src/write.rs", - "line": 110 - }, - "group": "clippy::restriction", - "docs": " **What it does:** Checks for use of `Debug` formatting. The purpose of this lint is to catch debugging remnants.\n\n **Why is this bad?** The purpose of the `Debug` trait is to facilitate\n debugging Rust code. It should not be used in user-facing output.\n\n **Example:**\n ```rust\n # let foo = \"bar\";\n println!(\"{:?}\", foo);\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "print_literal", - "id_span": { - "path": "src/write.rs", - "line": 133 - }, - "group": "clippy::style", - "docs": " **What it does:** This lint warns about the use of literals as `print!`/`println!` args.\n **Why is this bad?** Using literals as `println!` args is inefficient\n (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary\n (i.e., just put the literal in the format string)\n\n **Known problems:** Will also warn with macro calls as arguments that expand to literals\n -- e.g., `println!(\"{}\", env!(\"FOO\"))`.\n\n **Example:**\n ```rust\n println!(\"{}\", \"foo\");\n ```\n use the literal without formatting:\n ```rust\n println!(\"foo\");\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "writeln_empty_string", - "id_span": { - "path": "src/write.rs", - "line": 156 - }, - "group": "clippy::style", - "docs": " **What it does:** This lint warns when you use `writeln!(buf, \"\")` to print a newline.\n\n **Why is this bad?** You should use `writeln!(buf)`, which is simpler.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # use std::fmt::Write;\n # let mut buf = String::new();\n // Bad\n writeln!(buf, \"\");\n\n // Good\n writeln!(buf);\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": "MachineApplicable" - } - }, - { - "id": "write_with_newline", - "id_span": { - "path": "src/write.rs", - "line": 182 - }, - "group": "clippy::style", - "docs": " **What it does:** This lint warns when you use `write!()` with a format string that\n ends in a newline.\n\n **Why is this bad?** You should use `writeln!()` instead, which appends the\n newline.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n # use std::fmt::Write;\n # let mut buf = String::new();\n # let name = \"World\";\n // Bad\n write!(buf, \"Hello {}!\\n\", name);\n\n // Good\n writeln!(buf, \"Hello {}!\", name);\n ```\n", - "applicability": { - "is_multi_suggestion": true, - "applicability": "MachineApplicable" - } - }, - { - "id": "write_literal", - "id_span": { - "path": "src/write.rs", - "line": 207 - }, - "group": "clippy::style", - "docs": " **What it does:** This lint warns about the use of literals as `write!`/`writeln!` args.\n **Why is this bad?** Using literals as `writeln!` args is inefficient\n (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary\n (i.e., just put the literal in the format string)\n\n **Known problems:** Will also warn with macro calls as arguments that expand to literals\n -- e.g., `writeln!(buf, \"{}\", env!(\"FOO\"))`.\n\n **Example:**\n ```rust\n # use std::fmt::Write;\n # let mut buf = String::new();\n // Bad\n writeln!(buf, \"{}\", \"foo\");\n\n // Good\n writeln!(buf, \"foo\");\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "zero_divided_by_zero", - "id_span": { - "path": "src/zero_div_zero.rs", - "line": 23 - }, - "group": "clippy::complexity", - "docs": " **What it does:** Checks for `0.0 / 0.0`.\n **Why is this bad?** It's less readable than `f32::NAN` or `f64::NAN`.\n\n **Known problems:** None.\n\n **Example:**\n ```rust\n // Bad\n let nan = 0.0f32 / 0.0;\n\n // Good\n let nan = f32::NAN;\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - }, - { - "id": "zero_sized_map_values", - "id_span": { - "path": "src/zero_sized_map_values.rs", - "line": 37 - }, - "group": "clippy::pedantic", - "docs": " **What it does:** Checks for maps with zero-sized value types anywhere in the code.\n **Why is this bad?** Since there is only a single value for a zero-sized type, a map\n containing zero sized values is effectively a set. Using a set in that case improves\n readability and communicates intent more clearly.\n\n **Known problems:**\n * A zero-sized type cannot be recovered later if it contains private fields.\n * This lints the signature of public items\n\n **Example:**\n\n ```rust\n # use std::collections::HashMap;\n fn unique_words(text: &str) -> HashMap<&str, ()> {\n todo!();\n }\n ```\n Use instead:\n ```rust\n # use std::collections::HashSet;\n fn unique_words(text: &str) -> HashSet<&str> {\n todo!();\n }\n ```\n", - "applicability": { - "is_multi_suggestion": false, - "applicability": null - } - } -] diff --git a/tests/dogfood.rs b/tests/dogfood.rs index b0da0bfcc35..604968ad8b0 100644 --- a/tests/dogfood.rs +++ b/tests/dogfood.rs @@ -41,10 +41,6 @@ fn dogfood_clippy() { command.args(&["-D", "clippy::internal"]); } - if cfg!(feature = "metadata-collector-lint") { - command.args(&["-D", "clippy::internal"]); - } - let output = command.output().unwrap(); println!("status: {}", output.status); diff --git a/tests/ui-internal/metadata-collector/track_applicability_value.rs b/tests/ui-internal/metadata-collector/track_applicability_value.rs deleted file mode 100644 index b0f59e5cf8a..00000000000 --- a/tests/ui-internal/metadata-collector/track_applicability_value.rs +++ /dev/null @@ -1,50 +0,0 @@ -#![deny(clippy::internal)] -#![feature(rustc_private)] - -extern crate rustc_ast; -extern crate rustc_errors; -extern crate rustc_lint; -extern crate rustc_session; -extern crate rustc_span; - -use rustc_ast::ast::Expr; -use rustc_errors::{Applicability, DiagnosticBuilder}; -use rustc_lint::{EarlyContext, EarlyLintPass, Lint, LintContext}; -use rustc_session::{declare_lint_pass, declare_tool_lint}; -use rustc_span::source_map::Span; - -fn producer_fn() -> Applicability { - Applicability::MachineApplicable -} - -fn modifier_fn(applicability: &mut Applicability) { - if let Applicability::MaybeIncorrect = applicability { - *applicability = Applicability::HasPlaceholders; - } -} - -fn consumer_fn(_applicability: Applicability) {} - -struct Muh; - -impl Muh { - fn producer_method() -> Applicability { - Applicability::MachineApplicable - } -} - -fn main() { - let mut applicability = producer_fn(); - applicability = Applicability::MachineApplicable; - applicability = Muh::producer_method(); - - applicability = if true { - Applicability::HasPlaceholders - } else { - Applicability::MaybeIncorrect - }; - - modifier_fn(&mut applicability); - - consumer_fn(applicability); -} From c1fa1102d484b74cb7bc425994fa4246dd690ad3 Mon Sep 17 00:00:00 2001 From: xFrednet Date: Fri, 12 Mar 2021 21:52:01 +0100 Subject: [PATCH 13/15] ENABLE_METADATA_COLLECTION env-value to disable default metadata collection --- clippy_lints/src/lib.rs | 6 +++++- .../utils/internal_lints/metadata_collector.rs | 18 ------------------ tests/dogfood.rs | 2 ++ 3 files changed, 7 insertions(+), 19 deletions(-) diff --git a/clippy_lints/src/lib.rs b/clippy_lints/src/lib.rs index 7668d4dd0b1..1a74f641554 100644 --- a/clippy_lints/src/lib.rs +++ b/clippy_lints/src/lib.rs @@ -1005,7 +1005,11 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: store.register_late_pass(|| box utils::internal_lints::OuterExpnDataPass); } #[cfg(feature = "metadata-collector-lint")] - store.register_late_pass(|| box utils::internal_lints::metadata_collector::MetadataCollector::default()); + { + if std::env::var("ENABLE_METADATA_COLLECTION").eq(&Ok("1".to_string())) { + store.register_late_pass(|| box utils::internal_lints::metadata_collector::MetadataCollector::default()); + } + } store.register_late_pass(|| box utils::author::Author); store.register_late_pass(|| box await_holding_invalid::AwaitHolding); diff --git a/clippy_lints/src/utils/internal_lints/metadata_collector.rs b/clippy_lints/src/utils/internal_lints/metadata_collector.rs index 37e90bf8686..07abae31386 100644 --- a/clippy_lints/src/utils/internal_lints/metadata_collector.rs +++ b/clippy_lints/src/utils/internal_lints/metadata_collector.rs @@ -148,24 +148,6 @@ struct LintMetadata { applicability: Option, } -// impl Ord for LintMetadata { -// fn cmp(&self, other: &Self) -> Ordering { -// self.id.cmp(&other.id) -// } -// } -// -// impl PartialOrd for LintMetadata { -// fn partial_cmp(&self, other: &Self) -> Option { -// Some(self.cmp(other)) -// } -// } -// -// impl PartialEq for LintMetadata { -// fn eq(&self, other: &Self) -> bool { -// self.id == other.id -// } -// } - impl LintMetadata { fn new(id: String, id_span: SerializableSpan, group: String, docs: String) -> Self { Self { diff --git a/tests/dogfood.rs b/tests/dogfood.rs index 604968ad8b0..6524fd4706c 100644 --- a/tests/dogfood.rs +++ b/tests/dogfood.rs @@ -22,12 +22,14 @@ fn dogfood_clippy() { return; } let root_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + let enable_metadata_collection = std::env::var("ENABLE_METADATA_COLLECTION").unwrap_or_else(|_| "0".to_string()); let mut command = Command::new(&*CLIPPY_PATH); command .current_dir(root_dir) .env("CLIPPY_DOGFOOD", "1") .env("CARGO_INCREMENTAL", "0") + .env("ENABLE_METADATA_COLLECTION", &enable_metadata_collection) .arg("clippy") .arg("--all-targets") .arg("--all-features") From 62cafe2c02440cb1cc7cc9cbf1abe63942a19e51 Mon Sep 17 00:00:00 2001 From: xFrednet Date: Fri, 12 Mar 2021 20:59:41 +0100 Subject: [PATCH 14/15] Applying PR suggestions --- .../src/utils/internal_lints/metadata_collector.rs | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/clippy_lints/src/utils/internal_lints/metadata_collector.rs b/clippy_lints/src/utils/internal_lints/metadata_collector.rs index 07abae31386..b7bb557f957 100644 --- a/clippy_lints/src/utils/internal_lints/metadata_collector.rs +++ b/clippy_lints/src/utils/internal_lints/metadata_collector.rs @@ -32,7 +32,7 @@ }; /// This is the output file of the lint collector. -const OUTPUT_FILE: &str = "../metadata_collection.json"; +const OUTPUT_FILE: &str = "../util/gh-pages/metadata_collection.json"; /// These lints are excluded from the export. const BLACK_LISTED_LINTS: [&str; 3] = ["lint_author", "deep_code_inspection", "internal_metadata_collector"]; /// These groups will be ignored by the lint group matcher. This is useful for collections like @@ -62,7 +62,7 @@ ("span_suggestions", true), ]; const SUGGESTION_FUNCTIONS: [&[&str]; 2] = [ - &["clippy_utils", "diagnostics", "mutispan_sugg"], + &["clippy_utils", "diagnostics", "multispan_sugg"], &["clippy_utils", "diagnostics", "multispan_sugg_with_applicability"], ]; @@ -226,11 +226,8 @@ impl<'hir> LateLintPass<'hir> for MetadataCollector { fn check_item(&mut self, cx: &LateContext<'hir>, item: &'hir Item<'_>) { if_chain! { // item validation - if let ItemKind::Static(ref ty, Mutability::Not, body_id) = item.kind; + if let ItemKind::Static(ref ty, Mutability::Not, _) = item.kind; if is_lint_ref_type(cx, ty); - let expr = &cx.tcx.hir().body(body_id).value; - if let ExprKind::AddrOf(_, _, ref inner_exp) = expr.kind; - if let ExprKind::Struct(_, _, _) = inner_exp.kind; // blacklist check let lint_name = sym_to_string(item.ident.name).to_ascii_lowercase(); if !BLACK_LISTED_LINTS.contains(&lint_name.as_str()); From e0eb29c936602553f7952a4d12c7d193bc3a7513 Mon Sep 17 00:00:00 2001 From: xFrednet Date: Wed, 31 Mar 2021 20:03:38 +0200 Subject: [PATCH 15/15] Applying PR suggestions (mostly typos) Co-authored-by: flip1995 Co-authored-by: phansch --- Cargo.toml | 2 +- .../internal_lints/metadata_collector.rs | 19 ++++++++++--------- clippy_utils/src/diagnostics.rs | 8 ++++++++ 3 files changed, 19 insertions(+), 10 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index bdee8e40821..23a035f9715 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -52,7 +52,7 @@ rustc_tools_util = { version = "0.2.0", path = "rustc_tools_util" } deny-warnings = [] integration = ["tempfile"] internal-lints = ["clippy_lints/internal-lints"] -metadata-collector-lint = ["clippy_lints/metadata-collector-lint"] +metadata-collector-lint = ["internal-lints", "clippy_lints/metadata-collector-lint"] [package.metadata.rust-analyzer] # This package uses #[feature(rustc_private)] diff --git a/clippy_lints/src/utils/internal_lints/metadata_collector.rs b/clippy_lints/src/utils/internal_lints/metadata_collector.rs index b7bb557f957..e85637ca758 100644 --- a/clippy_lints/src/utils/internal_lints/metadata_collector.rs +++ b/clippy_lints/src/utils/internal_lints/metadata_collector.rs @@ -27,8 +27,9 @@ use std::path::Path; use crate::utils::internal_lints::is_lint_ref_type; -use crate::utils::{ - last_path_segment, match_function_call, match_path, match_type, paths, span_lint, walk_ptrs_ty_depth, +use clippy_utils::{ + diagnostics::span_lint, last_path_segment, match_function_call, match_path, paths, ty::match_type, + ty::walk_ptrs_ty_depth, }; /// This is the output file of the lint collector. @@ -107,7 +108,7 @@ pub struct MetadataCollector { /// /// We use a Heap here to have the lints added in alphabetic order in the export lints: BinaryHeap, - applicability_into: FxHashMap, + applicability_info: FxHashMap, } impl Drop for MetadataCollector { @@ -120,7 +121,7 @@ fn drop(&mut self) { return; } - let mut applicability_info = std::mem::take(&mut self.applicability_into); + let mut applicability_info = std::mem::take(&mut self.applicability_info); // Mapping the final data let mut lints = std::mem::take(&mut self.lints).into_sorted_vec(); @@ -272,7 +273,7 @@ fn check_expr(&mut self, cx: &LateContext<'hir>, expr: &'hir hir::Expr<'_>) { } for (lint_name, applicability, is_multi_part) in emission_info.drain(..) { - let app_info = self.applicability_into.entry(lint_name).or_default(); + let app_info = self.applicability_info.entry(lint_name).or_default(); app_info.applicability = applicability; app_info.is_multi_part_suggestion = is_multi_part; } @@ -354,7 +355,7 @@ fn lint_collection_error_item(cx: &LateContext<'_>, item: &Item<'_>, message: &s cx, INTERNAL_METADATA_COLLECTOR, item.ident.span, - &format!("Metadata collection error for `{}`: {}", item.ident.name, message), + &format!("metadata collection error for `{}`: {}", item.ident.name, message), ); } @@ -569,7 +570,7 @@ fn new(cx: &'a LateContext<'hir>) -> Self { } /// Add a new single expression suggestion to the counter - fn add_singe_span_suggestion(&mut self) { + fn add_single_span_suggestion(&mut self) { self.suggestion_count += 1; } @@ -604,7 +605,7 @@ fn visit_expr(&mut self, expr: &'hir hir::Expr<'hir>) { .any(|func_path| match_function_call(self.cx, fn_expr, func_path).is_some()); if found_function { // These functions are all multi part suggestions - self.add_singe_span_suggestion() + self.add_single_span_suggestion() } }, ExprKind::MethodCall(path, _path_span, arg, _arg_span) => { @@ -616,7 +617,7 @@ fn visit_expr(&mut self, expr: &'hir hir::Expr<'hir>) { if *is_multi_part { self.add_multi_part_suggestion(); } else { - self.add_singe_span_suggestion(); + self.add_single_span_suggestion(); } break; } diff --git a/clippy_utils/src/diagnostics.rs b/clippy_utils/src/diagnostics.rs index 7f827f1759d..a4efae54894 100644 --- a/clippy_utils/src/diagnostics.rs +++ b/clippy_utils/src/diagnostics.rs @@ -1,4 +1,12 @@ //! Clippy wrappers around rustc's diagnostic functions. +//! +//! These functions are used by the `INTERNAL_METADATA_COLLECTOR` lint to collect the corresponding +//! lint applicability. Please make sure that you update the `LINT_EMISSION_FUNCTIONS` variable in +//! `clippy_lints::utils::internal_lints::metadata_collector` when a new function is added +//! or renamed. +//! +//! Thank you! +//! ~The `INTERNAL_METADATA_COLLECTOR` lint use rustc_errors::{Applicability, DiagnosticBuilder}; use rustc_hir::HirId;