]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/utils/conf.rs
Auto merge of #89776 - rusticstuff:ci-overflow-checks, r=Mark-Simulacrum
[rust.git] / src / tools / clippy / clippy_lints / src / utils / conf.rs
1 //! Read configurations files.
2
3 #![allow(clippy::module_name_repetitions)]
4
5 use serde::de::{Deserializer, IgnoredAny, IntoDeserializer, MapAccess, Visitor};
6 use serde::Deserialize;
7 use std::error::Error;
8 use std::path::{Path, PathBuf};
9 use std::{env, fmt, fs, io};
10
11 /// Holds information used by `MISSING_ENFORCED_IMPORT_RENAMES` lint.
12 #[derive(Clone, Debug, Deserialize)]
13 pub struct Rename {
14     pub path: String,
15     pub rename: String,
16 }
17
18 /// A single disallowed method, used by the `DISALLOWED_METHOD` lint.
19 #[derive(Clone, Debug, Deserialize)]
20 #[serde(untagged)]
21 pub enum DisallowedMethod {
22     Simple(String),
23     WithReason { path: String, reason: Option<String> },
24 }
25
26 /// A single disallowed type, used by the `DISALLOWED_TYPE` lint.
27 #[derive(Clone, Debug, Deserialize)]
28 #[serde(untagged)]
29 pub enum DisallowedType {
30     Simple(String),
31     WithReason { path: String, reason: Option<String> },
32 }
33
34 /// Conf with parse errors
35 #[derive(Default)]
36 pub struct TryConf {
37     pub conf: Conf,
38     pub errors: Vec<String>,
39 }
40
41 impl TryConf {
42     fn from_error(error: impl Error) -> Self {
43         Self {
44             conf: Conf::default(),
45             errors: vec![error.to_string()],
46         }
47     }
48 }
49
50 macro_rules! define_Conf {
51     ($(
52         $(#[doc = $doc:literal])+
53         $(#[conf_deprecated($dep:literal)])?
54         ($name:ident: $ty:ty = $default:expr),
55     )*) => {
56         /// Clippy lint configuration
57         pub struct Conf {
58             $($(#[doc = $doc])+ pub $name: $ty,)*
59         }
60
61         mod defaults {
62             $(pub fn $name() -> $ty { $default })*
63         }
64
65         impl Default for Conf {
66             fn default() -> Self {
67                 Self { $($name: defaults::$name(),)* }
68             }
69         }
70
71         impl<'de> Deserialize<'de> for TryConf {
72             fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de> {
73                 deserializer.deserialize_map(ConfVisitor)
74             }
75         }
76
77         #[derive(Deserialize)]
78         #[serde(field_identifier, rename_all = "kebab-case")]
79         #[allow(non_camel_case_types)]
80         enum Field { $($name,)* third_party, }
81
82         struct ConfVisitor;
83
84         impl<'de> Visitor<'de> for ConfVisitor {
85             type Value = TryConf;
86
87             fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
88                 formatter.write_str("Conf")
89             }
90
91             fn visit_map<V>(self, mut map: V) -> Result<Self::Value, V::Error> where V: MapAccess<'de> {
92                 let mut errors = Vec::new();
93                 $(let mut $name = None;)*
94                 // could get `Field` here directly, but get `str` first for diagnostics
95                 while let Some(name) = map.next_key::<&str>()? {
96                     match Field::deserialize(name.into_deserializer())? {
97                         $(Field::$name => {
98                             $(errors.push(format!("deprecated field `{}`. {}", name, $dep));)?
99                             match map.next_value() {
100                                 Err(e) => errors.push(e.to_string()),
101                                 Ok(value) => match $name {
102                                     Some(_) => errors.push(format!("duplicate field `{}`", name)),
103                                     None => $name = Some(value),
104                                 }
105                             }
106                         })*
107                         // white-listed; ignore
108                         Field::third_party => drop(map.next_value::<IgnoredAny>())
109                     }
110                 }
111                 let conf = Conf { $($name: $name.unwrap_or_else(defaults::$name),)* };
112                 Ok(TryConf { conf, errors })
113             }
114         }
115
116         #[cfg(feature = "metadata-collector-lint")]
117         pub mod metadata {
118             use crate::utils::internal_lints::metadata_collector::ClippyConfiguration;
119
120             macro_rules! wrap_option {
121                 () => (None);
122                 ($x:literal) => (Some($x));
123             }
124
125             pub(crate) fn get_configuration_metadata() -> Vec<ClippyConfiguration> {
126                 vec![
127                     $(
128                         {
129                             let deprecation_reason = wrap_option!($($dep)?);
130
131                             ClippyConfiguration::new(
132                                 stringify!($name),
133                                 stringify!($ty),
134                                 format!("{:?}", super::defaults::$name()),
135                                 concat!($($doc, '\n',)*),
136                                 deprecation_reason,
137                             )
138                         },
139                     )+
140                 ]
141             }
142         }
143     };
144 }
145
146 define_Conf! {
147     /// Lint: ENUM_VARIANT_NAMES, LARGE_TYPES_PASSED_BY_VALUE, TRIVIALLY_COPY_PASS_BY_REF, UNNECESSARY_WRAPS, UPPER_CASE_ACRONYMS, WRONG_SELF_CONVENTION, BOX_COLLECTION, REDUNDANT_ALLOCATION, RC_BUFFER, VEC_BOX, OPTION_OPTION, LINKEDLIST, RC_MUTEX.
148     ///
149     /// Suppress lints whenever the suggested change would cause breakage for other crates.
150     (avoid_breaking_exported_api: bool = true),
151     /// Lint: MANUAL_SPLIT_ONCE, MANUAL_STR_REPEAT, CLONED_INSTEAD_OF_COPIED, REDUNDANT_FIELD_NAMES, REDUNDANT_STATIC_LIFETIMES, FILTER_MAP_NEXT, CHECKED_CONVERSIONS, MANUAL_RANGE_CONTAINS, USE_SELF, MEM_REPLACE_WITH_DEFAULT, MANUAL_NON_EXHAUSTIVE, OPTION_AS_REF_DEREF, MAP_UNWRAP_OR, MATCH_LIKE_MATCHES_MACRO, MANUAL_STRIP, MISSING_CONST_FOR_FN, UNNESTED_OR_PATTERNS, FROM_OVER_INTO, PTR_AS_PTR, IF_THEN_SOME_ELSE_NONE, APPROX_CONSTANT.
152     ///
153     /// The minimum rust version that the project supports
154     (msrv: Option<String> = None),
155     /// Lint: BLACKLISTED_NAME.
156     ///
157     /// The list of blacklisted names to lint about. NB: `bar` is not here since it has legitimate uses
158     (blacklisted_names: Vec<String> = ["foo", "baz", "quux"].iter().map(ToString::to_string).collect()),
159     /// Lint: COGNITIVE_COMPLEXITY.
160     ///
161     /// The maximum cognitive complexity a function can have
162     (cognitive_complexity_threshold: u64 = 25),
163     /// DEPRECATED LINT: CYCLOMATIC_COMPLEXITY.
164     ///
165     /// Use the Cognitive Complexity lint instead.
166     #[conf_deprecated("Please use `cognitive-complexity-threshold` instead")]
167     (cyclomatic_complexity_threshold: Option<u64> = None),
168     /// Lint: DOC_MARKDOWN.
169     ///
170     /// The list of words this lint should not consider as identifiers needing ticks
171     (doc_valid_idents: Vec<String> = [
172         "KiB", "MiB", "GiB", "TiB", "PiB", "EiB",
173         "DirectX",
174         "ECMAScript",
175         "GPLv2", "GPLv3",
176         "GitHub", "GitLab",
177         "IPv4", "IPv6",
178         "ClojureScript", "CoffeeScript", "JavaScript", "PureScript", "TypeScript",
179         "NaN", "NaNs",
180         "OAuth", "GraphQL",
181         "OCaml",
182         "OpenGL", "OpenMP", "OpenSSH", "OpenSSL", "OpenStreetMap", "OpenDNS",
183         "WebGL",
184         "TensorFlow",
185         "TrueType",
186         "iOS", "macOS", "FreeBSD",
187         "TeX", "LaTeX", "BibTeX", "BibLaTeX",
188         "MinGW",
189         "CamelCase",
190     ].iter().map(ToString::to_string).collect()),
191     /// Lint: TOO_MANY_ARGUMENTS.
192     ///
193     /// The maximum number of argument a function or method can have
194     (too_many_arguments_threshold: u64 = 7),
195     /// Lint: TYPE_COMPLEXITY.
196     ///
197     /// The maximum complexity a type can have
198     (type_complexity_threshold: u64 = 250),
199     /// Lint: MANY_SINGLE_CHAR_NAMES.
200     ///
201     /// The maximum number of single char bindings a scope may have
202     (single_char_binding_names_threshold: u64 = 4),
203     /// Lint: BOXED_LOCAL, USELESS_VEC.
204     ///
205     /// The maximum size of objects (in bytes) that will be linted. Larger objects are ok on the heap
206     (too_large_for_stack: u64 = 200),
207     /// Lint: ENUM_VARIANT_NAMES.
208     ///
209     /// The minimum number of enum variants for the lints about variant names to trigger
210     (enum_variant_name_threshold: u64 = 3),
211     /// Lint: LARGE_ENUM_VARIANT.
212     ///
213     /// The maximum size of an enum's variant to avoid box suggestion
214     (enum_variant_size_threshold: u64 = 200),
215     /// Lint: VERBOSE_BIT_MASK.
216     ///
217     /// The maximum allowed size of a bit mask before suggesting to use 'trailing_zeros'
218     (verbose_bit_mask_threshold: u64 = 1),
219     /// Lint: DECIMAL_LITERAL_REPRESENTATION.
220     ///
221     /// The lower bound for linting decimal literals
222     (literal_representation_threshold: u64 = 16384),
223     /// Lint: TRIVIALLY_COPY_PASS_BY_REF.
224     ///
225     /// The maximum size (in bytes) to consider a `Copy` type for passing by value instead of by reference.
226     (trivial_copy_size_limit: Option<u64> = None),
227     /// Lint: LARGE_TYPE_PASS_BY_MOVE.
228     ///
229     /// The minimum size (in bytes) to consider a type for passing by reference instead of by value.
230     (pass_by_value_size_limit: u64 = 256),
231     /// Lint: TOO_MANY_LINES.
232     ///
233     /// The maximum number of lines a function or method can have
234     (too_many_lines_threshold: u64 = 100),
235     /// Lint: LARGE_STACK_ARRAYS, LARGE_CONST_ARRAYS.
236     ///
237     /// The maximum allowed size for arrays on the stack
238     (array_size_threshold: u64 = 512_000),
239     /// Lint: VEC_BOX.
240     ///
241     /// The size of the boxed type in bytes, where boxing in a `Vec` is allowed
242     (vec_box_size_threshold: u64 = 4096),
243     /// Lint: TYPE_REPETITION_IN_BOUNDS.
244     ///
245     /// The maximum number of bounds a trait can have to be linted
246     (max_trait_bounds: u64 = 3),
247     /// Lint: STRUCT_EXCESSIVE_BOOLS.
248     ///
249     /// The maximum number of bool fields a struct can have
250     (max_struct_bools: u64 = 3),
251     /// Lint: FN_PARAMS_EXCESSIVE_BOOLS.
252     ///
253     /// The maximum number of bool parameters a function can have
254     (max_fn_params_bools: u64 = 3),
255     /// Lint: WILDCARD_IMPORTS.
256     ///
257     /// Whether to allow certain wildcard imports (prelude, super in tests).
258     (warn_on_all_wildcard_imports: bool = false),
259     /// Lint: DISALLOWED_METHOD.
260     ///
261     /// The list of disallowed methods, written as fully qualified paths.
262     (disallowed_methods: Vec<crate::utils::conf::DisallowedMethod> = Vec::new()),
263     /// Lint: DISALLOWED_TYPE.
264     ///
265     /// The list of disallowed types, written as fully qualified paths.
266     (disallowed_types: Vec<crate::utils::conf::DisallowedType> = Vec::new()),
267     /// Lint: UNREADABLE_LITERAL.
268     ///
269     /// Should the fraction of a decimal be linted to include separators.
270     (unreadable_literal_lint_fractions: bool = true),
271     /// Lint: UPPER_CASE_ACRONYMS.
272     ///
273     /// Enables verbose mode. Triggers if there is more than one uppercase char next to each other
274     (upper_case_acronyms_aggressive: bool = false),
275     /// Lint: _CARGO_COMMON_METADATA.
276     ///
277     /// For internal testing only, ignores the current `publish` settings in the Cargo manifest.
278     (cargo_ignore_publish: bool = false),
279     /// Lint: NONSTANDARD_MACRO_BRACES.
280     ///
281     /// Enforce the named macros always use the braces specified.
282     ///
283     /// A `MacroMatcher` can be added like so `{ name = "macro_name", brace = "(" }`. If the macro
284     /// is could be used with a full path two `MacroMatcher`s have to be added one with the full path
285     /// `crate_name::macro_name` and one with just the macro name.
286     (standard_macro_braces: Vec<crate::nonstandard_macro_braces::MacroMatcher> = Vec::new()),
287     /// Lint: MISSING_ENFORCED_IMPORT_RENAMES.
288     ///
289     /// The list of imports to always rename, a fully qualified path followed by the rename.
290     (enforced_import_renames: Vec<crate::utils::conf::Rename> = Vec::new()),
291     /// Lint: RESTRICTED_SCRIPTS.
292     ///
293     /// The list of unicode scripts allowed to be used in the scope.
294     (allowed_scripts: Vec<String> = vec!["Latin".to_string()]),
295     /// Lint: NON_SEND_FIELDS_IN_SEND_TY.
296     ///
297     /// Whether to apply the raw pointer heuristic to determine if a type is `Send`.
298     (enable_raw_pointer_heuristic_for_send: bool = true),
299 }
300
301 /// Search for the configuration file.
302 pub fn lookup_conf_file() -> io::Result<Option<PathBuf>> {
303     /// Possible filename to search for.
304     const CONFIG_FILE_NAMES: [&str; 2] = [".clippy.toml", "clippy.toml"];
305
306     // Start looking for a config file in CLIPPY_CONF_DIR, or failing that, CARGO_MANIFEST_DIR.
307     // If neither of those exist, use ".".
308     let mut current = env::var_os("CLIPPY_CONF_DIR")
309         .or_else(|| env::var_os("CARGO_MANIFEST_DIR"))
310         .map_or_else(|| PathBuf::from("."), PathBuf::from);
311     loop {
312         for config_file_name in &CONFIG_FILE_NAMES {
313             if let Ok(config_file) = current.join(config_file_name).canonicalize() {
314                 match fs::metadata(&config_file) {
315                     Err(e) if e.kind() == io::ErrorKind::NotFound => {},
316                     Err(e) => return Err(e),
317                     Ok(md) if md.is_dir() => {},
318                     Ok(_) => return Ok(Some(config_file)),
319                 }
320             }
321         }
322
323         // If the current directory has no parent, we're done searching.
324         if !current.pop() {
325             return Ok(None);
326         }
327     }
328 }
329
330 /// Read the `toml` configuration file.
331 ///
332 /// In case of error, the function tries to continue as much as possible.
333 pub fn read(path: &Path) -> TryConf {
334     let content = match fs::read_to_string(path) {
335         Err(e) => return TryConf::from_error(e),
336         Ok(content) => content,
337     };
338     toml::from_str(&content).unwrap_or_else(TryConf::from_error)
339 }