clippy_config/
conf.rs

1use crate::ClippyConfiguration;
2use crate::types::{
3    DisallowedPath, DisallowedPathWithoutReplacement, MacroMatcher, MatchLintBehaviour, PubUnderscoreFieldsBehaviour,
4    Rename, SourceItemOrdering, SourceItemOrderingCategory, SourceItemOrderingModuleItemGroupings,
5    SourceItemOrderingModuleItemKind, SourceItemOrderingTraitAssocItemKind, SourceItemOrderingTraitAssocItemKinds,
6    SourceItemOrderingWithinModuleItemGroupings,
7};
8use clippy_utils::msrvs::Msrv;
9use itertools::Itertools;
10use rustc_errors::Applicability;
11use rustc_session::Session;
12use rustc_span::edit_distance::edit_distance;
13use rustc_span::{BytePos, Pos, SourceFile, Span, SyntaxContext};
14use serde::de::{IgnoredAny, IntoDeserializer, MapAccess, Visitor};
15use serde::{Deserialize, Deserializer, Serialize};
16use std::collections::HashMap;
17use std::fmt::{Debug, Display, Formatter};
18use std::ops::Range;
19use std::path::PathBuf;
20use std::str::FromStr;
21use std::sync::OnceLock;
22use std::{cmp, env, fmt, fs, io};
23
24#[rustfmt::skip]
25const DEFAULT_DOC_VALID_IDENTS: &[&str] = &[
26    "KiB", "MiB", "GiB", "TiB", "PiB", "EiB",
27    "MHz", "GHz", "THz",
28    "AccessKit",
29    "CoAP", "CoreFoundation", "CoreGraphics", "CoreText",
30    "DevOps",
31    "Direct2D", "Direct3D", "DirectWrite", "DirectX",
32    "ECMAScript",
33    "GPLv2", "GPLv3",
34    "GitHub", "GitLab",
35    "IPv4", "IPv6",
36    "ClojureScript", "CoffeeScript", "JavaScript", "PostScript", "PureScript", "TypeScript",
37    "WebAssembly",
38    "NaN", "NaNs",
39    "OAuth", "GraphQL",
40    "OCaml",
41    "OpenAL", "OpenDNS", "OpenGL", "OpenMP", "OpenSSH", "OpenSSL", "OpenStreetMap", "OpenTelemetry",
42    "OpenType",
43    "WebGL", "WebGL2", "WebGPU", "WebRTC", "WebSocket", "WebTransport",
44    "WebP", "OpenExr", "YCbCr", "sRGB",
45    "TensorFlow",
46    "TrueType",
47    "iOS", "macOS", "FreeBSD", "NetBSD", "OpenBSD",
48    "TeX", "LaTeX", "BibTeX", "BibLaTeX",
49    "MinGW",
50    "CamelCase",
51];
52const DEFAULT_DISALLOWED_NAMES: &[&str] = &["foo", "baz", "quux"];
53const DEFAULT_ALLOWED_IDENTS_BELOW_MIN_CHARS: &[&str] = &["i", "j", "x", "y", "z", "w", "n"];
54const DEFAULT_ALLOWED_PREFIXES: &[&str] = &["to", "as", "into", "from", "try_into", "try_from"];
55const DEFAULT_ALLOWED_TRAITS_WITH_RENAMED_PARAMS: &[&str] =
56    &["core::convert::From", "core::convert::TryFrom", "core::str::FromStr"];
57const DEFAULT_MODULE_ITEM_ORDERING_GROUPS: &[(&str, &[SourceItemOrderingModuleItemKind])] = {
58    #[allow(clippy::enum_glob_use)] // Very local glob use for legibility.
59    use SourceItemOrderingModuleItemKind::*;
60    &[
61        ("modules", &[ExternCrate, Mod, ForeignMod]),
62        ("use", &[Use]),
63        ("macros", &[Macro]),
64        ("global_asm", &[GlobalAsm]),
65        ("UPPER_SNAKE_CASE", &[Static, Const]),
66        ("PascalCase", &[TyAlias, Enum, Struct, Union, Trait, TraitAlias, Impl]),
67        ("lower_snake_case", &[Fn]),
68    ]
69};
70const DEFAULT_TRAIT_ASSOC_ITEM_KINDS_ORDER: &[SourceItemOrderingTraitAssocItemKind] = {
71    #[allow(clippy::enum_glob_use)] // Very local glob use for legibility.
72    use SourceItemOrderingTraitAssocItemKind::*;
73    &[Const, Type, Fn]
74};
75const DEFAULT_SOURCE_ITEM_ORDERING: &[SourceItemOrderingCategory] = {
76    #[allow(clippy::enum_glob_use)] // Very local glob use for legibility.
77    use SourceItemOrderingCategory::*;
78    &[Enum, Impl, Module, Struct, Trait]
79};
80
81/// Conf with parse errors
82#[derive(Default)]
83struct TryConf {
84    conf: Conf,
85    value_spans: HashMap<String, Range<usize>>,
86    errors: Vec<ConfError>,
87    warnings: Vec<ConfError>,
88}
89
90impl TryConf {
91    fn from_toml_error(file: &SourceFile, error: &toml::de::Error) -> Self {
92        Self {
93            conf: Conf::default(),
94            value_spans: HashMap::default(),
95            errors: vec![ConfError::from_toml(file, error)],
96            warnings: vec![],
97        }
98    }
99}
100
101#[derive(Debug)]
102struct ConfError {
103    message: String,
104    suggestion: Option<Suggestion>,
105    span: Span,
106}
107
108impl ConfError {
109    fn from_toml(file: &SourceFile, error: &toml::de::Error) -> Self {
110        let span = error.span().unwrap_or(0..file.source_len.0 as usize);
111        Self::spanned(file, error.message(), None, span)
112    }
113
114    fn spanned(
115        file: &SourceFile,
116        message: impl Into<String>,
117        suggestion: Option<Suggestion>,
118        span: Range<usize>,
119    ) -> Self {
120        Self {
121            message: message.into(),
122            suggestion,
123            span: span_from_toml_range(file, span),
124        }
125    }
126}
127
128// Remove code tags and code behind '# 's, as they are not needed for the lint docs and --explain
129pub fn sanitize_explanation(raw_docs: &str) -> String {
130    // Remove tags and hidden code:
131    let mut explanation = String::with_capacity(128);
132    let mut in_code = false;
133    for line in raw_docs.lines() {
134        let line = line.strip_prefix(' ').unwrap_or(line);
135
136        if let Some(lang) = line.strip_prefix("```") {
137            let tag = lang.split_once(',').map_or(lang, |(left, _)| left);
138            if !in_code && matches!(tag, "" | "rust" | "ignore" | "should_panic" | "no_run" | "compile_fail") {
139                explanation += "```rust\n";
140            } else {
141                explanation += line;
142                explanation.push('\n');
143            }
144            in_code = !in_code;
145        } else if !(in_code && line.starts_with("# ")) {
146            explanation += line;
147            explanation.push('\n');
148        }
149    }
150
151    explanation
152}
153
154macro_rules! wrap_option {
155    () => {
156        None
157    };
158    ($x:literal) => {
159        Some($x)
160    };
161}
162
163macro_rules! default_text {
164    ($value:expr) => {{
165        let mut text = String::new();
166        $value.serialize(toml::ser::ValueSerializer::new(&mut text)).unwrap();
167        text
168    }};
169    ($value:expr, $override:expr) => {
170        $override.to_string()
171    };
172}
173
174macro_rules! deserialize {
175    ($map:expr, $ty:ty, $errors:expr, $file:expr) => {{
176        let raw_value = $map.next_value::<toml::Spanned<toml::Value>>()?;
177        let value_span = raw_value.span();
178        let value = match <$ty>::deserialize(raw_value.into_inner()) {
179            Err(e) => {
180                $errors.push(ConfError::spanned(
181                    $file,
182                    e.to_string().replace('\n', " ").trim(),
183                    None,
184                    value_span,
185                ));
186                continue;
187            },
188            Ok(value) => value,
189        };
190        (value, value_span)
191    }};
192
193    ($map:expr, $ty:ty, $errors:expr, $file:expr, $replacements_allowed:expr) => {{
194        let array = $map.next_value::<Vec<toml::Spanned<toml::Value>>>()?;
195        let mut disallowed_paths_span = Range {
196            start: usize::MAX,
197            end: usize::MIN,
198        };
199        let mut disallowed_paths = Vec::new();
200        for raw_value in array {
201            let value_span = raw_value.span();
202            let mut disallowed_path = match DisallowedPath::<$replacements_allowed>::deserialize(raw_value.into_inner())
203            {
204                Err(e) => {
205                    $errors.push(ConfError::spanned(
206                        $file,
207                        e.to_string().replace('\n', " ").trim(),
208                        None,
209                        value_span,
210                    ));
211                    continue;
212                },
213                Ok(disallowed_path) => disallowed_path,
214            };
215            disallowed_paths_span = union(&disallowed_paths_span, &value_span);
216            disallowed_path.set_span(span_from_toml_range($file, value_span));
217            disallowed_paths.push(disallowed_path);
218        }
219        (disallowed_paths, disallowed_paths_span)
220    }};
221}
222
223macro_rules! define_Conf {
224    ($(
225        $(#[doc = $doc:literal])+
226        $(#[conf_deprecated($dep:literal, $new_conf:ident)])?
227        $(#[default_text = $default_text:expr])?
228        $(#[disallowed_paths_allow_replacements = $replacements_allowed:expr])?
229        $(#[lints($($for_lints:ident),* $(,)?)])?
230        $name:ident: $ty:ty = $default:expr,
231    )*) => {
232        /// Clippy lint configuration
233        pub struct Conf {
234            $($(#[cfg_attr(doc, doc = $doc)])+ pub $name: $ty,)*
235        }
236
237        mod defaults {
238            use super::*;
239            $(pub fn $name() -> $ty { $default })*
240        }
241
242        impl Default for Conf {
243            fn default() -> Self {
244                Self { $($name: defaults::$name(),)* }
245            }
246        }
247
248        #[derive(Deserialize)]
249        #[serde(field_identifier, rename_all = "kebab-case")]
250        #[allow(non_camel_case_types)]
251        enum Field { $($name,)* third_party, }
252
253        struct ConfVisitor<'a>(&'a SourceFile);
254
255        impl<'de> Visitor<'de> for ConfVisitor<'_> {
256            type Value = TryConf;
257
258            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
259                formatter.write_str("Conf")
260            }
261
262            fn visit_map<V>(self, mut map: V) -> Result<Self::Value, V::Error> where V: MapAccess<'de> {
263                let mut value_spans = HashMap::new();
264                let mut errors = Vec::new();
265                let mut warnings = Vec::new();
266
267                // Declare a local variable for each field available to a configuration file.
268                $(let mut $name = None;)*
269
270                // could get `Field` here directly, but get `String` first for diagnostics
271                while let Some(name) = map.next_key::<toml::Spanned<String>>()? {
272                    let field = match Field::deserialize(name.get_ref().as_str().into_deserializer()) {
273                        Err(e) => {
274                            let e: FieldError = e;
275                            errors.push(ConfError::spanned(self.0, e.error, e.suggestion, name.span()));
276                            continue;
277                        }
278                        Ok(field) => field
279                    };
280
281                    match field {
282                        $(Field::$name => {
283                            // Is this a deprecated field, i.e., is `$dep` set? If so, push a warning.
284                            $(warnings.push(ConfError::spanned(self.0, format!("deprecated field `{}`. {}", name.get_ref(), $dep), None, name.span()));)?
285                            let (value, value_span) =
286                                deserialize!(map, $ty, errors, self.0 $(, $replacements_allowed)?);
287                            // Was this field set previously?
288                            if $name.is_some() {
289                                errors.push(ConfError::spanned(self.0, format!("duplicate field `{}`", name.get_ref()), None, name.span()));
290                                continue;
291                            }
292                            $name = Some(value);
293                            value_spans.insert(name.get_ref().as_str().to_string(), value_span);
294                            // If this is a deprecated field, was the new field (`$new_conf`) set previously?
295                            // Note that `$new_conf` is one of the defined `$name`s.
296                            $(match $new_conf {
297                                Some(_) => errors.push(ConfError::spanned(self.0, concat!(
298                                    "duplicate field `", stringify!($new_conf),
299                                    "` (provided as `", stringify!($name), "`)"
300                                ), None, name.span())),
301                                None => $new_conf = $name.clone(),
302                            })?
303                        })*
304                        // ignore contents of the third_party key
305                        Field::third_party => drop(map.next_value::<IgnoredAny>())
306                    }
307                }
308                let conf = Conf { $($name: $name.unwrap_or_else(defaults::$name),)* };
309                Ok(TryConf { conf, value_spans, errors, warnings })
310            }
311        }
312
313        pub fn get_configuration_metadata() -> Vec<ClippyConfiguration> {
314            vec![$(
315                ClippyConfiguration {
316                    name: stringify!($name).replace('_', "-"),
317                    default: default_text!(defaults::$name() $(, $default_text)?),
318                    lints: &[$($(stringify!($for_lints)),*)?],
319                    doc: concat!($($doc, '\n',)*),
320                    deprecation_reason: wrap_option!($($dep)?)
321                },
322            )*]
323        }
324    };
325}
326
327fn union(x: &Range<usize>, y: &Range<usize>) -> Range<usize> {
328    Range {
329        start: cmp::min(x.start, y.start),
330        end: cmp::max(x.end, y.end),
331    }
332}
333
334fn span_from_toml_range(file: &SourceFile, span: Range<usize>) -> Span {
335    Span::new(
336        file.start_pos + BytePos::from_usize(span.start),
337        file.start_pos + BytePos::from_usize(span.end),
338        SyntaxContext::root(),
339        None,
340    )
341}
342
343define_Conf! {
344    /// Which crates to allow absolute paths from
345    #[lints(absolute_paths)]
346    absolute_paths_allowed_crates: Vec<String> = Vec::new(),
347    /// The maximum number of segments a path can have before being linted, anything above this will
348    /// be linted.
349    #[lints(absolute_paths)]
350    absolute_paths_max_segments: u64 = 2,
351    /// Whether to accept a safety comment to be placed above the attributes for the `unsafe` block
352    #[lints(undocumented_unsafe_blocks)]
353    accept_comment_above_attributes: bool = true,
354    /// Whether to accept a safety comment to be placed above the statement containing the `unsafe` block
355    #[lints(undocumented_unsafe_blocks)]
356    accept_comment_above_statement: bool = true,
357    /// Don't lint when comparing the result of a modulo operation to zero.
358    #[lints(modulo_arithmetic)]
359    allow_comparison_to_zero: bool = true,
360    /// Whether `dbg!` should be allowed in test functions or `#[cfg(test)]`
361    #[lints(dbg_macro)]
362    allow_dbg_in_tests: bool = false,
363    /// Whether an item should be allowed to have the same name as its containing module
364    #[lints(module_name_repetitions)]
365    allow_exact_repetitions: bool = true,
366    /// Whether `expect` should be allowed in code always evaluated at compile time
367    #[lints(expect_used)]
368    allow_expect_in_consts: bool = true,
369    /// Whether `expect` should be allowed in test functions or `#[cfg(test)]`
370    #[lints(expect_used)]
371    allow_expect_in_tests: bool = false,
372    /// Whether `indexing_slicing` should be allowed in test functions or `#[cfg(test)]`
373    #[lints(indexing_slicing)]
374    allow_indexing_slicing_in_tests: bool = false,
375    /// Whether to allow mixed uninlined format args, e.g. `format!("{} {}", a, foo.bar)`
376    #[lints(uninlined_format_args)]
377    allow_mixed_uninlined_format_args: bool = true,
378    /// Whether to allow `r#""#` when `r""` can be used
379    #[lints(needless_raw_string_hashes)]
380    allow_one_hash_in_raw_strings: bool = false,
381    /// Whether `panic` should be allowed in test functions or `#[cfg(test)]`
382    #[lints(panic)]
383    allow_panic_in_tests: bool = false,
384    /// Whether print macros (ex. `println!`) should be allowed in test functions or `#[cfg(test)]`
385    #[lints(print_stderr, print_stdout)]
386    allow_print_in_tests: bool = false,
387    /// Whether to allow module inception if it's not public.
388    #[lints(module_inception)]
389    allow_private_module_inception: bool = false,
390    /// List of trait paths to ignore when checking renamed function parameters.
391    ///
392    /// #### Example
393    ///
394    /// ```toml
395    /// allow-renamed-params-for = [ "std::convert::From" ]
396    /// ```
397    ///
398    /// #### Noteworthy
399    ///
400    /// - By default, the following traits are ignored: `From`, `TryFrom`, `FromStr`
401    /// - `".."` can be used as part of the list to indicate that the configured values should be appended to the
402    /// default configuration of Clippy. By default, any configuration will replace the default value.
403    #[lints(renamed_function_params)]
404    allow_renamed_params_for: Vec<String> =
405        DEFAULT_ALLOWED_TRAITS_WITH_RENAMED_PARAMS.iter().map(ToString::to_string).collect(),
406    /// Whether `unwrap` should be allowed in code always evaluated at compile time
407    #[lints(unwrap_used)]
408    allow_unwrap_in_consts: bool = true,
409    /// Whether `unwrap` should be allowed in test functions or `#[cfg(test)]`
410    #[lints(unwrap_used)]
411    allow_unwrap_in_tests: bool = false,
412    /// Whether `useless_vec` should ignore test functions or `#[cfg(test)]`
413    #[lints(useless_vec)]
414    allow_useless_vec_in_tests: bool = false,
415    /// Additional dotfiles (files or directories starting with a dot) to allow
416    #[lints(path_ends_with_ext)]
417    allowed_dotfiles: Vec<String> = Vec::default(),
418    /// A list of crate names to allow duplicates of
419    #[lints(multiple_crate_versions)]
420    allowed_duplicate_crates: Vec<String> = Vec::new(),
421    /// Allowed names below the minimum allowed characters. The value `".."` can be used as part of
422    /// the list to indicate, that the configured values should be appended to the default
423    /// configuration of Clippy. By default, any configuration will replace the default value.
424    #[lints(min_ident_chars)]
425    allowed_idents_below_min_chars: Vec<String> =
426        DEFAULT_ALLOWED_IDENTS_BELOW_MIN_CHARS.iter().map(ToString::to_string).collect(),
427    /// List of prefixes to allow when determining whether an item's name ends with the module's name.
428    /// If the rest of an item's name is an allowed prefix (e.g. item `ToFoo` or `to_foo` in module `foo`),
429    /// then don't emit a warning.
430    ///
431    /// #### Example
432    ///
433    /// ```toml
434    /// allowed-prefixes = [ "to", "from" ]
435    /// ```
436    ///
437    /// #### Noteworthy
438    ///
439    /// - By default, the following prefixes are allowed: `to`, `as`, `into`, `from`, `try_into` and `try_from`
440    /// - PascalCase variant is included automatically for each snake_case variant (e.g. if `try_into` is included,
441    ///   `TryInto` will also be included)
442    /// - Use `".."` as part of the list to indicate that the configured values should be appended to the
443    /// default configuration of Clippy. By default, any configuration will replace the default value
444    #[lints(module_name_repetitions)]
445    allowed_prefixes: Vec<String> = DEFAULT_ALLOWED_PREFIXES.iter().map(ToString::to_string).collect(),
446    /// The list of unicode scripts allowed to be used in the scope.
447    #[lints(disallowed_script_idents)]
448    allowed_scripts: Vec<String> = vec!["Latin".to_string()],
449    /// List of path segments allowed to have wildcard imports.
450    ///
451    /// #### Example
452    ///
453    /// ```toml
454    /// allowed-wildcard-imports = [ "utils", "common" ]
455    /// ```
456    ///
457    /// #### Noteworthy
458    ///
459    /// 1. This configuration has no effects if used with `warn_on_all_wildcard_imports = true`.
460    /// 2. Paths with any segment that containing the word 'prelude'
461    /// are already allowed by default.
462    #[lints(wildcard_imports)]
463    allowed_wildcard_imports: Vec<String> = Vec::new(),
464    /// Suppress checking of the passed type names in all types of operations.
465    ///
466    /// If a specific operation is desired, consider using `arithmetic_side_effects_allowed_binary` or `arithmetic_side_effects_allowed_unary` instead.
467    ///
468    /// #### Example
469    ///
470    /// ```toml
471    /// arithmetic-side-effects-allowed = ["SomeType", "AnotherType"]
472    /// ```
473    ///
474    /// #### Noteworthy
475    ///
476    /// A type, say `SomeType`, listed in this configuration has the same behavior of
477    /// `["SomeType" , "*"], ["*", "SomeType"]` in `arithmetic_side_effects_allowed_binary`.
478    #[lints(arithmetic_side_effects)]
479    arithmetic_side_effects_allowed: Vec<String> = <_>::default(),
480    /// Suppress checking of the passed type pair names in binary operations like addition or
481    /// multiplication.
482    ///
483    /// Supports the "*" wildcard to indicate that a certain type won't trigger the lint regardless
484    /// of the involved counterpart. For example, `["SomeType", "*"]` or `["*", "AnotherType"]`.
485    ///
486    /// Pairs are asymmetric, which means that `["SomeType", "AnotherType"]` is not the same as
487    /// `["AnotherType", "SomeType"]`.
488    ///
489    /// #### Example
490    ///
491    /// ```toml
492    /// arithmetic-side-effects-allowed-binary = [["SomeType" , "f32"], ["AnotherType", "*"]]
493    /// ```
494    #[lints(arithmetic_side_effects)]
495    arithmetic_side_effects_allowed_binary: Vec<(String, String)> = <_>::default(),
496    /// Suppress checking of the passed type names in unary operations like "negation" (`-`).
497    ///
498    /// #### Example
499    ///
500    /// ```toml
501    /// arithmetic-side-effects-allowed-unary = ["SomeType", "AnotherType"]
502    /// ```
503    #[lints(arithmetic_side_effects)]
504    arithmetic_side_effects_allowed_unary: Vec<String> = <_>::default(),
505    /// The maximum allowed size for arrays on the stack
506    #[lints(large_const_arrays, large_stack_arrays)]
507    array_size_threshold: u64 = 16 * 1024,
508    /// Suppress lints whenever the suggested change would cause breakage for other crates.
509    #[lints(
510        box_collection,
511        enum_variant_names,
512        large_types_passed_by_value,
513        linkedlist,
514        needless_pass_by_ref_mut,
515        option_option,
516        owned_cow,
517        rc_buffer,
518        rc_mutex,
519        redundant_allocation,
520        ref_option,
521        single_call_fn,
522        trivially_copy_pass_by_ref,
523        unnecessary_box_returns,
524        unnecessary_wraps,
525        unused_self,
526        upper_case_acronyms,
527        vec_box,
528        wrong_self_convention,
529    )]
530    avoid_breaking_exported_api: bool = true,
531    /// The list of types which may not be held across an await point.
532    #[disallowed_paths_allow_replacements = false]
533    #[lints(await_holding_invalid_type)]
534    await_holding_invalid_types: Vec<DisallowedPathWithoutReplacement> = Vec::new(),
535    /// DEPRECATED LINT: BLACKLISTED_NAME.
536    ///
537    /// Use the Disallowed Names lint instead
538    #[conf_deprecated("Please use `disallowed-names` instead", disallowed_names)]
539    blacklisted_names: Vec<String> = Vec::new(),
540    /// For internal testing only, ignores the current `publish` settings in the Cargo manifest.
541    #[lints(cargo_common_metadata)]
542    cargo_ignore_publish: bool = false,
543    /// Whether to check MSRV compatibility in `#[test]` and `#[cfg(test)]` code.
544    #[lints(incompatible_msrv)]
545    check_incompatible_msrv_in_tests: bool = false,
546    /// Whether to suggest reordering constructor fields when initializers are present.
547    ///
548    /// Warnings produced by this configuration aren't necessarily fixed by just reordering the fields. Even if the
549    /// suggested code would compile, it can change semantics if the initializer expressions have side effects. The
550    /// following example [from rust-clippy#11846] shows how the suggestion can run into borrow check errors:
551    ///
552    /// ```rust
553    /// struct MyStruct {
554    ///     vector: Vec<u32>,
555    ///     length: usize
556    /// }
557    /// fn main() {
558    ///     let vector = vec![1,2,3];
559    ///     MyStruct { length: vector.len(), vector};
560    /// }
561    /// ```
562    ///
563    /// [from rust-clippy#11846]: https://github.com/rust-lang/rust-clippy/issues/11846#issuecomment-1820747924
564    #[lints(inconsistent_struct_constructor)]
565    check_inconsistent_struct_field_initializers: bool = false,
566    /// Whether to also run the listed lints on private items.
567    #[lints(missing_errors_doc, missing_panics_doc, missing_safety_doc, unnecessary_safety_doc)]
568    check_private_items: bool = false,
569    /// The maximum cognitive complexity a function can have
570    #[lints(cognitive_complexity)]
571    cognitive_complexity_threshold: u64 = 25,
572    /// DEPRECATED LINT: CYCLOMATIC_COMPLEXITY.
573    ///
574    /// Use the Cognitive Complexity lint instead.
575    #[conf_deprecated("Please use `cognitive-complexity-threshold` instead", cognitive_complexity_threshold)]
576    cyclomatic_complexity_threshold: u64 = 25,
577    /// The list of disallowed macros, written as fully qualified paths.
578    ///
579    /// **Fields:**
580    /// - `path` (required): the fully qualified path to the macro that should be disallowed
581    /// - `reason` (optional): explanation why this macro is disallowed
582    /// - `replacement` (optional): suggested alternative macro
583    /// - `allow-invalid` (optional, `false` by default): when set to `true`, it will ignore this entry
584    ///   if the path doesn't exist, instead of emitting an error
585    #[disallowed_paths_allow_replacements = true]
586    #[lints(disallowed_macros)]
587    disallowed_macros: Vec<DisallowedPath> = Vec::new(),
588    /// The list of disallowed methods, written as fully qualified paths.
589    ///
590    /// **Fields:**
591    /// - `path` (required): the fully qualified path to the method that should be disallowed
592    /// - `reason` (optional): explanation why this method is disallowed
593    /// - `replacement` (optional): suggested alternative method
594    /// - `allow-invalid` (optional, `false` by default): when set to `true`, it will ignore this entry
595    ///   if the path doesn't exist, instead of emitting an error
596    #[disallowed_paths_allow_replacements = true]
597    #[lints(disallowed_methods)]
598    disallowed_methods: Vec<DisallowedPath> = Vec::new(),
599    /// The list of disallowed names to lint about. NB: `bar` is not here since it has legitimate uses. The value
600    /// `".."` can be used as part of the list to indicate that the configured values should be appended to the
601    /// default configuration of Clippy. By default, any configuration will replace the default value.
602    #[lints(disallowed_names)]
603    disallowed_names: Vec<String> = DEFAULT_DISALLOWED_NAMES.iter().map(ToString::to_string).collect(),
604    /// The list of disallowed types, written as fully qualified paths.
605    ///
606    /// **Fields:**
607    /// - `path` (required): the fully qualified path to the type that should be disallowed
608    /// - `reason` (optional): explanation why this type is disallowed
609    /// - `replacement` (optional): suggested alternative type
610    /// - `allow-invalid` (optional, `false` by default): when set to `true`, it will ignore this entry
611    ///   if the path doesn't exist, instead of emitting an error
612    #[disallowed_paths_allow_replacements = true]
613    #[lints(disallowed_types)]
614    disallowed_types: Vec<DisallowedPath> = Vec::new(),
615    /// The list of words this lint should not consider as identifiers needing ticks. The value
616    /// `".."` can be used as part of the list to indicate, that the configured values should be appended to the
617    /// default configuration of Clippy. By default, any configuration will replace the default value. For example:
618    /// * `doc-valid-idents = ["ClipPy"]` would replace the default list with `["ClipPy"]`.
619    /// * `doc-valid-idents = ["ClipPy", ".."]` would append `ClipPy` to the default list.
620    #[lints(doc_markdown)]
621    doc_valid_idents: Vec<String> = DEFAULT_DOC_VALID_IDENTS.iter().map(ToString::to_string).collect(),
622    /// Whether to apply the raw pointer heuristic to determine if a type is `Send`.
623    #[lints(non_send_fields_in_send_ty)]
624    enable_raw_pointer_heuristic_for_send: bool = true,
625    /// Whether to recommend using implicit into iter for reborrowed values.
626    ///
627    /// #### Example
628    /// ```no_run
629    /// let mut vec = vec![1, 2, 3];
630    /// let rmvec = &mut vec;
631    /// for _ in rmvec.iter() {}
632    /// for _ in rmvec.iter_mut() {}
633    /// ```
634    ///
635    /// Use instead:
636    /// ```no_run
637    /// let mut vec = vec![1, 2, 3];
638    /// let rmvec = &mut vec;
639    /// for _ in &*rmvec {}
640    /// for _ in &mut *rmvec {}
641    /// ```
642    #[lints(explicit_iter_loop)]
643    enforce_iter_loop_reborrow: bool = false,
644    /// The list of imports to always rename, a fully qualified path followed by the rename.
645    #[lints(missing_enforced_import_renames)]
646    enforced_import_renames: Vec<Rename> = Vec::new(),
647    /// The minimum number of enum variants for the lints about variant names to trigger
648    #[lints(enum_variant_names)]
649    enum_variant_name_threshold: u64 = 3,
650    /// The maximum size of an enum's variant to avoid box suggestion
651    #[lints(large_enum_variant)]
652    enum_variant_size_threshold: u64 = 200,
653    /// The maximum amount of nesting a block can reside in
654    #[lints(excessive_nesting)]
655    excessive_nesting_threshold: u64 = 0,
656    /// The maximum byte size a `Future` can have, before it triggers the `clippy::large_futures` lint
657    #[lints(large_futures)]
658    future_size_threshold: u64 = 16 * 1024,
659    /// A list of paths to types that should be treated as if they do not contain interior mutability
660    #[lints(borrow_interior_mutable_const, declare_interior_mutable_const, ifs_same_cond, mutable_key_type)]
661    ignore_interior_mutability: Vec<String> = Vec::from(["bytes::Bytes".into()]),
662    /// The maximum size of the `Err`-variant in a `Result` returned from a function
663    #[lints(result_large_err)]
664    large_error_threshold: u64 = 128,
665    /// Whether collapsible `if` and `else if` chains are linted if they contain comments inside the parts
666    /// that would be collapsed.
667    #[lints(collapsible_else_if, collapsible_if)]
668    lint_commented_code: bool = false,
669    /// Whether to suggest reordering constructor fields when initializers are present.
670    /// DEPRECATED CONFIGURATION: lint-inconsistent-struct-field-initializers
671    ///
672    /// Use the `check-inconsistent-struct-field-initializers` configuration instead.
673    #[conf_deprecated("Please use `check-inconsistent-struct-field-initializers` instead", check_inconsistent_struct_field_initializers)]
674    lint_inconsistent_struct_field_initializers: bool = false,
675    /// The lower bound for linting decimal literals
676    #[lints(decimal_literal_representation)]
677    literal_representation_threshold: u64 = 16384,
678    /// Whether the matches should be considered by the lint, and whether there should
679    /// be filtering for common types.
680    #[lints(manual_let_else)]
681    matches_for_let_else: MatchLintBehaviour = MatchLintBehaviour::WellKnownTypes,
682    /// The maximum number of bool parameters a function can have
683    #[lints(fn_params_excessive_bools)]
684    max_fn_params_bools: u64 = 3,
685    /// The maximum size of a file included via `include_bytes!()` or `include_str!()`, in bytes
686    #[lints(large_include_file)]
687    max_include_file_size: u64 = 1_000_000,
688    /// The maximum number of bool fields a struct can have
689    #[lints(struct_excessive_bools)]
690    max_struct_bools: u64 = 3,
691    /// When Clippy suggests using a slice pattern, this is the maximum number of elements allowed in
692    /// the slice pattern that is suggested. If more elements are necessary, the lint is suppressed.
693    /// For example, `[_, _, _, e, ..]` is a slice pattern with 4 elements.
694    #[lints(index_refutable_slice)]
695    max_suggested_slice_pattern_length: u64 = 3,
696    /// The maximum number of bounds a trait can have to be linted
697    #[lints(type_repetition_in_bounds)]
698    max_trait_bounds: u64 = 3,
699    /// Minimum chars an ident can have, anything below or equal to this will be linted.
700    #[lints(min_ident_chars)]
701    min_ident_chars_threshold: u64 = 1,
702    /// Whether to allow fields starting with an underscore to skip documentation requirements
703    #[lints(missing_docs_in_private_items)]
704    missing_docs_allow_unused: bool = false,
705    /// Whether to **only** check for missing documentation in items visible within the current
706    /// crate. For example, `pub(crate)` items.
707    #[lints(missing_docs_in_private_items)]
708    missing_docs_in_crate_items: bool = false,
709    /// The named groupings of different source item kinds within modules.
710    #[lints(arbitrary_source_item_ordering)]
711    module_item_order_groupings: SourceItemOrderingModuleItemGroupings = DEFAULT_MODULE_ITEM_ORDERING_GROUPS.into(),
712    /// Whether the items within module groups should be ordered alphabetically or not.
713    ///
714    /// This option can be configured to "all", "none", or a list of specific grouping names that should be checked
715    /// (e.g. only "enums").
716    #[lints(arbitrary_source_item_ordering)]
717    module_items_ordered_within_groupings: SourceItemOrderingWithinModuleItemGroupings =
718        SourceItemOrderingWithinModuleItemGroupings::None,
719    /// The minimum rust version that the project supports. Defaults to the `rust-version` field in `Cargo.toml`
720    #[default_text = "current version"]
721    #[lints(
722        allow_attributes,
723        allow_attributes_without_reason,
724        almost_complete_range,
725        approx_constant,
726        assigning_clones,
727        borrow_as_ptr,
728        cast_abs_to_unsigned,
729        checked_conversions,
730        cloned_instead_of_copied,
731        collapsible_match,
732        collapsible_str_replace,
733        deprecated_cfg_attr,
734        derivable_impls,
735        err_expect,
736        filter_map_next,
737        from_over_into,
738        if_then_some_else_none,
739        index_refutable_slice,
740        io_other_error,
741        iter_kv_map,
742        legacy_numeric_constants,
743        lines_filter_map_ok,
744        manual_abs_diff,
745        manual_bits,
746        manual_c_str_literals,
747        manual_clamp,
748        manual_div_ceil,
749        manual_flatten,
750        manual_hash_one,
751        manual_is_ascii_check,
752        manual_is_power_of_two,
753        manual_let_else,
754        manual_midpoint,
755        manual_non_exhaustive,
756        manual_option_as_slice,
757        manual_pattern_char_comparison,
758        manual_range_contains,
759        manual_rem_euclid,
760        manual_repeat_n,
761        manual_retain,
762        manual_slice_fill,
763        manual_slice_size_calculation,
764        manual_split_once,
765        manual_str_repeat,
766        manual_strip,
767        manual_try_fold,
768        map_clone,
769        map_unwrap_or,
770        map_with_unused_argument_over_ranges,
771        match_like_matches_macro,
772        mem_replace_option_with_some,
773        mem_replace_with_default,
774        missing_const_for_fn,
775        needless_borrow,
776        non_std_lazy_statics,
777        option_as_ref_deref,
778        option_map_unwrap_or,
779        ptr_as_ptr,
780        question_mark,
781        redundant_field_names,
782        redundant_static_lifetimes,
783        repeat_vec_with_capacity,
784        same_item_push,
785        seek_from_current,
786        seek_rewind,
787        to_digit_is_some,
788        transmute_ptr_to_ref,
789        tuple_array_conversions,
790        type_repetition_in_bounds,
791        unchecked_duration_subtraction,
792        uninlined_format_args,
793        unnecessary_lazy_evaluations,
794        unnested_or_patterns,
795        unused_trait_names,
796        use_self,
797    )]
798    msrv: Msrv = Msrv::default(),
799    /// The minimum size (in bytes) to consider a type for passing by reference instead of by value.
800    #[lints(large_types_passed_by_value)]
801    pass_by_value_size_limit: u64 = 256,
802    /// Lint "public" fields in a struct that are prefixed with an underscore based on their
803    /// exported visibility, or whether they are marked as "pub".
804    #[lints(pub_underscore_fields)]
805    pub_underscore_fields_behavior: PubUnderscoreFieldsBehaviour = PubUnderscoreFieldsBehaviour::PubliclyExported,
806    /// Whether to lint only if it's multiline.
807    #[lints(semicolon_inside_block)]
808    semicolon_inside_block_ignore_singleline: bool = false,
809    /// Whether to lint only if it's singleline.
810    #[lints(semicolon_outside_block)]
811    semicolon_outside_block_ignore_multiline: bool = false,
812    /// The maximum number of single char bindings a scope may have
813    #[lints(many_single_char_names)]
814    single_char_binding_names_threshold: u64 = 4,
815    /// Which kind of elements should be ordered internally, possible values being `enum`, `impl`, `module`, `struct`, `trait`.
816    #[lints(arbitrary_source_item_ordering)]
817    source_item_ordering: SourceItemOrdering = DEFAULT_SOURCE_ITEM_ORDERING.into(),
818    /// The maximum allowed stack size for functions in bytes
819    #[lints(large_stack_frames)]
820    stack_size_threshold: u64 = 512_000,
821    /// Enforce the named macros always use the braces specified.
822    ///
823    /// A `MacroMatcher` can be added like so `{ name = "macro_name", brace = "(" }`. If the macro
824    /// could be used with a full path two `MacroMatcher`s have to be added one with the full path
825    /// `crate_name::macro_name` and one with just the macro name.
826    #[lints(nonstandard_macro_braces)]
827    standard_macro_braces: Vec<MacroMatcher> = Vec::new(),
828    /// The minimum number of struct fields for the lints about field names to trigger
829    #[lints(struct_field_names)]
830    struct_field_name_threshold: u64 = 3,
831    /// Whether to suppress a restriction lint in constant code. In same
832    /// cases the restructured operation might not be unavoidable, as the
833    /// suggested counterparts are unavailable in constant code. This
834    /// configuration will cause restriction lints to trigger even
835    /// if no suggestion can be made.
836    #[lints(indexing_slicing)]
837    suppress_restriction_lint_in_const: bool = false,
838    /// The maximum size of objects (in bytes) that will be linted. Larger objects are ok on the heap
839    #[lints(boxed_local, useless_vec)]
840    too_large_for_stack: u64 = 200,
841    /// The maximum number of argument a function or method can have
842    #[lints(too_many_arguments)]
843    too_many_arguments_threshold: u64 = 7,
844    /// The maximum number of lines a function or method can have
845    #[lints(too_many_lines)]
846    too_many_lines_threshold: u64 = 100,
847    /// The order of associated items in traits.
848    #[lints(arbitrary_source_item_ordering)]
849    trait_assoc_item_kinds_order: SourceItemOrderingTraitAssocItemKinds = DEFAULT_TRAIT_ASSOC_ITEM_KINDS_ORDER.into(),
850    /// The maximum size (in bytes) to consider a `Copy` type for passing by value instead of by
851    /// reference.
852    #[default_text = "target_pointer_width"]
853    #[lints(trivially_copy_pass_by_ref)]
854    trivial_copy_size_limit: Option<u64> = None,
855    /// The maximum complexity a type can have
856    #[lints(type_complexity)]
857    type_complexity_threshold: u64 = 250,
858    /// The byte size a `T` in `Box<T>` can have, below which it triggers the `clippy::unnecessary_box` lint
859    #[lints(unnecessary_box_returns)]
860    unnecessary_box_size: u64 = 128,
861    /// Should the fraction of a decimal be linted to include separators.
862    #[lints(unreadable_literal)]
863    unreadable_literal_lint_fractions: bool = true,
864    /// Enables verbose mode. Triggers if there is more than one uppercase char next to each other
865    #[lints(upper_case_acronyms)]
866    upper_case_acronyms_aggressive: bool = false,
867    /// The size of the boxed type in bytes, where boxing in a `Vec` is allowed
868    #[lints(vec_box)]
869    vec_box_size_threshold: u64 = 4096,
870    /// The maximum allowed size of a bit mask before suggesting to use 'trailing_zeros'
871    #[lints(verbose_bit_mask)]
872    verbose_bit_mask_threshold: u64 = 1,
873    /// Whether to emit warnings on all wildcard imports, including those from `prelude`, from `super` in tests,
874    /// or for `pub use` reexports.
875    #[lints(wildcard_imports)]
876    warn_on_all_wildcard_imports: bool = false,
877    /// Whether to also emit warnings for unsafe blocks with metavariable expansions in **private** macros.
878    #[lints(macro_metavars_in_unsafe)]
879    warn_unsafe_macro_metavars_in_private_macros: bool = false,
880}
881
882/// Search for the configuration file.
883///
884/// # Errors
885///
886/// Returns any unexpected filesystem error encountered when searching for the config file
887pub fn lookup_conf_file() -> io::Result<(Option<PathBuf>, Vec<String>)> {
888    /// Possible filename to search for.
889    const CONFIG_FILE_NAMES: [&str; 2] = [".clippy.toml", "clippy.toml"];
890
891    // Start looking for a config file in CLIPPY_CONF_DIR, or failing that, CARGO_MANIFEST_DIR.
892    // If neither of those exist, use ".". (Update documentation if this priority changes)
893    let mut current = env::var_os("CLIPPY_CONF_DIR")
894        .or_else(|| env::var_os("CARGO_MANIFEST_DIR"))
895        .map_or_else(|| PathBuf::from("."), PathBuf::from)
896        .canonicalize()?;
897
898    let mut found_config: Option<PathBuf> = None;
899    let mut warnings = vec![];
900
901    loop {
902        for config_file_name in &CONFIG_FILE_NAMES {
903            if let Ok(config_file) = current.join(config_file_name).canonicalize() {
904                match fs::metadata(&config_file) {
905                    Err(e) if e.kind() == io::ErrorKind::NotFound => {},
906                    Err(e) => return Err(e),
907                    Ok(md) if md.is_dir() => {},
908                    Ok(_) => {
909                        // warn if we happen to find two config files #8323
910                        if let Some(ref found_config) = found_config {
911                            warnings.push(format!(
912                                "using config file `{}`, `{}` will be ignored",
913                                found_config.display(),
914                                config_file.display()
915                            ));
916                        } else {
917                            found_config = Some(config_file);
918                        }
919                    },
920                }
921            }
922        }
923
924        if found_config.is_some() {
925            return Ok((found_config, warnings));
926        }
927
928        // If the current directory has no parent, we're done searching.
929        if !current.pop() {
930            return Ok((None, warnings));
931        }
932    }
933}
934
935fn deserialize(file: &SourceFile) -> TryConf {
936    match toml::de::Deserializer::new(file.src.as_ref().unwrap()).deserialize_map(ConfVisitor(file)) {
937        Ok(mut conf) => {
938            extend_vec_if_indicator_present(&mut conf.conf.disallowed_names, DEFAULT_DISALLOWED_NAMES);
939            extend_vec_if_indicator_present(&mut conf.conf.allowed_prefixes, DEFAULT_ALLOWED_PREFIXES);
940            extend_vec_if_indicator_present(
941                &mut conf.conf.allow_renamed_params_for,
942                DEFAULT_ALLOWED_TRAITS_WITH_RENAMED_PARAMS,
943            );
944
945            // Confirms that the user has not accidentally configured ordering requirements for groups that
946            // aren't configured.
947            if let SourceItemOrderingWithinModuleItemGroupings::Custom(groupings) =
948                &conf.conf.module_items_ordered_within_groupings
949            {
950                for grouping in groupings {
951                    if !conf.conf.module_item_order_groupings.is_grouping(grouping) {
952                        // Since this isn't fixable by rustfix, don't emit a `Suggestion`. This just adds some useful
953                        // info for the user instead.
954
955                        let names = conf.conf.module_item_order_groupings.grouping_names();
956                        let suggestion = suggest_candidate(grouping, names.iter().map(String::as_str))
957                            .map(|s| format!(" perhaps you meant `{s}`?"))
958                            .unwrap_or_default();
959                        let names = names.iter().map(|s| format!("`{s}`")).join(", ");
960                        let message = format!(
961                            "unknown ordering group: `{grouping}` was not specified in `module-items-ordered-within-groupings`,{suggestion} expected one of: {names}"
962                        );
963
964                        let span = conf
965                            .value_spans
966                            .get("module_item_order_groupings")
967                            .cloned()
968                            .unwrap_or_default();
969                        conf.errors.push(ConfError::spanned(file, message, None, span));
970                    }
971                }
972            }
973
974            // TODO: THIS SHOULD BE TESTED, this comment will be gone soon
975            if conf.conf.allowed_idents_below_min_chars.iter().any(|e| e == "..") {
976                conf.conf
977                    .allowed_idents_below_min_chars
978                    .extend(DEFAULT_ALLOWED_IDENTS_BELOW_MIN_CHARS.iter().map(ToString::to_string));
979            }
980            if conf.conf.doc_valid_idents.iter().any(|e| e == "..") {
981                conf.conf
982                    .doc_valid_idents
983                    .extend(DEFAULT_DOC_VALID_IDENTS.iter().map(ToString::to_string));
984            }
985
986            conf
987        },
988        Err(e) => TryConf::from_toml_error(file, &e),
989    }
990}
991
992fn extend_vec_if_indicator_present(vec: &mut Vec<String>, default: &[&str]) {
993    if vec.contains(&"..".to_string()) {
994        vec.extend(default.iter().map(ToString::to_string));
995    }
996}
997
998impl Conf {
999    pub fn read(sess: &Session, path: &io::Result<(Option<PathBuf>, Vec<String>)>) -> &'static Conf {
1000        static CONF: OnceLock<Conf> = OnceLock::new();
1001        CONF.get_or_init(|| Conf::read_inner(sess, path))
1002    }
1003
1004    fn read_inner(sess: &Session, path: &io::Result<(Option<PathBuf>, Vec<String>)>) -> Conf {
1005        match path {
1006            Ok((_, warnings)) => {
1007                for warning in warnings {
1008                    sess.dcx().warn(warning.clone());
1009                }
1010            },
1011            Err(error) => {
1012                sess.dcx()
1013                    .err(format!("error finding Clippy's configuration file: {error}"));
1014            },
1015        }
1016
1017        let TryConf {
1018            mut conf,
1019            value_spans: _,
1020            errors,
1021            warnings,
1022        } = match path {
1023            Ok((Some(path), _)) => match sess.source_map().load_file(path) {
1024                Ok(file) => deserialize(&file),
1025                Err(error) => {
1026                    sess.dcx().err(format!("failed to read `{}`: {error}", path.display()));
1027                    TryConf::default()
1028                },
1029            },
1030            _ => TryConf::default(),
1031        };
1032
1033        conf.msrv.read_cargo(sess);
1034
1035        // all conf errors are non-fatal, we just use the default conf in case of error
1036        for error in errors {
1037            let mut diag = sess.dcx().struct_span_err(
1038                error.span,
1039                format!("error reading Clippy's configuration file: {}", error.message),
1040            );
1041
1042            if let Some(sugg) = error.suggestion {
1043                diag.span_suggestion(error.span, sugg.message, sugg.suggestion, Applicability::MaybeIncorrect);
1044            }
1045
1046            diag.emit();
1047        }
1048
1049        for warning in warnings {
1050            sess.dcx().span_warn(
1051                warning.span,
1052                format!("error reading Clippy's configuration file: {}", warning.message),
1053            );
1054        }
1055
1056        conf
1057    }
1058}
1059
1060const SEPARATOR_WIDTH: usize = 4;
1061
1062#[derive(Debug)]
1063struct FieldError {
1064    error: String,
1065    suggestion: Option<Suggestion>,
1066}
1067
1068#[derive(Debug)]
1069struct Suggestion {
1070    message: &'static str,
1071    suggestion: &'static str,
1072}
1073
1074impl std::error::Error for FieldError {}
1075
1076impl Display for FieldError {
1077    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1078        f.pad(&self.error)
1079    }
1080}
1081
1082impl serde::de::Error for FieldError {
1083    fn custom<T: Display>(msg: T) -> Self {
1084        Self {
1085            error: msg.to_string(),
1086            suggestion: None,
1087        }
1088    }
1089
1090    fn unknown_field(field: &str, expected: &'static [&'static str]) -> Self {
1091        // List the available fields sorted and at least one per line, more if `CLIPPY_TERMINAL_WIDTH` is
1092        // set and allows it.
1093        use fmt::Write;
1094
1095        let metadata = get_configuration_metadata();
1096        let deprecated = metadata
1097            .iter()
1098            .filter_map(|conf| {
1099                if conf.deprecation_reason.is_some() {
1100                    Some(conf.name.as_str())
1101                } else {
1102                    None
1103                }
1104            })
1105            .collect::<Vec<_>>();
1106
1107        let mut expected = expected
1108            .iter()
1109            .copied()
1110            .filter(|name| !deprecated.contains(name))
1111            .collect::<Vec<_>>();
1112        expected.sort_unstable();
1113
1114        let (rows, column_widths) = calculate_dimensions(&expected);
1115
1116        let mut msg = format!("unknown field `{field}`, expected one of");
1117        for row in 0..rows {
1118            writeln!(msg).unwrap();
1119            for (column, column_width) in column_widths.iter().copied().enumerate() {
1120                let index = column * rows + row;
1121                let field = expected.get(index).copied().unwrap_or_default();
1122                write!(msg, "{:SEPARATOR_WIDTH$}{field:column_width$}", " ").unwrap();
1123            }
1124        }
1125
1126        let suggestion = suggest_candidate(field, expected).map(|suggestion| Suggestion {
1127            message: "perhaps you meant",
1128            suggestion,
1129        });
1130
1131        Self { error: msg, suggestion }
1132    }
1133}
1134
1135fn calculate_dimensions(fields: &[&str]) -> (usize, Vec<usize>) {
1136    let columns = env::var("CLIPPY_TERMINAL_WIDTH")
1137        .ok()
1138        .and_then(|s| <usize as FromStr>::from_str(&s).ok())
1139        .map_or(1, |terminal_width| {
1140            let max_field_width = fields.iter().map(|field| field.len()).max().unwrap();
1141            cmp::max(1, terminal_width / (SEPARATOR_WIDTH + max_field_width))
1142        });
1143
1144    let rows = fields.len().div_ceil(columns);
1145
1146    let column_widths = (0..columns)
1147        .map(|column| {
1148            if column < columns - 1 {
1149                (0..rows)
1150                    .map(|row| {
1151                        let index = column * rows + row;
1152                        let field = fields.get(index).copied().unwrap_or_default();
1153                        field.len()
1154                    })
1155                    .max()
1156                    .unwrap()
1157            } else {
1158                // Avoid adding extra space to the last column.
1159                0
1160            }
1161        })
1162        .collect::<Vec<_>>();
1163
1164    (rows, column_widths)
1165}
1166
1167/// Given a user-provided value that couldn't be matched to a known option, finds the most likely
1168/// candidate among candidates that the user might have meant.
1169fn suggest_candidate<'a, I>(value: &str, candidates: I) -> Option<&'a str>
1170where
1171    I: IntoIterator<Item = &'a str>,
1172{
1173    candidates
1174        .into_iter()
1175        .filter_map(|expected| {
1176            let dist = edit_distance(value, expected, 4)?;
1177            Some((dist, expected))
1178        })
1179        .min_by_key(|&(dist, _)| dist)
1180        .map(|(_, suggestion)| suggestion)
1181}
1182
1183#[cfg(test)]
1184mod tests {
1185    use serde::de::IgnoredAny;
1186    use std::collections::{HashMap, HashSet};
1187    use std::fs;
1188    use walkdir::WalkDir;
1189
1190    #[test]
1191    fn configs_are_tested() {
1192        let mut names: HashSet<String> = crate::get_configuration_metadata()
1193            .into_iter()
1194            .filter_map(|meta| {
1195                if meta.deprecation_reason.is_none() {
1196                    Some(meta.name.replace('_', "-"))
1197                } else {
1198                    None
1199                }
1200            })
1201            .collect();
1202
1203        let toml_files = WalkDir::new("../tests")
1204            .into_iter()
1205            .map(Result::unwrap)
1206            .filter(|entry| entry.file_name() == "clippy.toml");
1207
1208        for entry in toml_files {
1209            let file = fs::read_to_string(entry.path()).unwrap();
1210            #[allow(clippy::zero_sized_map_values)]
1211            if let Ok(map) = toml::from_str::<HashMap<String, IgnoredAny>>(&file) {
1212                for name in map.keys() {
1213                    names.remove(name.as_str());
1214                }
1215            }
1216        }
1217
1218        assert!(
1219            names.is_empty(),
1220            "Configuration variable lacks test: {names:?}\nAdd a test to `tests/ui-toml`"
1221        );
1222    }
1223}