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