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)] 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)] use SourceItemOrderingTraitAssocItemKind::*;
73 &[Const, Type, Fn]
74};
75const DEFAULT_SOURCE_ITEM_ORDERING: &[SourceItemOrderingCategory] = {
76 #[allow(clippy::enum_glob_use)] use SourceItemOrderingCategory::*;
78 &[Enum, Impl, Module, Struct, Trait]
79};
80
81#[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
128pub fn sanitize_explanation(raw_docs: &str) -> String {
130 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 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 $(let mut $name = None;)*
269
270 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 $(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 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 $(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 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 #[lints(absolute_paths)]
346 absolute_paths_allowed_crates: Vec<String> = Vec::new(),
347 #[lints(absolute_paths)]
350 absolute_paths_max_segments: u64 = 2,
351 #[lints(undocumented_unsafe_blocks)]
353 accept_comment_above_attributes: bool = true,
354 #[lints(undocumented_unsafe_blocks)]
356 accept_comment_above_statement: bool = true,
357 #[lints(modulo_arithmetic)]
359 allow_comparison_to_zero: bool = true,
360 #[lints(dbg_macro)]
362 allow_dbg_in_tests: bool = false,
363 #[lints(module_name_repetitions)]
365 allow_exact_repetitions: bool = true,
366 #[lints(expect_used)]
368 allow_expect_in_consts: bool = true,
369 #[lints(expect_used)]
371 allow_expect_in_tests: bool = false,
372 #[lints(indexing_slicing)]
374 allow_indexing_slicing_in_tests: bool = false,
375 #[lints(uninlined_format_args)]
377 allow_mixed_uninlined_format_args: bool = true,
378 #[lints(needless_raw_string_hashes)]
380 allow_one_hash_in_raw_strings: bool = false,
381 #[lints(panic)]
383 allow_panic_in_tests: bool = false,
384 #[lints(print_stderr, print_stdout)]
386 allow_print_in_tests: bool = false,
387 #[lints(module_inception)]
389 allow_private_module_inception: bool = false,
390 #[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 #[lints(unwrap_used)]
408 allow_unwrap_in_consts: bool = true,
409 #[lints(unwrap_used)]
411 allow_unwrap_in_tests: bool = false,
412 #[lints(useless_vec)]
414 allow_useless_vec_in_tests: bool = false,
415 #[lints(path_ends_with_ext)]
417 allowed_dotfiles: Vec<String> = Vec::default(),
418 #[lints(multiple_crate_versions)]
420 allowed_duplicate_crates: Vec<String> = Vec::new(),
421 #[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 #[lints(module_name_repetitions)]
445 allowed_prefixes: Vec<String> = DEFAULT_ALLOWED_PREFIXES.iter().map(ToString::to_string).collect(),
446 #[lints(disallowed_script_idents)]
448 allowed_scripts: Vec<String> = vec!["Latin".to_string()],
449 #[lints(wildcard_imports)]
463 allowed_wildcard_imports: Vec<String> = Vec::new(),
464 #[lints(arithmetic_side_effects)]
479 arithmetic_side_effects_allowed: Vec<String> = <_>::default(),
480 #[lints(arithmetic_side_effects)]
495 arithmetic_side_effects_allowed_binary: Vec<(String, String)> = <_>::default(),
496 #[lints(arithmetic_side_effects)]
504 arithmetic_side_effects_allowed_unary: Vec<String> = <_>::default(),
505 #[lints(large_const_arrays, large_stack_arrays)]
507 array_size_threshold: u64 = 16 * 1024,
508 #[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 #[disallowed_paths_allow_replacements = false]
533 #[lints(await_holding_invalid_type)]
534 await_holding_invalid_types: Vec<DisallowedPathWithoutReplacement> = Vec::new(),
535 #[conf_deprecated("Please use `disallowed-names` instead", disallowed_names)]
539 blacklisted_names: Vec<String> = Vec::new(),
540 #[lints(cargo_common_metadata)]
542 cargo_ignore_publish: bool = false,
543 #[lints(incompatible_msrv)]
545 check_incompatible_msrv_in_tests: bool = false,
546 #[lints(inconsistent_struct_constructor)]
565 check_inconsistent_struct_field_initializers: bool = false,
566 #[lints(missing_errors_doc, missing_panics_doc, missing_safety_doc, unnecessary_safety_doc)]
568 check_private_items: bool = false,
569 #[lints(cognitive_complexity)]
571 cognitive_complexity_threshold: u64 = 25,
572 #[conf_deprecated("Please use `cognitive-complexity-threshold` instead", cognitive_complexity_threshold)]
576 cyclomatic_complexity_threshold: u64 = 25,
577 #[disallowed_paths_allow_replacements = true]
579 #[lints(disallowed_macros)]
580 disallowed_macros: Vec<DisallowedPath> = Vec::new(),
581 #[disallowed_paths_allow_replacements = true]
583 #[lints(disallowed_methods)]
584 disallowed_methods: Vec<DisallowedPath> = Vec::new(),
585 #[lints(disallowed_names)]
589 disallowed_names: Vec<String> = DEFAULT_DISALLOWED_NAMES.iter().map(ToString::to_string).collect(),
590 #[disallowed_paths_allow_replacements = true]
592 #[lints(disallowed_types)]
593 disallowed_types: Vec<DisallowedPath> = Vec::new(),
594 #[lints(doc_markdown)]
600 doc_valid_idents: Vec<String> = DEFAULT_DOC_VALID_IDENTS.iter().map(ToString::to_string).collect(),
601 #[lints(non_send_fields_in_send_ty)]
603 enable_raw_pointer_heuristic_for_send: bool = true,
604 #[lints(explicit_iter_loop)]
622 enforce_iter_loop_reborrow: bool = false,
623 #[lints(missing_enforced_import_renames)]
625 enforced_import_renames: Vec<Rename> = Vec::new(),
626 #[lints(enum_variant_names)]
628 enum_variant_name_threshold: u64 = 3,
629 #[lints(large_enum_variant)]
631 enum_variant_size_threshold: u64 = 200,
632 #[lints(excessive_nesting)]
634 excessive_nesting_threshold: u64 = 0,
635 #[lints(large_futures)]
637 future_size_threshold: u64 = 16 * 1024,
638 #[lints(borrow_interior_mutable_const, declare_interior_mutable_const, ifs_same_cond, mutable_key_type)]
640 ignore_interior_mutability: Vec<String> = Vec::from(["bytes::Bytes".into()]),
641 #[lints(result_large_err)]
643 large_error_threshold: u64 = 128,
644 #[lints(collapsible_if)]
647 lint_commented_code: bool = false,
648 #[conf_deprecated("Please use `check-inconsistent-struct-field-initializers` instead", check_inconsistent_struct_field_initializers)]
653 lint_inconsistent_struct_field_initializers: bool = false,
654 #[lints(decimal_literal_representation)]
656 literal_representation_threshold: u64 = 16384,
657 #[lints(manual_let_else)]
660 matches_for_let_else: MatchLintBehaviour = MatchLintBehaviour::WellKnownTypes,
661 #[lints(fn_params_excessive_bools)]
663 max_fn_params_bools: u64 = 3,
664 #[lints(large_include_file)]
666 max_include_file_size: u64 = 1_000_000,
667 #[lints(struct_excessive_bools)]
669 max_struct_bools: u64 = 3,
670 #[lints(index_refutable_slice)]
674 max_suggested_slice_pattern_length: u64 = 3,
675 #[lints(type_repetition_in_bounds)]
677 max_trait_bounds: u64 = 3,
678 #[lints(min_ident_chars)]
680 min_ident_chars_threshold: u64 = 1,
681 #[lints(missing_docs_in_private_items)]
683 missing_docs_allow_unused: bool = false,
684 #[lints(missing_docs_in_private_items)]
687 missing_docs_in_crate_items: bool = false,
688 #[lints(arbitrary_source_item_ordering)]
690 module_item_order_groupings: SourceItemOrderingModuleItemGroupings = DEFAULT_MODULE_ITEM_ORDERING_GROUPS.into(),
691 #[lints(arbitrary_source_item_ordering)]
696 module_items_ordered_within_groupings: SourceItemOrderingWithinModuleItemGroupings =
697 SourceItemOrderingWithinModuleItemGroupings::None,
698 #[default_text = "current version"]
700 #[lints(
701 allow_attributes,
702 allow_attributes_without_reason,
703 almost_complete_range,
704 approx_constant,
705 assigning_clones,
706 borrow_as_ptr,
707 cast_abs_to_unsigned,
708 checked_conversions,
709 cloned_instead_of_copied,
710 collapsible_match,
711 collapsible_str_replace,
712 deprecated_cfg_attr,
713 derivable_impls,
714 err_expect,
715 filter_map_next,
716 from_over_into,
717 if_then_some_else_none,
718 index_refutable_slice,
719 io_other_error,
720 iter_kv_map,
721 legacy_numeric_constants,
722 lines_filter_map_ok,
723 manual_abs_diff,
724 manual_bits,
725 manual_c_str_literals,
726 manual_clamp,
727 manual_div_ceil,
728 manual_flatten,
729 manual_hash_one,
730 manual_is_ascii_check,
731 manual_is_power_of_two,
732 manual_let_else,
733 manual_midpoint,
734 manual_non_exhaustive,
735 manual_option_as_slice,
736 manual_pattern_char_comparison,
737 manual_range_contains,
738 manual_rem_euclid,
739 manual_repeat_n,
740 manual_retain,
741 manual_slice_fill,
742 manual_slice_size_calculation,
743 manual_split_once,
744 manual_str_repeat,
745 manual_strip,
746 manual_try_fold,
747 map_clone,
748 map_unwrap_or,
749 map_with_unused_argument_over_ranges,
750 match_like_matches_macro,
751 mem_replace_option_with_some,
752 mem_replace_with_default,
753 missing_const_for_fn,
754 needless_borrow,
755 non_std_lazy_statics,
756 option_as_ref_deref,
757 option_map_unwrap_or,
758 ptr_as_ptr,
759 question_mark,
760 redundant_field_names,
761 redundant_static_lifetimes,
762 repeat_vec_with_capacity,
763 same_item_push,
764 seek_from_current,
765 seek_rewind,
766 to_digit_is_some,
767 transmute_ptr_to_ref,
768 tuple_array_conversions,
769 type_repetition_in_bounds,
770 unchecked_duration_subtraction,
771 uninlined_format_args,
772 unnecessary_lazy_evaluations,
773 unnested_or_patterns,
774 unused_trait_names,
775 use_self,
776 )]
777 msrv: Msrv = Msrv::default(),
778 #[lints(large_types_passed_by_value)]
780 pass_by_value_size_limit: u64 = 256,
781 #[lints(pub_underscore_fields)]
784 pub_underscore_fields_behavior: PubUnderscoreFieldsBehaviour = PubUnderscoreFieldsBehaviour::PubliclyExported,
785 #[lints(semicolon_inside_block)]
787 semicolon_inside_block_ignore_singleline: bool = false,
788 #[lints(semicolon_outside_block)]
790 semicolon_outside_block_ignore_multiline: bool = false,
791 #[lints(many_single_char_names)]
793 single_char_binding_names_threshold: u64 = 4,
794 #[lints(arbitrary_source_item_ordering)]
796 source_item_ordering: SourceItemOrdering = DEFAULT_SOURCE_ITEM_ORDERING.into(),
797 #[lints(large_stack_frames)]
799 stack_size_threshold: u64 = 512_000,
800 #[lints(nonstandard_macro_braces)]
806 standard_macro_braces: Vec<MacroMatcher> = Vec::new(),
807 #[lints(struct_field_names)]
809 struct_field_name_threshold: u64 = 3,
810 #[lints(indexing_slicing)]
816 suppress_restriction_lint_in_const: bool = false,
817 #[lints(boxed_local, useless_vec)]
819 too_large_for_stack: u64 = 200,
820 #[lints(too_many_arguments)]
822 too_many_arguments_threshold: u64 = 7,
823 #[lints(too_many_lines)]
825 too_many_lines_threshold: u64 = 100,
826 #[lints(arbitrary_source_item_ordering)]
828 trait_assoc_item_kinds_order: SourceItemOrderingTraitAssocItemKinds = DEFAULT_TRAIT_ASSOC_ITEM_KINDS_ORDER.into(),
829 #[default_text = "target_pointer_width * 2"]
832 #[lints(trivially_copy_pass_by_ref)]
833 trivial_copy_size_limit: Option<u64> = None,
834 #[lints(type_complexity)]
836 type_complexity_threshold: u64 = 250,
837 #[lints(unnecessary_box_returns)]
839 unnecessary_box_size: u64 = 128,
840 #[lints(unreadable_literal)]
842 unreadable_literal_lint_fractions: bool = true,
843 #[lints(upper_case_acronyms)]
845 upper_case_acronyms_aggressive: bool = false,
846 #[lints(vec_box)]
848 vec_box_size_threshold: u64 = 4096,
849 #[lints(verbose_bit_mask)]
851 verbose_bit_mask_threshold: u64 = 1,
852 #[lints(wildcard_imports)]
855 warn_on_all_wildcard_imports: bool = false,
856 #[lints(macro_metavars_in_unsafe)]
858 warn_unsafe_macro_metavars_in_private_macros: bool = false,
859}
860
861pub fn lookup_conf_file() -> io::Result<(Option<PathBuf>, Vec<String>)> {
867 const CONFIG_FILE_NAMES: [&str; 2] = [".clippy.toml", "clippy.toml"];
869
870 let mut current = env::var_os("CLIPPY_CONF_DIR")
873 .or_else(|| env::var_os("CARGO_MANIFEST_DIR"))
874 .map_or_else(|| PathBuf::from("."), PathBuf::from)
875 .canonicalize()?;
876
877 let mut found_config: Option<PathBuf> = None;
878 let mut warnings = vec![];
879
880 loop {
881 for config_file_name in &CONFIG_FILE_NAMES {
882 if let Ok(config_file) = current.join(config_file_name).canonicalize() {
883 match fs::metadata(&config_file) {
884 Err(e) if e.kind() == io::ErrorKind::NotFound => {},
885 Err(e) => return Err(e),
886 Ok(md) if md.is_dir() => {},
887 Ok(_) => {
888 if let Some(ref found_config) = found_config {
890 warnings.push(format!(
891 "using config file `{}`, `{}` will be ignored",
892 found_config.display(),
893 config_file.display()
894 ));
895 } else {
896 found_config = Some(config_file);
897 }
898 },
899 }
900 }
901 }
902
903 if found_config.is_some() {
904 return Ok((found_config, warnings));
905 }
906
907 if !current.pop() {
909 return Ok((None, warnings));
910 }
911 }
912}
913
914fn deserialize(file: &SourceFile) -> TryConf {
915 match toml::de::Deserializer::new(file.src.as_ref().unwrap()).deserialize_map(ConfVisitor(file)) {
916 Ok(mut conf) => {
917 extend_vec_if_indicator_present(&mut conf.conf.disallowed_names, DEFAULT_DISALLOWED_NAMES);
918 extend_vec_if_indicator_present(&mut conf.conf.allowed_prefixes, DEFAULT_ALLOWED_PREFIXES);
919 extend_vec_if_indicator_present(
920 &mut conf.conf.allow_renamed_params_for,
921 DEFAULT_ALLOWED_TRAITS_WITH_RENAMED_PARAMS,
922 );
923
924 if let SourceItemOrderingWithinModuleItemGroupings::Custom(groupings) =
927 &conf.conf.module_items_ordered_within_groupings
928 {
929 for grouping in groupings {
930 if !conf.conf.module_item_order_groupings.is_grouping(grouping) {
931 let names = conf.conf.module_item_order_groupings.grouping_names();
935 let suggestion = suggest_candidate(grouping, names.iter().map(String::as_str))
936 .map(|s| format!(" perhaps you meant `{s}`?"))
937 .unwrap_or_default();
938 let names = names.iter().map(|s| format!("`{s}`")).join(", ");
939 let message = format!(
940 "unknown ordering group: `{grouping}` was not specified in `module-items-ordered-within-groupings`,{suggestion} expected one of: {names}"
941 );
942
943 let span = conf
944 .value_spans
945 .get("module_item_order_groupings")
946 .cloned()
947 .unwrap_or_default();
948 conf.errors.push(ConfError::spanned(file, message, None, span));
949 }
950 }
951 }
952
953 if conf.conf.allowed_idents_below_min_chars.iter().any(|e| e == "..") {
955 conf.conf
956 .allowed_idents_below_min_chars
957 .extend(DEFAULT_ALLOWED_IDENTS_BELOW_MIN_CHARS.iter().map(ToString::to_string));
958 }
959 if conf.conf.doc_valid_idents.iter().any(|e| e == "..") {
960 conf.conf
961 .doc_valid_idents
962 .extend(DEFAULT_DOC_VALID_IDENTS.iter().map(ToString::to_string));
963 }
964
965 conf
966 },
967 Err(e) => TryConf::from_toml_error(file, &e),
968 }
969}
970
971fn extend_vec_if_indicator_present(vec: &mut Vec<String>, default: &[&str]) {
972 if vec.contains(&"..".to_string()) {
973 vec.extend(default.iter().map(ToString::to_string));
974 }
975}
976
977impl Conf {
978 pub fn read(sess: &Session, path: &io::Result<(Option<PathBuf>, Vec<String>)>) -> &'static Conf {
979 static CONF: OnceLock<Conf> = OnceLock::new();
980 CONF.get_or_init(|| Conf::read_inner(sess, path))
981 }
982
983 fn read_inner(sess: &Session, path: &io::Result<(Option<PathBuf>, Vec<String>)>) -> Conf {
984 match path {
985 Ok((_, warnings)) => {
986 for warning in warnings {
987 sess.dcx().warn(warning.clone());
988 }
989 },
990 Err(error) => {
991 sess.dcx()
992 .err(format!("error finding Clippy's configuration file: {error}"));
993 },
994 }
995
996 let TryConf {
997 mut conf,
998 value_spans: _,
999 errors,
1000 warnings,
1001 } = match path {
1002 Ok((Some(path), _)) => match sess.source_map().load_file(path) {
1003 Ok(file) => deserialize(&file),
1004 Err(error) => {
1005 sess.dcx().err(format!("failed to read `{}`: {error}", path.display()));
1006 TryConf::default()
1007 },
1008 },
1009 _ => TryConf::default(),
1010 };
1011
1012 conf.msrv.read_cargo(sess);
1013
1014 for error in errors {
1016 let mut diag = sess.dcx().struct_span_err(
1017 error.span,
1018 format!("error reading Clippy's configuration file: {}", error.message),
1019 );
1020
1021 if let Some(sugg) = error.suggestion {
1022 diag.span_suggestion(error.span, sugg.message, sugg.suggestion, Applicability::MaybeIncorrect);
1023 }
1024
1025 diag.emit();
1026 }
1027
1028 for warning in warnings {
1029 sess.dcx().span_warn(
1030 warning.span,
1031 format!("error reading Clippy's configuration file: {}", warning.message),
1032 );
1033 }
1034
1035 conf
1036 }
1037}
1038
1039const SEPARATOR_WIDTH: usize = 4;
1040
1041#[derive(Debug)]
1042struct FieldError {
1043 error: String,
1044 suggestion: Option<Suggestion>,
1045}
1046
1047#[derive(Debug)]
1048struct Suggestion {
1049 message: &'static str,
1050 suggestion: &'static str,
1051}
1052
1053impl std::error::Error for FieldError {}
1054
1055impl Display for FieldError {
1056 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1057 f.pad(&self.error)
1058 }
1059}
1060
1061impl serde::de::Error for FieldError {
1062 fn custom<T: Display>(msg: T) -> Self {
1063 Self {
1064 error: msg.to_string(),
1065 suggestion: None,
1066 }
1067 }
1068
1069 fn unknown_field(field: &str, expected: &'static [&'static str]) -> Self {
1070 use fmt::Write;
1073
1074 let metadata = get_configuration_metadata();
1075 let deprecated = metadata
1076 .iter()
1077 .filter_map(|conf| {
1078 if conf.deprecation_reason.is_some() {
1079 Some(conf.name.as_str())
1080 } else {
1081 None
1082 }
1083 })
1084 .collect::<Vec<_>>();
1085
1086 let mut expected = expected
1087 .iter()
1088 .copied()
1089 .filter(|name| !deprecated.contains(name))
1090 .collect::<Vec<_>>();
1091 expected.sort_unstable();
1092
1093 let (rows, column_widths) = calculate_dimensions(&expected);
1094
1095 let mut msg = format!("unknown field `{field}`, expected one of");
1096 for row in 0..rows {
1097 writeln!(msg).unwrap();
1098 for (column, column_width) in column_widths.iter().copied().enumerate() {
1099 let index = column * rows + row;
1100 let field = expected.get(index).copied().unwrap_or_default();
1101 write!(msg, "{:SEPARATOR_WIDTH$}{field:column_width$}", " ").unwrap();
1102 }
1103 }
1104
1105 let suggestion = suggest_candidate(field, expected).map(|suggestion| Suggestion {
1106 message: "perhaps you meant",
1107 suggestion,
1108 });
1109
1110 Self { error: msg, suggestion }
1111 }
1112}
1113
1114fn calculate_dimensions(fields: &[&str]) -> (usize, Vec<usize>) {
1115 let columns = env::var("CLIPPY_TERMINAL_WIDTH")
1116 .ok()
1117 .and_then(|s| <usize as FromStr>::from_str(&s).ok())
1118 .map_or(1, |terminal_width| {
1119 let max_field_width = fields.iter().map(|field| field.len()).max().unwrap();
1120 cmp::max(1, terminal_width / (SEPARATOR_WIDTH + max_field_width))
1121 });
1122
1123 let rows = fields.len().div_ceil(columns);
1124
1125 let column_widths = (0..columns)
1126 .map(|column| {
1127 if column < columns - 1 {
1128 (0..rows)
1129 .map(|row| {
1130 let index = column * rows + row;
1131 let field = fields.get(index).copied().unwrap_or_default();
1132 field.len()
1133 })
1134 .max()
1135 .unwrap()
1136 } else {
1137 0
1139 }
1140 })
1141 .collect::<Vec<_>>();
1142
1143 (rows, column_widths)
1144}
1145
1146fn suggest_candidate<'a, I>(value: &str, candidates: I) -> Option<&'a str>
1149where
1150 I: IntoIterator<Item = &'a str>,
1151{
1152 candidates
1153 .into_iter()
1154 .filter_map(|expected| {
1155 let dist = edit_distance(value, expected, 4)?;
1156 Some((dist, expected))
1157 })
1158 .min_by_key(|&(dist, _)| dist)
1159 .map(|(_, suggestion)| suggestion)
1160}
1161
1162#[cfg(test)]
1163mod tests {
1164 use serde::de::IgnoredAny;
1165 use std::collections::{HashMap, HashSet};
1166 use std::fs;
1167 use walkdir::WalkDir;
1168
1169 #[test]
1170 fn configs_are_tested() {
1171 let mut names: HashSet<String> = crate::get_configuration_metadata()
1172 .into_iter()
1173 .filter_map(|meta| {
1174 if meta.deprecation_reason.is_none() {
1175 Some(meta.name.replace('_', "-"))
1176 } else {
1177 None
1178 }
1179 })
1180 .collect();
1181
1182 let toml_files = WalkDir::new("../tests")
1183 .into_iter()
1184 .map(Result::unwrap)
1185 .filter(|entry| entry.file_name() == "clippy.toml");
1186
1187 for entry in toml_files {
1188 let file = fs::read_to_string(entry.path()).unwrap();
1189 #[allow(clippy::zero_sized_map_values)]
1190 if let Ok(map) = toml::from_str::<HashMap<String, IgnoredAny>>(&file) {
1191 for name in map.keys() {
1192 names.remove(name.as_str());
1193 }
1194 }
1195 }
1196
1197 assert!(
1198 names.is_empty(),
1199 "Configuration variable lacks test: {names:?}\nAdd a test to `tests/ui-toml`"
1200 );
1201 }
1202}