1 // error-pattern:cargo-clippy
3 #![feature(array_windows)]
4 #![feature(binary_heap_into_iter_sorted)]
5 #![feature(box_patterns)]
6 #![feature(control_flow_enum)]
7 #![feature(drain_filter)]
8 #![feature(iter_intersperse)]
9 #![feature(let_chains)]
11 #![feature(once_cell)]
12 #![feature(rustc_private)]
13 #![feature(stmt_expr_attributes)]
14 #![recursion_limit = "512"]
15 #![cfg_attr(feature = "deny-warnings", deny(warnings))]
16 #![allow(clippy::missing_docs_in_private_items, clippy::must_use_candidate)]
17 #![warn(trivial_casts, trivial_numeric_casts)]
18 // warn on lints, that are included in `rust-lang/rust`s bootstrap
19 #![warn(rust_2018_idioms, unused_lifetimes)]
20 // warn on rustc internal lints
21 #![warn(rustc::internal)]
22 // Disable this rustc lint for now, as it was also done in rustc
23 #![allow(rustc::potential_query_instability)]
25 // FIXME: switch to something more ergonomic here, once available.
26 // (Currently there is no way to opt into sysroot crates without `extern crate`.)
27 extern crate rustc_arena;
28 extern crate rustc_ast;
29 extern crate rustc_ast_pretty;
30 extern crate rustc_attr;
31 extern crate rustc_data_structures;
32 extern crate rustc_driver;
33 extern crate rustc_errors;
34 extern crate rustc_hir;
35 extern crate rustc_hir_pretty;
36 extern crate rustc_index;
37 extern crate rustc_infer;
38 extern crate rustc_lexer;
39 extern crate rustc_lint;
40 extern crate rustc_middle;
41 extern crate rustc_mir_dataflow;
42 extern crate rustc_parse;
43 extern crate rustc_parse_format;
44 extern crate rustc_session;
45 extern crate rustc_span;
46 extern crate rustc_target;
47 extern crate rustc_trait_selection;
48 extern crate rustc_typeck;
51 extern crate clippy_utils;
53 use clippy_utils::parse_msrv;
54 use rustc_data_structures::fx::FxHashSet;
55 use rustc_lint::LintId;
56 use rustc_session::Session;
58 /// Macro used to declare a Clippy lint.
60 /// Every lint declaration consists of 4 parts:
62 /// 1. The documentation, which is used for the website
63 /// 2. The `LINT_NAME`. See [lint naming][lint_naming] on lint naming conventions.
64 /// 3. The `lint_level`, which is a mapping from *one* of our lint groups to `Allow`, `Warn` or
65 /// `Deny`. The lint level here has nothing to do with what lint groups the lint is a part of.
66 /// 4. The `description` that contains a short explanation on what's wrong with code where the
67 /// lint is triggered.
69 /// Currently the categories `style`, `correctness`, `suspicious`, `complexity` and `perf` are
70 /// enabled by default. As said in the README.md of this repository, if the lint level mapping
71 /// changes, please update README.md.
76 /// #![feature(rustc_private)]
77 /// extern crate rustc_session;
78 /// use rustc_session::declare_tool_lint;
79 /// use clippy_lints::declare_clippy_lint;
81 /// declare_clippy_lint! {
82 /// /// ### What it does
83 /// /// Checks for ... (describe what the lint matches).
85 /// /// ### Why is this bad?
86 /// /// Supply the reason for linting the code.
91 /// /// Insert a short example of code that triggers the lint
94 /// /// Insert a short example of improved code that doesn't trigger the lint
101 /// [lint_naming]: https://rust-lang.github.io/rfcs/0344-conventions-galore.html#lints
103 macro_rules! declare_clippy_lint {
104 { $(#[$attr:meta])* pub $name:tt, style, $description:tt } => {
106 $(#[$attr])* pub clippy::$name, Warn, $description, report_in_external_macro: true
109 { $(#[$attr:meta])* pub $name:tt, correctness, $description:tt } => {
111 $(#[$attr])* pub clippy::$name, Deny, $description, report_in_external_macro: true
114 { $(#[$attr:meta])* pub $name:tt, suspicious, $description:tt } => {
116 $(#[$attr])* pub clippy::$name, Warn, $description, report_in_external_macro: true
119 { $(#[$attr:meta])* pub $name:tt, complexity, $description:tt } => {
121 $(#[$attr])* pub clippy::$name, Warn, $description, report_in_external_macro: true
124 { $(#[$attr:meta])* pub $name:tt, perf, $description:tt } => {
126 $(#[$attr])* pub clippy::$name, Warn, $description, report_in_external_macro: true
129 { $(#[$attr:meta])* pub $name:tt, pedantic, $description:tt } => {
131 $(#[$attr])* pub clippy::$name, Allow, $description, report_in_external_macro: true
134 { $(#[$attr:meta])* pub $name:tt, restriction, $description:tt } => {
136 $(#[$attr])* pub clippy::$name, Allow, $description, report_in_external_macro: true
139 { $(#[$attr:meta])* pub $name:tt, cargo, $description:tt } => {
141 $(#[$attr])* pub clippy::$name, Allow, $description, report_in_external_macro: true
144 { $(#[$attr:meta])* pub $name:tt, nursery, $description:tt } => {
146 $(#[$attr])* pub clippy::$name, Allow, $description, report_in_external_macro: true
149 { $(#[$attr:meta])* pub $name:tt, internal, $description:tt } => {
151 $(#[$attr])* pub clippy::$name, Allow, $description, report_in_external_macro: true
154 { $(#[$attr:meta])* pub $name:tt, internal_warn, $description:tt } => {
156 $(#[$attr])* pub clippy::$name, Warn, $description, report_in_external_macro: true
161 #[cfg(feature = "internal")]
162 mod deprecated_lints;
163 #[cfg_attr(feature = "internal", allow(clippy::missing_clippy_version_attribute))]
166 // begin lints modules, do not remove this comment, it’s used in `update_lints`
167 mod absurd_extreme_comparisons;
172 mod assertions_on_constants;
174 mod async_yields_async;
176 mod await_holding_invalid;
178 mod blacklisted_name;
179 mod blocks_in_if_conditions;
180 mod bool_assert_comparison;
185 mod case_sensitive_file_extension_comparisons;
187 mod checked_conversions;
188 mod cognitive_complexity;
190 mod collapsible_match;
191 mod comparison_chain;
194 mod crate_in_macro_def;
198 mod default_numeric_fallback;
199 mod default_union_representation;
203 mod disallowed_methods;
204 mod disallowed_script_idents;
205 mod disallowed_types;
207 mod double_comparison;
211 mod else_if_without_else;
213 mod empty_structs_with_brackets;
218 mod equatable_if_let;
222 mod eval_order_dependence;
224 mod exhaustive_items;
227 mod fallible_impl_from;
228 mod float_equality_without_abs;
230 mod floating_point_arithmetic;
236 mod from_str_radix_10;
239 mod get_last_with_len;
243 mod if_then_some_else_none;
246 mod implicit_saturating_sub;
247 mod inconsistent_struct_constructor;
248 mod index_refutable_slice;
249 mod indexing_slicing;
252 mod inherent_to_string;
253 mod init_numbered_fields;
254 mod inline_fn_without_body;
256 mod integer_division;
257 mod invalid_upcast_comparisons;
258 mod items_after_statements;
259 mod iter_not_returning_iterator;
260 mod large_const_arrays;
261 mod large_enum_variant;
262 mod large_stack_arrays;
267 mod literal_representation;
275 mod manual_non_exhaustive;
278 mod manual_unwrap_or;
282 mod match_on_vec_items;
284 mod match_str_case_mismatch;
292 mod missing_const_for_fn;
294 mod missing_enforced_import_rename;
297 mod modulo_arithmetic;
302 mod mutable_debug_assertion;
304 mod needless_arbitrary_self_type;
305 mod needless_bitwise_bool;
307 mod needless_borrowed_ref;
308 mod needless_continue;
309 mod needless_for_each;
310 mod needless_late_init;
311 mod needless_pass_by_value;
312 mod needless_question_mark;
314 mod neg_cmp_op_on_partial_ord;
316 mod new_without_default;
319 mod non_expressive_names;
320 mod non_octal_unix_permissions;
321 mod non_send_fields_in_send_ty;
322 mod nonstandard_macro_braces;
324 mod only_used_in_recursion;
326 mod option_env_unwrap;
327 mod option_if_let_else;
328 mod overflow_check_conditional;
329 mod panic_in_result_fn;
330 mod panic_unimplemented;
331 mod partialeq_ne_impl;
332 mod pass_by_ref_or_value;
333 mod path_buf_push_overwrite;
334 mod pattern_type_mismatch;
338 mod ptr_offset_with_cast;
342 mod redundant_closure_call;
344 mod redundant_field_names;
345 mod redundant_pub_crate;
346 mod redundant_slicing;
347 mod redundant_static_lifetimes;
352 mod return_self_not_must_use;
354 mod same_name_method;
356 mod self_named_constructors;
357 mod semicolon_if_nothing_returned;
360 mod single_char_lifetime_names;
361 mod single_component_path_imports;
362 mod size_of_in_element_count;
363 mod slow_vector_initialization;
364 mod stable_sort_primitive;
366 mod strlen_on_c_strings;
367 mod suspicious_operation_groupings;
368 mod suspicious_trait_impl;
370 mod tabs_in_doc_comments;
371 mod temporary_assignment;
372 mod to_digit_is_some;
373 mod trailing_empty_array;
376 mod transmuting_null;
379 mod undocumented_unsafe_blocks;
383 mod unit_return_expecting_ord;
386 mod unnecessary_self_imports;
387 mod unnecessary_sort_by;
388 mod unnecessary_wraps;
389 mod unnested_or_patterns;
390 mod unsafe_removed_from_name;
392 mod unused_io_amount;
396 mod unwrap_in_result;
397 mod upper_case_acronyms;
399 mod useless_conversion;
401 mod vec_init_then_push;
402 mod vec_resize_to_zero;
403 mod verbose_file_reads;
404 mod wildcard_imports;
407 mod zero_sized_map_values;
408 // end lints modules, do not remove this comment, it’s used in `update_lints`
410 pub use crate::utils::conf::Conf;
411 use crate::utils::conf::TryConf;
413 /// Register all pre expansion lints
415 /// Pre-expansion lints run before any macro expansion has happened.
417 /// Note that due to the architecture of the compiler, currently `cfg_attr` attributes on crate
418 /// level (i.e `#![cfg_attr(...)]`) will still be expanded even when using a pre-expansion pass.
420 /// Used in `./src/driver.rs`.
421 pub fn register_pre_expansion_lints(store: &mut rustc_lint::LintStore, sess: &Session, conf: &Conf) {
422 // NOTE: Do not add any more pre-expansion passes. These should be removed eventually.
424 let msrv = conf.msrv.as_ref().and_then(|s| {
425 parse_msrv(s, None, None).or_else(|| {
427 "error reading Clippy's configuration file. `{}` is not a valid Rust version",
434 store.register_pre_expansion_pass(|| Box::new(write::Write::default()));
435 store.register_pre_expansion_pass(move || Box::new(attrs::EarlyAttributes { msrv }));
439 pub fn read_conf(sess: &Session) -> Conf {
440 let file_name = match utils::conf::lookup_conf_file() {
441 Ok(Some(path)) => path,
442 Ok(None) => return Conf::default(),
444 sess.struct_err(&format!("error finding Clippy's configuration file: {}", error))
446 return Conf::default();
450 let TryConf { conf, errors } = utils::conf::read(&file_name);
451 // all conf errors are non-fatal, we just use the default conf in case of error
452 for error in errors {
453 sess.struct_err(&format!(
454 "error reading Clippy's configuration file `{}`: {}",
464 /// Register all lints and lint groups with the rustc plugin registry
466 /// Used in `./src/driver.rs`.
467 #[allow(clippy::too_many_lines)]
468 pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: &Conf) {
469 register_removed_non_tool_lints(store);
471 include!("lib.deprecated.rs");
473 include!("lib.register_lints.rs");
474 include!("lib.register_restriction.rs");
475 include!("lib.register_pedantic.rs");
477 #[cfg(feature = "internal")]
478 include!("lib.register_internal.rs");
480 include!("lib.register_all.rs");
481 include!("lib.register_style.rs");
482 include!("lib.register_complexity.rs");
483 include!("lib.register_correctness.rs");
484 include!("lib.register_suspicious.rs");
485 include!("lib.register_perf.rs");
486 include!("lib.register_cargo.rs");
487 include!("lib.register_nursery.rs");
489 #[cfg(feature = "internal")]
491 if std::env::var("ENABLE_METADATA_COLLECTION").eq(&Ok("1".to_string())) {
492 store.register_late_pass(|| Box::new(utils::internal_lints::metadata_collector::MetadataCollector::new()));
497 // all the internal lints
498 #[cfg(feature = "internal")]
500 store.register_early_pass(|| Box::new(utils::internal_lints::ClippyLintsInternal));
501 store.register_early_pass(|| Box::new(utils::internal_lints::ProduceIce));
502 store.register_late_pass(|| Box::new(utils::inspector::DeepCodeInspector));
503 store.register_late_pass(|| Box::new(utils::internal_lints::CollapsibleCalls));
504 store.register_late_pass(|| Box::new(utils::internal_lints::CompilerLintFunctions::new()));
505 store.register_late_pass(|| Box::new(utils::internal_lints::IfChainStyle));
506 store.register_late_pass(|| Box::new(utils::internal_lints::InvalidPaths));
507 store.register_late_pass(|| Box::new(utils::internal_lints::InterningDefinedSymbol::default()));
508 store.register_late_pass(|| Box::new(utils::internal_lints::LintWithoutLintPass::default()));
509 store.register_late_pass(|| Box::new(utils::internal_lints::MatchTypeOnDiagItem));
510 store.register_late_pass(|| Box::new(utils::internal_lints::OuterExpnDataPass));
511 store.register_late_pass(|| Box::new(utils::internal_lints::MsrvAttrImpl));
514 store.register_late_pass(|| Box::new(utils::author::Author));
515 store.register_late_pass(|| Box::new(await_holding_invalid::AwaitHolding));
516 store.register_late_pass(|| Box::new(serde_api::SerdeApi));
517 let vec_box_size_threshold = conf.vec_box_size_threshold;
518 let type_complexity_threshold = conf.type_complexity_threshold;
519 let avoid_breaking_exported_api = conf.avoid_breaking_exported_api;
520 store.register_late_pass(move || {
521 Box::new(types::Types::new(
522 vec_box_size_threshold,
523 type_complexity_threshold,
524 avoid_breaking_exported_api,
527 store.register_late_pass(|| Box::new(booleans::NonminimalBool));
528 store.register_late_pass(|| Box::new(needless_bitwise_bool::NeedlessBitwiseBool));
529 store.register_late_pass(|| Box::new(eq_op::EqOp));
530 store.register_late_pass(|| Box::new(enum_clike::UnportableVariant));
531 store.register_late_pass(|| Box::new(float_literal::FloatLiteral));
532 let verbose_bit_mask_threshold = conf.verbose_bit_mask_threshold;
533 store.register_late_pass(move || Box::new(bit_mask::BitMask::new(verbose_bit_mask_threshold)));
534 store.register_late_pass(|| Box::new(ptr::Ptr));
535 store.register_late_pass(|| Box::new(ptr_eq::PtrEq));
536 store.register_late_pass(|| Box::new(needless_bool::NeedlessBool));
537 store.register_late_pass(|| Box::new(needless_bool::BoolComparison));
538 store.register_late_pass(|| Box::new(needless_for_each::NeedlessForEach));
539 store.register_late_pass(|| Box::new(misc::MiscLints));
540 store.register_late_pass(|| Box::new(eta_reduction::EtaReduction));
541 store.register_late_pass(|| Box::new(identity_op::IdentityOp));
542 store.register_late_pass(|| Box::new(erasing_op::ErasingOp));
543 store.register_late_pass(|| Box::new(mut_mut::MutMut));
544 store.register_late_pass(|| Box::new(mut_reference::UnnecessaryMutPassed));
545 store.register_late_pass(|| Box::new(len_zero::LenZero));
546 store.register_late_pass(|| Box::new(attrs::Attributes));
547 store.register_late_pass(|| Box::new(blocks_in_if_conditions::BlocksInIfConditions));
548 store.register_late_pass(|| Box::new(collapsible_match::CollapsibleMatch));
549 store.register_late_pass(|| Box::new(unicode::Unicode));
550 store.register_late_pass(|| Box::new(uninit_vec::UninitVec));
551 store.register_late_pass(|| Box::new(unit_hash::UnitHash));
552 store.register_late_pass(|| Box::new(unit_return_expecting_ord::UnitReturnExpectingOrd));
553 store.register_late_pass(|| Box::new(strings::StringAdd));
554 store.register_late_pass(|| Box::new(implicit_return::ImplicitReturn));
555 store.register_late_pass(|| Box::new(implicit_saturating_sub::ImplicitSaturatingSub));
556 store.register_late_pass(|| Box::new(default_numeric_fallback::DefaultNumericFallback));
557 store.register_late_pass(|| Box::new(inconsistent_struct_constructor::InconsistentStructConstructor));
558 store.register_late_pass(|| Box::new(non_octal_unix_permissions::NonOctalUnixPermissions));
559 store.register_early_pass(|| Box::new(unnecessary_self_imports::UnnecessarySelfImports));
561 let msrv = conf.msrv.as_ref().and_then(|s| {
562 parse_msrv(s, None, None).or_else(|| {
564 "error reading Clippy's configuration file. `{}` is not a valid Rust version",
571 let avoid_breaking_exported_api = conf.avoid_breaking_exported_api;
572 store.register_late_pass(move || Box::new(approx_const::ApproxConstant::new(msrv)));
573 store.register_late_pass(move || Box::new(methods::Methods::new(avoid_breaking_exported_api, msrv)));
574 store.register_late_pass(move || Box::new(matches::Matches::new(msrv)));
575 store.register_early_pass(move || Box::new(manual_non_exhaustive::ManualNonExhaustive::new(msrv)));
576 store.register_late_pass(move || Box::new(manual_strip::ManualStrip::new(msrv)));
577 store.register_early_pass(move || Box::new(redundant_static_lifetimes::RedundantStaticLifetimes::new(msrv)));
578 store.register_early_pass(move || Box::new(redundant_field_names::RedundantFieldNames::new(msrv)));
579 store.register_late_pass(move || Box::new(checked_conversions::CheckedConversions::new(msrv)));
580 store.register_late_pass(move || Box::new(mem_replace::MemReplace::new(msrv)));
581 store.register_late_pass(move || Box::new(ranges::Ranges::new(msrv)));
582 store.register_late_pass(move || Box::new(from_over_into::FromOverInto::new(msrv)));
583 store.register_late_pass(move || Box::new(use_self::UseSelf::new(msrv)));
584 store.register_late_pass(move || Box::new(missing_const_for_fn::MissingConstForFn::new(msrv)));
585 store.register_late_pass(move || Box::new(needless_question_mark::NeedlessQuestionMark));
586 store.register_late_pass(move || Box::new(casts::Casts::new(msrv)));
587 store.register_early_pass(move || Box::new(unnested_or_patterns::UnnestedOrPatterns::new(msrv)));
588 store.register_late_pass(move || Box::new(map_clone::MapClone::new(msrv)));
590 store.register_late_pass(|| Box::new(size_of_in_element_count::SizeOfInElementCount));
591 store.register_late_pass(|| Box::new(same_name_method::SameNameMethod));
592 let max_suggested_slice_pattern_length = conf.max_suggested_slice_pattern_length;
593 store.register_late_pass(move || {
594 Box::new(index_refutable_slice::IndexRefutableSlice::new(
595 max_suggested_slice_pattern_length,
599 store.register_late_pass(|| Box::new(map_err_ignore::MapErrIgnore));
600 store.register_late_pass(|| Box::new(shadow::Shadow::default()));
601 store.register_late_pass(|| Box::new(unit_types::UnitTypes));
602 store.register_late_pass(|| Box::new(loops::Loops));
603 store.register_late_pass(|| Box::new(main_recursion::MainRecursion::default()));
604 store.register_late_pass(|| Box::new(lifetimes::Lifetimes));
605 store.register_late_pass(|| Box::new(entry::HashMapPass));
606 store.register_late_pass(|| Box::new(minmax::MinMaxPass));
607 store.register_late_pass(|| Box::new(open_options::OpenOptions));
608 store.register_late_pass(|| Box::new(zero_div_zero::ZeroDiv));
609 store.register_late_pass(|| Box::new(mutex_atomic::Mutex));
610 store.register_late_pass(|| Box::new(needless_update::NeedlessUpdate));
611 store.register_late_pass(|| Box::new(needless_borrowed_ref::NeedlessBorrowedRef));
612 store.register_late_pass(|| Box::new(no_effect::NoEffect));
613 store.register_late_pass(|| Box::new(temporary_assignment::TemporaryAssignment));
614 store.register_late_pass(|| Box::new(transmute::Transmute));
615 let cognitive_complexity_threshold = conf.cognitive_complexity_threshold;
616 store.register_late_pass(move || {
617 Box::new(cognitive_complexity::CognitiveComplexity::new(
618 cognitive_complexity_threshold,
621 let too_large_for_stack = conf.too_large_for_stack;
622 store.register_late_pass(move || Box::new(escape::BoxedLocal { too_large_for_stack }));
623 store.register_late_pass(move || Box::new(vec::UselessVec { too_large_for_stack }));
624 store.register_late_pass(|| Box::new(panic_unimplemented::PanicUnimplemented));
625 store.register_late_pass(|| Box::new(strings::StringLitAsBytes));
626 store.register_late_pass(|| Box::new(derive::Derive));
627 store.register_late_pass(|| Box::new(derivable_impls::DerivableImpls));
628 store.register_late_pass(|| Box::new(get_last_with_len::GetLastWithLen));
629 store.register_late_pass(|| Box::new(drop_forget_ref::DropForgetRef));
630 store.register_late_pass(|| Box::new(empty_enum::EmptyEnum));
631 store.register_late_pass(|| Box::new(absurd_extreme_comparisons::AbsurdExtremeComparisons));
632 store.register_late_pass(|| Box::new(invalid_upcast_comparisons::InvalidUpcastComparisons));
633 store.register_late_pass(|| Box::new(regex::Regex));
634 store.register_late_pass(|| Box::new(copies::CopyAndPaste));
635 store.register_late_pass(|| Box::new(copy_iterator::CopyIterator));
636 store.register_late_pass(|| Box::new(format::UselessFormat));
637 store.register_late_pass(|| Box::new(swap::Swap));
638 store.register_late_pass(|| Box::new(overflow_check_conditional::OverflowCheckConditional));
639 store.register_late_pass(|| Box::new(new_without_default::NewWithoutDefault::default()));
640 let blacklisted_names = conf.blacklisted_names.iter().cloned().collect::<FxHashSet<_>>();
641 store.register_late_pass(move || Box::new(blacklisted_name::BlacklistedName::new(blacklisted_names.clone())));
642 let too_many_arguments_threshold = conf.too_many_arguments_threshold;
643 let too_many_lines_threshold = conf.too_many_lines_threshold;
644 store.register_late_pass(move || {
645 Box::new(functions::Functions::new(
646 too_many_arguments_threshold,
647 too_many_lines_threshold,
650 let doc_valid_idents = conf.doc_valid_idents.iter().cloned().collect::<FxHashSet<_>>();
651 store.register_late_pass(move || Box::new(doc::DocMarkdown::new(doc_valid_idents.clone())));
652 store.register_late_pass(|| Box::new(neg_multiply::NegMultiply));
653 store.register_late_pass(|| Box::new(mem_forget::MemForget));
654 store.register_late_pass(|| Box::new(arithmetic::Arithmetic::default()));
655 store.register_late_pass(|| Box::new(assign_ops::AssignOps));
656 store.register_late_pass(|| Box::new(let_if_seq::LetIfSeq));
657 store.register_late_pass(|| Box::new(eval_order_dependence::EvalOrderDependence));
658 store.register_late_pass(|| Box::new(missing_doc::MissingDoc::new()));
659 store.register_late_pass(|| Box::new(missing_inline::MissingInline));
660 store.register_late_pass(move || Box::new(exhaustive_items::ExhaustiveItems));
661 store.register_late_pass(|| Box::new(match_result_ok::MatchResultOk));
662 store.register_late_pass(|| Box::new(partialeq_ne_impl::PartialEqNeImpl));
663 store.register_late_pass(|| Box::new(unused_io_amount::UnusedIoAmount));
664 let enum_variant_size_threshold = conf.enum_variant_size_threshold;
665 store.register_late_pass(move || Box::new(large_enum_variant::LargeEnumVariant::new(enum_variant_size_threshold)));
666 store.register_late_pass(|| Box::new(explicit_write::ExplicitWrite));
667 store.register_late_pass(|| Box::new(needless_pass_by_value::NeedlessPassByValue));
668 let pass_by_ref_or_value = pass_by_ref_or_value::PassByRefOrValue::new(
669 conf.trivial_copy_size_limit,
670 conf.pass_by_value_size_limit,
671 conf.avoid_breaking_exported_api,
674 store.register_late_pass(move || Box::new(pass_by_ref_or_value));
675 store.register_late_pass(|| Box::new(ref_option_ref::RefOptionRef));
676 store.register_late_pass(|| Box::new(try_err::TryErr));
677 store.register_late_pass(|| Box::new(bytecount::ByteCount));
678 store.register_late_pass(|| Box::new(infinite_iter::InfiniteIter));
679 store.register_late_pass(|| Box::new(inline_fn_without_body::InlineFnWithoutBody));
680 store.register_late_pass(|| Box::new(useless_conversion::UselessConversion::default()));
681 store.register_late_pass(|| Box::new(implicit_hasher::ImplicitHasher));
682 store.register_late_pass(|| Box::new(fallible_impl_from::FallibleImplFrom));
683 store.register_late_pass(|| Box::new(double_comparison::DoubleComparisons));
684 store.register_late_pass(|| Box::new(question_mark::QuestionMark));
685 store.register_early_pass(|| Box::new(suspicious_operation_groupings::SuspiciousOperationGroupings));
686 store.register_late_pass(|| Box::new(suspicious_trait_impl::SuspiciousImpl));
687 store.register_late_pass(|| Box::new(map_unit_fn::MapUnit));
688 store.register_late_pass(|| Box::new(inherent_impl::MultipleInherentImpl));
689 store.register_late_pass(|| Box::new(neg_cmp_op_on_partial_ord::NoNegCompOpForPartialOrd));
690 store.register_late_pass(|| Box::new(unwrap::Unwrap));
691 store.register_late_pass(|| Box::new(duration_subsec::DurationSubsec));
692 store.register_late_pass(|| Box::new(indexing_slicing::IndexingSlicing));
693 store.register_late_pass(|| Box::new(non_copy_const::NonCopyConst));
694 store.register_late_pass(|| Box::new(ptr_offset_with_cast::PtrOffsetWithCast));
695 store.register_late_pass(|| Box::new(redundant_clone::RedundantClone));
696 store.register_late_pass(|| Box::new(slow_vector_initialization::SlowVectorInit));
697 store.register_late_pass(|| Box::new(unnecessary_sort_by::UnnecessarySortBy));
698 store.register_late_pass(move || Box::new(unnecessary_wraps::UnnecessaryWraps::new(avoid_breaking_exported_api)));
699 store.register_late_pass(|| Box::new(assertions_on_constants::AssertionsOnConstants));
700 store.register_late_pass(|| Box::new(transmuting_null::TransmutingNull));
701 store.register_late_pass(|| Box::new(path_buf_push_overwrite::PathBufPushOverwrite));
702 store.register_late_pass(|| Box::new(integer_division::IntegerDivision));
703 store.register_late_pass(|| Box::new(inherent_to_string::InherentToString));
704 let max_trait_bounds = conf.max_trait_bounds;
705 store.register_late_pass(move || Box::new(trait_bounds::TraitBounds::new(max_trait_bounds)));
706 store.register_late_pass(|| Box::new(comparison_chain::ComparisonChain));
707 store.register_late_pass(|| Box::new(mut_key::MutableKeyType));
708 store.register_late_pass(|| Box::new(modulo_arithmetic::ModuloArithmetic));
709 store.register_early_pass(|| Box::new(reference::DerefAddrOf));
710 store.register_early_pass(|| Box::new(double_parens::DoubleParens));
711 store.register_late_pass(|| Box::new(format_impl::FormatImpl::new()));
712 store.register_early_pass(|| Box::new(unsafe_removed_from_name::UnsafeNameRemoval));
713 store.register_early_pass(|| Box::new(else_if_without_else::ElseIfWithoutElse));
714 store.register_early_pass(|| Box::new(int_plus_one::IntPlusOne));
715 store.register_early_pass(|| Box::new(formatting::Formatting));
716 store.register_early_pass(|| Box::new(misc_early::MiscEarlyLints));
717 store.register_early_pass(|| Box::new(redundant_closure_call::RedundantClosureCall));
718 store.register_late_pass(|| Box::new(redundant_closure_call::RedundantClosureCall));
719 store.register_early_pass(|| Box::new(unused_unit::UnusedUnit));
720 store.register_late_pass(|| Box::new(returns::Return));
721 store.register_early_pass(|| Box::new(collapsible_if::CollapsibleIf));
722 store.register_early_pass(|| Box::new(items_after_statements::ItemsAfterStatements));
723 store.register_early_pass(|| Box::new(precedence::Precedence));
724 store.register_early_pass(|| Box::new(needless_continue::NeedlessContinue));
725 store.register_early_pass(|| Box::new(redundant_else::RedundantElse));
726 store.register_late_pass(|| Box::new(create_dir::CreateDir));
727 store.register_early_pass(|| Box::new(needless_arbitrary_self_type::NeedlessArbitrarySelfType));
728 let literal_representation_lint_fraction_readability = conf.unreadable_literal_lint_fractions;
729 store.register_early_pass(move || {
730 Box::new(literal_representation::LiteralDigitGrouping::new(
731 literal_representation_lint_fraction_readability,
734 let literal_representation_threshold = conf.literal_representation_threshold;
735 store.register_early_pass(move || {
736 Box::new(literal_representation::DecimalLiteralRepresentation::new(
737 literal_representation_threshold,
740 let enum_variant_name_threshold = conf.enum_variant_name_threshold;
741 store.register_late_pass(move || {
742 Box::new(enum_variants::EnumVariantNames::new(
743 enum_variant_name_threshold,
744 avoid_breaking_exported_api,
747 store.register_early_pass(|| Box::new(tabs_in_doc_comments::TabsInDocComments));
748 let upper_case_acronyms_aggressive = conf.upper_case_acronyms_aggressive;
749 store.register_late_pass(move || {
750 Box::new(upper_case_acronyms::UpperCaseAcronyms::new(
751 avoid_breaking_exported_api,
752 upper_case_acronyms_aggressive,
755 store.register_late_pass(|| Box::new(default::Default::default()));
756 store.register_late_pass(|| Box::new(unused_self::UnusedSelf));
757 store.register_late_pass(|| Box::new(mutable_debug_assertion::DebugAssertWithMutCall));
758 store.register_late_pass(|| Box::new(exit::Exit));
759 store.register_late_pass(|| Box::new(to_digit_is_some::ToDigitIsSome));
760 let array_size_threshold = conf.array_size_threshold;
761 store.register_late_pass(move || Box::new(large_stack_arrays::LargeStackArrays::new(array_size_threshold)));
762 store.register_late_pass(move || Box::new(large_const_arrays::LargeConstArrays::new(array_size_threshold)));
763 store.register_late_pass(|| Box::new(floating_point_arithmetic::FloatingPointArithmetic));
764 store.register_early_pass(|| Box::new(as_conversions::AsConversions));
765 store.register_late_pass(|| Box::new(let_underscore::LetUnderscore));
766 store.register_early_pass(|| Box::new(single_component_path_imports::SingleComponentPathImports));
767 let max_fn_params_bools = conf.max_fn_params_bools;
768 let max_struct_bools = conf.max_struct_bools;
769 store.register_early_pass(move || {
770 Box::new(excessive_bools::ExcessiveBools::new(
775 store.register_early_pass(|| Box::new(option_env_unwrap::OptionEnvUnwrap));
776 let warn_on_all_wildcard_imports = conf.warn_on_all_wildcard_imports;
777 store.register_late_pass(move || Box::new(wildcard_imports::WildcardImports::new(warn_on_all_wildcard_imports)));
778 store.register_late_pass(|| Box::new(verbose_file_reads::VerboseFileReads));
779 store.register_late_pass(|| Box::new(redundant_pub_crate::RedundantPubCrate::default()));
780 store.register_late_pass(|| Box::new(unnamed_address::UnnamedAddress));
781 store.register_late_pass(|| Box::new(dereference::Dereferencing::default()));
782 store.register_late_pass(|| Box::new(option_if_let_else::OptionIfLetElse));
783 store.register_late_pass(|| Box::new(future_not_send::FutureNotSend));
784 store.register_late_pass(|| Box::new(if_let_mutex::IfLetMutex));
785 store.register_late_pass(|| Box::new(if_not_else::IfNotElse));
786 store.register_late_pass(|| Box::new(equatable_if_let::PatternEquality));
787 store.register_late_pass(|| Box::new(mut_mutex_lock::MutMutexLock));
788 store.register_late_pass(|| Box::new(match_on_vec_items::MatchOnVecItems));
789 store.register_late_pass(|| Box::new(manual_async_fn::ManualAsyncFn));
790 store.register_late_pass(|| Box::new(vec_resize_to_zero::VecResizeToZero));
791 store.register_late_pass(|| Box::new(panic_in_result_fn::PanicInResultFn));
792 let single_char_binding_names_threshold = conf.single_char_binding_names_threshold;
793 store.register_early_pass(move || {
794 Box::new(non_expressive_names::NonExpressiveNames {
795 single_char_binding_names_threshold,
798 let macro_matcher = conf.standard_macro_braces.iter().cloned().collect::<FxHashSet<_>>();
799 store.register_early_pass(move || Box::new(nonstandard_macro_braces::MacroBraces::new(¯o_matcher)));
800 store.register_late_pass(|| Box::new(macro_use::MacroUseImports::default()));
801 store.register_late_pass(|| Box::new(pattern_type_mismatch::PatternTypeMismatch));
802 store.register_late_pass(|| Box::new(stable_sort_primitive::StableSortPrimitive));
803 store.register_late_pass(|| Box::new(repeat_once::RepeatOnce));
804 store.register_late_pass(|| Box::new(unwrap_in_result::UnwrapInResult));
805 store.register_late_pass(|| Box::new(self_assignment::SelfAssignment));
806 store.register_late_pass(|| Box::new(manual_unwrap_or::ManualUnwrapOr));
807 store.register_late_pass(|| Box::new(manual_ok_or::ManualOkOr));
808 store.register_late_pass(|| Box::new(float_equality_without_abs::FloatEqualityWithoutAbs));
809 store.register_late_pass(|| Box::new(semicolon_if_nothing_returned::SemicolonIfNothingReturned));
810 store.register_late_pass(|| Box::new(async_yields_async::AsyncYieldsAsync));
811 let disallowed_methods = conf.disallowed_methods.clone();
812 store.register_late_pass(move || Box::new(disallowed_methods::DisallowedMethods::new(disallowed_methods.clone())));
813 store.register_early_pass(|| Box::new(asm_syntax::InlineAsmX86AttSyntax));
814 store.register_early_pass(|| Box::new(asm_syntax::InlineAsmX86IntelSyntax));
815 store.register_late_pass(|| Box::new(strings::StrToString));
816 store.register_late_pass(|| Box::new(strings::StringToString));
817 store.register_late_pass(|| Box::new(zero_sized_map_values::ZeroSizedMapValues));
818 store.register_late_pass(|| Box::new(vec_init_then_push::VecInitThenPush::default()));
819 store.register_late_pass(|| {
820 Box::new(case_sensitive_file_extension_comparisons::CaseSensitiveFileExtensionComparisons)
822 store.register_late_pass(|| Box::new(redundant_slicing::RedundantSlicing));
823 store.register_late_pass(|| Box::new(from_str_radix_10::FromStrRadix10));
824 store.register_late_pass(|| Box::new(manual_map::ManualMap));
825 store.register_late_pass(move || Box::new(if_then_some_else_none::IfThenSomeElseNone::new(msrv)));
826 store.register_late_pass(|| Box::new(bool_assert_comparison::BoolAssertComparison));
827 store.register_early_pass(move || Box::new(module_style::ModStyle));
828 store.register_late_pass(|| Box::new(unused_async::UnusedAsync));
829 let disallowed_types = conf.disallowed_types.clone();
830 store.register_late_pass(move || Box::new(disallowed_types::DisallowedTypes::new(disallowed_types.clone())));
831 let import_renames = conf.enforced_import_renames.clone();
832 store.register_late_pass(move || {
833 Box::new(missing_enforced_import_rename::ImportRename::new(
834 import_renames.clone(),
837 let scripts = conf.allowed_scripts.clone();
838 store.register_early_pass(move || Box::new(disallowed_script_idents::DisallowedScriptIdents::new(&scripts)));
839 store.register_late_pass(|| Box::new(strlen_on_c_strings::StrlenOnCStrings));
840 store.register_late_pass(move || Box::new(self_named_constructors::SelfNamedConstructors));
841 store.register_late_pass(move || Box::new(iter_not_returning_iterator::IterNotReturningIterator));
842 store.register_late_pass(move || Box::new(manual_assert::ManualAssert));
843 let enable_raw_pointer_heuristic_for_send = conf.enable_raw_pointer_heuristic_for_send;
844 store.register_late_pass(move || {
845 Box::new(non_send_fields_in_send_ty::NonSendFieldInSendTy::new(
846 enable_raw_pointer_heuristic_for_send,
849 store.register_late_pass(move || Box::new(undocumented_unsafe_blocks::UndocumentedUnsafeBlocks));
850 store.register_late_pass(|| Box::new(match_str_case_mismatch::MatchStrCaseMismatch));
851 store.register_late_pass(move || Box::new(format_args::FormatArgs));
852 store.register_late_pass(|| Box::new(trailing_empty_array::TrailingEmptyArray));
853 store.register_early_pass(|| Box::new(octal_escapes::OctalEscapes));
854 store.register_late_pass(|| Box::new(needless_late_init::NeedlessLateInit));
855 store.register_late_pass(|| Box::new(return_self_not_must_use::ReturnSelfNotMustUse));
856 store.register_late_pass(|| Box::new(init_numbered_fields::NumberedFields));
857 store.register_early_pass(|| Box::new(single_char_lifetime_names::SingleCharLifetimeNames));
858 store.register_late_pass(move || Box::new(borrow_as_ptr::BorrowAsPtr::new(msrv)));
859 store.register_late_pass(move || Box::new(manual_bits::ManualBits::new(msrv)));
860 store.register_late_pass(|| Box::new(default_union_representation::DefaultUnionRepresentation));
861 store.register_late_pass(|| Box::new(only_used_in_recursion::OnlyUsedInRecursion));
862 store.register_late_pass(|| Box::new(dbg_macro::DbgMacro));
863 let cargo_ignore_publish = conf.cargo_ignore_publish;
864 store.register_late_pass(move || {
865 Box::new(cargo::Cargo {
866 ignore_publish: cargo_ignore_publish,
869 store.register_early_pass(|| Box::new(crate_in_macro_def::CrateInMacroDef));
870 store.register_early_pass(|| Box::new(empty_structs_with_brackets::EmptyStructsWithBrackets));
871 // add lints here, do not remove this comment, it's used in `new_lint`
875 fn register_removed_non_tool_lints(store: &mut rustc_lint::LintStore) {
876 store.register_removed(
878 "`assert!()` will be more flexible with RFC 2011",
880 store.register_removed(
882 "`.extend_from_slice(_)` is a faster way to extend a Vec by a slice",
884 store.register_removed(
885 "range_step_by_zero",
886 "`iterator.step_by(0)` panics nowadays",
888 store.register_removed(
890 "`Vec::as_slice` has been stabilized in 1.7",
892 store.register_removed(
893 "unstable_as_mut_slice",
894 "`Vec::as_mut_slice` has been stabilized in 1.7",
896 store.register_removed(
897 "misaligned_transmute",
898 "this lint has been split into cast_ptr_alignment and transmute_ptr_to_ptr",
900 store.register_removed(
902 "using compound assignment operators (e.g., `+=`) is harmless",
904 store.register_removed(
905 "if_let_redundant_pattern_matching",
906 "this lint has been changed to redundant_pattern_matching",
908 store.register_removed(
909 "unsafe_vector_initialization",
910 "the replacement suggested by this lint had substantially different behavior",
912 store.register_removed(
913 "reverse_range_loop",
914 "this lint is now included in reversed_empty_ranges",
918 /// Register renamed lints.
920 /// Used in `./src/driver.rs`.
921 pub fn register_renamed(ls: &mut rustc_lint::LintStore) {
922 // NOTE: when renaming a lint, add a corresponding test to tests/ui/rename.rs
923 ls.register_renamed("clippy::stutter", "clippy::module_name_repetitions");
924 ls.register_renamed("clippy::new_without_default_derive", "clippy::new_without_default");
925 ls.register_renamed("clippy::cyclomatic_complexity", "clippy::cognitive_complexity");
926 ls.register_renamed("clippy::const_static_lifetime", "clippy::redundant_static_lifetimes");
927 ls.register_renamed("clippy::option_and_then_some", "clippy::bind_instead_of_map");
928 ls.register_renamed("clippy::box_vec", "clippy::box_collection");
929 ls.register_renamed("clippy::block_in_if_condition_expr", "clippy::blocks_in_if_conditions");
930 ls.register_renamed("clippy::block_in_if_condition_stmt", "clippy::blocks_in_if_conditions");
931 ls.register_renamed("clippy::option_map_unwrap_or", "clippy::map_unwrap_or");
932 ls.register_renamed("clippy::option_map_unwrap_or_else", "clippy::map_unwrap_or");
933 ls.register_renamed("clippy::result_map_unwrap_or_else", "clippy::map_unwrap_or");
934 ls.register_renamed("clippy::option_unwrap_used", "clippy::unwrap_used");
935 ls.register_renamed("clippy::result_unwrap_used", "clippy::unwrap_used");
936 ls.register_renamed("clippy::option_expect_used", "clippy::expect_used");
937 ls.register_renamed("clippy::result_expect_used", "clippy::expect_used");
938 ls.register_renamed("clippy::for_loop_over_option", "clippy::for_loops_over_fallibles");
939 ls.register_renamed("clippy::for_loop_over_result", "clippy::for_loops_over_fallibles");
940 ls.register_renamed("clippy::identity_conversion", "clippy::useless_conversion");
941 ls.register_renamed("clippy::zero_width_space", "clippy::invisible_characters");
942 ls.register_renamed("clippy::single_char_push_str", "clippy::single_char_add_str");
943 ls.register_renamed("clippy::if_let_some_result", "clippy::match_result_ok");
944 ls.register_renamed("clippy::disallowed_type", "clippy::disallowed_types");
945 ls.register_renamed("clippy::disallowed_method", "clippy::disallowed_methods");
946 ls.register_renamed("clippy::ref_in_deref", "clippy::needless_borrow");
947 ls.register_renamed("clippy::to_string_in_display", "clippy::recursive_format_impl");
950 ls.register_renamed("clippy::invalid_ref", "invalid_value");
951 ls.register_renamed("clippy::into_iter_on_array", "array_into_iter");
952 ls.register_renamed("clippy::unused_label", "unused_labels");
953 ls.register_renamed("clippy::drop_bounds", "drop_bounds");
954 ls.register_renamed("clippy::temporary_cstring_as_ptr", "temporary_cstring_as_ptr");
955 ls.register_renamed("clippy::panic_params", "non_fmt_panics");
956 ls.register_renamed("clippy::unknown_clippy_lints", "unknown_lints");
957 ls.register_renamed("clippy::invalid_atomic_ordering", "invalid_atomic_ordering");
958 ls.register_renamed("clippy::mem_discriminant_non_enum", "enum_intrinsics_non_enums");
961 // only exists to let the dogfood integration test works.
962 // Don't run clippy as an executable directly
965 panic!("Please use the cargo-clippy executable");