Skip to content

Commit f74037e

Browse files
committed
Auto merge of rust-lang#13088 - Jarcho:conf_refactor2, r=flip1995
Create lint passes using `Conf` This slightly reduces the amount of code changes needed to add a config to a lint and makes things makes things more consistent between passes. A dependence on the config being a static reference is also added. This would only ever be a problem if multiple crates end up compiled in a single process. Other changes include: * Removing useless `#[derive(..)]`s * Removing `#[must_use]` on lint pass constructors. * Unified the parsing of the `DisallowedPath` struct in lint passes. * Update `disallowed_types` and `await_holding_invalid` messages to be consistent with other disallowed lints. * Remove the `(from clippy.toml)` message. I plan on having all the configured lints point to point to a span in `clippy.toml` which will be more useful. changelog: none
2 parents 0ee9f44 + e34c6db commit f74037e

File tree

115 files changed

+824
-994
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

115 files changed

+824
-994
lines changed

book/src/development/adding_lints.md

+5-9
Original file line numberDiff line numberDiff line change
@@ -458,9 +458,8 @@ pub struct ManualStrip {
458458
}
459459

460460
impl ManualStrip {
461-
#[must_use]
462-
pub fn new(msrv: Msrv) -> Self {
463-
Self { msrv }
461+
pub fn new(conf: &'static Conf) -> Self {
462+
Self { msrv: conf.msrv.clone() }
464463
}
465464
}
466465
```
@@ -689,7 +688,6 @@ for some users. Adding a configuration is done in the following steps:
689688
]);
690689

691690
// New manual definition struct
692-
#[derive(Copy, Clone)]
693691
pub struct StructName {}
694692

695693
impl_lint_pass!(StructName => [
@@ -700,17 +698,16 @@ for some users. Adding a configuration is done in the following steps:
700698
2. Next add the configuration value and a corresponding creation method like
701699
this:
702700
```rust
703-
#[derive(Copy, Clone)]
704701
pub struct StructName {
705702
configuration_ident: Type,
706703
}
707704

708705
// ...
709706

710707
impl StructName {
711-
pub fn new(configuration_ident: Type) -> Self {
708+
pub fn new(conf: &'static Conf) -> Self {
712709
Self {
713-
configuration_ident,
710+
configuration_ident: conf.configuration_ident,
714711
}
715712
}
716713
}
@@ -726,8 +723,7 @@ for some users. Adding a configuration is done in the following steps:
726723
store.register_*_pass(|| box module::StructName);
727724

728725
// New registration with configuration value
729-
let configuration_ident = conf.configuration_ident.clone();
730-
store.register_*_pass(move || box module::StructName::new(configuration_ident));
726+
store.register_*_pass(move || box module::StructName::new(conf));
731727
```
732728

733729
Congratulations the work is almost done. The configuration value can now be

book/src/lint_configuration.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -455,7 +455,7 @@ default configuration of Clippy. By default, any configuration will replace the
455455
* `doc-valid-idents = ["ClipPy"]` would replace the default list with `["ClipPy"]`.
456456
* `doc-valid-idents = ["ClipPy", ".."]` would append `ClipPy` to the default list.
457457

458-
**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"]`
458+
**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"]`
459459

460460
---
461461
**Affected lints:**

clippy_config/src/conf.rs

+9-5
Original file line numberDiff line numberDiff line change
@@ -238,7 +238,7 @@ define_Conf! {
238238
///
239239
/// A type, say `SomeType`, listed in this configuration has the same behavior of
240240
/// `["SomeType" , "*"], ["*", "SomeType"]` in `arithmetic_side_effects_allowed_binary`.
241-
(arithmetic_side_effects_allowed: FxHashSet<String> = <_>::default()),
241+
(arithmetic_side_effects_allowed: Vec<String> = <_>::default()),
242242
/// Lint: ARITHMETIC_SIDE_EFFECTS.
243243
///
244244
/// Suppress checking of the passed type pair names in binary operations like addition or
@@ -265,7 +265,7 @@ define_Conf! {
265265
/// ```toml
266266
/// arithmetic-side-effects-allowed-unary = ["SomeType", "AnotherType"]
267267
/// ```
268-
(arithmetic_side_effects_allowed_unary: FxHashSet<String> = <_>::default()),
268+
(arithmetic_side_effects_allowed_unary: Vec<String> = <_>::default()),
269269
/// 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.
270270
///
271271
/// Suppress lints whenever the suggested change would cause breakage for other crates.
@@ -314,7 +314,7 @@ define_Conf! {
314314
/// default configuration of Clippy. By default, any configuration will replace the default value. For example:
315315
/// * `doc-valid-idents = ["ClipPy"]` would replace the default list with `["ClipPy"]`.
316316
/// * `doc-valid-idents = ["ClipPy", ".."]` would append `ClipPy` to the default list.
317-
(doc_valid_idents: Vec<String> = DEFAULT_DOC_VALID_IDENTS.iter().map(ToString::to_string).collect()),
317+
(doc_valid_idents: FxHashSet<String> = DEFAULT_DOC_VALID_IDENTS.iter().map(ToString::to_string).collect()),
318318
/// Lint: TOO_MANY_ARGUMENTS.
319319
///
320320
/// The maximum number of argument a function or method can have
@@ -550,7 +550,7 @@ define_Conf! {
550550
/// Lint: PATH_ENDS_WITH_EXT.
551551
///
552552
/// Additional dotfiles (files or directories starting with a dot) to allow
553-
(allowed_dotfiles: FxHashSet<String> = FxHashSet::default()),
553+
(allowed_dotfiles: Vec<String> = Vec::default()),
554554
/// Lint: MULTIPLE_CRATE_VERSIONS.
555555
///
556556
/// A list of crate names to allow duplicates of
@@ -703,7 +703,6 @@ pub fn lookup_conf_file() -> io::Result<(Option<PathBuf>, Vec<String>)> {
703703
fn deserialize(file: &SourceFile) -> TryConf {
704704
match toml::de::Deserializer::new(file.src.as_ref().unwrap()).deserialize_map(ConfVisitor(file)) {
705705
Ok(mut conf) => {
706-
extend_vec_if_indicator_present(&mut conf.conf.doc_valid_idents, DEFAULT_DOC_VALID_IDENTS);
707706
extend_vec_if_indicator_present(&mut conf.conf.disallowed_names, DEFAULT_DISALLOWED_NAMES);
708707
extend_vec_if_indicator_present(&mut conf.conf.allowed_prefixes, DEFAULT_ALLOWED_PREFIXES);
709708
extend_vec_if_indicator_present(
@@ -716,6 +715,11 @@ fn deserialize(file: &SourceFile) -> TryConf {
716715
.allowed_idents_below_min_chars
717716
.extend(DEFAULT_ALLOWED_IDENTS_BELOW_MIN_CHARS.iter().map(ToString::to_string));
718717
}
718+
if conf.conf.doc_valid_idents.contains("..") {
719+
conf.conf
720+
.doc_valid_idents
721+
.extend(DEFAULT_DOC_VALID_IDENTS.iter().map(ToString::to_string));
722+
}
719723

720724
conf
721725
},

clippy_config/src/types.rs

+6-8
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,13 @@ use serde::de::{self, Deserializer, Visitor};
22
use serde::{ser, Deserialize, Serialize};
33
use std::fmt;
44

5-
#[derive(Clone, Debug, Deserialize)]
5+
#[derive(Debug, Deserialize)]
66
pub struct Rename {
77
pub path: String,
88
pub rename: String,
99
}
1010

11-
#[derive(Clone, Debug, Deserialize)]
11+
#[derive(Debug, Deserialize)]
1212
#[serde(untagged)]
1313
pub enum DisallowedPath {
1414
Simple(String),
@@ -22,12 +22,10 @@ impl DisallowedPath {
2222
path
2323
}
2424

25-
pub fn reason(&self) -> Option<String> {
26-
match self {
27-
Self::WithReason {
28-
reason: Some(reason), ..
29-
} => Some(format!("{reason} (from clippy.toml)")),
30-
_ => None,
25+
pub fn reason(&self) -> Option<&str> {
26+
match &self {
27+
Self::WithReason { reason, .. } => reason.as_deref(),
28+
Self::Simple(_) => None,
3129
}
3230
}
3331
}

clippy_dev/src/new_lint.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,7 @@ fn add_lint(lint: &LintData<'_>, enable_msrv: bool) -> io::Result<()> {
140140

141141
let new_lint = if enable_msrv {
142142
format!(
143-
"store.register_{lint_pass}_pass(move |{ctor_arg}| Box::new({module_name}::{camel_name}::new(msrv())));\n ",
143+
"store.register_{lint_pass}_pass(move |{ctor_arg}| Box::new({module_name}::{camel_name}::new(conf)));\n ",
144144
lint_pass = lint.pass,
145145
ctor_arg = if lint.pass == "late" { "_" } else { "" },
146146
module_name = lint.name,
@@ -274,6 +274,7 @@ fn get_lint_file_contents(lint: &LintData<'_>, enable_msrv: bool) -> String {
274274
formatdoc!(
275275
r#"
276276
use clippy_config::msrvs::{{self, Msrv}};
277+
use clippy_config::Conf;
277278
{pass_import}
278279
use rustc_lint::{{{context_import}, {pass_type}, LintContext}};
279280
use rustc_session::impl_lint_pass;
@@ -301,9 +302,8 @@ fn get_lint_file_contents(lint: &LintData<'_>, enable_msrv: bool) -> String {
301302
}}
302303
303304
impl {name_camel} {{
304-
#[must_use]
305-
pub fn new(msrv: Msrv) -> Self {{
306-
Self {{ msrv }}
305+
pub fn new(conf: &'static Conf) -> Self {{
306+
Self {{ msrv: conf.msrv.clone() }}
307307
}}
308308
}}
309309

clippy_lints/src/absolute_paths.rs

+11-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
use clippy_config::Conf;
12
use clippy_utils::diagnostics::span_lint;
23
use clippy_utils::source::snippet_opt;
34
use rustc_data_structures::fx::FxHashSet;
@@ -47,7 +48,16 @@ impl_lint_pass!(AbsolutePaths => [ABSOLUTE_PATHS]);
4748

4849
pub struct AbsolutePaths {
4950
pub absolute_paths_max_segments: u64,
50-
pub absolute_paths_allowed_crates: FxHashSet<String>,
51+
pub absolute_paths_allowed_crates: &'static FxHashSet<String>,
52+
}
53+
54+
impl AbsolutePaths {
55+
pub fn new(conf: &'static Conf) -> Self {
56+
Self {
57+
absolute_paths_max_segments: conf.absolute_paths_max_segments,
58+
absolute_paths_allowed_crates: &conf.absolute_paths_allowed_crates,
59+
}
60+
}
5161
}
5262

5363
impl LateLintPass<'_> for AbsolutePaths {

clippy_lints/src/almost_complete_range.rs

+5-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use clippy_config::msrvs::{self, Msrv};
2+
use clippy_config::Conf;
23
use clippy_utils::diagnostics::span_lint_and_then;
34
use clippy_utils::source::{trim_span, walk_span_to_context};
45
use rustc_ast::ast::{Expr, ExprKind, LitKind, Pat, PatKind, RangeEnd, RangeLimits};
@@ -34,8 +35,10 @@ pub struct AlmostCompleteRange {
3435
msrv: Msrv,
3536
}
3637
impl AlmostCompleteRange {
37-
pub fn new(msrv: Msrv) -> Self {
38-
Self { msrv }
38+
pub fn new(conf: &'static Conf) -> Self {
39+
Self {
40+
msrv: conf.msrv.clone(),
41+
}
3942
}
4043
}
4144
impl EarlyLintPass for AlmostCompleteRange {

clippy_lints/src/approx_const.rs

+5-3
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use clippy_config::msrvs::{self, Msrv};
2+
use clippy_config::Conf;
23
use clippy_utils::diagnostics::span_lint_and_help;
34
use rustc_ast::ast::{FloatTy, LitFloatType, LitKind};
45
use rustc_hir::{Expr, ExprKind};
@@ -67,9 +68,10 @@ pub struct ApproxConstant {
6768
}
6869

6970
impl ApproxConstant {
70-
#[must_use]
71-
pub fn new(msrv: Msrv) -> Self {
72-
Self { msrv }
71+
pub fn new(conf: &'static Conf) -> Self {
72+
Self {
73+
msrv: conf.msrv.clone(),
74+
}
7375
}
7476

7577
fn check_lit(&self, cx: &LateContext<'_>, lit: &LitKind, e: &Expr<'_>) {

clippy_lints/src/assigning_clones.rs

+5-3
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use clippy_config::msrvs::{self, Msrv};
2+
use clippy_config::Conf;
23
use clippy_utils::diagnostics::span_lint_and_then;
34
use clippy_utils::mir::{enclosing_mir, PossibleBorrowerMap};
45
use clippy_utils::sugg::Sugg;
@@ -57,9 +58,10 @@ pub struct AssigningClones {
5758
}
5859

5960
impl AssigningClones {
60-
#[must_use]
61-
pub fn new(msrv: Msrv) -> Self {
62-
Self { msrv }
61+
pub fn new(conf: &'static Conf) -> Self {
62+
Self {
63+
msrv: conf.msrv.clone(),
64+
}
6365
}
6466
}
6567

clippy_lints/src/attrs/mod.rs

+14-5
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ mod useless_attribute;
1616
mod utils;
1717

1818
use clippy_config::msrvs::{self, Msrv};
19+
use clippy_config::Conf;
1920
use rustc_ast::{Attribute, MetaItemKind, NestedMetaItem};
2021
use rustc_hir::{ImplItem, Item, ItemKind, TraitItem};
2122
use rustc_lint::{EarlyContext, EarlyLintPass, LateContext, LateLintPass};
@@ -499,7 +500,6 @@ declare_clippy_lint! {
499500
"duplicated attribute"
500501
}
501502

502-
#[derive(Clone)]
503503
pub struct Attributes {
504504
msrv: Msrv,
505505
}
@@ -517,9 +517,10 @@ impl_lint_pass!(Attributes => [
517517
]);
518518

519519
impl Attributes {
520-
#[must_use]
521-
pub fn new(msrv: Msrv) -> Self {
522-
Self { msrv }
520+
pub fn new(conf: &'static Conf) -> Self {
521+
Self {
522+
msrv: conf.msrv.clone(),
523+
}
523524
}
524525
}
525526

@@ -589,7 +590,15 @@ impl<'tcx> LateLintPass<'tcx> for Attributes {
589590
}
590591

591592
pub struct EarlyAttributes {
592-
pub msrv: Msrv,
593+
msrv: Msrv,
594+
}
595+
596+
impl EarlyAttributes {
597+
pub fn new(conf: &'static Conf) -> Self {
598+
Self {
599+
msrv: conf.msrv.clone(),
600+
}
601+
}
593602
}
594603

595604
impl_lint_pass!(EarlyAttributes => [

clippy_lints/src/await_holding_invalid.rs

+12-27
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
1-
use clippy_config::types::DisallowedPath;
1+
use clippy_config::Conf;
22
use clippy_utils::diagnostics::span_lint_and_then;
3-
use clippy_utils::{match_def_path, paths};
4-
use rustc_data_structures::fx::FxHashMap;
3+
use clippy_utils::{create_disallowed_map, match_def_path, paths};
54
use rustc_hir as hir;
6-
use rustc_hir::def_id::DefId;
5+
use rustc_hir::def_id::{DefId, DefIdMap};
76
use rustc_lint::{LateContext, LateLintPass};
87
use rustc_middle::mir::CoroutineLayout;
8+
use rustc_middle::ty::TyCtxt;
99
use rustc_session::impl_lint_pass;
1010
use rustc_span::{sym, Span};
1111

@@ -172,31 +172,19 @@ declare_clippy_lint! {
172172

173173
impl_lint_pass!(AwaitHolding => [AWAIT_HOLDING_LOCK, AWAIT_HOLDING_REFCELL_REF, AWAIT_HOLDING_INVALID_TYPE]);
174174

175-
#[derive(Debug)]
176175
pub struct AwaitHolding {
177-
conf_invalid_types: Vec<DisallowedPath>,
178-
def_ids: FxHashMap<DefId, DisallowedPath>,
176+
def_ids: DefIdMap<(&'static str, Option<&'static str>)>,
179177
}
180178

181179
impl AwaitHolding {
182-
pub(crate) fn new(conf_invalid_types: Vec<DisallowedPath>) -> Self {
180+
pub(crate) fn new(tcx: TyCtxt<'_>, conf: &'static Conf) -> Self {
183181
Self {
184-
conf_invalid_types,
185-
def_ids: FxHashMap::default(),
182+
def_ids: create_disallowed_map(tcx, &conf.await_holding_invalid_types),
186183
}
187184
}
188185
}
189186

190187
impl<'tcx> LateLintPass<'tcx> for AwaitHolding {
191-
fn check_crate(&mut self, cx: &LateContext<'tcx>) {
192-
for conf in &self.conf_invalid_types {
193-
let segs: Vec<_> = conf.path().split("::").collect();
194-
for id in clippy_utils::def_path_def_ids(cx, &segs) {
195-
self.def_ids.insert(id, conf.clone());
196-
}
197-
}
198-
}
199-
200188
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) {
201189
if let hir::ExprKind::Closure(hir::Closure {
202190
kind: hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)),
@@ -258,25 +246,22 @@ impl AwaitHolding {
258246
);
259247
},
260248
);
261-
} else if let Some(disallowed) = self.def_ids.get(&adt.did()) {
262-
emit_invalid_type(cx, ty_cause.source_info.span, disallowed);
249+
} else if let Some(&(path, reason)) = self.def_ids.get(&adt.did()) {
250+
emit_invalid_type(cx, ty_cause.source_info.span, path, reason);
263251
}
264252
}
265253
}
266254
}
267255
}
268256

269-
fn emit_invalid_type(cx: &LateContext<'_>, span: Span, disallowed: &DisallowedPath) {
257+
fn emit_invalid_type(cx: &LateContext<'_>, span: Span, path: &'static str, reason: Option<&'static str>) {
270258
span_lint_and_then(
271259
cx,
272260
AWAIT_HOLDING_INVALID_TYPE,
273261
span,
274-
format!(
275-
"`{}` may not be held across an await point per `clippy.toml`",
276-
disallowed.path()
277-
),
262+
format!("holding a disallowed type across an await point `{path}`"),
278263
|diag| {
279-
if let Some(reason) = disallowed.reason() {
264+
if let Some(reason) = reason {
280265
diag.note(reason);
281266
}
282267
},

0 commit comments

Comments
 (0)