Refactor for using config values:

* Construct lint passes by taking `Conf` by reference.
* Use `HashSet` configs in less places
* Move some `check_crate` code into the pass constructor when possible.
This commit is contained in:
Jason Newcomb 2024-07-12 00:00:03 -04:00
parent 0ee9f44568
commit e34c6dbae5
115 changed files with 824 additions and 994 deletions

View file

@ -458,9 +458,8 @@ pub struct ManualStrip {
}
impl ManualStrip {
#[must_use]
pub fn new(msrv: Msrv) -> Self {
Self { msrv }
pub fn new(conf: &'static Conf) -> Self {
Self { msrv: conf.msrv.clone() }
}
}
```
@ -689,7 +688,6 @@ for some users. Adding a configuration is done in the following steps:
]);
// New manual definition struct
#[derive(Copy, Clone)]
pub struct StructName {}
impl_lint_pass!(StructName => [
@ -700,7 +698,6 @@ for some users. Adding a configuration is done in the following steps:
2. Next add the configuration value and a corresponding creation method like
this:
```rust
#[derive(Copy, Clone)]
pub struct StructName {
configuration_ident: Type,
}
@ -708,9 +705,9 @@ for some users. Adding a configuration is done in the following steps:
// ...
impl StructName {
pub fn new(configuration_ident: Type) -> Self {
pub fn new(conf: &'static Conf) -> Self {
Self {
configuration_ident,
configuration_ident: conf.configuration_ident,
}
}
}
@ -726,8 +723,7 @@ for some users. Adding a configuration is done in the following steps:
store.register_*_pass(|| box module::StructName);
// New registration with configuration value
let configuration_ident = conf.configuration_ident.clone();
store.register_*_pass(move || box module::StructName::new(configuration_ident));
store.register_*_pass(move || box module::StructName::new(conf));
```
Congratulations the work is almost done. The configuration value can now be

View file

@ -455,7 +455,7 @@ default configuration of Clippy. By default, any configuration will replace the
* `doc-valid-idents = ["ClipPy"]` would replace the default list with `["ClipPy"]`.
* `doc-valid-idents = ["ClipPy", ".."]` would append `ClipPy` to the default list.
**Default Value:** `["KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "AccessKit", "CoreFoundation", "CoreGraphics", "CoreText", "DevOps", "Direct2D", "Direct3D", "DirectWrite", "DirectX", "ECMAScript", "GPLv2", "GPLv3", "GitHub", "GitLab", "IPv4", "IPv6", "ClojureScript", "CoffeeScript", "JavaScript", "PostScript", "PureScript", "TypeScript", "WebAssembly", "NaN", "NaNs", "OAuth", "GraphQL", "OCaml", "OpenAL", "OpenDNS", "OpenGL", "OpenMP", "OpenSSH", "OpenSSL", "OpenStreetMap", "OpenTelemetry", "OpenType", "WebGL", "WebGL2", "WebGPU", "WebRTC", "WebSocket", "WebTransport", "WebP", "OpenExr", "YCbCr", "sRGB", "TensorFlow", "TrueType", "iOS", "macOS", "FreeBSD", "NetBSD", "OpenBSD", "TeX", "LaTeX", "BibTeX", "BibLaTeX", "MinGW", "CamelCase"]`
**Default Value:** `["TiB", "CoreGraphics", "CoffeeScript", "TeX", "Direct2D", "PiB", "DirectX", "NetBSD", "OAuth", "NaN", "OpenType", "WebGL2", "WebTransport", "JavaScript", "OpenSSL", "OpenSSH", "EiB", "PureScript", "OpenAL", "MiB", "WebAssembly", "MinGW", "CoreFoundation", "WebGPU", "ClojureScript", "CamelCase", "OpenDNS", "NaNs", "OpenMP", "GitLab", "KiB", "sRGB", "CoreText", "macOS", "TypeScript", "GiB", "OpenExr", "YCbCr", "OpenTelemetry", "OpenBSD", "FreeBSD", "GPLv2", "PostScript", "WebP", "LaTeX", "TensorFlow", "AccessKit", "TrueType", "OpenStreetMap", "OpenGL", "DevOps", "OCaml", "WebRTC", "WebGL", "BibLaTeX", "GitHub", "GraphQL", "iOS", "Direct3D", "BibTeX", "DirectWrite", "GPLv3", "IPv6", "WebSocket", "IPv4", "ECMAScript"]`
---
**Affected lints:**

View file

@ -238,7 +238,7 @@ define_Conf! {
///
/// A type, say `SomeType`, listed in this configuration has the same behavior of
/// `["SomeType" , "*"], ["*", "SomeType"]` in `arithmetic_side_effects_allowed_binary`.
(arithmetic_side_effects_allowed: FxHashSet<String> = <_>::default()),
(arithmetic_side_effects_allowed: Vec<String> = <_>::default()),
/// Lint: ARITHMETIC_SIDE_EFFECTS.
///
/// Suppress checking of the passed type pair names in binary operations like addition or
@ -265,7 +265,7 @@ define_Conf! {
/// ```toml
/// arithmetic-side-effects-allowed-unary = ["SomeType", "AnotherType"]
/// ```
(arithmetic_side_effects_allowed_unary: FxHashSet<String> = <_>::default()),
(arithmetic_side_effects_allowed_unary: Vec<String> = <_>::default()),
/// Lint: ENUM_VARIANT_NAMES, LARGE_TYPES_PASSED_BY_VALUE, TRIVIALLY_COPY_PASS_BY_REF, UNNECESSARY_WRAPS, UNUSED_SELF, UPPER_CASE_ACRONYMS, WRONG_SELF_CONVENTION, BOX_COLLECTION, REDUNDANT_ALLOCATION, RC_BUFFER, VEC_BOX, OPTION_OPTION, LINKEDLIST, RC_MUTEX, UNNECESSARY_BOX_RETURNS, SINGLE_CALL_FN, NEEDLESS_PASS_BY_REF_MUT.
///
/// Suppress lints whenever the suggested change would cause breakage for other crates.
@ -314,7 +314,7 @@ define_Conf! {
/// default configuration of Clippy. By default, any configuration will replace the default value. For example:
/// * `doc-valid-idents = ["ClipPy"]` would replace the default list with `["ClipPy"]`.
/// * `doc-valid-idents = ["ClipPy", ".."]` would append `ClipPy` to the default list.
(doc_valid_idents: Vec<String> = DEFAULT_DOC_VALID_IDENTS.iter().map(ToString::to_string).collect()),
(doc_valid_idents: FxHashSet<String> = DEFAULT_DOC_VALID_IDENTS.iter().map(ToString::to_string).collect()),
/// Lint: TOO_MANY_ARGUMENTS.
///
/// The maximum number of argument a function or method can have
@ -550,7 +550,7 @@ define_Conf! {
/// Lint: PATH_ENDS_WITH_EXT.
///
/// Additional dotfiles (files or directories starting with a dot) to allow
(allowed_dotfiles: FxHashSet<String> = FxHashSet::default()),
(allowed_dotfiles: Vec<String> = Vec::default()),
/// Lint: MULTIPLE_CRATE_VERSIONS.
///
/// A list of crate names to allow duplicates of
@ -703,7 +703,6 @@ pub fn lookup_conf_file() -> io::Result<(Option<PathBuf>, Vec<String>)> {
fn deserialize(file: &SourceFile) -> TryConf {
match toml::de::Deserializer::new(file.src.as_ref().unwrap()).deserialize_map(ConfVisitor(file)) {
Ok(mut conf) => {
extend_vec_if_indicator_present(&mut conf.conf.doc_valid_idents, DEFAULT_DOC_VALID_IDENTS);
extend_vec_if_indicator_present(&mut conf.conf.disallowed_names, DEFAULT_DISALLOWED_NAMES);
extend_vec_if_indicator_present(&mut conf.conf.allowed_prefixes, DEFAULT_ALLOWED_PREFIXES);
extend_vec_if_indicator_present(
@ -716,6 +715,11 @@ fn deserialize(file: &SourceFile) -> TryConf {
.allowed_idents_below_min_chars
.extend(DEFAULT_ALLOWED_IDENTS_BELOW_MIN_CHARS.iter().map(ToString::to_string));
}
if conf.conf.doc_valid_idents.contains("..") {
conf.conf
.doc_valid_idents
.extend(DEFAULT_DOC_VALID_IDENTS.iter().map(ToString::to_string));
}
conf
},

View file

@ -2,13 +2,13 @@ use serde::de::{self, Deserializer, Visitor};
use serde::{ser, Deserialize, Serialize};
use std::fmt;
#[derive(Clone, Debug, Deserialize)]
#[derive(Debug, Deserialize)]
pub struct Rename {
pub path: String,
pub rename: String,
}
#[derive(Clone, Debug, Deserialize)]
#[derive(Debug, Deserialize)]
#[serde(untagged)]
pub enum DisallowedPath {
Simple(String),
@ -22,12 +22,10 @@ impl DisallowedPath {
path
}
pub fn reason(&self) -> Option<String> {
match self {
Self::WithReason {
reason: Some(reason), ..
} => Some(format!("{reason} (from clippy.toml)")),
_ => None,
pub fn reason(&self) -> Option<&str> {
match &self {
Self::WithReason { reason, .. } => reason.as_deref(),
Self::Simple(_) => None,
}
}
}

View file

@ -140,7 +140,7 @@ fn add_lint(lint: &LintData<'_>, enable_msrv: bool) -> io::Result<()> {
let new_lint = if enable_msrv {
format!(
"store.register_{lint_pass}_pass(move |{ctor_arg}| Box::new({module_name}::{camel_name}::new(msrv())));\n ",
"store.register_{lint_pass}_pass(move |{ctor_arg}| Box::new({module_name}::{camel_name}::new(conf)));\n ",
lint_pass = lint.pass,
ctor_arg = if lint.pass == "late" { "_" } else { "" },
module_name = lint.name,
@ -274,6 +274,7 @@ fn get_lint_file_contents(lint: &LintData<'_>, enable_msrv: bool) -> String {
formatdoc!(
r#"
use clippy_config::msrvs::{{self, Msrv}};
use clippy_config::Conf;
{pass_import}
use rustc_lint::{{{context_import}, {pass_type}, LintContext}};
use rustc_session::impl_lint_pass;
@ -301,9 +302,8 @@ fn get_lint_file_contents(lint: &LintData<'_>, enable_msrv: bool) -> String {
}}
impl {name_camel} {{
#[must_use]
pub fn new(msrv: Msrv) -> Self {{
Self {{ msrv }}
pub fn new(conf: &'static Conf) -> Self {{
Self {{ msrv: conf.msrv.clone() }}
}}
}}

View file

@ -1,3 +1,4 @@
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint;
use clippy_utils::source::snippet_opt;
use rustc_data_structures::fx::FxHashSet;
@ -47,7 +48,16 @@ impl_lint_pass!(AbsolutePaths => [ABSOLUTE_PATHS]);
pub struct AbsolutePaths {
pub absolute_paths_max_segments: u64,
pub absolute_paths_allowed_crates: FxHashSet<String>,
pub absolute_paths_allowed_crates: &'static FxHashSet<String>,
}
impl AbsolutePaths {
pub fn new(conf: &'static Conf) -> Self {
Self {
absolute_paths_max_segments: conf.absolute_paths_max_segments,
absolute_paths_allowed_crates: &conf.absolute_paths_allowed_crates,
}
}
}
impl LateLintPass<'_> for AbsolutePaths {

View file

@ -1,4 +1,5 @@
use clippy_config::msrvs::{self, Msrv};
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::source::{trim_span, walk_span_to_context};
use rustc_ast::ast::{Expr, ExprKind, LitKind, Pat, PatKind, RangeEnd, RangeLimits};
@ -34,8 +35,10 @@ pub struct AlmostCompleteRange {
msrv: Msrv,
}
impl AlmostCompleteRange {
pub fn new(msrv: Msrv) -> Self {
Self { msrv }
pub fn new(conf: &'static Conf) -> Self {
Self {
msrv: conf.msrv.clone(),
}
}
}
impl EarlyLintPass for AlmostCompleteRange {

View file

@ -1,4 +1,5 @@
use clippy_config::msrvs::{self, Msrv};
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_and_help;
use rustc_ast::ast::{FloatTy, LitFloatType, LitKind};
use rustc_hir::{Expr, ExprKind};
@ -67,9 +68,10 @@ pub struct ApproxConstant {
}
impl ApproxConstant {
#[must_use]
pub fn new(msrv: Msrv) -> Self {
Self { msrv }
pub fn new(conf: &'static Conf) -> Self {
Self {
msrv: conf.msrv.clone(),
}
}
fn check_lit(&self, cx: &LateContext<'_>, lit: &LitKind, e: &Expr<'_>) {

View file

@ -1,4 +1,5 @@
use clippy_config::msrvs::{self, Msrv};
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::mir::{enclosing_mir, PossibleBorrowerMap};
use clippy_utils::sugg::Sugg;
@ -57,9 +58,10 @@ pub struct AssigningClones {
}
impl AssigningClones {
#[must_use]
pub fn new(msrv: Msrv) -> Self {
Self { msrv }
pub fn new(conf: &'static Conf) -> Self {
Self {
msrv: conf.msrv.clone(),
}
}
}

View file

@ -16,6 +16,7 @@ mod useless_attribute;
mod utils;
use clippy_config::msrvs::{self, Msrv};
use clippy_config::Conf;
use rustc_ast::{Attribute, MetaItemKind, NestedMetaItem};
use rustc_hir::{ImplItem, Item, ItemKind, TraitItem};
use rustc_lint::{EarlyContext, EarlyLintPass, LateContext, LateLintPass};
@ -499,7 +500,6 @@ declare_clippy_lint! {
"duplicated attribute"
}
#[derive(Clone)]
pub struct Attributes {
msrv: Msrv,
}
@ -517,9 +517,10 @@ impl_lint_pass!(Attributes => [
]);
impl Attributes {
#[must_use]
pub fn new(msrv: Msrv) -> Self {
Self { msrv }
pub fn new(conf: &'static Conf) -> Self {
Self {
msrv: conf.msrv.clone(),
}
}
}
@ -589,7 +590,15 @@ impl<'tcx> LateLintPass<'tcx> for Attributes {
}
pub struct EarlyAttributes {
pub msrv: Msrv,
msrv: Msrv,
}
impl EarlyAttributes {
pub fn new(conf: &'static Conf) -> Self {
Self {
msrv: conf.msrv.clone(),
}
}
}
impl_lint_pass!(EarlyAttributes => [

View file

@ -1,11 +1,11 @@
use clippy_config::types::DisallowedPath;
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::{match_def_path, paths};
use rustc_data_structures::fx::FxHashMap;
use clippy_utils::{create_disallowed_map, match_def_path, paths};
use rustc_hir as hir;
use rustc_hir::def_id::DefId;
use rustc_hir::def_id::{DefId, DefIdMap};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::mir::CoroutineLayout;
use rustc_middle::ty::TyCtxt;
use rustc_session::impl_lint_pass;
use rustc_span::{sym, Span};
@ -172,31 +172,19 @@ declare_clippy_lint! {
impl_lint_pass!(AwaitHolding => [AWAIT_HOLDING_LOCK, AWAIT_HOLDING_REFCELL_REF, AWAIT_HOLDING_INVALID_TYPE]);
#[derive(Debug)]
pub struct AwaitHolding {
conf_invalid_types: Vec<DisallowedPath>,
def_ids: FxHashMap<DefId, DisallowedPath>,
def_ids: DefIdMap<(&'static str, Option<&'static str>)>,
}
impl AwaitHolding {
pub(crate) fn new(conf_invalid_types: Vec<DisallowedPath>) -> Self {
pub(crate) fn new(tcx: TyCtxt<'_>, conf: &'static Conf) -> Self {
Self {
conf_invalid_types,
def_ids: FxHashMap::default(),
def_ids: create_disallowed_map(tcx, &conf.await_holding_invalid_types),
}
}
}
impl<'tcx> LateLintPass<'tcx> for AwaitHolding {
fn check_crate(&mut self, cx: &LateContext<'tcx>) {
for conf in &self.conf_invalid_types {
let segs: Vec<_> = conf.path().split("::").collect();
for id in clippy_utils::def_path_def_ids(cx, &segs) {
self.def_ids.insert(id, conf.clone());
}
}
}
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) {
if let hir::ExprKind::Closure(hir::Closure {
kind: hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)),
@ -258,25 +246,22 @@ impl AwaitHolding {
);
},
);
} else if let Some(disallowed) = self.def_ids.get(&adt.did()) {
emit_invalid_type(cx, ty_cause.source_info.span, disallowed);
} else if let Some(&(path, reason)) = self.def_ids.get(&adt.did()) {
emit_invalid_type(cx, ty_cause.source_info.span, path, reason);
}
}
}
}
}
fn emit_invalid_type(cx: &LateContext<'_>, span: Span, disallowed: &DisallowedPath) {
fn emit_invalid_type(cx: &LateContext<'_>, span: Span, path: &'static str, reason: Option<&'static str>) {
span_lint_and_then(
cx,
AWAIT_HOLDING_INVALID_TYPE,
span,
format!(
"`{}` may not be held across an await point per `clippy.toml`",
disallowed.path()
),
format!("holding a disallowed type across an await point `{path}`"),
|diag| {
if let Some(reason) = disallowed.reason() {
if let Some(reason) = reason {
diag.note(reason);
}
},

View file

@ -5,6 +5,7 @@ mod multiple_crate_versions;
mod wildcard_dependencies;
use cargo_metadata::MetadataCommand;
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint;
use clippy_utils::is_lint_allowed;
use rustc_data_structures::fx::FxHashSet;
@ -204,8 +205,8 @@ declare_clippy_lint! {
}
pub struct Cargo {
pub allowed_duplicate_crates: FxHashSet<String>,
pub ignore_publish: bool,
allowed_duplicate_crates: &'static FxHashSet<String>,
ignore_publish: bool,
}
impl_lint_pass!(Cargo => [
@ -217,6 +218,15 @@ impl_lint_pass!(Cargo => [
LINT_GROUPS_PRIORITY,
]);
impl Cargo {
pub fn new(conf: &'static Conf) -> Self {
Self {
allowed_duplicate_crates: &conf.allowed_duplicate_crates,
ignore_publish: conf.cargo_ignore_publish,
}
}
}
impl LateLintPass<'_> for Cargo {
fn check_crate(&mut self, cx: &LateContext<'_>) {
static NO_DEPS_LINTS: &[&Lint] = &[
@ -253,7 +263,7 @@ impl LateLintPass<'_> for Cargo {
{
match MetadataCommand::new().exec() {
Ok(metadata) => {
multiple_crate_versions::check(cx, &metadata, &self.allowed_duplicate_crates);
multiple_crate_versions::check(cx, &metadata, self.allowed_duplicate_crates);
},
Err(e) => {
for lint in WITH_DEPS_LINTS {

View file

@ -24,6 +24,7 @@ mod utils;
mod zero_ptr;
use clippy_config::msrvs::{self, Msrv};
use clippy_config::Conf;
use clippy_utils::is_hir_ty_cfg_dependant;
use rustc_hir::{Expr, ExprKind};
use rustc_lint::{LateContext, LateLintPass, LintContext};
@ -722,9 +723,10 @@ pub struct Casts {
}
impl Casts {
#[must_use]
pub fn new(msrv: Msrv) -> Self {
Self { msrv }
pub fn new(conf: &'static Conf) -> Self {
Self {
msrv: conf.msrv.clone(),
}
}
}

View file

@ -1,6 +1,7 @@
//! lint on manually implemented checked conversions that could be transformed into `try_from`
use clippy_config::msrvs::{self, Msrv};
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::source::snippet_with_applicability;
use clippy_utils::{in_constant, is_integer_literal, SpanlessEq};
@ -40,9 +41,10 @@ pub struct CheckedConversions {
}
impl CheckedConversions {
#[must_use]
pub fn new(msrv: Msrv) -> Self {
Self { msrv }
pub fn new(conf: &'static Conf) -> Self {
Self {
msrv: conf.msrv.clone(),
}
}
}

View file

@ -1,5 +1,6 @@
//! calculate cognitive complexity and warn about overly complex functions
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_and_help;
use clippy_utils::source::{IntoSpan, SpanRangeExt};
use clippy_utils::ty::is_type_diagnostic_item;
@ -39,10 +40,9 @@ pub struct CognitiveComplexity {
}
impl CognitiveComplexity {
#[must_use]
pub fn new(limit: u64) -> Self {
pub fn new(conf: &'static Conf) -> Self {
Self {
limit: LimitStack::new(limit),
limit: LimitStack::new(conf.cognitive_complexity_threshold),
}
}
}

View file

@ -1,3 +1,4 @@
use clippy_config::Conf;
use clippy_utils::diagnostics::{span_lint_and_note, span_lint_and_then};
use clippy_utils::source::{first_line_of_span, indent_of, reindent_multiline, snippet, IntoSpan, SpanRangeExt};
use clippy_utils::ty::{needs_ordered_drop, InteriorMut};
@ -11,6 +12,7 @@ use core::ops::ControlFlow;
use rustc_errors::Applicability;
use rustc_hir::{intravisit, BinOpKind, Block, Expr, ExprKind, HirId, HirIdSet, Stmt, StmtKind};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::ty::TyCtxt;
use rustc_session::impl_lint_pass;
use rustc_span::hygiene::walk_chain;
use rustc_span::source_map::SourceMap;
@ -159,15 +161,13 @@ declare_clippy_lint! {
}
pub struct CopyAndPaste<'tcx> {
ignore_interior_mutability: Vec<String>,
interior_mut: InteriorMut<'tcx>,
}
impl CopyAndPaste<'_> {
pub fn new(ignore_interior_mutability: Vec<String>) -> Self {
impl<'tcx> CopyAndPaste<'tcx> {
pub fn new(tcx: TyCtxt<'tcx>, conf: &'static Conf) -> Self {
Self {
ignore_interior_mutability,
interior_mut: InteriorMut::default(),
interior_mut: InteriorMut::new(tcx, &conf.ignore_interior_mutability),
}
}
}
@ -180,10 +180,6 @@ impl_lint_pass!(CopyAndPaste<'_> => [
]);
impl<'tcx> LateLintPass<'tcx> for CopyAndPaste<'tcx> {
fn check_crate(&mut self, cx: &LateContext<'tcx>) {
self.interior_mut = InteriorMut::new(cx, &self.ignore_interior_mutability);
}
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
if !expr.span.from_expansion() && matches!(expr.kind, ExprKind::If(..)) && !is_else_clause(cx.tcx, expr) {
let (conds, blocks) = if_sequence(expr);

View file

@ -1,3 +1,4 @@
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::is_in_test;
use clippy_utils::macros::{macro_backtrace, MacroCall};
@ -33,7 +34,6 @@ declare_clippy_lint! {
"`dbg!` macro is intended as a debugging tool"
}
#[derive(Clone)]
pub struct DbgMacro {
allow_dbg_in_tests: bool,
/// Tracks the `dbg!` macro callsites that are already checked.
@ -45,9 +45,9 @@ pub struct DbgMacro {
impl_lint_pass!(DbgMacro => [DBG_MACRO]);
impl DbgMacro {
pub fn new(allow_dbg_in_tests: bool) -> Self {
pub fn new(conf: &'static Conf) -> Self {
DbgMacro {
allow_dbg_in_tests,
allow_dbg_in_tests: conf.allow_dbg_in_tests,
checked_dbg_call_site: FxHashSet::default(),
prev_ctxt: SyntaxContext::root(),
}

View file

@ -1,4 +1,5 @@
use clippy_config::msrvs::{self, Msrv};
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::source::indent_of;
use clippy_utils::{is_default_equivalent, peel_blocks};
@ -60,9 +61,10 @@ pub struct DerivableImpls {
}
impl DerivableImpls {
#[must_use]
pub fn new(msrv: Msrv) -> Self {
DerivableImpls { msrv }
pub fn new(conf: &'static Conf) -> Self {
DerivableImpls {
msrv: conf.msrv.clone(),
}
}
}

View file

@ -1,4 +1,5 @@
use clippy_config::types::DisallowedPath;
use clippy_config::Conf;
use clippy_utils::create_disallowed_map;
use clippy_utils::diagnostics::{span_lint_and_then, span_lint_hir_and_then};
use clippy_utils::macros::macro_backtrace;
use rustc_ast::Attribute;
@ -9,6 +10,7 @@ use rustc_hir::{
Expr, ExprKind, ForeignItem, HirId, ImplItem, Item, ItemKind, OwnerId, Pat, Path, Stmt, TraitItem, Ty,
};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::ty::TyCtxt;
use rustc_session::impl_lint_pass;
use rustc_span::{ExpnId, MacroKind, Span};
@ -57,27 +59,24 @@ declare_clippy_lint! {
}
pub struct DisallowedMacros {
conf_disallowed: Vec<DisallowedPath>,
disallowed: DefIdMap<usize>,
disallowed: DefIdMap<(&'static str, Option<&'static str>)>,
seen: FxHashSet<ExpnId>,
// Track the most recently seen node that can have a `derive` attribute.
// Needed to use the correct lint level.
derive_src: Option<OwnerId>,
}
impl DisallowedMacros {
pub fn new(conf_disallowed: Vec<DisallowedPath>) -> Self {
pub fn new(tcx: TyCtxt<'_>, conf: &'static Conf) -> Self {
Self {
conf_disallowed,
disallowed: DefIdMap::default(),
disallowed: create_disallowed_map(tcx, &conf.disallowed_macros),
seen: FxHashSet::default(),
derive_src: None,
}
}
fn check(&mut self, cx: &LateContext<'_>, span: Span, derive_src: Option<OwnerId>) {
if self.conf_disallowed.is_empty() {
if self.disallowed.is_empty() {
return;
}
@ -86,11 +85,10 @@ impl DisallowedMacros {
return;
}
if let Some(&index) = self.disallowed.get(&mac.def_id) {
let conf = &self.conf_disallowed[index];
let msg = format!("use of a disallowed macro `{}`", conf.path());
if let Some(&(path, reason)) = self.disallowed.get(&mac.def_id) {
let msg = format!("use of a disallowed macro `{path}`");
let add_note = |diag: &mut Diag<'_, _>| {
if let Some(reason) = conf.reason() {
if let Some(reason) = reason {
diag.note(reason);
}
};
@ -116,15 +114,6 @@ impl DisallowedMacros {
impl_lint_pass!(DisallowedMacros => [DISALLOWED_MACROS]);
impl LateLintPass<'_> for DisallowedMacros {
fn check_crate(&mut self, cx: &LateContext<'_>) {
for (index, conf) in self.conf_disallowed.iter().enumerate() {
let segs: Vec<_> = conf.path().split("::").collect();
for id in clippy_utils::def_path_def_ids(cx, &segs) {
self.disallowed.insert(id, index);
}
}
}
fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
self.check(cx, expr.span, None);
// `$t + $t` can have the context of $t, check also the span of the binary operator

View file

@ -1,9 +1,11 @@
use clippy_config::types::DisallowedPath;
use clippy_config::Conf;
use clippy_utils::create_disallowed_map;
use clippy_utils::diagnostics::span_lint_and_then;
use rustc_hir::def::{CtorKind, DefKind, Res};
use rustc_hir::def_id::DefIdMap;
use rustc_hir::{Expr, ExprKind};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::ty::TyCtxt;
use rustc_session::impl_lint_pass;
declare_clippy_lint! {
@ -55,17 +57,14 @@ declare_clippy_lint! {
"use of a disallowed method call"
}
#[derive(Clone, Debug)]
pub struct DisallowedMethods {
conf_disallowed: Vec<DisallowedPath>,
disallowed: DefIdMap<usize>,
disallowed: DefIdMap<(&'static str, Option<&'static str>)>,
}
impl DisallowedMethods {
pub fn new(conf_disallowed: Vec<DisallowedPath>) -> Self {
pub fn new(tcx: TyCtxt<'_>, conf: &'static Conf) -> Self {
Self {
conf_disallowed,
disallowed: DefIdMap::default(),
disallowed: create_disallowed_map(tcx, &conf.disallowed_methods),
}
}
}
@ -73,15 +72,6 @@ impl DisallowedMethods {
impl_lint_pass!(DisallowedMethods => [DISALLOWED_METHODS]);
impl<'tcx> LateLintPass<'tcx> for DisallowedMethods {
fn check_crate(&mut self, cx: &LateContext<'_>) {
for (index, conf) in self.conf_disallowed.iter().enumerate() {
let segs: Vec<_> = conf.path().split("::").collect();
for id in clippy_utils::def_path_def_ids(cx, &segs) {
self.disallowed.insert(id, index);
}
}
}
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
let (id, span) = match &expr.kind {
ExprKind::Path(path)
@ -95,14 +85,18 @@ impl<'tcx> LateLintPass<'tcx> for DisallowedMethods {
},
_ => return,
};
if let Some(&index) = self.disallowed.get(&id) {
let conf = &self.conf_disallowed[index];
let msg = format!("use of a disallowed method `{}`", conf.path());
span_lint_and_then(cx, DISALLOWED_METHODS, span, msg, |diag| {
if let Some(reason) = conf.reason() {
diag.note(reason);
}
});
if let Some(&(path, reason)) = self.disallowed.get(&id) {
span_lint_and_then(
cx,
DISALLOWED_METHODS,
span,
format!("use of a disallowed method `{path}`"),
|diag| {
if let Some(reason) = reason {
diag.note(reason);
}
},
);
}
}
}

View file

@ -1,9 +1,11 @@
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint;
use clippy_utils::is_in_test;
use rustc_data_structures::fx::FxHashSet;
use rustc_hir::{Pat, PatKind};
use rustc_lint::{LateContext, LateLintPass};
use rustc_session::impl_lint_pass;
use rustc_span::Symbol;
declare_clippy_lint! {
/// ### What it does
@ -24,15 +26,14 @@ declare_clippy_lint! {
"usage of a disallowed/placeholder name"
}
#[derive(Clone, Debug)]
pub struct DisallowedNames {
disallow: FxHashSet<String>,
disallow: FxHashSet<Symbol>,
}
impl DisallowedNames {
pub fn new(disallowed_names: &[String]) -> Self {
pub fn new(conf: &'static Conf) -> Self {
Self {
disallow: disallowed_names.iter().cloned().collect(),
disallow: conf.disallowed_names.iter().map(|x| Symbol::intern(x)).collect(),
}
}
}
@ -42,7 +43,7 @@ impl_lint_pass!(DisallowedNames => [DISALLOWED_NAMES]);
impl<'tcx> LateLintPass<'tcx> for DisallowedNames {
fn check_pat(&mut self, cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>) {
if let PatKind::Binding(.., ident, _) = pat.kind
&& self.disallow.contains(&ident.name.to_string())
&& self.disallow.contains(&ident.name)
&& !is_in_test(cx.tcx, pat.hir_id)
{
span_lint(

View file

@ -1,3 +1,4 @@
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint;
use rustc_ast::ast;
use rustc_data_structures::fx::FxHashSet;
@ -44,19 +45,20 @@ declare_clippy_lint! {
"usage of non-allowed Unicode scripts"
}
#[derive(Clone, Debug)]
pub struct DisallowedScriptIdents {
whitelist: FxHashSet<Script>,
}
impl DisallowedScriptIdents {
pub fn new(whitelist: &[String]) -> Self {
let whitelist = whitelist
.iter()
.map(String::as_str)
.filter_map(Script::from_full_name)
.collect();
Self { whitelist }
pub fn new(conf: &'static Conf) -> Self {
Self {
whitelist: conf
.allowed_scripts
.iter()
.map(String::as_str)
.filter_map(Script::from_full_name)
.collect(),
}
}
}

View file

@ -1,10 +1,11 @@
use clippy_config::types::DisallowedPath;
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_and_then;
use rustc_data_structures::fx::FxHashMap;
use rustc_hir::def::Res;
use rustc_hir::def_id::DefId;
use rustc_hir::def_id::DefIdMap;
use rustc_hir::{Item, ItemKind, PolyTraitRef, PrimTy, Ty, TyKind, UseKind};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::ty::TyCtxt;
use rustc_session::impl_lint_pass;
use rustc_span::Span;
@ -49,60 +50,56 @@ declare_clippy_lint! {
"use of disallowed types"
}
#[derive(Clone, Debug)]
pub struct DisallowedTypes {
conf_disallowed: Vec<DisallowedPath>,
def_ids: FxHashMap<DefId, usize>,
prim_tys: FxHashMap<PrimTy, usize>,
def_ids: DefIdMap<(&'static str, Option<&'static str>)>,
prim_tys: FxHashMap<PrimTy, (&'static str, Option<&'static str>)>,
}
impl DisallowedTypes {
pub fn new(conf_disallowed: Vec<DisallowedPath>) -> Self {
Self {
conf_disallowed,
def_ids: FxHashMap::default(),
prim_tys: FxHashMap::default(),
pub fn new(tcx: TyCtxt<'_>, conf: &'static Conf) -> Self {
let mut def_ids = DefIdMap::default();
let mut prim_tys = FxHashMap::default();
for x in &conf.disallowed_types {
let path: Vec<_> = x.path().split("::").collect::<Vec<_>>();
let reason = x.reason();
for res in clippy_utils::def_path_res(tcx, &path) {
match res {
Res::Def(_, id) => {
def_ids.insert(id, (x.path(), reason));
},
Res::PrimTy(ty) => {
prim_tys.insert(ty, (x.path(), reason));
},
_ => {},
}
}
}
Self { def_ids, prim_tys }
}
fn check_res_emit(&self, cx: &LateContext<'_>, res: &Res, span: Span) {
match res {
Res::Def(_, did) => {
if let Some(&index) = self.def_ids.get(did) {
emit(cx, &cx.tcx.def_path_str(*did), span, &self.conf_disallowed[index]);
let (path, reason) = match res {
Res::Def(_, did) if let Some(&x) = self.def_ids.get(did) => x,
Res::PrimTy(prim) if let Some(&x) = self.prim_tys.get(prim) => x,
_ => return,
};
span_lint_and_then(
cx,
DISALLOWED_TYPES,
span,
format!("use of a disallowed type `{path}`"),
|diag| {
if let Some(reason) = reason {
diag.note(reason);
}
},
Res::PrimTy(prim) => {
if let Some(&index) = self.prim_tys.get(prim) {
emit(cx, prim.name_str(), span, &self.conf_disallowed[index]);
}
},
_ => {},
}
);
}
}
impl_lint_pass!(DisallowedTypes => [DISALLOWED_TYPES]);
impl<'tcx> LateLintPass<'tcx> for DisallowedTypes {
fn check_crate(&mut self, cx: &LateContext<'_>) {
for (index, conf) in self.conf_disallowed.iter().enumerate() {
let segs: Vec<_> = conf.path().split("::").collect();
for res in clippy_utils::def_path_res(cx, &segs) {
match res {
Res::Def(_, id) => {
self.def_ids.insert(id, index);
},
Res::PrimTy(ty) => {
self.prim_tys.insert(ty, index);
},
_ => {},
}
}
}
}
fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'tcx>) {
if let ItemKind::Use(path, UseKind::Single) = &item.kind {
for res in &path.res {
@ -121,17 +118,3 @@ impl<'tcx> LateLintPass<'tcx> for DisallowedTypes {
self.check_res_emit(cx, &poly.trait_ref.path.res, poly.trait_ref.path.span);
}
}
fn emit(cx: &LateContext<'_>, name: &str, span: Span, conf: &DisallowedPath) {
span_lint_and_then(
cx,
DISALLOWED_TYPES,
span,
format!("`{name}` is not allowed according to config"),
|diag| {
if let Some(reason) = conf.reason() {
diag.note(reason);
}
},
);
}

View file

@ -1,4 +1,5 @@
mod lazy_continuation;
use clippy_config::Conf;
use clippy_utils::attrs::is_doc_hidden;
use clippy_utils::diagnostics::{span_lint, span_lint_and_help};
use clippy_utils::macros::{is_panic, root_macro_call_first_node};
@ -421,17 +422,16 @@ declare_clippy_lint! {
"require every line of a paragraph to be indented and marked"
}
#[derive(Clone)]
pub struct Documentation {
valid_idents: FxHashSet<String>,
valid_idents: &'static FxHashSet<String>,
check_private_items: bool,
}
impl Documentation {
pub fn new(valid_idents: &[String], check_private_items: bool) -> Self {
pub fn new(conf: &'static Conf) -> Self {
Self {
valid_idents: valid_idents.iter().cloned().collect(),
check_private_items,
valid_idents: &conf.doc_valid_idents,
check_private_items: conf.check_private_items,
}
}
}
@ -452,7 +452,7 @@ impl_lint_pass!(Documentation => [
impl<'tcx> LateLintPass<'tcx> for Documentation {
fn check_attributes(&mut self, cx: &LateContext<'tcx>, attrs: &'tcx [Attribute]) {
let Some(headers) = check_attrs(cx, &self.valid_idents, attrs) else {
let Some(headers) = check_attrs(cx, self.valid_idents, attrs) else {
return;
};

View file

@ -1,3 +1,4 @@
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_hir;
use rustc_hir::{intravisit, AssocItemKind, Body, FnDecl, HirId, HirIdSet, Impl, ItemKind, Node, Pat, PatKind};
use rustc_hir_typeck::expr_use_visitor::{Delegate, ExprUseVisitor, PlaceBase, PlaceWithHirId};
@ -11,9 +12,16 @@ use rustc_span::symbol::kw;
use rustc_span::Span;
use rustc_target::spec::abi::Abi;
#[derive(Copy, Clone)]
pub struct BoxedLocal {
pub too_large_for_stack: u64,
too_large_for_stack: u64,
}
impl BoxedLocal {
pub fn new(conf: &'static Conf) -> Self {
Self {
too_large_for_stack: conf.too_large_for_stack,
}
}
}
declare_clippy_lint! {

View file

@ -1,3 +1,4 @@
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_and_help;
use clippy_utils::{get_parent_as_impl, has_repr_attr, is_bool};
use rustc_hir::intravisit::FnKind;
@ -94,11 +95,10 @@ enum Kind {
}
impl ExcessiveBools {
#[must_use]
pub fn new(max_struct_bools: u64, max_fn_params_bools: u64) -> Self {
pub fn new(conf: &'static Conf) -> Self {
Self {
max_struct_bools,
max_fn_params_bools,
max_struct_bools: conf.max_struct_bools,
max_fn_params_bools: conf.max_fn_params_bools,
}
}

View file

@ -1,3 +1,4 @@
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_and_help;
use clippy_utils::source::snippet;
use rustc_ast::node_id::NodeSet;
@ -63,13 +64,19 @@ declare_clippy_lint! {
}
impl_lint_pass!(ExcessiveNesting => [EXCESSIVE_NESTING]);
#[derive(Clone)]
pub struct ExcessiveNesting {
pub excessive_nesting_threshold: u64,
pub nodes: NodeSet,
}
impl ExcessiveNesting {
pub fn new(conf: &'static Conf) -> Self {
Self {
excessive_nesting_threshold: conf.excessive_nesting_threshold,
nodes: NodeSet::default(),
}
}
pub fn check_node_id(&self, cx: &EarlyContext<'_>, span: Span, node_id: NodeId) {
if self.nodes.contains(&node_id) {
span_lint_and_help(

View file

@ -1,3 +1,4 @@
use clippy_config::Conf;
use clippy_utils::diagnostics::{span_lint_and_help, span_lint_and_then};
use clippy_utils::{is_from_proc_macro, trait_ref_of_method};
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
@ -45,9 +46,9 @@ pub struct ExtraUnusedTypeParameters {
}
impl ExtraUnusedTypeParameters {
pub fn new(avoid_breaking_exported_api: bool) -> Self {
pub fn new(conf: &'static Conf) -> Self {
Self {
avoid_breaking_exported_api,
avoid_breaking_exported_api: conf.avoid_breaking_exported_api,
}
}

View file

@ -1,5 +1,6 @@
use arrayvec::ArrayVec;
use clippy_config::msrvs::{self, Msrv};
use clippy_config::Conf;
use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then};
use clippy_utils::is_diag_trait_item;
use clippy_utils::macros::{
@ -175,12 +176,11 @@ pub struct FormatArgs {
}
impl FormatArgs {
#[must_use]
pub fn new(format_args: FormatArgsStorage, msrv: Msrv, allow_mixed_uninlined_format_args: bool) -> Self {
pub fn new(conf: &'static Conf, format_args: FormatArgsStorage) -> Self {
Self {
format_args,
msrv,
ignore_mixed: allow_mixed_uninlined_format_args,
msrv: conf.msrv.clone(),
ignore_mixed: conf.allow_mixed_uninlined_format_args,
}
}
}

View file

@ -97,7 +97,6 @@ struct FormatTraitNames {
formatter_name: Option<Symbol>,
}
#[derive(Default)]
pub struct FormatImpl {
format_args: FormatArgsStorage,
// Whether we are inside Display or Debug trait impl - None for neither

View file

@ -1,4 +1,5 @@
use clippy_config::msrvs::{self, Msrv};
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::macros::span_is_local;
use clippy_utils::path_def_id;
@ -54,9 +55,10 @@ pub struct FromOverInto {
}
impl FromOverInto {
#[must_use]
pub fn new(msrv: Msrv) -> Self {
FromOverInto { msrv }
pub fn new(conf: &'static Conf) -> Self {
FromOverInto {
msrv: conf.msrv.clone(),
}
}
}

View file

@ -7,10 +7,12 @@ mod result;
mod too_many_arguments;
mod too_many_lines;
use clippy_config::Conf;
use clippy_utils::def_path_def_ids;
use rustc_hir as hir;
use rustc_hir::intravisit;
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::ty::TyCtxt;
use rustc_session::impl_lint_pass;
use rustc_span::def_id::{DefIdSet, LocalDefId};
use rustc_span::Span;
@ -397,33 +399,28 @@ declare_clippy_lint! {
"renamed function parameters in trait implementation"
}
#[derive(Clone)]
pub struct Functions {
too_many_arguments_threshold: u64,
too_many_lines_threshold: u64,
large_error_threshold: u64,
avoid_breaking_exported_api: bool,
allow_renamed_params_for: Vec<String>,
/// A set of resolved `def_id` of traits that are configured to allow
/// function params renaming.
trait_ids: DefIdSet,
}
impl Functions {
pub fn new(
too_many_arguments_threshold: u64,
too_many_lines_threshold: u64,
large_error_threshold: u64,
avoid_breaking_exported_api: bool,
allow_renamed_params_for: Vec<String>,
) -> Self {
pub fn new(tcx: TyCtxt<'_>, conf: &'static Conf) -> Self {
Self {
too_many_arguments_threshold,
too_many_lines_threshold,
large_error_threshold,
avoid_breaking_exported_api,
allow_renamed_params_for,
trait_ids: DefIdSet::default(),
too_many_arguments_threshold: conf.too_many_arguments_threshold,
too_many_lines_threshold: conf.too_many_lines_threshold,
large_error_threshold: conf.large_error_threshold,
avoid_breaking_exported_api: conf.avoid_breaking_exported_api,
trait_ids: conf
.allow_renamed_params_for
.iter()
.flat_map(|p| def_path_def_ids(tcx, &p.split("::").collect::<Vec<_>>()))
.collect(),
}
}
}
@ -479,12 +476,4 @@ impl<'tcx> LateLintPass<'tcx> for Functions {
result::check_trait_item(cx, item, self.large_error_threshold);
impl_trait_in_params::check_trait_item(cx, item, self.avoid_breaking_exported_api);
}
fn check_crate(&mut self, cx: &LateContext<'tcx>) {
for path in &self.allow_renamed_params_for {
let path_segments: Vec<&str> = path.split("::").collect();
let ids = def_path_def_ids(cx, &path_segments);
self.trait_ids.extend(ids);
}
}
}

View file

@ -1,4 +1,5 @@
use clippy_config::msrvs::{self, Msrv};
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_and_help;
use clippy_utils::eager_or_lazy::switch_to_eager_eval;
use clippy_utils::source::snippet_with_context;
@ -51,9 +52,10 @@ pub struct IfThenSomeElseNone {
}
impl IfThenSomeElseNone {
#[must_use]
pub fn new(msrv: Msrv) -> Self {
Self { msrv }
pub fn new(conf: &'static Conf) -> Self {
Self {
msrv: conf.msrv.clone(),
}
}
}

View file

@ -1,4 +1,5 @@
use clippy_config::msrvs::Msrv;
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint;
use clippy_utils::is_in_test;
use rustc_attr::{StabilityLevel, StableSince};
@ -47,9 +48,9 @@ pub struct IncompatibleMsrv {
impl_lint_pass!(IncompatibleMsrv => [INCOMPATIBLE_MSRV]);
impl IncompatibleMsrv {
pub fn new(msrv: Msrv) -> Self {
pub fn new(conf: &'static Conf) -> Self {
Self {
msrv,
msrv: conf.msrv.clone(),
is_above_msrv: FxHashMap::default(),
}
}

View file

@ -1,4 +1,5 @@
use clippy_config::msrvs::{self, Msrv};
use clippy_config::Conf;
use clippy_utils::consts::{constant, Constant};
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::higher::IfLet;
@ -58,10 +59,10 @@ pub struct IndexRefutableSlice {
}
impl IndexRefutableSlice {
pub fn new(max_suggested_slice_pattern_length: u64, msrv: Msrv) -> Self {
pub fn new(conf: &'static Conf) -> Self {
Self {
max_suggested_slice: max_suggested_slice_pattern_length,
msrv,
max_suggested_slice: conf.max_suggested_slice_pattern_length,
msrv: conf.msrv.clone(),
}
}
}

View file

@ -1,5 +1,6 @@
//! lint on indexing and slicing operations
use clippy_config::Conf;
use clippy_utils::consts::{constant, Constant};
use clippy_utils::diagnostics::{span_lint, span_lint_and_then};
use clippy_utils::ty::{deref_chain, get_adt_inherent_method};
@ -87,15 +88,14 @@ declare_clippy_lint! {
impl_lint_pass!(IndexingSlicing => [INDEXING_SLICING, OUT_OF_BOUNDS_INDEXING]);
#[derive(Copy, Clone)]
pub struct IndexingSlicing {
suppress_restriction_lint_in_const: bool,
}
impl IndexingSlicing {
pub fn new(suppress_restriction_lint_in_const: bool) -> Self {
pub fn new(conf: &'static Conf) -> Self {
Self {
suppress_restriction_lint_in_const,
suppress_restriction_lint_in_const: conf.suppress_restriction_lint_in_const,
}
}
}

View file

@ -1,4 +1,5 @@
use clippy_config::msrvs::{self, Msrv};
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::source::snippet_with_context;
use clippy_utils::sugg::Sugg;
@ -68,9 +69,10 @@ pub struct InstantSubtraction {
}
impl InstantSubtraction {
#[must_use]
pub fn new(msrv: Msrv) -> Self {
Self { msrv }
pub fn new(conf: &'static Conf) -> Self {
Self {
msrv: conf.msrv.clone(),
}
}
}

View file

@ -1,5 +1,6 @@
//! lint on enum variants that are prefixed or suffixed by the same characters
use clippy_config::Conf;
use clippy_utils::diagnostics::{span_lint, span_lint_and_help, span_lint_hir};
use clippy_utils::is_bool;
use clippy_utils::macros::span_is_local;
@ -152,21 +153,14 @@ pub struct ItemNameRepetitions {
}
impl ItemNameRepetitions {
#[must_use]
pub fn new(
enum_threshold: u64,
struct_threshold: u64,
avoid_breaking_exported_api: bool,
allow_private_module_inception: bool,
allowed_prefixes: &[String],
) -> Self {
pub fn new(conf: &'static Conf) -> Self {
Self {
modules: Vec::new(),
enum_threshold,
struct_threshold,
avoid_breaking_exported_api,
allow_private_module_inception,
allowed_prefixes: allowed_prefixes.iter().map(|s| to_camel_case(s)).collect(),
enum_threshold: conf.enum_variant_name_threshold,
struct_threshold: conf.struct_field_name_threshold,
avoid_breaking_exported_api: conf.avoid_breaking_exported_api,
allow_private_module_inception: conf.allow_private_module_inception,
allowed_prefixes: conf.allowed_prefixes.iter().map(|s| to_camel_case(s)).collect(),
}
}

View file

@ -1,3 +1,4 @@
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_and_then;
use rustc_errors::Applicability;
use rustc_hir::{Item, ItemKind};
@ -32,13 +33,14 @@ declare_clippy_lint! {
}
pub struct LargeConstArrays {
maximum_allowed_size: u128,
maximum_allowed_size: u64,
}
impl LargeConstArrays {
#[must_use]
pub fn new(maximum_allowed_size: u128) -> Self {
Self { maximum_allowed_size }
pub fn new(conf: &'static Conf) -> Self {
Self {
maximum_allowed_size: conf.array_size_threshold,
}
}
}
@ -57,7 +59,7 @@ impl<'tcx> LateLintPass<'tcx> for LargeConstArrays {
&& let ConstKind::Value(_, ty::ValTree::Leaf(element_count)) = cst.kind()
&& let element_count = element_count.to_target_usize(cx.tcx)
&& let Ok(element_size) = cx.layout_of(*element_type).map(|l| l.size.bytes())
&& self.maximum_allowed_size < u128::from(element_count) * u128::from(element_size)
&& u128::from(self.maximum_allowed_size) < u128::from(element_count) * u128::from(element_size)
{
let hi_pos = item.ident.span.lo() - BytePos::from_usize(1);
let sugg_span = Span::new(

View file

@ -1,5 +1,6 @@
//! lint when there is a large size difference between variants on an enum
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::source::snippet_with_applicability;
use clippy_utils::ty::{approx_ty_size, is_copy, AdtVariantInfo};
@ -59,16 +60,14 @@ declare_clippy_lint! {
"large size difference between variants on an enum"
}
#[derive(Copy, Clone)]
pub struct LargeEnumVariant {
maximum_size_difference_allowed: u64,
}
impl LargeEnumVariant {
#[must_use]
pub fn new(maximum_size_difference_allowed: u64) -> Self {
pub fn new(conf: &'static Conf) -> Self {
Self {
maximum_size_difference_allowed,
maximum_size_difference_allowed: conf.enum_variant_size_threshold,
}
}
}

View file

@ -1,3 +1,4 @@
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::source::snippet;
use clippy_utils::ty::implements_trait;
@ -39,14 +40,15 @@ declare_clippy_lint! {
"large future may lead to unexpected stack overflows"
}
#[derive(Copy, Clone)]
pub struct LargeFuture {
future_size_threshold: u64,
}
impl LargeFuture {
pub fn new(future_size_threshold: u64) -> Self {
Self { future_size_threshold }
pub fn new(conf: &'static Conf) -> Self {
Self {
future_size_threshold: conf.future_size_threshold,
}
}
}

View file

@ -1,3 +1,4 @@
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_and_note;
use clippy_utils::macros::root_macro_call_first_node;
use rustc_ast::LitKind;
@ -41,9 +42,10 @@ pub struct LargeIncludeFile {
}
impl LargeIncludeFile {
#[must_use]
pub fn new(max_file_size: u64) -> Self {
Self { max_file_size }
pub fn new(conf: &'static Conf) -> Self {
Self {
max_file_size: conf.max_include_file_size,
}
}
}

View file

@ -1,3 +1,4 @@
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::is_from_proc_macro;
use clippy_utils::macros::macro_backtrace;
@ -27,15 +28,14 @@ declare_clippy_lint! {
}
pub struct LargeStackArrays {
maximum_allowed_size: u128,
maximum_allowed_size: u64,
prev_vec_macro_callsite: Option<Span>,
}
impl LargeStackArrays {
#[must_use]
pub fn new(maximum_allowed_size: u128) -> Self {
pub fn new(conf: &'static Conf) -> Self {
Self {
maximum_allowed_size,
maximum_allowed_size: conf.array_size_threshold,
prev_vec_macro_callsite: None,
}
}
@ -76,7 +76,7 @@ impl<'tcx> LateLintPass<'tcx> for LargeStackArrays {
})
)
})
&& self.maximum_allowed_size < u128::from(element_count) * u128::from(element_size)
&& u128::from(self.maximum_allowed_size) < u128::from(element_count) * u128::from(element_size)
{
span_lint_and_then(
cx,

View file

@ -1,5 +1,6 @@
use std::{fmt, ops};
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::fn_has_unsatisfiable_preds;
use clippy_utils::source::snippet_opt;
@ -85,10 +86,9 @@ pub struct LargeStackFrames {
}
impl LargeStackFrames {
#[must_use]
pub fn new(size: u64) -> Self {
pub fn new(conf: &'static Conf) -> Self {
Self {
maximum_allowed_size: size,
maximum_allowed_size: conf.stack_size_threshold,
}
}
}

View file

@ -1,4 +1,5 @@
use clippy_config::msrvs::{Msrv, NUMERIC_ASSOCIATED_CONSTANTS};
use clippy_config::Conf;
use clippy_utils::diagnostics::{span_lint_and_then, span_lint_hir_and_then};
use clippy_utils::{get_parent_expr, is_from_proc_macro};
use hir::def_id::DefId;
@ -38,9 +39,10 @@ pub struct LegacyNumericConstants {
}
impl LegacyNumericConstants {
#[must_use]
pub fn new(msrv: Msrv) -> Self {
Self { msrv }
pub fn new(conf: &'static Conf) -> Self {
Self {
msrv: conf.msrv.clone(),
}
}
}

View file

@ -393,7 +393,6 @@ use clippy_config::{get_configuration_metadata, Conf};
use clippy_utils::macros::FormatArgsStorage;
use rustc_data_structures::fx::FxHashSet;
use rustc_lint::{Lint, LintId};
use std::collections::BTreeMap;
/// Register all pre expansion lints
///
@ -405,9 +404,7 @@ use std::collections::BTreeMap;
/// Used in `./src/driver.rs`.
pub fn register_pre_expansion_lints(store: &mut rustc_lint::LintStore, conf: &'static Conf) {
// NOTE: Do not add any more pre-expansion passes. These should be removed eventually.
let msrv = || conf.msrv.clone();
store.register_pre_expansion_pass(move || Box::new(attrs::EarlyAttributes { msrv: msrv() }));
store.register_pre_expansion_pass(move || Box::new(attrs::EarlyAttributes::new(conf)));
}
#[derive(Default)]
@ -533,88 +530,6 @@ fn register_categories(store: &mut rustc_lint::LintStore) {
/// Used in `./src/driver.rs`.
#[expect(clippy::too_many_lines)]
pub fn register_lints(store: &mut rustc_lint::LintStore, conf: &'static Conf) {
let Conf {
ref absolute_paths_allowed_crates,
absolute_paths_max_segments,
accept_comment_above_attributes,
accept_comment_above_statement,
allow_dbg_in_tests,
allow_expect_in_tests,
allow_mixed_uninlined_format_args,
allow_one_hash_in_raw_strings,
allow_panic_in_tests,
allow_print_in_tests,
allow_private_module_inception,
allow_unwrap_in_tests,
allow_useless_vec_in_tests,
ref allowed_dotfiles,
ref allowed_idents_below_min_chars,
ref allowed_scripts,
ref allowed_wildcard_imports,
ref arithmetic_side_effects_allowed_binary,
ref arithmetic_side_effects_allowed_unary,
ref arithmetic_side_effects_allowed,
array_size_threshold,
avoid_breaking_exported_api,
ref await_holding_invalid_types,
cargo_ignore_publish,
cognitive_complexity_threshold,
ref disallowed_macros,
ref disallowed_methods,
ref disallowed_names,
ref disallowed_types,
ref doc_valid_idents,
enable_raw_pointer_heuristic_for_send,
enforce_iter_loop_reborrow,
ref enforced_import_renames,
enum_variant_name_threshold,
enum_variant_size_threshold,
excessive_nesting_threshold,
future_size_threshold,
ref ignore_interior_mutability,
large_error_threshold,
literal_representation_threshold,
matches_for_let_else,
max_fn_params_bools,
max_include_file_size,
max_struct_bools,
max_suggested_slice_pattern_length,
max_trait_bounds,
min_ident_chars_threshold,
missing_docs_in_crate_items,
ref msrv,
pass_by_value_size_limit,
semicolon_inside_block_ignore_singleline,
semicolon_outside_block_ignore_multiline,
single_char_binding_names_threshold,
stack_size_threshold,
ref standard_macro_braces,
struct_field_name_threshold,
suppress_restriction_lint_in_const,
too_large_for_stack,
too_many_arguments_threshold,
too_many_lines_threshold,
trivial_copy_size_limit,
type_complexity_threshold,
unnecessary_box_size,
unreadable_literal_lint_fractions,
upper_case_acronyms_aggressive,
vec_box_size_threshold,
verbose_bit_mask_threshold,
warn_on_all_wildcard_imports,
check_private_items,
pub_underscore_fields_behavior,
ref allowed_duplicate_crates,
allow_comparison_to_zero,
ref allowed_prefixes,
ref allow_renamed_params_for,
blacklisted_names: _,
cyclomatic_complexity_threshold: _,
warn_unsafe_macro_metavars_in_private_macros,
} = *conf;
let msrv = || msrv.clone();
register_removed_non_tool_lints(store);
register_categories(store);
@ -659,35 +574,12 @@ pub fn register_lints(store: &mut rustc_lint::LintStore, conf: &'static Conf) {
});
}
store.register_late_pass(move |_| {
Box::new(operators::arithmetic_side_effects::ArithmeticSideEffects::new(
arithmetic_side_effects_allowed
.iter()
.flat_map(|el| [[el.clone(), "*".to_string()], ["*".to_string(), el.clone()]])
.chain(arithmetic_side_effects_allowed_binary.clone())
.collect(),
arithmetic_side_effects_allowed
.iter()
.chain(arithmetic_side_effects_allowed_unary.iter())
.cloned()
.collect(),
))
});
store.register_late_pass(move |_| Box::new(operators::arithmetic_side_effects::ArithmeticSideEffects::new(conf)));
store.register_late_pass(|_| Box::new(utils::dump_hir::DumpHir));
store.register_late_pass(|_| Box::new(utils::author::Author));
store.register_late_pass(move |_| {
Box::new(await_holding_invalid::AwaitHolding::new(
await_holding_invalid_types.clone(),
))
});
store.register_late_pass(move |tcx| Box::new(await_holding_invalid::AwaitHolding::new(tcx, conf)));
store.register_late_pass(|_| Box::new(serde_api::SerdeApi));
store.register_late_pass(move |_| {
Box::new(types::Types::new(
vec_box_size_threshold,
type_complexity_threshold,
avoid_breaking_exported_api,
))
});
store.register_late_pass(move |_| Box::new(types::Types::new(conf)));
store.register_late_pass(|_| Box::new(booleans::NonminimalBool));
store.register_late_pass(|_| Box::new(enum_clike::UnportableVariant));
store.register_late_pass(|_| Box::new(float_literal::FloatLiteral));
@ -701,7 +593,7 @@ pub fn register_lints(store: &mut rustc_lint::LintStore, conf: &'static Conf) {
store.register_late_pass(|_| Box::new(mut_reference::UnnecessaryMutPassed));
store.register_late_pass(|_| Box::<significant_drop_tightening::SignificantDropTightening<'_>>::default());
store.register_late_pass(|_| Box::new(len_zero::LenZero));
store.register_late_pass(move |_| Box::new(attrs::Attributes::new(msrv())));
store.register_late_pass(move |_| Box::new(attrs::Attributes::new(conf)));
store.register_late_pass(|_| Box::new(blocks_in_conditions::BlocksInConditions));
store.register_late_pass(|_| Box::new(unicode::Unicode));
store.register_late_pass(|_| Box::new(uninit_vec::UninitVec));
@ -713,44 +605,30 @@ pub fn register_lints(store: &mut rustc_lint::LintStore, conf: &'static Conf) {
store.register_late_pass(|_| Box::new(inconsistent_struct_constructor::InconsistentStructConstructor));
store.register_late_pass(|_| Box::new(non_octal_unix_permissions::NonOctalUnixPermissions));
store.register_early_pass(|| Box::new(unnecessary_self_imports::UnnecessarySelfImports));
store.register_late_pass(move |_| Box::new(approx_const::ApproxConstant::new(msrv())));
store.register_late_pass(move |_| Box::new(approx_const::ApproxConstant::new(conf)));
let format_args = format_args_storage.clone();
store.register_late_pass(move |_| {
Box::new(methods::Methods::new(
avoid_breaking_exported_api,
msrv(),
allow_expect_in_tests,
allow_unwrap_in_tests,
allowed_dotfiles.clone(),
format_args.clone(),
))
});
store.register_late_pass(move |_| Box::new(matches::Matches::new(msrv())));
store.register_early_pass(move || Box::new(manual_non_exhaustive::ManualNonExhaustiveStruct::new(msrv())));
store.register_late_pass(move |_| Box::new(manual_non_exhaustive::ManualNonExhaustiveEnum::new(msrv())));
store.register_late_pass(move |_| Box::new(manual_strip::ManualStrip::new(msrv())));
store.register_early_pass(move || Box::new(redundant_static_lifetimes::RedundantStaticLifetimes::new(msrv())));
store.register_early_pass(move || Box::new(redundant_field_names::RedundantFieldNames::new(msrv())));
store.register_late_pass(move |_| Box::new(checked_conversions::CheckedConversions::new(msrv())));
store.register_late_pass(move |_| Box::new(mem_replace::MemReplace::new(msrv())));
store.register_late_pass(move |_| Box::new(ranges::Ranges::new(msrv())));
store.register_late_pass(move |_| Box::new(from_over_into::FromOverInto::new(msrv())));
store.register_late_pass(move |_| Box::new(use_self::UseSelf::new(msrv())));
store.register_late_pass(move |_| Box::new(missing_const_for_fn::MissingConstForFn::new(msrv())));
store.register_late_pass(move |_| Box::new(methods::Methods::new(conf, format_args.clone())));
store.register_late_pass(move |_| Box::new(matches::Matches::new(conf)));
store.register_early_pass(move || Box::new(manual_non_exhaustive::ManualNonExhaustiveStruct::new(conf)));
store.register_late_pass(move |_| Box::new(manual_non_exhaustive::ManualNonExhaustiveEnum::new(conf)));
store.register_late_pass(move |_| Box::new(manual_strip::ManualStrip::new(conf)));
store.register_early_pass(move || Box::new(redundant_static_lifetimes::RedundantStaticLifetimes::new(conf)));
store.register_early_pass(move || Box::new(redundant_field_names::RedundantFieldNames::new(conf)));
store.register_late_pass(move |_| Box::new(checked_conversions::CheckedConversions::new(conf)));
store.register_late_pass(move |_| Box::new(mem_replace::MemReplace::new(conf)));
store.register_late_pass(move |_| Box::new(ranges::Ranges::new(conf)));
store.register_late_pass(move |_| Box::new(from_over_into::FromOverInto::new(conf)));
store.register_late_pass(move |_| Box::new(use_self::UseSelf::new(conf)));
store.register_late_pass(move |_| Box::new(missing_const_for_fn::MissingConstForFn::new(conf)));
store.register_late_pass(move |_| Box::new(needless_question_mark::NeedlessQuestionMark));
store.register_late_pass(move |_| Box::new(casts::Casts::new(msrv())));
store.register_early_pass(move || Box::new(unnested_or_patterns::UnnestedOrPatterns::new(msrv())));
store.register_late_pass(move |_| Box::new(casts::Casts::new(conf)));
store.register_early_pass(move || Box::new(unnested_or_patterns::UnnestedOrPatterns::new(conf)));
store.register_late_pass(|_| Box::new(size_of_in_element_count::SizeOfInElementCount));
store.register_late_pass(|_| Box::new(same_name_method::SameNameMethod));
store.register_late_pass(move |_| {
Box::new(index_refutable_slice::IndexRefutableSlice::new(
max_suggested_slice_pattern_length,
msrv(),
))
});
store.register_late_pass(move |_| Box::new(index_refutable_slice::IndexRefutableSlice::new(conf)));
store.register_late_pass(|_| Box::<shadow::Shadow>::default());
store.register_late_pass(|_| Box::new(unit_types::UnitTypes));
store.register_late_pass(move |_| Box::new(loops::Loops::new(msrv(), enforce_iter_loop_reborrow)));
store.register_late_pass(move |_| Box::new(loops::Loops::new(conf)));
store.register_late_pass(|_| Box::<main_recursion::MainRecursion>::default());
store.register_late_pass(|_| Box::new(lifetimes::Lifetimes));
store.register_late_pass(|_| Box::new(entry::HashMapPass));
@ -762,75 +640,49 @@ pub fn register_lints(store: &mut rustc_lint::LintStore, conf: &'static Conf) {
store.register_late_pass(|_| Box::new(borrow_deref_ref::BorrowDerefRef));
store.register_late_pass(|_| Box::<no_effect::NoEffect>::default());
store.register_late_pass(|_| Box::new(temporary_assignment::TemporaryAssignment));
store.register_late_pass(move |_| Box::new(transmute::Transmute::new(msrv())));
store.register_late_pass(move |_| {
Box::new(cognitive_complexity::CognitiveComplexity::new(
cognitive_complexity_threshold,
))
});
store.register_late_pass(move |_| Box::new(escape::BoxedLocal { too_large_for_stack }));
store.register_late_pass(move |_| {
Box::new(vec::UselessVec {
too_large_for_stack,
msrv: msrv(),
span_to_lint_map: BTreeMap::new(),
allow_in_test: allow_useless_vec_in_tests,
})
});
store.register_late_pass(move |_| Box::new(panic_unimplemented::PanicUnimplemented { allow_panic_in_tests }));
store.register_late_pass(move |_| Box::new(transmute::Transmute::new(conf)));
store.register_late_pass(move |_| Box::new(cognitive_complexity::CognitiveComplexity::new(conf)));
store.register_late_pass(move |_| Box::new(escape::BoxedLocal::new(conf)));
store.register_late_pass(move |_| Box::new(vec::UselessVec::new(conf)));
store.register_late_pass(move |_| Box::new(panic_unimplemented::PanicUnimplemented::new(conf)));
store.register_late_pass(|_| Box::new(strings::StringLitAsBytes));
store.register_late_pass(|_| Box::new(derive::Derive));
store.register_late_pass(move |_| Box::new(derivable_impls::DerivableImpls::new(msrv())));
store.register_late_pass(move |_| Box::new(derivable_impls::DerivableImpls::new(conf)));
store.register_late_pass(|_| Box::new(drop_forget_ref::DropForgetRef));
store.register_late_pass(|_| Box::new(empty_enum::EmptyEnum));
store.register_late_pass(|_| Box::new(invalid_upcast_comparisons::InvalidUpcastComparisons));
store.register_late_pass(|_| Box::<regex::Regex>::default());
store.register_late_pass(move |_| Box::new(copies::CopyAndPaste::new(ignore_interior_mutability.clone())));
store.register_late_pass(move |tcx| Box::new(copies::CopyAndPaste::new(tcx, conf)));
store.register_late_pass(|_| Box::new(copy_iterator::CopyIterator));
let format_args = format_args_storage.clone();
store.register_late_pass(move |_| Box::new(format::UselessFormat::new(format_args.clone())));
store.register_late_pass(|_| Box::new(swap::Swap));
store.register_late_pass(|_| Box::new(panicking_overflow_checks::PanickingOverflowChecks));
store.register_late_pass(|_| Box::<new_without_default::NewWithoutDefault>::default());
store.register_late_pass(move |_| Box::new(disallowed_names::DisallowedNames::new(disallowed_names)));
store.register_late_pass(move |_| {
Box::new(functions::Functions::new(
too_many_arguments_threshold,
too_many_lines_threshold,
large_error_threshold,
avoid_breaking_exported_api,
allow_renamed_params_for.clone(),
))
});
store.register_late_pass(move |_| Box::new(doc::Documentation::new(doc_valid_idents, check_private_items)));
store.register_late_pass(move |_| Box::new(disallowed_names::DisallowedNames::new(conf)));
store.register_late_pass(move |tcx| Box::new(functions::Functions::new(tcx, conf)));
store.register_late_pass(move |_| Box::new(doc::Documentation::new(conf)));
store.register_late_pass(|_| Box::new(neg_multiply::NegMultiply));
store.register_late_pass(|_| Box::new(let_if_seq::LetIfSeq));
store.register_late_pass(|_| Box::new(mixed_read_write_in_expression::EvalOrderDependence));
store.register_late_pass(move |_| Box::new(missing_doc::MissingDoc::new(missing_docs_in_crate_items)));
store.register_late_pass(move |_| Box::new(missing_doc::MissingDoc::new(conf)));
store.register_late_pass(|_| Box::new(missing_inline::MissingInline));
store.register_late_pass(move |_| Box::new(exhaustive_items::ExhaustiveItems));
store.register_late_pass(|_| Box::new(match_result_ok::MatchResultOk));
store.register_late_pass(|_| Box::new(partialeq_ne_impl::PartialEqNeImpl));
store.register_late_pass(|_| Box::new(unused_io_amount::UnusedIoAmount));
store.register_late_pass(move |_| Box::new(large_enum_variant::LargeEnumVariant::new(enum_variant_size_threshold)));
store.register_late_pass(move |_| Box::new(large_enum_variant::LargeEnumVariant::new(conf)));
let format_args = format_args_storage.clone();
store.register_late_pass(move |_| Box::new(explicit_write::ExplicitWrite::new(format_args.clone())));
store.register_late_pass(|_| Box::new(needless_pass_by_value::NeedlessPassByValue));
store.register_late_pass(move |tcx| {
Box::new(pass_by_ref_or_value::PassByRefOrValue::new(
trivial_copy_size_limit,
pass_by_value_size_limit,
avoid_breaking_exported_api,
tcx.sess.target.pointer_width,
))
});
store.register_late_pass(move |tcx| Box::new(pass_by_ref_or_value::PassByRefOrValue::new(tcx, conf)));
store.register_late_pass(|_| Box::new(ref_option_ref::RefOptionRef));
store.register_late_pass(|_| Box::new(infinite_iter::InfiniteIter));
store.register_late_pass(|_| Box::new(inline_fn_without_body::InlineFnWithoutBody));
store.register_late_pass(|_| Box::<useless_conversion::UselessConversion>::default());
store.register_late_pass(|_| Box::new(implicit_hasher::ImplicitHasher));
store.register_late_pass(|_| Box::new(fallible_impl_from::FallibleImplFrom));
store.register_late_pass(move |_| Box::new(question_mark::QuestionMark::new(msrv(), matches_for_let_else)));
store.register_late_pass(move |_| Box::new(question_mark::QuestionMark::new(conf)));
store.register_late_pass(|_| Box::new(question_mark_used::QuestionMarkUsed));
store.register_early_pass(|| Box::new(suspicious_operation_groupings::SuspiciousOperationGroupings));
store.register_late_pass(|_| Box::new(suspicious_trait_impl::SuspiciousImpl));
@ -838,22 +690,18 @@ pub fn register_lints(store: &mut rustc_lint::LintStore, conf: &'static Conf) {
store.register_late_pass(|_| Box::new(inherent_impl::MultipleInherentImpl));
store.register_late_pass(|_| Box::new(neg_cmp_op_on_partial_ord::NoNegCompOpForPartialOrd));
store.register_late_pass(|_| Box::new(unwrap::Unwrap));
store.register_late_pass(move |_| {
Box::new(indexing_slicing::IndexingSlicing::new(
suppress_restriction_lint_in_const,
))
});
store.register_late_pass(move |_| Box::new(non_copy_const::NonCopyConst::new(ignore_interior_mutability.clone())));
store.register_late_pass(move |_| Box::new(indexing_slicing::IndexingSlicing::new(conf)));
store.register_late_pass(move |tcx| Box::new(non_copy_const::NonCopyConst::new(tcx, conf)));
store.register_late_pass(|_| Box::new(ptr_offset_with_cast::PtrOffsetWithCast));
store.register_late_pass(|_| Box::new(redundant_clone::RedundantClone));
store.register_late_pass(|_| Box::new(slow_vector_initialization::SlowVectorInit));
store.register_late_pass(move |_| Box::new(unnecessary_wraps::UnnecessaryWraps::new(avoid_breaking_exported_api)));
store.register_late_pass(move |_| Box::new(unnecessary_wraps::UnnecessaryWraps::new(conf)));
store.register_late_pass(|_| Box::new(assertions_on_constants::AssertionsOnConstants));
store.register_late_pass(|_| Box::new(assertions_on_result_states::AssertionsOnResultStates));
store.register_late_pass(|_| Box::new(inherent_to_string::InherentToString));
store.register_late_pass(move |_| Box::new(trait_bounds::TraitBounds::new(max_trait_bounds, msrv())));
store.register_late_pass(move |_| Box::new(trait_bounds::TraitBounds::new(conf)));
store.register_late_pass(|_| Box::new(comparison_chain::ComparisonChain));
store.register_late_pass(move |_| Box::new(mut_key::MutableKeyType::new(ignore_interior_mutability.clone())));
store.register_late_pass(move |tcx| Box::new(mut_key::MutableKeyType::new(tcx, conf)));
store.register_early_pass(|| Box::new(reference::DerefAddrOf));
store.register_early_pass(|| Box::new(double_parens::DoubleParens));
let format_args = format_args_storage.clone();
@ -874,80 +722,45 @@ pub fn register_lints(store: &mut rustc_lint::LintStore, conf: &'static Conf) {
store.register_early_pass(|| Box::new(redundant_else::RedundantElse));
store.register_late_pass(|_| Box::new(create_dir::CreateDir));
store.register_early_pass(|| Box::new(needless_arbitrary_self_type::NeedlessArbitrarySelfType));
store.register_early_pass(move || {
Box::new(literal_representation::LiteralDigitGrouping::new(
unreadable_literal_lint_fractions,
))
});
store.register_early_pass(move || {
Box::new(literal_representation::DecimalLiteralRepresentation::new(
literal_representation_threshold,
))
});
store.register_late_pass(move |_| {
Box::new(item_name_repetitions::ItemNameRepetitions::new(
enum_variant_name_threshold,
struct_field_name_threshold,
avoid_breaking_exported_api,
allow_private_module_inception,
allowed_prefixes,
))
});
store.register_early_pass(move || Box::new(literal_representation::LiteralDigitGrouping::new(conf)));
store.register_early_pass(move || Box::new(literal_representation::DecimalLiteralRepresentation::new(conf)));
store.register_late_pass(move |_| Box::new(item_name_repetitions::ItemNameRepetitions::new(conf)));
store.register_early_pass(|| Box::new(tabs_in_doc_comments::TabsInDocComments));
store.register_late_pass(move |_| {
Box::new(upper_case_acronyms::UpperCaseAcronyms::new(
avoid_breaking_exported_api,
upper_case_acronyms_aggressive,
))
});
store.register_late_pass(move |_| Box::new(upper_case_acronyms::UpperCaseAcronyms::new(conf)));
store.register_late_pass(|_| Box::<default::Default>::default());
store.register_late_pass(move |_| Box::new(unused_self::UnusedSelf::new(avoid_breaking_exported_api)));
store.register_late_pass(move |_| Box::new(unused_self::UnusedSelf::new(conf)));
store.register_late_pass(|_| Box::new(mutable_debug_assertion::DebugAssertWithMutCall));
store.register_late_pass(|_| Box::new(exit::Exit));
store.register_late_pass(|_| Box::new(to_digit_is_some::ToDigitIsSome));
store.register_late_pass(move |_| Box::new(large_stack_arrays::LargeStackArrays::new(array_size_threshold.into())));
store.register_late_pass(move |_| Box::new(large_const_arrays::LargeConstArrays::new(array_size_threshold.into())));
store.register_late_pass(move |_| Box::new(large_stack_arrays::LargeStackArrays::new(conf)));
store.register_late_pass(move |_| Box::new(large_const_arrays::LargeConstArrays::new(conf)));
store.register_late_pass(|_| Box::new(floating_point_arithmetic::FloatingPointArithmetic));
store.register_late_pass(|_| Box::new(as_conversions::AsConversions));
store.register_late_pass(|_| Box::new(let_underscore::LetUnderscore));
store.register_early_pass(|| Box::<single_component_path_imports::SingleComponentPathImports>::default());
store.register_late_pass(move |_| {
Box::new(excessive_bools::ExcessiveBools::new(
max_struct_bools,
max_fn_params_bools,
))
});
store.register_late_pass(move |_| Box::new(excessive_bools::ExcessiveBools::new(conf)));
store.register_early_pass(|| Box::new(option_env_unwrap::OptionEnvUnwrap));
store.register_late_pass(move |_| {
Box::new(wildcard_imports::WildcardImports::new(
warn_on_all_wildcard_imports,
allowed_wildcard_imports.clone(),
))
});
store.register_late_pass(move |_| Box::new(wildcard_imports::WildcardImports::new(conf)));
store.register_late_pass(|_| Box::<redundant_pub_crate::RedundantPubCrate>::default());
store.register_late_pass(|_| Box::new(unnamed_address::UnnamedAddress));
store.register_late_pass(|_| Box::<dereference::Dereferencing<'_>>::default());
store.register_late_pass(|_| Box::new(option_if_let_else::OptionIfLetElse));
store.register_late_pass(|_| Box::new(future_not_send::FutureNotSend));
store.register_late_pass(move |_| Box::new(large_futures::LargeFuture::new(future_size_threshold)));
store.register_late_pass(move |_| Box::new(large_futures::LargeFuture::new(conf)));
store.register_late_pass(|_| Box::new(if_let_mutex::IfLetMutex));
store.register_late_pass(|_| Box::new(if_not_else::IfNotElse));
store.register_late_pass(|_| Box::new(equatable_if_let::PatternEquality));
store.register_late_pass(|_| Box::new(manual_async_fn::ManualAsyncFn));
store.register_late_pass(|_| Box::new(panic_in_result_fn::PanicInResultFn));
store.register_early_pass(move || {
Box::new(non_expressive_names::NonExpressiveNames {
single_char_binding_names_threshold,
})
});
store.register_early_pass(move || Box::new(nonstandard_macro_braces::MacroBraces::new(standard_macro_braces)));
store.register_early_pass(move || Box::new(non_expressive_names::NonExpressiveNames::new(conf)));
store.register_early_pass(move || Box::new(nonstandard_macro_braces::MacroBraces::new(conf)));
store.register_late_pass(|_| Box::<macro_use::MacroUseImports>::default());
store.register_late_pass(|_| Box::new(pattern_type_mismatch::PatternTypeMismatch));
store.register_late_pass(|_| Box::new(unwrap_in_result::UnwrapInResult));
store.register_late_pass(|_| Box::new(semicolon_if_nothing_returned::SemicolonIfNothingReturned));
store.register_late_pass(|_| Box::new(async_yields_async::AsyncYieldsAsync));
store.register_late_pass(move |_| Box::new(disallowed_macros::DisallowedMacros::new(disallowed_macros.clone())));
store.register_late_pass(move |_| Box::new(disallowed_methods::DisallowedMethods::new(disallowed_methods.clone())));
store.register_late_pass(move |tcx| Box::new(disallowed_macros::DisallowedMacros::new(tcx, conf)));
store.register_late_pass(move |tcx| Box::new(disallowed_methods::DisallowedMethods::new(tcx, conf)));
store.register_early_pass(|| Box::new(asm_syntax::InlineAsmX86AttSyntax));
store.register_early_pass(|| Box::new(asm_syntax::InlineAsmX86IntelSyntax));
store.register_late_pass(|_| Box::new(empty_drop::EmptyDrop));
@ -957,86 +770,57 @@ pub fn register_lints(store: &mut rustc_lint::LintStore, conf: &'static Conf) {
store.register_late_pass(|_| Box::<vec_init_then_push::VecInitThenPush>::default());
store.register_late_pass(|_| Box::new(redundant_slicing::RedundantSlicing));
store.register_late_pass(|_| Box::new(from_str_radix_10::FromStrRadix10));
store.register_late_pass(move |_| Box::new(if_then_some_else_none::IfThenSomeElseNone::new(msrv())));
store.register_late_pass(move |_| Box::new(if_then_some_else_none::IfThenSomeElseNone::new(conf)));
store.register_late_pass(|_| Box::new(bool_assert_comparison::BoolAssertComparison));
store.register_early_pass(move || Box::new(module_style::ModStyle));
store.register_late_pass(|_| Box::<unused_async::UnusedAsync>::default());
store.register_late_pass(move |_| Box::new(disallowed_types::DisallowedTypes::new(disallowed_types.clone())));
store.register_late_pass(move |_| {
Box::new(missing_enforced_import_rename::ImportRename::new(
enforced_import_renames.clone(),
))
});
store.register_early_pass(move || Box::new(disallowed_script_idents::DisallowedScriptIdents::new(allowed_scripts)));
store.register_late_pass(move |tcx| Box::new(disallowed_types::DisallowedTypes::new(tcx, conf)));
store.register_late_pass(move |tcx| Box::new(missing_enforced_import_rename::ImportRename::new(tcx, conf)));
store.register_early_pass(move || Box::new(disallowed_script_idents::DisallowedScriptIdents::new(conf)));
store.register_late_pass(|_| Box::new(strlen_on_c_strings::StrlenOnCStrings));
store.register_late_pass(move |_| Box::new(self_named_constructors::SelfNamedConstructors));
store.register_late_pass(move |_| Box::new(iter_not_returning_iterator::IterNotReturningIterator));
store.register_late_pass(move |_| Box::new(manual_assert::ManualAssert));
store.register_late_pass(move |_| {
Box::new(non_send_fields_in_send_ty::NonSendFieldInSendTy::new(
enable_raw_pointer_heuristic_for_send,
))
});
store.register_late_pass(move |_| {
Box::new(undocumented_unsafe_blocks::UndocumentedUnsafeBlocks::new(
accept_comment_above_statement,
accept_comment_above_attributes,
))
});
store.register_late_pass(move |_| Box::new(non_send_fields_in_send_ty::NonSendFieldInSendTy::new(conf)));
store.register_late_pass(move |_| Box::new(undocumented_unsafe_blocks::UndocumentedUnsafeBlocks::new(conf)));
let format_args = format_args_storage.clone();
store.register_late_pass(move |_| {
Box::new(format_args::FormatArgs::new(
format_args.clone(),
msrv(),
allow_mixed_uninlined_format_args,
))
});
store.register_late_pass(move |_| Box::new(format_args::FormatArgs::new(conf, format_args.clone())));
store.register_late_pass(|_| Box::new(trailing_empty_array::TrailingEmptyArray));
store.register_early_pass(|| Box::new(octal_escapes::OctalEscapes));
store.register_late_pass(|_| Box::new(needless_late_init::NeedlessLateInit));
store.register_late_pass(|_| Box::new(return_self_not_must_use::ReturnSelfNotMustUse));
store.register_late_pass(|_| Box::new(init_numbered_fields::NumberedFields));
store.register_early_pass(|| Box::new(single_char_lifetime_names::SingleCharLifetimeNames));
store.register_late_pass(move |_| Box::new(manual_bits::ManualBits::new(msrv())));
store.register_late_pass(move |_| Box::new(manual_bits::ManualBits::new(conf)));
store.register_late_pass(|_| Box::new(default_union_representation::DefaultUnionRepresentation));
store.register_late_pass(|_| Box::<only_used_in_recursion::OnlyUsedInRecursion>::default());
store.register_late_pass(move |_| Box::new(dbg_macro::DbgMacro::new(allow_dbg_in_tests)));
store.register_late_pass(move |_| Box::new(dbg_macro::DbgMacro::new(conf)));
let format_args = format_args_storage.clone();
store.register_late_pass(move |_| Box::new(write::Write::new(format_args.clone(), allow_print_in_tests)));
store.register_late_pass(move |_| {
Box::new(cargo::Cargo {
ignore_publish: cargo_ignore_publish,
allowed_duplicate_crates: allowed_duplicate_crates.clone(),
})
});
store.register_late_pass(move |_| Box::new(write::Write::new(conf, format_args.clone())));
store.register_late_pass(move |_| Box::new(cargo::Cargo::new(conf)));
store.register_early_pass(|| Box::new(crate_in_macro_def::CrateInMacroDef));
store.register_early_pass(|| Box::new(empty_with_brackets::EmptyWithBrackets));
store.register_late_pass(|_| Box::new(unnecessary_owned_empty_strings::UnnecessaryOwnedEmptyStrings));
store.register_early_pass(|| Box::new(pub_use::PubUse));
store.register_late_pass(|_| Box::new(format_push_string::FormatPushString));
store.register_late_pass(move |_| Box::new(large_include_file::LargeIncludeFile::new(max_include_file_size)));
store.register_late_pass(move |_| Box::new(large_include_file::LargeIncludeFile::new(conf)));
store.register_late_pass(|_| Box::new(strings::TrimSplitWhitespace));
store.register_late_pass(|_| Box::new(rc_clone_in_vec_init::RcCloneInVecInit));
store.register_early_pass(|| Box::<duplicate_mod::DuplicateMod>::default());
store.register_early_pass(|| Box::new(unused_rounding::UnusedRounding));
store.register_early_pass(move || Box::new(almost_complete_range::AlmostCompleteRange::new(msrv())));
store.register_early_pass(move || Box::new(almost_complete_range::AlmostCompleteRange::new(conf)));
store.register_late_pass(|_| Box::new(swap_ptr_to_ref::SwapPtrToRef));
store.register_late_pass(|_| Box::new(mismatching_type_param_order::TypeParamMismatch));
store.register_late_pass(|_| Box::new(read_zero_byte_vec::ReadZeroByteVec));
store.register_late_pass(|_| Box::new(default_instead_of_iter_empty::DefaultIterEmpty));
store.register_late_pass(move |_| Box::new(manual_rem_euclid::ManualRemEuclid::new(msrv())));
store.register_late_pass(move |_| Box::new(manual_retain::ManualRetain::new(msrv())));
store.register_late_pass(move |_| Box::new(manual_rem_euclid::ManualRemEuclid::new(conf)));
store.register_late_pass(move |_| Box::new(manual_retain::ManualRetain::new(conf)));
store.register_late_pass(move |_| Box::new(manual_rotate::ManualRotate));
store.register_late_pass(move |_| {
Box::new(operators::Operators::new(
verbose_bit_mask_threshold,
allow_comparison_to_zero,
))
});
store.register_late_pass(move |_| Box::new(operators::Operators::new(conf)));
store.register_late_pass(|_| Box::<std_instead_of_core::StdReexports>::default());
store.register_late_pass(move |_| Box::new(instant_subtraction::InstantSubtraction::new(msrv())));
store.register_late_pass(move |_| Box::new(instant_subtraction::InstantSubtraction::new(conf)));
store.register_late_pass(|_| Box::new(partialeq_to_none::PartialeqToNone));
store.register_late_pass(move |_| Box::new(manual_clamp::ManualClamp::new(msrv())));
store.register_late_pass(move |_| Box::new(manual_clamp::ManualClamp::new(conf)));
store.register_late_pass(|_| Box::new(manual_string_new::ManualStringNew));
store.register_late_pass(|_| Box::new(unused_peekable::UnusedPeekable));
store.register_early_pass(|| Box::new(multi_assignments::MultiAssignments));
@ -1047,44 +831,25 @@ pub fn register_lints(store: &mut rustc_lint::LintStore, conf: &'static Conf) {
store.register_late_pass(|_| Box::new(missing_trait_methods::MissingTraitMethods));
store.register_late_pass(|_| Box::new(from_raw_with_void_ptr::FromRawWithVoidPtr));
store.register_late_pass(|_| Box::new(suspicious_xor_used_as_pow::ConfusingXorAndPow));
store.register_late_pass(move |_| Box::new(manual_is_ascii_check::ManualIsAsciiCheck::new(msrv())));
store.register_late_pass(move |_| {
Box::new(semicolon_block::SemicolonBlock::new(
semicolon_inside_block_ignore_singleline,
semicolon_outside_block_ignore_multiline,
))
});
store.register_late_pass(move |_| Box::new(manual_is_ascii_check::ManualIsAsciiCheck::new(conf)));
store.register_late_pass(move |_| Box::new(semicolon_block::SemicolonBlock::new(conf)));
store.register_late_pass(|_| Box::new(permissions_set_readonly_false::PermissionsSetReadonlyFalse));
store.register_late_pass(|_| Box::new(size_of_ref::SizeOfRef));
store.register_late_pass(|_| Box::new(multiple_unsafe_ops_per_block::MultipleUnsafeOpsPerBlock));
store.register_late_pass(move |_| {
Box::new(extra_unused_type_parameters::ExtraUnusedTypeParameters::new(
avoid_breaking_exported_api,
))
});
store.register_late_pass(move |_| Box::new(extra_unused_type_parameters::ExtraUnusedTypeParameters::new(conf)));
store.register_late_pass(|_| Box::new(no_mangle_with_rust_abi::NoMangleWithRustAbi));
store.register_late_pass(|_| Box::new(collection_is_never_read::CollectionIsNeverRead));
store.register_late_pass(|_| Box::new(missing_assert_message::MissingAssertMessage));
store.register_late_pass(|_| Box::new(needless_maybe_sized::NeedlessMaybeSized));
store.register_late_pass(|_| Box::new(redundant_async_block::RedundantAsyncBlock));
store.register_late_pass(|_| Box::new(let_with_type_underscore::UnderscoreTyped));
store.register_late_pass(move |_| Box::new(manual_main_separator_str::ManualMainSeparatorStr::new(msrv())));
store.register_late_pass(move |_| Box::new(manual_main_separator_str::ManualMainSeparatorStr::new(conf)));
store.register_late_pass(|_| Box::new(unnecessary_struct_initialization::UnnecessaryStruct));
store.register_late_pass(move |_| {
Box::new(unnecessary_box_returns::UnnecessaryBoxReturns::new(
avoid_breaking_exported_api,
unnecessary_box_size,
))
});
store.register_late_pass(move |_| Box::new(unnecessary_box_returns::UnnecessaryBoxReturns::new(conf)));
store.register_late_pass(|_| Box::new(lines_filter_map_ok::LinesFilterMapOk));
store.register_late_pass(|_| Box::new(tests_outside_test_module::TestsOutsideTestModule));
store.register_late_pass(|_| Box::new(manual_slice_size_calculation::ManualSliceSizeCalculation));
store.register_early_pass(move || {
Box::new(excessive_nesting::ExcessiveNesting {
excessive_nesting_threshold,
nodes: rustc_ast::node_id::NodeSet::new(),
})
});
store.register_early_pass(move || Box::new(excessive_nesting::ExcessiveNesting::new(conf)));
store.register_late_pass(|_| Box::new(items_after_test_module::ItemsAfterTestModule));
store.register_early_pass(|| Box::new(ref_patterns::RefPatterns));
store.register_late_pass(|_| Box::new(default_constructed_unit_structs::DefaultConstructedUnitStructs));
@ -1094,44 +859,21 @@ pub fn register_lints(store: &mut rustc_lint::LintStore, conf: &'static Conf) {
store.register_late_pass(|_| Box::new(redundant_type_annotations::RedundantTypeAnnotations));
store.register_late_pass(|_| Box::new(arc_with_non_send_sync::ArcWithNonSendSync));
store.register_late_pass(|_| Box::new(needless_if::NeedlessIf));
store.register_late_pass(move |_| {
Box::new(min_ident_chars::MinIdentChars {
allowed_idents_below_min_chars: allowed_idents_below_min_chars.clone(),
min_ident_chars_threshold,
})
});
store.register_late_pass(move |_| Box::new(large_stack_frames::LargeStackFrames::new(stack_size_threshold)));
store.register_late_pass(move |_| Box::new(min_ident_chars::MinIdentChars::new(conf)));
store.register_late_pass(move |_| Box::new(large_stack_frames::LargeStackFrames::new(conf)));
store.register_late_pass(|_| Box::new(single_range_in_vec_init::SingleRangeInVecInit));
store.register_late_pass(move |_| {
Box::new(needless_pass_by_ref_mut::NeedlessPassByRefMut::new(
avoid_breaking_exported_api,
))
});
store.register_late_pass(move |_| Box::new(needless_pass_by_ref_mut::NeedlessPassByRefMut::new(conf)));
store.register_late_pass(|_| Box::new(non_canonical_impls::NonCanonicalImpls));
store.register_late_pass(move |_| {
Box::new(single_call_fn::SingleCallFn {
avoid_breaking_exported_api,
def_id_to_usage: rustc_data_structures::fx::FxIndexMap::default(),
})
});
store.register_early_pass(move || {
Box::new(raw_strings::RawStrings {
allow_one_hash_in_raw_strings,
})
});
store.register_late_pass(move |_| Box::new(legacy_numeric_constants::LegacyNumericConstants::new(msrv())));
store.register_late_pass(move |_| Box::new(single_call_fn::SingleCallFn::new(conf)));
store.register_early_pass(move || Box::new(raw_strings::RawStrings::new(conf)));
store.register_late_pass(move |_| Box::new(legacy_numeric_constants::LegacyNumericConstants::new(conf)));
store.register_late_pass(|_| Box::new(manual_range_patterns::ManualRangePatterns));
store.register_early_pass(|| Box::new(visibility::Visibility));
store.register_late_pass(move |_| Box::new(tuple_array_conversions::TupleArrayConversions { msrv: msrv() }));
store.register_late_pass(move |_| Box::new(tuple_array_conversions::TupleArrayConversions::new(conf)));
store.register_late_pass(|_| Box::new(manual_float_methods::ManualFloatMethods));
store.register_late_pass(|_| Box::new(four_forward_slashes::FourForwardSlashes));
store.register_late_pass(|_| Box::new(error_impl_error::ErrorImplError));
store.register_late_pass(move |_| {
Box::new(absolute_paths::AbsolutePaths {
absolute_paths_max_segments,
absolute_paths_allowed_crates: absolute_paths_allowed_crates.clone(),
})
});
store.register_late_pass(move |_| Box::new(absolute_paths::AbsolutePaths::new(conf)));
store.register_late_pass(|_| Box::new(redundant_locals::RedundantLocals));
store.register_late_pass(|_| Box::new(ignored_unit_patterns::IgnoredUnitPatterns));
store.register_late_pass(|_| Box::<reserve_after_initialization::ReserveAfterInitialization>::default());
@ -1140,10 +882,10 @@ pub fn register_lints(store: &mut rustc_lint::LintStore, conf: &'static Conf) {
store.register_late_pass(|_| Box::new(unnecessary_map_on_constructor::UnnecessaryMapOnConstructor));
store.register_late_pass(move |_| {
Box::new(needless_borrows_for_generic_args::NeedlessBorrowsForGenericArgs::new(
msrv(),
conf,
))
});
store.register_late_pass(move |_| Box::new(manual_hash_one::ManualHashOne::new(msrv())));
store.register_late_pass(move |_| Box::new(manual_hash_one::ManualHashOne::new(conf)));
store.register_late_pass(|_| Box::new(iter_without_into_iter::IterWithoutIntoIter));
store.register_late_pass(|_| Box::new(iter_over_hash_type::IterOverHashType));
store.register_late_pass(|_| Box::new(impl_hash_with_borrow_str_and_bytes::ImplHashWithBorrowStrBytes));
@ -1151,27 +893,17 @@ pub fn register_lints(store: &mut rustc_lint::LintStore, conf: &'static Conf) {
store.register_late_pass(|_| Box::new(uninhabited_references::UninhabitedReferences));
store.register_late_pass(|_| Box::new(ineffective_open_options::IneffectiveOpenOptions));
store.register_late_pass(|_| Box::<unconditional_recursion::UnconditionalRecursion>::default());
store.register_late_pass(move |_| {
Box::new(pub_underscore_fields::PubUnderscoreFields {
behavior: pub_underscore_fields_behavior,
})
});
store
.register_late_pass(move |_| Box::new(missing_const_for_thread_local::MissingConstForThreadLocal::new(msrv())));
store.register_late_pass(move |_| Box::new(incompatible_msrv::IncompatibleMsrv::new(msrv())));
store.register_late_pass(move |_| Box::new(pub_underscore_fields::PubUnderscoreFields::new(conf)));
store.register_late_pass(move |_| Box::new(missing_const_for_thread_local::MissingConstForThreadLocal::new(conf)));
store.register_late_pass(move |_| Box::new(incompatible_msrv::IncompatibleMsrv::new(conf)));
store.register_late_pass(|_| Box::new(to_string_trait_impl::ToStringTraitImpl));
store.register_early_pass(|| Box::new(multiple_bound_locations::MultipleBoundLocations));
store.register_late_pass(move |_| Box::new(assigning_clones::AssigningClones::new(msrv())));
store.register_late_pass(move |_| Box::new(assigning_clones::AssigningClones::new(conf)));
store.register_late_pass(|_| Box::new(zero_repeat_side_effects::ZeroRepeatSideEffects));
store.register_late_pass(|_| Box::new(manual_unwrap_or_default::ManualUnwrapOrDefault));
store.register_late_pass(|_| Box::new(integer_division_remainder_used::IntegerDivisionRemainderUsed));
store.register_late_pass(move |_| {
Box::new(macro_metavars_in_unsafe::ExprMetavarsInUnsafe {
warn_unsafe_macro_metavars_in_private_macros,
..Default::default()
})
});
store.register_late_pass(move |_| Box::new(string_patterns::StringPatterns::new(msrv())));
store.register_late_pass(move |_| Box::new(macro_metavars_in_unsafe::ExprMetavarsInUnsafe::new(conf)));
store.register_late_pass(move |_| Box::new(string_patterns::StringPatterns::new(conf)));
store.register_early_pass(|| Box::new(field_scoped_visibility_modifiers::FieldScopedVisibilityModifiers));
store.register_late_pass(|_| Box::new(set_contains_or_insert::HashsetInsertAfterContains));
store.register_early_pass(|| Box::new(byte_char_slices::ByteCharSlice));

View file

@ -1,6 +1,7 @@
//! Lints concerned with the grouping of digits with underscores in integral or
//! floating-point literal expressions.
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::numeric_literal::{NumericLiteral, Radix};
use clippy_utils::source::snippet_opt;
@ -218,7 +219,6 @@ impl WarningType {
}
}
#[derive(Copy, Clone)]
pub struct LiteralDigitGrouping {
lint_fraction_readability: bool,
}
@ -245,13 +245,13 @@ impl EarlyLintPass for LiteralDigitGrouping {
const UUID_GROUP_LENS: [usize; 5] = [8, 4, 4, 4, 12];
impl LiteralDigitGrouping {
pub fn new(lint_fraction_readability: bool) -> Self {
pub fn new(conf: &'static Conf) -> Self {
Self {
lint_fraction_readability,
lint_fraction_readability: conf.unreadable_literal_lint_fractions,
}
}
fn check_lit(self, cx: &EarlyContext<'_>, lit: token::Lit, span: Span) {
fn check_lit(&self, cx: &EarlyContext<'_>, lit: token::Lit, span: Span) {
if let Some(src) = snippet_opt(cx, span)
&& let Ok(lit_kind) = LitKind::from_token_lit(lit)
&& let Some(mut num_lit) = NumericLiteral::from_lit_kind(&src, &lit_kind)
@ -437,7 +437,6 @@ impl LiteralDigitGrouping {
}
#[expect(clippy::module_name_repetitions)]
#[derive(Copy, Clone)]
pub struct DecimalLiteralRepresentation {
threshold: u64,
}
@ -455,11 +454,12 @@ impl EarlyLintPass for DecimalLiteralRepresentation {
}
impl DecimalLiteralRepresentation {
#[must_use]
pub fn new(threshold: u64) -> Self {
Self { threshold }
pub fn new(conf: &'static Conf) -> Self {
Self {
threshold: conf.literal_representation_threshold,
}
}
fn check_lit(self, cx: &EarlyContext<'_>, lit: token::Lit, span: Span) {
fn check_lit(&self, cx: &EarlyContext<'_>, lit: token::Lit, span: Span) {
// Lint integral literals.
if let Ok(lit_kind) = LitKind::from_token_lit(lit)
&& let LitKind::Int(val, _) = lit_kind

View file

@ -23,6 +23,7 @@ mod while_let_loop;
mod while_let_on_iterator;
use clippy_config::msrvs::Msrv;
use clippy_config::Conf;
use clippy_utils::higher;
use rustc_hir::{Expr, ExprKind, LoopSource, Pat};
use rustc_lint::{LateContext, LateLintPass};
@ -717,10 +718,10 @@ pub struct Loops {
enforce_iter_loop_reborrow: bool,
}
impl Loops {
pub fn new(msrv: Msrv, enforce_iter_loop_reborrow: bool) -> Self {
pub fn new(conf: &'static Conf) -> Self {
Self {
msrv,
enforce_iter_loop_reborrow,
msrv: conf.msrv.clone(),
enforce_iter_loop_reborrow: conf.enforce_iter_loop_reborrow,
}
}
}

View file

@ -1,6 +1,4 @@
use std::collections::btree_map::Entry;
use std::collections::BTreeMap;
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_hir_and_then;
use clippy_utils::is_lint_allowed;
use itertools::Itertools;
@ -10,6 +8,8 @@ use rustc_hir::{BlockCheckMode, Expr, ExprKind, HirId, Stmt, UnsafeSource};
use rustc_lint::{LateContext, LateLintPass};
use rustc_session::impl_lint_pass;
use rustc_span::{sym, Span, SyntaxContext};
use std::collections::btree_map::Entry;
use std::collections::BTreeMap;
declare_clippy_lint! {
/// ### What it does
@ -90,9 +90,8 @@ pub enum MetavarState {
ReferencedInSafe,
}
#[derive(Default)]
pub struct ExprMetavarsInUnsafe {
pub warn_unsafe_macro_metavars_in_private_macros: bool,
warn_unsafe_macro_metavars_in_private_macros: bool,
/// A metavariable can be expanded more than once, potentially across multiple bodies, so it
/// requires some state kept across HIR nodes to make it possible to delay a warning
/// and later undo:
@ -106,7 +105,16 @@ pub struct ExprMetavarsInUnsafe {
/// }
/// }
/// ```
pub metavar_expns: BTreeMap<Span, MetavarState>,
metavar_expns: BTreeMap<Span, MetavarState>,
}
impl ExprMetavarsInUnsafe {
pub fn new(conf: &'static Conf) -> Self {
Self {
warn_unsafe_macro_metavars_in_private_macros: conf.warn_unsafe_macro_metavars_in_private_macros,
metavar_expns: BTreeMap::new(),
}
}
}
struct BodyVisitor<'a, 'tcx> {

View file

@ -1,4 +1,5 @@
use clippy_config::msrvs::{self, Msrv};
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::get_parent_expr;
use clippy_utils::source::snippet_with_context;
@ -34,15 +35,15 @@ declare_clippy_lint! {
"manual implementation of `size_of::<T>() * 8` can be simplified with `T::BITS`"
}
#[derive(Clone)]
pub struct ManualBits {
msrv: Msrv,
}
impl ManualBits {
#[must_use]
pub fn new(msrv: Msrv) -> Self {
Self { msrv }
pub fn new(conf: &'static Conf) -> Self {
Self {
msrv: conf.msrv.clone(),
}
}
}

View file

@ -1,4 +1,5 @@
use clippy_config::msrvs::{self, Msrv};
use clippy_config::Conf;
use clippy_utils::consts::{constant, Constant};
use clippy_utils::diagnostics::{span_lint_and_then, span_lint_hir_and_then};
use clippy_utils::higher::If;
@ -97,8 +98,10 @@ pub struct ManualClamp {
}
impl ManualClamp {
pub fn new(msrv: Msrv) -> Self {
Self { msrv }
pub fn new(conf: &'static Conf) -> Self {
Self {
msrv: conf.msrv.clone(),
}
}
}

View file

@ -1,4 +1,5 @@
use clippy_config::msrvs::{self, Msrv};
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_hir_and_then;
use clippy_utils::source::snippet_opt;
use clippy_utils::visitors::{is_local_used, local_used_once};
@ -51,9 +52,10 @@ pub struct ManualHashOne {
}
impl ManualHashOne {
#[must_use]
pub fn new(msrv: Msrv) -> Self {
Self { msrv }
pub fn new(conf: &'static Conf) -> Self {
Self {
msrv: conf.msrv.clone(),
}
}
}

View file

@ -1,4 +1,5 @@
use clippy_config::msrvs::{self, Msrv};
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::macros::matching_root_macro_call;
use clippy_utils::sugg::Sugg;
@ -62,9 +63,10 @@ pub struct ManualIsAsciiCheck {
}
impl ManualIsAsciiCheck {
#[must_use]
pub fn new(msrv: Msrv) -> Self {
Self { msrv }
pub fn new(conf: &'static Conf) -> Self {
Self {
msrv: conf.msrv.clone(),
}
}
}

View file

@ -1,4 +1,5 @@
use clippy_config::msrvs::{self, Msrv};
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::{is_trait_method, match_def_path, paths, peel_hir_expr_refs};
use rustc_errors::Applicability;
@ -37,9 +38,10 @@ pub struct ManualMainSeparatorStr {
}
impl ManualMainSeparatorStr {
#[must_use]
pub fn new(msrv: Msrv) -> Self {
Self { msrv }
pub fn new(conf: &'static Conf) -> Self {
Self {
msrv: conf.msrv.clone(),
}
}
}

View file

@ -1,4 +1,5 @@
use clippy_config::msrvs::{self, Msrv};
use clippy_config::Conf;
use clippy_utils::diagnostics::{span_lint_and_then, span_lint_hir_and_then};
use clippy_utils::is_doc_hidden;
use clippy_utils::source::snippet_opt;
@ -67,9 +68,10 @@ pub struct ManualNonExhaustiveStruct {
}
impl ManualNonExhaustiveStruct {
#[must_use]
pub fn new(msrv: Msrv) -> Self {
Self { msrv }
pub fn new(conf: &'static Conf) -> Self {
Self {
msrv: conf.msrv.clone(),
}
}
}
@ -83,10 +85,9 @@ pub struct ManualNonExhaustiveEnum {
}
impl ManualNonExhaustiveEnum {
#[must_use]
pub fn new(msrv: Msrv) -> Self {
pub fn new(conf: &'static Conf) -> Self {
Self {
msrv,
msrv: conf.msrv.clone(),
constructed_enum_variants: FxHashSet::default(),
potential_enums: Vec::new(),
}

View file

@ -1,4 +1,5 @@
use clippy_config::msrvs::{self, Msrv};
use clippy_config::Conf;
use clippy_utils::consts::{constant_full_int, FullInt};
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::source::snippet_with_context;
@ -38,9 +39,10 @@ pub struct ManualRemEuclid {
}
impl ManualRemEuclid {
#[must_use]
pub fn new(msrv: Msrv) -> Self {
Self { msrv }
pub fn new(conf: &'static Conf) -> Self {
Self {
msrv: conf.msrv.clone(),
}
}
}

View file

@ -1,4 +1,5 @@
use clippy_config::msrvs::{self, Msrv};
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::source::snippet;
use clippy_utils::ty::{is_type_diagnostic_item, is_type_lang_item};
@ -59,9 +60,10 @@ pub struct ManualRetain {
}
impl ManualRetain {
#[must_use]
pub fn new(msrv: Msrv) -> Self {
Self { msrv }
pub fn new(conf: &'static Conf) -> Self {
Self {
msrv: conf.msrv.clone(),
}
}
}

View file

@ -1,4 +1,5 @@
use clippy_config::msrvs::{self, Msrv};
use clippy_config::Conf;
use clippy_utils::consts::{constant, Constant};
use clippy_utils::diagnostics::{multispan_sugg, span_lint_and_then};
use clippy_utils::source::snippet;
@ -50,9 +51,10 @@ pub struct ManualStrip {
}
impl ManualStrip {
#[must_use]
pub fn new(msrv: Msrv) -> Self {
Self { msrv }
pub fn new(conf: &'static Conf) -> Self {
Self {
msrv: conf.msrv.clone(),
}
}
}

View file

@ -25,6 +25,7 @@ mod try_err;
mod wild_in_or_pats;
use clippy_config::msrvs::{self, Msrv};
use clippy_config::Conf;
use clippy_utils::source::walk_span_to_context;
use clippy_utils::{higher, in_constant, is_direct_expn_of, is_span_match, span_contains_cfg};
use rustc_hir::{Arm, Expr, ExprKind, LetStmt, MatchSource, Pat, PatKind};
@ -980,10 +981,9 @@ pub struct Matches {
}
impl Matches {
#[must_use]
pub fn new(msrv: Msrv) -> Self {
pub fn new(conf: &'static Conf) -> Self {
Self {
msrv,
msrv: conf.msrv.clone(),
infallible_destructuring_match_linted: false,
}
}

View file

@ -1,4 +1,5 @@
use clippy_config::msrvs::{self, Msrv};
use clippy_config::Conf;
use clippy_utils::diagnostics::{span_lint_and_help, span_lint_and_sugg, span_lint_and_then};
use clippy_utils::source::{snippet, snippet_with_applicability};
use clippy_utils::sugg::Sugg;
@ -217,9 +218,10 @@ pub struct MemReplace {
}
impl MemReplace {
#[must_use]
pub fn new(msrv: Msrv) -> Self {
Self { msrv }
pub fn new(conf: &'static Conf) -> Self {
Self {
msrv: conf.msrv.clone(),
}
}
}

View file

@ -133,6 +133,7 @@ mod zst_offset;
use bind_instead_of_map::BindInsteadOfMap;
use clippy_config::msrvs::{self, Msrv};
use clippy_config::Conf;
use clippy_utils::consts::{constant, Constant};
use clippy_utils::diagnostics::{span_lint, span_lint_and_help};
use clippy_utils::macros::FormatArgsStorage;
@ -4131,27 +4132,20 @@ pub struct Methods {
msrv: Msrv,
allow_expect_in_tests: bool,
allow_unwrap_in_tests: bool,
allowed_dotfiles: FxHashSet<String>,
allowed_dotfiles: FxHashSet<&'static str>,
format_args: FormatArgsStorage,
}
impl Methods {
#[must_use]
pub fn new(
avoid_breaking_exported_api: bool,
msrv: Msrv,
allow_expect_in_tests: bool,
allow_unwrap_in_tests: bool,
mut allowed_dotfiles: FxHashSet<String>,
format_args: FormatArgsStorage,
) -> Self {
allowed_dotfiles.extend(DEFAULT_ALLOWED_DOTFILES.iter().map(ToString::to_string));
pub fn new(conf: &'static Conf, format_args: FormatArgsStorage) -> Self {
let mut allowed_dotfiles: FxHashSet<_> = conf.allowed_dotfiles.iter().map(|s| &**s).collect();
allowed_dotfiles.extend(DEFAULT_ALLOWED_DOTFILES);
Self {
avoid_breaking_exported_api,
msrv,
allow_expect_in_tests,
allow_unwrap_in_tests,
avoid_breaking_exported_api: conf.avoid_breaking_exported_api,
msrv: conf.msrv.clone(),
allow_expect_in_tests: conf.allow_expect_in_tests,
allow_unwrap_in_tests: conf.allow_unwrap_in_tests,
allowed_dotfiles,
format_args,
}

View file

@ -21,7 +21,7 @@ pub(super) fn check(
path: &Expr<'_>,
expr: &Expr<'_>,
msrv: &Msrv,
allowed_dotfiles: &FxHashSet<String>,
allowed_dotfiles: &FxHashSet<&'static str>,
) {
if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(recv).peel_refs(), sym::Path)
&& !path.span.from_expansion()

View file

@ -1,3 +1,4 @@
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint;
use clippy_utils::is_from_proc_macro;
use rustc_data_structures::fx::FxHashSet;
@ -39,13 +40,19 @@ declare_clippy_lint! {
}
impl_lint_pass!(MinIdentChars => [MIN_IDENT_CHARS]);
#[derive(Clone)]
pub struct MinIdentChars {
pub allowed_idents_below_min_chars: FxHashSet<String>,
pub min_ident_chars_threshold: u64,
allowed_idents_below_min_chars: &'static FxHashSet<String>,
min_ident_chars_threshold: u64,
}
impl MinIdentChars {
pub fn new(conf: &'static Conf) -> Self {
Self {
allowed_idents_below_min_chars: &conf.allowed_idents_below_min_chars,
min_ident_chars_threshold: conf.min_ident_chars_threshold,
}
}
#[expect(clippy::cast_possible_truncation)]
fn is_ident_too_short(&self, cx: &LateContext<'_>, str: &str, span: Span) -> bool {
!in_external_macro(cx.sess(), span)

View file

@ -1,4 +1,5 @@
use clippy_config::msrvs::{self, Msrv};
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::qualify_min_const_fn::is_min_const_fn;
use clippy_utils::{fn_has_unsatisfiable_preds, is_entrypoint_fn, is_from_proc_macro, trait_ref_of_method};
@ -79,9 +80,10 @@ pub struct MissingConstForFn {
}
impl MissingConstForFn {
#[must_use]
pub fn new(msrv: Msrv) -> Self {
Self { msrv }
pub fn new(conf: &'static Conf) -> Self {
Self {
msrv: conf.msrv.clone(),
}
}
}

View file

@ -1,4 +1,5 @@
use clippy_config::msrvs::{self, Msrv};
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::macros::macro_backtrace;
use clippy_utils::qualify_min_const_fn::is_min_const_fn;
@ -49,9 +50,10 @@ pub struct MissingConstForThreadLocal {
}
impl MissingConstForThreadLocal {
#[must_use]
pub fn new(msrv: Msrv) -> Self {
Self { msrv }
pub fn new(conf: &'static Conf) -> Self {
Self {
msrv: conf.msrv.clone(),
}
}
}

View file

@ -5,6 +5,7 @@
// [`missing_doc`]: https://github.com/rust-lang/rust/blob/cf9cf7c923eb01146971429044f216a3ca905e06/compiler/rustc_lint/src/builtin.rs#L415
//
use clippy_config::Conf;
use clippy_utils::attrs::is_doc_hidden;
use clippy_utils::diagnostics::span_lint;
use clippy_utils::is_from_proc_macro;
@ -51,18 +52,10 @@ pub struct MissingDoc {
prev_span: Option<Span>,
}
impl Default for MissingDoc {
#[must_use]
fn default() -> Self {
Self::new(false)
}
}
impl MissingDoc {
#[must_use]
pub fn new(crate_items_only: bool) -> Self {
pub fn new(conf: &'static Conf) -> Self {
Self {
crate_items_only,
crate_items_only: conf.missing_docs_in_crate_items,
doc_hidden_stack: vec![false],
prev_span: None,
}

View file

@ -1,12 +1,13 @@
use clippy_config::types::Rename;
use clippy_config::Conf;
use clippy_utils::def_path_def_ids;
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::source::snippet_opt;
use rustc_data_structures::fx::FxHashMap;
use rustc_errors::Applicability;
use rustc_hir::def::Res;
use rustc_hir::def_id::DefId;
use rustc_hir::def_id::DefIdMap;
use rustc_hir::{Item, ItemKind, UseKind};
use rustc_lint::{LateContext, LateLintPass, LintContext};
use rustc_middle::ty::TyCtxt;
use rustc_session::impl_lint_pass;
use rustc_span::Symbol;
@ -46,15 +47,18 @@ declare_clippy_lint! {
}
pub struct ImportRename {
conf_renames: Vec<Rename>,
renames: FxHashMap<DefId, Symbol>,
renames: DefIdMap<Symbol>,
}
impl ImportRename {
pub fn new(conf_renames: Vec<Rename>) -> Self {
pub fn new(tcx: TyCtxt<'_>, conf: &'static Conf) -> Self {
Self {
conf_renames,
renames: FxHashMap::default(),
renames: conf
.enforced_import_renames
.iter()
.map(|x| (x.path.split("::").collect::<Vec<_>>(), Symbol::intern(&x.rename)))
.flat_map(|(path, rename)| def_path_def_ids(tcx, &path).map(move |id| (id, rename)))
.collect(),
}
}
}
@ -62,15 +66,6 @@ impl ImportRename {
impl_lint_pass!(ImportRename => [MISSING_ENFORCED_IMPORT_RENAMES]);
impl LateLintPass<'_> for ImportRename {
fn check_crate(&mut self, cx: &LateContext<'_>) {
for Rename { path, rename } in &self.conf_renames {
let segs = path.split("::").collect::<Vec<_>>();
for id in clippy_utils::def_path_def_ids(cx, &segs) {
self.renames.insert(id, Symbol::intern(rename));
}
}
}
fn check_item(&mut self, cx: &LateContext<'_>, item: &Item<'_>) {
if let ItemKind::Use(path, UseKind::Single) = &item.kind {
for &res in &path.res {

View file

@ -1,9 +1,10 @@
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint;
use clippy_utils::trait_ref_of_method;
use clippy_utils::ty::InteriorMut;
use rustc_hir as hir;
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::ty::{self, Ty};
use rustc_middle::ty::{self, Ty, TyCtxt};
use rustc_session::impl_lint_pass;
use rustc_span::def_id::LocalDefId;
use rustc_span::symbol::sym;
@ -67,17 +68,12 @@ declare_clippy_lint! {
}
pub struct MutableKeyType<'tcx> {
ignore_interior_mutability: Vec<String>,
interior_mut: InteriorMut<'tcx>,
}
impl_lint_pass!(MutableKeyType<'_> => [ MUTABLE_KEY_TYPE ]);
impl<'tcx> LateLintPass<'tcx> for MutableKeyType<'tcx> {
fn check_crate(&mut self, cx: &LateContext<'tcx>) {
self.interior_mut = InteriorMut::without_pointers(cx, &self.ignore_interior_mutability);
}
fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'tcx>) {
if let hir::ItemKind::Fn(ref sig, ..) = item.kind {
self.check_sig(cx, item.owner_id.def_id, sig.decl);
@ -107,10 +103,9 @@ impl<'tcx> LateLintPass<'tcx> for MutableKeyType<'tcx> {
}
impl<'tcx> MutableKeyType<'tcx> {
pub fn new(ignore_interior_mutability: Vec<String>) -> Self {
pub fn new(tcx: TyCtxt<'tcx>, conf: &'static Conf) -> Self {
Self {
ignore_interior_mutability,
interior_mut: InteriorMut::default(),
interior_mut: InteriorMut::without_pointers(tcx, &conf.ignore_interior_mutability),
}
}

View file

@ -1,4 +1,5 @@
use clippy_config::msrvs::{self, Msrv};
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::mir::PossibleBorrowerMap;
use clippy_utils::source::snippet_with_context;
@ -67,11 +68,10 @@ pub struct NeedlessBorrowsForGenericArgs<'tcx> {
impl_lint_pass!(NeedlessBorrowsForGenericArgs<'_> => [NEEDLESS_BORROWS_FOR_GENERIC_ARGS]);
impl NeedlessBorrowsForGenericArgs<'_> {
#[must_use]
pub fn new(msrv: Msrv) -> Self {
pub fn new(conf: &'static Conf) -> Self {
Self {
possible_borrowers: Vec::new(),
msrv,
msrv: conf.msrv.clone(),
}
}
}

View file

@ -1,8 +1,10 @@
use super::needless_pass_by_value::requires_exact_signature;
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_hir_and_then;
use clippy_utils::source::snippet;
use clippy_utils::visitors::for_each_expr;
use clippy_utils::{inherits_cfg, is_from_proc_macro, is_self};
use core::ops::ControlFlow;
use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
use rustc_errors::Applicability;
use rustc_hir::intravisit::FnKind;
@ -20,8 +22,6 @@ use rustc_span::symbol::kw;
use rustc_span::Span;
use rustc_target::spec::abi::Abi;
use core::ops::ControlFlow;
declare_clippy_lint! {
/// ### What it does
/// Check if a `&mut` function argument is actually used mutably.
@ -51,7 +51,6 @@ declare_clippy_lint! {
"using a `&mut` argument when it's not mutated"
}
#[derive(Clone)]
pub struct NeedlessPassByRefMut<'tcx> {
avoid_breaking_exported_api: bool,
used_fn_def_ids: FxHashSet<LocalDefId>,
@ -59,9 +58,9 @@ pub struct NeedlessPassByRefMut<'tcx> {
}
impl NeedlessPassByRefMut<'_> {
pub fn new(avoid_breaking_exported_api: bool) -> Self {
pub fn new(conf: &'static Conf) -> Self {
Self {
avoid_breaking_exported_api,
avoid_breaking_exported_api: conf.avoid_breaking_exported_api,
used_fn_def_ids: FxHashSet::default(),
fn_def_ids_to_maybe_unused_mut: FxIndexMap::default(),
}

View file

@ -4,6 +4,7 @@
use std::ptr;
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::in_constant;
use clippy_utils::macros::macro_backtrace;
@ -179,17 +180,15 @@ fn lint<'tcx>(cx: &LateContext<'tcx>, source: Source<'tcx>) {
}
pub struct NonCopyConst<'tcx> {
ignore_interior_mutability: Vec<String>,
interior_mut: InteriorMut<'tcx>,
}
impl_lint_pass!(NonCopyConst<'_> => [DECLARE_INTERIOR_MUTABLE_CONST, BORROW_INTERIOR_MUTABLE_CONST]);
impl<'tcx> NonCopyConst<'tcx> {
pub fn new(ignore_interior_mutability: Vec<String>) -> Self {
pub fn new(tcx: TyCtxt<'tcx>, conf: &'static Conf) -> Self {
Self {
ignore_interior_mutability,
interior_mut: InteriorMut::default(),
interior_mut: InteriorMut::new(tcx, &conf.ignore_interior_mutability),
}
}
@ -308,10 +307,6 @@ impl<'tcx> NonCopyConst<'tcx> {
}
impl<'tcx> LateLintPass<'tcx> for NonCopyConst<'tcx> {
fn check_crate(&mut self, cx: &LateContext<'tcx>) {
self.interior_mut = InteriorMut::new(cx, &self.ignore_interior_mutability);
}
fn check_item(&mut self, cx: &LateContext<'tcx>, it: &'tcx Item<'_>) {
if let ItemKind::Const(.., body_id) = it.kind {
let ty = cx.tcx.type_of(it.owner_id).instantiate_identity();

View file

@ -1,3 +1,4 @@
use clippy_config::Conf;
use clippy_utils::diagnostics::{span_lint, span_lint_and_then};
use rustc_ast::ast::{
self, Arm, AssocItem, AssocItemKind, Attribute, Block, FnDecl, Item, ItemKind, Local, Pat, PatKind,
@ -73,13 +74,20 @@ declare_clippy_lint! {
"unclear name"
}
#[derive(Copy, Clone)]
pub struct NonExpressiveNames {
pub single_char_binding_names_threshold: u64,
}
impl_lint_pass!(NonExpressiveNames => [SIMILAR_NAMES, MANY_SINGLE_CHAR_NAMES, JUST_UNDERSCORES_AND_DIGITS]);
impl NonExpressiveNames {
pub fn new(conf: &'static Conf) -> Self {
Self {
single_char_binding_names_threshold: conf.single_char_binding_names_threshold,
}
}
}
struct ExistingName {
interned: Symbol,
span: Span,
@ -90,7 +98,7 @@ struct ExistingName {
struct SimilarNamesLocalVisitor<'a, 'tcx> {
names: Vec<ExistingName>,
cx: &'a EarlyContext<'tcx>,
lint: NonExpressiveNames,
threshold: u64,
/// A stack of scopes containing the single-character bindings in each scope.
single_char_names: Vec<Vec<Ident>>,
@ -103,8 +111,7 @@ impl<'a, 'tcx> SimilarNamesLocalVisitor<'a, 'tcx> {
}
let num_single_char_names = self.single_char_names.iter().flatten().count();
let threshold = self.lint.single_char_binding_names_threshold;
if num_single_char_names as u64 > threshold {
if num_single_char_names as u64 > self.threshold {
let span = self
.single_char_names
.iter()
@ -384,7 +391,7 @@ impl EarlyLintPass for NonExpressiveNames {
..
}) = item.kind
{
do_check(*self, cx, &item.attrs, &sig.decl, blk);
do_check(self, cx, &item.attrs, &sig.decl, blk);
}
}
@ -399,17 +406,17 @@ impl EarlyLintPass for NonExpressiveNames {
..
}) = item.kind
{
do_check(*self, cx, &item.attrs, &sig.decl, blk);
do_check(self, cx, &item.attrs, &sig.decl, blk);
}
}
}
fn do_check(lint: NonExpressiveNames, cx: &EarlyContext<'_>, attrs: &[Attribute], decl: &FnDecl, blk: &Block) {
fn do_check(lint: &NonExpressiveNames, cx: &EarlyContext<'_>, attrs: &[Attribute], decl: &FnDecl, blk: &Block) {
if !attrs.iter().any(|attr| attr.has_name(sym::test)) {
let mut visitor = SimilarNamesLocalVisitor {
names: Vec::new(),
cx,
lint,
threshold: lint.single_char_binding_names_threshold,
single_char_names: vec![vec![]],
};

View file

@ -1,3 +1,4 @@
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::is_lint_allowed;
use clippy_utils::source::snippet;
@ -54,15 +55,14 @@ declare_clippy_lint! {
"there is a field that is not safe to be sent to another thread in a `Send` struct"
}
#[derive(Copy, Clone)]
pub struct NonSendFieldInSendTy {
enable_raw_pointer_heuristic: bool,
}
impl NonSendFieldInSendTy {
pub fn new(enable_raw_pointer_heuristic: bool) -> Self {
pub fn new(conf: &'static Conf) -> Self {
Self {
enable_raw_pointer_heuristic,
enable_raw_pointer_heuristic: conf.enable_raw_pointer_heuristic_for_send,
}
}
}

View file

@ -1,4 +1,5 @@
use clippy_config::types::MacroMatcher;
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::source::snippet_opt;
use rustc_ast::ast;
@ -35,17 +36,15 @@ declare_clippy_lint! {
/// The (callsite span, (open brace, close brace), source snippet)
type MacroInfo = (Span, (char, char), String);
#[derive(Debug)]
pub struct MacroBraces {
macro_braces: FxHashMap<String, (char, char)>,
done: FxHashSet<Span>,
}
impl MacroBraces {
pub fn new(conf: &[MacroMatcher]) -> Self {
let macro_braces = macro_braces(conf);
pub fn new(conf: &'static Conf) -> Self {
Self {
macro_braces,
macro_braces: macro_braces(&conf.standard_macro_braces),
done: FxHashSet::default(),
}
}

View file

@ -1,4 +1,5 @@
use super::ARITHMETIC_SIDE_EFFECTS;
use clippy_config::Conf;
use clippy_utils::consts::{constant, constant_simple, Constant};
use clippy_utils::diagnostics::span_lint;
use clippy_utils::ty::is_type_diagnostic_item;
@ -11,19 +12,9 @@ use rustc_span::symbol::sym;
use rustc_span::{Span, Symbol};
use {rustc_ast as ast, rustc_hir as hir};
const HARD_CODED_ALLOWED_BINARY: &[[&str; 2]] = &[["f32", "f32"], ["f64", "f64"], ["std::string::String", "str"]];
const HARD_CODED_ALLOWED_UNARY: &[&str] = &["f32", "f64", "std::num::Saturating", "std::num::Wrapping"];
const DISALLOWED_INT_METHODS: &[Symbol] = &[
sym::saturating_div,
sym::wrapping_div,
sym::wrapping_rem,
sym::wrapping_rem_euclid,
];
#[derive(Debug)]
pub struct ArithmeticSideEffects {
allowed_binary: FxHashMap<String, FxHashSet<String>>,
allowed_unary: FxHashSet<String>,
allowed_binary: FxHashMap<&'static str, FxHashSet<&'static str>>,
allowed_unary: FxHashSet<&'static str>,
// Used to check whether expressions are constants, such as in enum discriminants and consts
const_span: Option<Span>,
disallowed_int_methods: FxHashSet<Symbol>,
@ -33,26 +24,38 @@ pub struct ArithmeticSideEffects {
impl_lint_pass!(ArithmeticSideEffects => [ARITHMETIC_SIDE_EFFECTS]);
impl ArithmeticSideEffects {
#[must_use]
pub fn new(user_allowed_binary: Vec<[String; 2]>, user_allowed_unary: Vec<String>) -> Self {
let mut allowed_binary: FxHashMap<String, FxHashSet<String>> = <_>::default();
for [lhs, rhs] in user_allowed_binary.into_iter().chain(
HARD_CODED_ALLOWED_BINARY
.iter()
.copied()
.map(|[lhs, rhs]| [lhs.to_string(), rhs.to_string()]),
) {
pub fn new(conf: &'static Conf) -> Self {
let mut allowed_binary = FxHashMap::<&'static str, FxHashSet<&'static str>>::default();
let mut allowed_unary = FxHashSet::<&'static str>::default();
allowed_unary.extend(["f32", "f64", "std::num::Saturating", "std::num::Wrapping"]);
allowed_unary.extend(conf.arithmetic_side_effects_allowed_unary.iter().map(|x| &**x));
allowed_binary.extend([
("f32", FxHashSet::from_iter(["f32"])),
("f64", FxHashSet::from_iter(["f64"])),
("std::string::String", FxHashSet::from_iter(["str"])),
]);
for [lhs, rhs] in &conf.arithmetic_side_effects_allowed_binary {
allowed_binary.entry(lhs).or_default().insert(rhs);
}
let allowed_unary = user_allowed_unary
.into_iter()
.chain(HARD_CODED_ALLOWED_UNARY.iter().copied().map(String::from))
.collect();
for s in &conf.arithmetic_side_effects_allowed {
allowed_binary.entry(s).or_default().insert("*");
allowed_binary.entry("*").or_default().insert(s);
allowed_unary.insert(s);
}
Self {
allowed_binary,
allowed_unary,
disallowed_int_methods: [
sym::saturating_div,
sym::wrapping_div,
sym::wrapping_rem,
sym::wrapping_rem_euclid,
]
.into_iter()
.collect(),
const_span: None,
disallowed_int_methods: DISALLOWED_INT_METHODS.iter().copied().collect(),
expr_span: None,
}
}

View file

@ -23,6 +23,7 @@ mod verbose_bit_mask;
pub(crate) mod arithmetic_side_effects;
use clippy_config::Conf;
use rustc_hir::{Body, Expr, ExprKind, UnOp};
use rustc_lint::{LateContext, LateLintPass};
use rustc_session::impl_lint_pass;
@ -841,6 +842,16 @@ pub struct Operators {
verbose_bit_mask_threshold: u64,
modulo_arithmetic_allow_comparison_to_zero: bool,
}
impl Operators {
pub fn new(conf: &'static Conf) -> Self {
Self {
arithmetic_context: numeric_arithmetic::Context::default(),
verbose_bit_mask_threshold: conf.verbose_bit_mask_threshold,
modulo_arithmetic_allow_comparison_to_zero: conf.allow_comparison_to_zero,
}
}
}
impl_lint_pass!(Operators => [
ABSURD_EXTREME_COMPARISONS,
ARITHMETIC_SIDE_EFFECTS,
@ -869,15 +880,7 @@ impl_lint_pass!(Operators => [
PTR_EQ,
SELF_ASSIGNMENT,
]);
impl Operators {
pub fn new(verbose_bit_mask_threshold: u64, modulo_arithmetic_allow_comparison_to_zero: bool) -> Self {
Self {
arithmetic_context: numeric_arithmetic::Context::default(),
verbose_bit_mask_threshold,
modulo_arithmetic_allow_comparison_to_zero,
}
}
}
impl<'tcx> LateLintPass<'tcx> for Operators {
fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
eq_op::check_assert(cx, e);

View file

@ -1,3 +1,4 @@
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint;
use clippy_utils::is_in_test;
use clippy_utils::macros::{is_panic, root_macro_call_first_node};
@ -5,9 +6,16 @@ use rustc_hir::Expr;
use rustc_lint::{LateContext, LateLintPass};
use rustc_session::impl_lint_pass;
#[derive(Clone)]
pub struct PanicUnimplemented {
pub allow_panic_in_tests: bool,
allow_panic_in_tests: bool,
}
impl PanicUnimplemented {
pub fn new(conf: &'static Conf) -> Self {
Self {
allow_panic_in_tests: conf.allow_panic_in_tests,
}
}
}
declare_clippy_lint! {

View file

@ -1,5 +1,6 @@
use std::{cmp, iter};
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::source::snippet;
use clippy_utils::ty::{for_each_top_level_late_bound_region, is_copy};
@ -14,7 +15,7 @@ use rustc_hir::{BindingMode, Body, FnDecl, Impl, ItemKind, MutTy, Mutability, No
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::ty::adjustment::{Adjust, PointerCoercion};
use rustc_middle::ty::layout::LayoutOf;
use rustc_middle::ty::{self, RegionKind};
use rustc_middle::ty::{self, RegionKind, TyCtxt};
use rustc_session::impl_lint_pass;
use rustc_span::def_id::LocalDefId;
use rustc_span::{sym, Span};
@ -103,7 +104,6 @@ declare_clippy_lint! {
"functions taking large arguments by value"
}
#[derive(Copy, Clone)]
pub struct PassByRefOrValue {
ref_min_size: u64,
value_max_size: u64,
@ -111,14 +111,9 @@ pub struct PassByRefOrValue {
}
impl<'tcx> PassByRefOrValue {
pub fn new(
ref_min_size: Option<u64>,
value_max_size: u64,
avoid_breaking_exported_api: bool,
pointer_width: u32,
) -> Self {
let ref_min_size = ref_min_size.unwrap_or_else(|| {
let bit_width = u64::from(pointer_width);
pub fn new(tcx: TyCtxt<'_>, conf: &'static Conf) -> Self {
let ref_min_size = conf.trivial_copy_size_limit.unwrap_or_else(|| {
let bit_width = u64::from(tcx.sess.target.pointer_width);
// Cap the calculated bit width at 32-bits to reduce
// portability problems between 32 and 64-bit targets
let bit_width = cmp::min(bit_width, 32);
@ -130,8 +125,8 @@ impl<'tcx> PassByRefOrValue {
Self {
ref_min_size,
value_max_size,
avoid_breaking_exported_api,
value_max_size: conf.pass_by_value_size_limit,
avoid_breaking_exported_api: conf.avoid_breaking_exported_api,
}
}

View file

@ -1,4 +1,5 @@
use clippy_config::types::PubUnderscoreFieldsBehaviour;
use clippy_config::Conf;
use clippy_utils::attrs::is_doc_hidden;
use clippy_utils::diagnostics::span_lint_hir_and_then;
use clippy_utils::is_path_lang_item;
@ -42,10 +43,18 @@ declare_clippy_lint! {
}
pub struct PubUnderscoreFields {
pub behavior: PubUnderscoreFieldsBehaviour,
behavior: PubUnderscoreFieldsBehaviour,
}
impl_lint_pass!(PubUnderscoreFields => [PUB_UNDERSCORE_FIELDS]);
impl PubUnderscoreFields {
pub fn new(conf: &'static Conf) -> Self {
Self {
behavior: conf.pub_underscore_fields_behavior,
}
}
}
impl<'tcx> LateLintPass<'tcx> for PubUnderscoreFields {
fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
// This lint only pertains to structs.

View file

@ -2,6 +2,7 @@ use crate::manual_let_else::MANUAL_LET_ELSE;
use crate::question_mark_used::QUESTION_MARK_USED;
use clippy_config::msrvs::Msrv;
use clippy_config::types::MatchLintBehaviour;
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::source::snippet_with_applicability;
use clippy_utils::ty::{implements_trait, is_type_diagnostic_item};
@ -62,11 +63,10 @@ pub struct QuestionMark {
impl_lint_pass!(QuestionMark => [QUESTION_MARK, MANUAL_LET_ELSE]);
impl QuestionMark {
#[must_use]
pub fn new(msrv: Msrv, matches_behaviour: MatchLintBehaviour) -> Self {
pub fn new(conf: &'static Conf) -> Self {
Self {
msrv,
matches_behaviour,
msrv: conf.msrv.clone(),
matches_behaviour: conf.matches_for_let_else,
try_block_depth_stack: Vec::new(),
}
}

View file

@ -1,4 +1,5 @@
use clippy_config::msrvs::{self, Msrv};
use clippy_config::Conf;
use clippy_utils::consts::{constant, Constant};
use clippy_utils::diagnostics::{span_lint, span_lint_and_sugg, span_lint_and_then};
use clippy_utils::source::{snippet, snippet_with_applicability, SpanRangeExt};
@ -164,9 +165,10 @@ pub struct Ranges {
}
impl Ranges {
#[must_use]
pub fn new(msrv: Msrv) -> Self {
Self { msrv }
pub fn new(conf: &'static Conf) -> Self {
Self {
msrv: conf.msrv.clone(),
}
}
}

View file

@ -1,6 +1,4 @@
use std::iter::once;
use std::ops::ControlFlow;
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::source::snippet;
use rustc_ast::ast::{Expr, ExprKind};
@ -10,6 +8,8 @@ use rustc_lint::{EarlyContext, EarlyLintPass, LintContext};
use rustc_middle::lint::in_external_macro;
use rustc_session::impl_lint_pass;
use rustc_span::{BytePos, Pos, Span};
use std::iter::once;
use std::ops::ControlFlow;
declare_clippy_lint! {
/// ### What it does
@ -61,6 +61,14 @@ pub struct RawStrings {
pub allow_one_hash_in_raw_strings: bool,
}
impl RawStrings {
pub fn new(conf: &'static Conf) -> Self {
Self {
allow_one_hash_in_raw_strings: conf.allow_one_hash_in_raw_strings,
}
}
}
impl EarlyLintPass for RawStrings {
fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
if !in_external_macro(cx.sess(), expr.span)

View file

@ -1,4 +1,5 @@
use clippy_config::msrvs::{self, Msrv};
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_and_sugg;
use rustc_ast::ast::{Expr, ExprKind};
use rustc_errors::Applicability;
@ -40,9 +41,10 @@ pub struct RedundantFieldNames {
}
impl RedundantFieldNames {
#[must_use]
pub fn new(msrv: Msrv) -> Self {
Self { msrv }
pub fn new(conf: &'static Conf) -> Self {
Self {
msrv: conf.msrv.clone(),
}
}
}

View file

@ -1,4 +1,5 @@
use clippy_config::msrvs::{self, Msrv};
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::source::snippet;
use rustc_ast::ast::{ConstItem, Item, ItemKind, StaticItem, Ty, TyKind};
@ -38,9 +39,10 @@ pub struct RedundantStaticLifetimes {
}
impl RedundantStaticLifetimes {
#[must_use]
pub fn new(msrv: Msrv) -> Self {
Self { msrv }
pub fn new(conf: &'static Conf) -> Self {
Self {
msrv: conf.msrv.clone(),
}
}
}

View file

@ -78,7 +78,7 @@ impl<'tcx> LateLintPass<'tcx> for Regex {
// `def_path_def_ids` will resolve through re-exports but is relatively heavy, so we only perform
// the operation once and store the results
let mut resolve = |path, kind| {
for id in def_path_def_ids(cx, path) {
for id in def_path_def_ids(cx.tcx, path) {
self.definitions.insert(id, kind);
}
};

View file

@ -1,3 +1,4 @@
use clippy_config::Conf;
use clippy_utils::diagnostics::{multispan_sugg_with_applicability, span_lint_and_then};
use rustc_errors::Applicability;
use rustc_hir::{Block, Expr, ExprKind, Stmt, StmtKind};
@ -64,21 +65,20 @@ declare_clippy_lint! {
}
impl_lint_pass!(SemicolonBlock => [SEMICOLON_INSIDE_BLOCK, SEMICOLON_OUTSIDE_BLOCK]);
#[derive(Copy, Clone)]
pub struct SemicolonBlock {
semicolon_inside_block_ignore_singleline: bool,
semicolon_outside_block_ignore_multiline: bool,
}
impl SemicolonBlock {
pub fn new(semicolon_inside_block_ignore_singleline: bool, semicolon_outside_block_ignore_multiline: bool) -> Self {
pub fn new(conf: &'static Conf) -> Self {
Self {
semicolon_inside_block_ignore_singleline,
semicolon_outside_block_ignore_multiline,
semicolon_inside_block_ignore_singleline: conf.semicolon_inside_block_ignore_singleline,
semicolon_outside_block_ignore_multiline: conf.semicolon_outside_block_ignore_multiline,
}
}
fn semicolon_inside_block(self, cx: &LateContext<'_>, block: &Block<'_>, tail: &Expr<'_>, semi_span: Span) {
fn semicolon_inside_block(&self, cx: &LateContext<'_>, block: &Block<'_>, tail: &Expr<'_>, semi_span: Span) {
let insert_span = tail.span.source_callsite().shrink_to_hi();
let remove_span = semi_span.with_lo(block.span.hi());
@ -103,7 +103,7 @@ impl SemicolonBlock {
}
fn semicolon_outside_block(
self,
&self,
cx: &LateContext<'_>,
block: &Block<'_>,
tail_stmt_expr: &Expr<'_>,

View file

@ -32,7 +32,7 @@ impl<'tcx> LateLintPass<'tcx> for SerdeApi {
}) = item.kind
{
let did = trait_ref.path.res.def_id();
if let Some(visit_did) = get_trait_def_id(cx, &paths::SERDE_DE_VISITOR) {
if let Some(visit_did) = get_trait_def_id(cx.tcx, &paths::SERDE_DE_VISITOR) {
if did == visit_did {
let mut seen_str = None;
let mut seen_string = None;

View file

@ -1,3 +1,4 @@
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_hir_and_then;
use clippy_utils::{is_from_proc_macro, is_in_test_function};
use rustc_data_structures::fx::{FxIndexMap, IndexEntry};
@ -66,13 +67,19 @@ pub enum CallState {
Multiple,
}
#[derive(Clone)]
pub struct SingleCallFn {
pub avoid_breaking_exported_api: bool,
pub def_id_to_usage: FxIndexMap<LocalDefId, CallState>,
avoid_breaking_exported_api: bool,
def_id_to_usage: FxIndexMap<LocalDefId, CallState>,
}
impl SingleCallFn {
pub fn new(conf: &'static Conf) -> Self {
Self {
avoid_breaking_exported_api: conf.avoid_breaking_exported_api,
def_id_to_usage: FxIndexMap::default(),
}
}
fn is_function_allowed(
&self,
cx: &LateContext<'_>,

View file

@ -99,7 +99,7 @@ impl LateLintPass<'_> for SingleRangeInVecInit {
&& let Some(start_snippet) = snippet_opt(cx, start.span)
&& let Some(end_snippet) = snippet_opt(cx, end.span)
{
let should_emit_every_value = if let Some(step_def_id) = get_trait_def_id(cx, &["core", "iter", "Step"])
let should_emit_every_value = if let Some(step_def_id) = get_trait_def_id(cx.tcx, &["core", "iter", "Step"])
&& implements_trait(cx, ty, step_def_id, &[])
{
true

View file

@ -1,6 +1,7 @@
use std::ops::ControlFlow;
use clippy_config::msrvs::{self, Msrv};
use clippy_config::Conf;
use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then};
use clippy_utils::eager_or_lazy::switch_to_eager_eval;
use clippy_utils::macros::matching_root_macro_call;
@ -75,9 +76,10 @@ pub struct StringPatterns {
}
impl StringPatterns {
#[must_use]
pub fn new(msrv: Msrv) -> Self {
Self { msrv }
pub fn new(conf: &'static Conf) -> Self {
Self {
msrv: conf.msrv.clone(),
}
}
}

View file

@ -1,4 +1,5 @@
use clippy_config::msrvs::{self, Msrv};
use clippy_config::Conf;
use clippy_utils::diagnostics::{span_lint_and_help, span_lint_and_sugg};
use clippy_utils::source::{snippet, snippet_opt, snippet_with_applicability};
use clippy_utils::{is_from_proc_macro, SpanlessEq, SpanlessHash};
@ -86,16 +87,17 @@ declare_clippy_lint! {
"check if the same trait bounds are specified more than once during a generic declaration"
}
#[derive(Clone)]
pub struct TraitBounds {
max_trait_bounds: u64,
msrv: Msrv,
}
impl TraitBounds {
#[must_use]
pub fn new(max_trait_bounds: u64, msrv: Msrv) -> Self {
Self { max_trait_bounds, msrv }
pub fn new(conf: &'static Conf) -> Self {
Self {
max_trait_bounds: conf.max_trait_bounds,
msrv: conf.msrv.clone(),
}
}
}

View file

@ -20,6 +20,7 @@ mod utils;
mod wrong_transmute;
use clippy_config::msrvs::Msrv;
use clippy_config::Conf;
use clippy_utils::in_constant;
use rustc_hir::{Expr, ExprKind, QPath};
use rustc_lint::{LateContext, LateLintPass};
@ -577,9 +578,10 @@ impl_lint_pass!(Transmute => [
MISSING_TRANSMUTE_ANNOTATIONS,
]);
impl Transmute {
#[must_use]
pub fn new(msrv: Msrv) -> Self {
Self { msrv }
pub fn new(conf: &'static Conf) -> Self {
Self {
msrv: conf.msrv.clone(),
}
}
}
impl<'tcx> LateLintPass<'tcx> for Transmute {

View file

@ -1,4 +1,5 @@
use clippy_config::msrvs::{self, Msrv};
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_and_help;
use clippy_utils::visitors::for_each_local_use_after_expr;
use clippy_utils::{is_from_proc_macro, path_to_local};
@ -42,9 +43,15 @@ declare_clippy_lint! {
}
impl_lint_pass!(TupleArrayConversions => [TUPLE_ARRAY_CONVERSIONS]);
#[derive(Clone)]
pub struct TupleArrayConversions {
pub msrv: Msrv,
msrv: Msrv,
}
impl TupleArrayConversions {
pub fn new(conf: &'static Conf) -> Self {
Self {
msrv: conf.msrv.clone(),
}
}
}
impl LateLintPass<'_> for TupleArrayConversions {

View file

@ -9,6 +9,7 @@ mod type_complexity;
mod utils;
mod vec_box;
use clippy_config::Conf;
use rustc_hir as hir;
use rustc_hir::intravisit::FnKind;
use rustc_hir::{
@ -446,11 +447,11 @@ impl<'tcx> LateLintPass<'tcx> for Types {
}
impl Types {
pub fn new(vec_box_size_threshold: u64, type_complexity_threshold: u64, avoid_breaking_exported_api: bool) -> Self {
pub fn new(conf: &'static Conf) -> Self {
Self {
vec_box_size_threshold,
type_complexity_threshold,
avoid_breaking_exported_api,
vec_box_size_threshold: conf.vec_box_size_threshold,
type_complexity_threshold: conf.type_complexity_threshold,
avoid_breaking_exported_api: conf.avoid_breaking_exported_api,
}
}

View file

@ -1,5 +1,6 @@
use std::ops::ControlFlow;
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_and_help;
use clippy_utils::is_lint_allowed;
use clippy_utils::source::walk_span_to_context;
@ -91,17 +92,16 @@ declare_clippy_lint! {
"annotating safe code with a safety comment"
}
#[derive(Copy, Clone)]
pub struct UndocumentedUnsafeBlocks {
accept_comment_above_statement: bool,
accept_comment_above_attributes: bool,
}
impl UndocumentedUnsafeBlocks {
pub fn new(accept_comment_above_statement: bool, accept_comment_above_attributes: bool) -> Self {
pub fn new(conf: &'static Conf) -> Self {
Self {
accept_comment_above_statement,
accept_comment_above_attributes,
accept_comment_above_statement: conf.accept_comment_above_statement,
accept_comment_above_attributes: conf.accept_comment_above_attributes,
}
}
}

View file

@ -1,3 +1,4 @@
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::ty::approx_ty_size;
use rustc_errors::Applicability;
@ -47,10 +48,10 @@ pub struct UnnecessaryBoxReturns {
impl_lint_pass!(UnnecessaryBoxReturns => [UNNECESSARY_BOX_RETURNS]);
impl UnnecessaryBoxReturns {
pub fn new(avoid_breaking_exported_api: bool, maximum_size: u64) -> Self {
pub fn new(conf: &'static Conf) -> Self {
Self {
avoid_breaking_exported_api,
maximum_size,
avoid_breaking_exported_api: conf.avoid_breaking_exported_api,
maximum_size: conf.unnecessary_box_size,
}
}

View file

@ -1,3 +1,4 @@
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::source::snippet;
use clippy_utils::visitors::find_all_ret_expressions;
@ -63,9 +64,9 @@ pub struct UnnecessaryWraps {
impl_lint_pass!(UnnecessaryWraps => [UNNECESSARY_WRAPS]);
impl UnnecessaryWraps {
pub fn new(avoid_breaking_exported_api: bool) -> Self {
pub fn new(conf: &'static Conf) -> Self {
Self {
avoid_breaking_exported_api,
avoid_breaking_exported_api: conf.avoid_breaking_exported_api,
}
}
}

View file

@ -1,6 +1,7 @@
#![allow(clippy::wildcard_imports, clippy::enum_glob_use)]
use clippy_config::msrvs::{self, Msrv};
use clippy_config::Conf;
use clippy_utils::ast_utils::{eq_field_pat, eq_id, eq_maybe_qself, eq_pat, eq_path};
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::over;
@ -51,9 +52,10 @@ pub struct UnnestedOrPatterns {
}
impl UnnestedOrPatterns {
#[must_use]
pub fn new(msrv: Msrv) -> Self {
Self { msrv }
pub fn new(conf: &'static Conf) -> Self {
Self {
msrv: conf.msrv.clone(),
}
}
}

View file

@ -1,3 +1,4 @@
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_and_help;
use clippy_utils::macros::root_macro_call_first_node;
use clippy_utils::visitors::is_local_used;
@ -43,9 +44,9 @@ pub struct UnusedSelf {
impl_lint_pass!(UnusedSelf => [UNUSED_SELF]);
impl UnusedSelf {
pub fn new(avoid_breaking_exported_api: bool) -> Self {
pub fn new(conf: &'static Conf) -> Self {
Self {
avoid_breaking_exported_api,
avoid_breaking_exported_api: conf.avoid_breaking_exported_api,
}
}
}

View file

@ -1,3 +1,4 @@
use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_hir_and_then;
use core::mem::replace;
use rustc_errors::Applicability;
@ -39,17 +40,16 @@ declare_clippy_lint! {
"capitalized acronyms are against the naming convention"
}
#[derive(Default)]
pub struct UpperCaseAcronyms {
avoid_breaking_exported_api: bool,
upper_case_acronyms_aggressive: bool,
}
impl UpperCaseAcronyms {
pub fn new(avoid_breaking_exported_api: bool, aggressive: bool) -> Self {
pub fn new(conf: &'static Conf) -> Self {
Self {
avoid_breaking_exported_api,
upper_case_acronyms_aggressive: aggressive,
avoid_breaking_exported_api: conf.avoid_breaking_exported_api,
upper_case_acronyms_aggressive: conf.upper_case_acronyms_aggressive,
}
}
}

Some files were not shown because too many files have changed in this diff Show more