]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/utils/conf.rs
Merge commit '3c7e7dbc1583a0b06df5bd7623dd354a4debd23d' into clippyup
[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::str::FromStr;
10 use std::{cmp, env, fmt, fs, io, iter};
11
12 #[rustfmt::skip]
13 const DEFAULT_DOC_VALID_IDENTS: &[&str] = &[
14     "KiB", "MiB", "GiB", "TiB", "PiB", "EiB",
15     "DirectX",
16     "ECMAScript",
17     "GPLv2", "GPLv3",
18     "GitHub", "GitLab",
19     "IPv4", "IPv6",
20     "ClojureScript", "CoffeeScript", "JavaScript", "PureScript", "TypeScript",
21     "NaN", "NaNs",
22     "OAuth", "GraphQL",
23     "OCaml",
24     "OpenGL", "OpenMP", "OpenSSH", "OpenSSL", "OpenStreetMap", "OpenDNS",
25     "WebGL",
26     "TensorFlow",
27     "TrueType",
28     "iOS", "macOS", "FreeBSD",
29     "TeX", "LaTeX", "BibTeX", "BibLaTeX",
30     "MinGW",
31     "CamelCase",
32 ];
33 const DEFAULT_BLACKLISTED_NAMES: &[&str] = &["foo", "baz", "quux"];
34
35 /// Holds information used by `MISSING_ENFORCED_IMPORT_RENAMES` lint.
36 #[derive(Clone, Debug, Deserialize)]
37 pub struct Rename {
38     pub path: String,
39     pub rename: String,
40 }
41
42 /// A single disallowed method, used by the `DISALLOWED_METHODS` lint.
43 #[derive(Clone, Debug, Deserialize)]
44 #[serde(untagged)]
45 pub enum DisallowedMethod {
46     Simple(String),
47     WithReason { path: String, reason: Option<String> },
48 }
49
50 impl DisallowedMethod {
51     pub fn path(&self) -> &str {
52         let (Self::Simple(path) | Self::WithReason { path, .. }) = self;
53
54         path
55     }
56 }
57
58 /// A single disallowed type, used by the `DISALLOWED_TYPES` lint.
59 #[derive(Clone, Debug, Deserialize)]
60 #[serde(untagged)]
61 pub enum DisallowedType {
62     Simple(String),
63     WithReason { path: String, reason: Option<String> },
64 }
65
66 /// Conf with parse errors
67 #[derive(Default)]
68 pub struct TryConf {
69     pub conf: Conf,
70     pub errors: Vec<Box<dyn Error>>,
71 }
72
73 impl TryConf {
74     fn from_error(error: impl Error + 'static) -> Self {
75         Self {
76             conf: Conf::default(),
77             errors: vec![Box::new(error)],
78         }
79     }
80 }
81
82 #[derive(Debug)]
83 struct ConfError(String);
84
85 impl fmt::Display for ConfError {
86     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87         <String as fmt::Display>::fmt(&self.0, f)
88     }
89 }
90
91 impl Error for ConfError {}
92
93 fn conf_error(s: String) -> Box<dyn Error> {
94     Box::new(ConfError(s))
95 }
96
97 macro_rules! define_Conf {
98     ($(
99         $(#[doc = $doc:literal])+
100         $(#[conf_deprecated($dep:literal)])?
101         ($name:ident: $ty:ty = $default:expr),
102     )*) => {
103         /// Clippy lint configuration
104         pub struct Conf {
105             $($(#[doc = $doc])+ pub $name: $ty,)*
106         }
107
108         mod defaults {
109             $(pub fn $name() -> $ty { $default })*
110         }
111
112         impl Default for Conf {
113             fn default() -> Self {
114                 Self { $($name: defaults::$name(),)* }
115             }
116         }
117
118         impl<'de> Deserialize<'de> for TryConf {
119             fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de> {
120                 deserializer.deserialize_map(ConfVisitor)
121             }
122         }
123
124         #[derive(Deserialize)]
125         #[serde(field_identifier, rename_all = "kebab-case")]
126         #[allow(non_camel_case_types)]
127         enum Field { $($name,)* third_party, }
128
129         struct ConfVisitor;
130
131         impl<'de> Visitor<'de> for ConfVisitor {
132             type Value = TryConf;
133
134             fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
135                 formatter.write_str("Conf")
136             }
137
138             fn visit_map<V>(self, mut map: V) -> Result<Self::Value, V::Error> where V: MapAccess<'de> {
139                 let mut errors = Vec::new();
140                 $(let mut $name = None;)*
141                 // could get `Field` here directly, but get `str` first for diagnostics
142                 while let Some(name) = map.next_key::<&str>()? {
143                     match Field::deserialize(name.into_deserializer())? {
144                         $(Field::$name => {
145                             $(errors.push(conf_error(format!("deprecated field `{}`. {}", name, $dep)));)?
146                             match map.next_value() {
147                                 Err(e) => errors.push(conf_error(e.to_string())),
148                                 Ok(value) => match $name {
149                                     Some(_) => errors.push(conf_error(format!("duplicate field `{}`", name))),
150                                     None => $name = Some(value),
151                                 }
152                             }
153                         })*
154                         // white-listed; ignore
155                         Field::third_party => drop(map.next_value::<IgnoredAny>())
156                     }
157                 }
158                 let conf = Conf { $($name: $name.unwrap_or_else(defaults::$name),)* };
159                 Ok(TryConf { conf, errors })
160             }
161         }
162
163         #[cfg(feature = "internal")]
164         pub mod metadata {
165             use crate::utils::internal_lints::metadata_collector::ClippyConfiguration;
166
167             macro_rules! wrap_option {
168                 () => (None);
169                 ($x:literal) => (Some($x));
170             }
171
172             pub(crate) fn get_configuration_metadata() -> Vec<ClippyConfiguration> {
173                 vec![
174                     $(
175                         {
176                             let deprecation_reason = wrap_option!($($dep)?);
177
178                             ClippyConfiguration::new(
179                                 stringify!($name),
180                                 stringify!($ty),
181                                 format!("{:?}", super::defaults::$name()),
182                                 concat!($($doc, '\n',)*),
183                                 deprecation_reason,
184                             )
185                         },
186                     )+
187                 ]
188             }
189         }
190     };
191 }
192
193 define_Conf! {
194     /// Lint: Arithmetic.
195     ///
196     /// Suppress checking of the passed type names.
197     (arithmetic_allowed: rustc_data_structures::fx::FxHashSet<String> = <_>::default()),
198     /// 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.
199     ///
200     /// Suppress lints whenever the suggested change would cause breakage for other crates.
201     (avoid_breaking_exported_api: bool = true),
202     /// 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, DEPRECATED_CFG_ATTR, INDEX_REFUTABLE_SLICE, MAP_CLONE, BORROW_AS_PTR, MANUAL_BITS, ERR_EXPECT, CAST_ABS_TO_UNSIGNED.
203     ///
204     /// The minimum rust version that the project supports
205     (msrv: Option<String> = None),
206     /// Lint: BLACKLISTED_NAME.
207     ///
208     /// The list of blacklisted names to lint about. NB: `bar` is not here since it has legitimate uses. The value
209     /// `".."` can be used as part of the list to indicate, that the configured values should be appended to the
210     /// default configuration of Clippy. By default any configuraction will replace the default value.
211     (blacklisted_names: Vec<String> = super::DEFAULT_BLACKLISTED_NAMES.iter().map(ToString::to_string).collect()),
212     /// Lint: COGNITIVE_COMPLEXITY.
213     ///
214     /// The maximum cognitive complexity a function can have
215     (cognitive_complexity_threshold: u64 = 25),
216     /// DEPRECATED LINT: CYCLOMATIC_COMPLEXITY.
217     ///
218     /// Use the Cognitive Complexity lint instead.
219     #[conf_deprecated("Please use `cognitive-complexity-threshold` instead")]
220     (cyclomatic_complexity_threshold: Option<u64> = None),
221     /// Lint: DOC_MARKDOWN.
222     ///
223     /// The list of words this lint should not consider as identifiers needing ticks. The value
224     /// `".."` can be used as part of the list to indicate, that the configured values should be appended to the
225     /// default configuration of Clippy. By default any configuraction will replace the default value. For example:
226     /// * `doc-valid-idents = ["ClipPy"]` would replace the default list with `["ClipPy"]`.
227     /// * `doc-valid-idents = ["ClipPy", ".."]` would append `ClipPy` to the default list.
228     ///
229     /// Default list:
230     (doc_valid_idents: Vec<String> = super::DEFAULT_DOC_VALID_IDENTS.iter().map(ToString::to_string).collect()),
231     /// Lint: TOO_MANY_ARGUMENTS.
232     ///
233     /// The maximum number of argument a function or method can have
234     (too_many_arguments_threshold: u64 = 7),
235     /// Lint: TYPE_COMPLEXITY.
236     ///
237     /// The maximum complexity a type can have
238     (type_complexity_threshold: u64 = 250),
239     /// Lint: MANY_SINGLE_CHAR_NAMES.
240     ///
241     /// The maximum number of single char bindings a scope may have
242     (single_char_binding_names_threshold: u64 = 4),
243     /// Lint: BOXED_LOCAL, USELESS_VEC.
244     ///
245     /// The maximum size of objects (in bytes) that will be linted. Larger objects are ok on the heap
246     (too_large_for_stack: u64 = 200),
247     /// Lint: ENUM_VARIANT_NAMES.
248     ///
249     /// The minimum number of enum variants for the lints about variant names to trigger
250     (enum_variant_name_threshold: u64 = 3),
251     /// Lint: LARGE_ENUM_VARIANT.
252     ///
253     /// The maximum size of an enum's variant to avoid box suggestion
254     (enum_variant_size_threshold: u64 = 200),
255     /// Lint: VERBOSE_BIT_MASK.
256     ///
257     /// The maximum allowed size of a bit mask before suggesting to use 'trailing_zeros'
258     (verbose_bit_mask_threshold: u64 = 1),
259     /// Lint: DECIMAL_LITERAL_REPRESENTATION.
260     ///
261     /// The lower bound for linting decimal literals
262     (literal_representation_threshold: u64 = 16384),
263     /// Lint: TRIVIALLY_COPY_PASS_BY_REF.
264     ///
265     /// The maximum size (in bytes) to consider a `Copy` type for passing by value instead of by reference.
266     (trivial_copy_size_limit: Option<u64> = None),
267     /// Lint: LARGE_TYPE_PASS_BY_MOVE.
268     ///
269     /// The minimum size (in bytes) to consider a type for passing by reference instead of by value.
270     (pass_by_value_size_limit: u64 = 256),
271     /// Lint: TOO_MANY_LINES.
272     ///
273     /// The maximum number of lines a function or method can have
274     (too_many_lines_threshold: u64 = 100),
275     /// Lint: LARGE_STACK_ARRAYS, LARGE_CONST_ARRAYS.
276     ///
277     /// The maximum allowed size for arrays on the stack
278     (array_size_threshold: u64 = 512_000),
279     /// Lint: VEC_BOX.
280     ///
281     /// The size of the boxed type in bytes, where boxing in a `Vec` is allowed
282     (vec_box_size_threshold: u64 = 4096),
283     /// Lint: TYPE_REPETITION_IN_BOUNDS.
284     ///
285     /// The maximum number of bounds a trait can have to be linted
286     (max_trait_bounds: u64 = 3),
287     /// Lint: STRUCT_EXCESSIVE_BOOLS.
288     ///
289     /// The maximum number of bool fields a struct can have
290     (max_struct_bools: u64 = 3),
291     /// Lint: FN_PARAMS_EXCESSIVE_BOOLS.
292     ///
293     /// The maximum number of bool parameters a function can have
294     (max_fn_params_bools: u64 = 3),
295     /// Lint: WILDCARD_IMPORTS.
296     ///
297     /// Whether to allow certain wildcard imports (prelude, super in tests).
298     (warn_on_all_wildcard_imports: bool = false),
299     /// Lint: DISALLOWED_METHODS.
300     ///
301     /// The list of disallowed methods, written as fully qualified paths.
302     (disallowed_methods: Vec<crate::utils::conf::DisallowedMethod> = Vec::new()),
303     /// Lint: DISALLOWED_TYPES.
304     ///
305     /// The list of disallowed types, written as fully qualified paths.
306     (disallowed_types: Vec<crate::utils::conf::DisallowedType> = Vec::new()),
307     /// Lint: UNREADABLE_LITERAL.
308     ///
309     /// Should the fraction of a decimal be linted to include separators.
310     (unreadable_literal_lint_fractions: bool = true),
311     /// Lint: UPPER_CASE_ACRONYMS.
312     ///
313     /// Enables verbose mode. Triggers if there is more than one uppercase char next to each other
314     (upper_case_acronyms_aggressive: bool = false),
315     /// Lint: _CARGO_COMMON_METADATA.
316     ///
317     /// For internal testing only, ignores the current `publish` settings in the Cargo manifest.
318     (cargo_ignore_publish: bool = false),
319     /// Lint: NONSTANDARD_MACRO_BRACES.
320     ///
321     /// Enforce the named macros always use the braces specified.
322     ///
323     /// A `MacroMatcher` can be added like so `{ name = "macro_name", brace = "(" }`. If the macro
324     /// is could be used with a full path two `MacroMatcher`s have to be added one with the full path
325     /// `crate_name::macro_name` and one with just the macro name.
326     (standard_macro_braces: Vec<crate::nonstandard_macro_braces::MacroMatcher> = Vec::new()),
327     /// Lint: MISSING_ENFORCED_IMPORT_RENAMES.
328     ///
329     /// The list of imports to always rename, a fully qualified path followed by the rename.
330     (enforced_import_renames: Vec<crate::utils::conf::Rename> = Vec::new()),
331     /// Lint: DISALLOWED_SCRIPT_IDENTS.
332     ///
333     /// The list of unicode scripts allowed to be used in the scope.
334     (allowed_scripts: Vec<String> = ["Latin"].iter().map(ToString::to_string).collect()),
335     /// Lint: NON_SEND_FIELDS_IN_SEND_TY.
336     ///
337     /// Whether to apply the raw pointer heuristic to determine if a type is `Send`.
338     (enable_raw_pointer_heuristic_for_send: bool = true),
339     /// Lint: INDEX_REFUTABLE_SLICE.
340     ///
341     /// When Clippy suggests using a slice pattern, this is the maximum number of elements allowed in
342     /// the slice pattern that is suggested. If more elements would be necessary, the lint is suppressed.
343     /// For example, `[_, _, _, e, ..]` is a slice pattern with 4 elements.
344     (max_suggested_slice_pattern_length: u64 = 3),
345     /// Lint: AWAIT_HOLDING_INVALID_TYPE
346     (await_holding_invalid_types: Vec<crate::utils::conf::DisallowedType> = Vec::new()),
347     /// Lint: LARGE_INCLUDE_FILE.
348     ///
349     /// The maximum size of a file included via `include_bytes!()` or `include_str!()`, in bytes
350     (max_include_file_size: u64 = 1_000_000),
351     /// Lint: EXPECT_USED.
352     ///
353     /// Whether `expect` should be allowed in test functions
354     (allow_expect_in_tests: bool = false),
355     /// Lint: UNWRAP_USED.
356     ///
357     /// Whether `unwrap` should be allowed in test functions
358     (allow_unwrap_in_tests: bool = false),
359     /// Lint: DBG_MACRO.
360     ///
361     /// Whether `dbg!` should be allowed in test functions
362     (allow_dbg_in_tests: bool = false),
363 }
364
365 /// Search for the configuration file.
366 pub fn lookup_conf_file() -> io::Result<Option<PathBuf>> {
367     /// Possible filename to search for.
368     const CONFIG_FILE_NAMES: [&str; 2] = [".clippy.toml", "clippy.toml"];
369
370     // Start looking for a config file in CLIPPY_CONF_DIR, or failing that, CARGO_MANIFEST_DIR.
371     // If neither of those exist, use ".".
372     let mut current = env::var_os("CLIPPY_CONF_DIR")
373         .or_else(|| env::var_os("CARGO_MANIFEST_DIR"))
374         .map_or_else(|| PathBuf::from("."), PathBuf::from);
375
376     let mut found_config: Option<PathBuf> = None;
377
378     loop {
379         for config_file_name in &CONFIG_FILE_NAMES {
380             if let Ok(config_file) = current.join(config_file_name).canonicalize() {
381                 match fs::metadata(&config_file) {
382                     Err(e) if e.kind() == io::ErrorKind::NotFound => {},
383                     Err(e) => return Err(e),
384                     Ok(md) if md.is_dir() => {},
385                     Ok(_) => {
386                         // warn if we happen to find two config files #8323
387                         if let Some(ref found_config_) = found_config {
388                             eprintln!(
389                                 "Using config file `{}`\nWarning: `{}` will be ignored.",
390                                 found_config_.display(),
391                                 config_file.display(),
392                             );
393                         } else {
394                             found_config = Some(config_file);
395                         }
396                     },
397                 }
398             }
399         }
400
401         if found_config.is_some() {
402             return Ok(found_config);
403         }
404
405         // If the current directory has no parent, we're done searching.
406         if !current.pop() {
407             return Ok(None);
408         }
409     }
410 }
411
412 /// Read the `toml` configuration file.
413 ///
414 /// In case of error, the function tries to continue as much as possible.
415 pub fn read(path: &Path) -> TryConf {
416     let content = match fs::read_to_string(path) {
417         Err(e) => return TryConf::from_error(e),
418         Ok(content) => content,
419     };
420     match toml::from_str::<TryConf>(&content) {
421         Ok(mut conf) => {
422             extend_vec_if_indicator_present(&mut conf.conf.doc_valid_idents, DEFAULT_DOC_VALID_IDENTS);
423             extend_vec_if_indicator_present(&mut conf.conf.blacklisted_names, DEFAULT_BLACKLISTED_NAMES);
424
425             conf
426         },
427         Err(e) => TryConf::from_error(e),
428     }
429 }
430
431 fn extend_vec_if_indicator_present(vec: &mut Vec<String>, default: &[&str]) {
432     if vec.contains(&"..".to_string()) {
433         vec.extend(default.iter().map(ToString::to_string));
434     }
435 }
436
437 const SEPARATOR_WIDTH: usize = 4;
438
439 // Check whether the error is "unknown field" and, if so, list the available fields sorted and at
440 // least one per line, more if `CLIPPY_TERMINAL_WIDTH` is set and allows it.
441 pub fn format_error(error: Box<dyn Error>) -> String {
442     let s = error.to_string();
443
444     if_chain! {
445         if error.downcast::<toml::de::Error>().is_ok();
446         if let Some((prefix, mut fields, suffix)) = parse_unknown_field_message(&s);
447         then {
448             use fmt::Write;
449
450             fields.sort_unstable();
451
452             let (rows, column_widths) = calculate_dimensions(&fields);
453
454             let mut msg = String::from(prefix);
455             for row in 0..rows {
456                 write!(msg, "\n").unwrap();
457                 for (column, column_width) in column_widths.iter().copied().enumerate() {
458                     let index = column * rows + row;
459                     let field = fields.get(index).copied().unwrap_or_default();
460                     write!(
461                         msg,
462                         "{:separator_width$}{:field_width$}",
463                         " ",
464                         field,
465                         separator_width = SEPARATOR_WIDTH,
466                         field_width = column_width
467                     )
468                     .unwrap();
469                 }
470             }
471             write!(msg, "\n{}", suffix).unwrap();
472             msg
473         } else {
474             s
475         }
476     }
477 }
478
479 // `parse_unknown_field_message` will become unnecessary if
480 // https://github.com/alexcrichton/toml-rs/pull/364 is merged.
481 fn parse_unknown_field_message(s: &str) -> Option<(&str, Vec<&str>, &str)> {
482     // An "unknown field" message has the following form:
483     //   unknown field `UNKNOWN`, expected one of `FIELD0`, `FIELD1`, ..., `FIELDN` at line X column Y
484     //                                           ^^      ^^^^                     ^^
485     if_chain! {
486         if s.starts_with("unknown field");
487         let slices = s.split("`, `").collect::<Vec<_>>();
488         let n = slices.len();
489         if n >= 2;
490         if let Some((prefix, first_field)) = slices[0].rsplit_once(" `");
491         if let Some((last_field, suffix)) = slices[n - 1].split_once("` ");
492         then {
493             let fields = iter::once(first_field)
494                 .chain(slices[1..n - 1].iter().copied())
495                 .chain(iter::once(last_field))
496                 .collect::<Vec<_>>();
497             Some((prefix, fields, suffix))
498         } else {
499             None
500         }
501     }
502 }
503
504 fn calculate_dimensions(fields: &[&str]) -> (usize, Vec<usize>) {
505     let columns = env::var("CLIPPY_TERMINAL_WIDTH")
506         .ok()
507         .and_then(|s| <usize as FromStr>::from_str(&s).ok())
508         .map_or(1, |terminal_width| {
509             let max_field_width = fields.iter().map(|field| field.len()).max().unwrap();
510             cmp::max(1, terminal_width / (SEPARATOR_WIDTH + max_field_width))
511         });
512
513     let rows = (fields.len() + (columns - 1)) / columns;
514
515     let column_widths = (0..columns)
516         .map(|column| {
517             if column < columns - 1 {
518                 (0..rows)
519                     .map(|row| {
520                         let index = column * rows + row;
521                         let field = fields.get(index).copied().unwrap_or_default();
522                         field.len()
523                     })
524                     .max()
525                     .unwrap()
526             } else {
527                 // Avoid adding extra space to the last column.
528                 0
529             }
530         })
531         .collect::<Vec<_>>();
532
533     (rows, column_widths)
534 }