]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/lib.rs
Auto merge of #8799 - Alexendoo:lintcheck-common, r=giraffate
[rust.git] / clippy_lints / src / lib.rs
1 // error-pattern:cargo-clippy
2
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)]
10 #![feature(let_else)]
11 #![feature(lint_reasons)]
12 #![feature(once_cell)]
13 #![feature(rustc_private)]
14 #![feature(stmt_expr_attributes)]
15 #![recursion_limit = "512"]
16 #![cfg_attr(feature = "deny-warnings", deny(warnings))]
17 #![allow(clippy::missing_docs_in_private_items, clippy::must_use_candidate)]
18 #![warn(trivial_casts, trivial_numeric_casts)]
19 // warn on lints, that are included in `rust-lang/rust`s bootstrap
20 #![warn(rust_2018_idioms, unused_lifetimes)]
21 // warn on rustc internal lints
22 #![warn(rustc::internal)]
23 // Disable this rustc lint for now, as it was also done in rustc
24 #![allow(rustc::potential_query_instability)]
25
26 // FIXME: switch to something more ergonomic here, once available.
27 // (Currently there is no way to opt into sysroot crates without `extern crate`.)
28 extern crate rustc_arena;
29 extern crate rustc_ast;
30 extern crate rustc_ast_pretty;
31 extern crate rustc_attr;
32 extern crate rustc_data_structures;
33 extern crate rustc_driver;
34 extern crate rustc_errors;
35 extern crate rustc_hir;
36 extern crate rustc_hir_pretty;
37 extern crate rustc_index;
38 extern crate rustc_infer;
39 extern crate rustc_lexer;
40 extern crate rustc_lint;
41 extern crate rustc_middle;
42 extern crate rustc_mir_dataflow;
43 extern crate rustc_parse;
44 extern crate rustc_parse_format;
45 extern crate rustc_session;
46 extern crate rustc_span;
47 extern crate rustc_target;
48 extern crate rustc_trait_selection;
49 extern crate rustc_typeck;
50
51 #[macro_use]
52 extern crate clippy_utils;
53
54 use clippy_utils::parse_msrv;
55 use rustc_data_structures::fx::FxHashSet;
56 use rustc_lint::LintId;
57 use rustc_session::Session;
58
59 /// Macro used to declare a Clippy lint.
60 ///
61 /// Every lint declaration consists of 4 parts:
62 ///
63 /// 1. The documentation, which is used for the website
64 /// 2. The `LINT_NAME`. See [lint naming][lint_naming] on lint naming conventions.
65 /// 3. The `lint_level`, which is a mapping from *one* of our lint groups to `Allow`, `Warn` or
66 ///    `Deny`. The lint level here has nothing to do with what lint groups the lint is a part of.
67 /// 4. The `description` that contains a short explanation on what's wrong with code where the
68 ///    lint is triggered.
69 ///
70 /// Currently the categories `style`, `correctness`, `suspicious`, `complexity` and `perf` are
71 /// enabled by default. As said in the README.md of this repository, if the lint level mapping
72 /// changes, please update README.md.
73 ///
74 /// # Example
75 ///
76 /// ```
77 /// #![feature(rustc_private)]
78 /// extern crate rustc_session;
79 /// use rustc_session::declare_tool_lint;
80 /// use clippy_lints::declare_clippy_lint;
81 ///
82 /// declare_clippy_lint! {
83 ///     /// ### What it does
84 ///     /// Checks for ... (describe what the lint matches).
85 ///     ///
86 ///     /// ### Why is this bad?
87 ///     /// Supply the reason for linting the code.
88 ///     ///
89 ///     /// ### Example
90 ///     /// ```rust
91 ///     /// // Bad
92 ///     /// Insert a short example of code that triggers the lint
93 ///     ///
94 ///     /// // Good
95 ///     /// Insert a short example of improved code that doesn't trigger the lint
96 ///     /// ```
97 ///     pub LINT_NAME,
98 ///     pedantic,
99 ///     "description"
100 /// }
101 /// ```
102 /// [lint_naming]: https://rust-lang.github.io/rfcs/0344-conventions-galore.html#lints
103 #[macro_export]
104 macro_rules! declare_clippy_lint {
105     { $(#[$attr:meta])* pub $name:tt, style, $description:tt } => {
106         declare_tool_lint! {
107             $(#[$attr])* pub clippy::$name, Warn, $description, report_in_external_macro: true
108         }
109     };
110     { $(#[$attr:meta])* pub $name:tt, correctness, $description:tt } => {
111         declare_tool_lint! {
112             $(#[$attr])* pub clippy::$name, Deny, $description, report_in_external_macro: true
113         }
114     };
115     { $(#[$attr:meta])* pub $name:tt, suspicious, $description:tt } => {
116         declare_tool_lint! {
117             $(#[$attr])* pub clippy::$name, Warn, $description, report_in_external_macro: true
118         }
119     };
120     { $(#[$attr:meta])* pub $name:tt, complexity, $description:tt } => {
121         declare_tool_lint! {
122             $(#[$attr])* pub clippy::$name, Warn, $description, report_in_external_macro: true
123         }
124     };
125     { $(#[$attr:meta])* pub $name:tt, perf, $description:tt } => {
126         declare_tool_lint! {
127             $(#[$attr])* pub clippy::$name, Warn, $description, report_in_external_macro: true
128         }
129     };
130     { $(#[$attr:meta])* pub $name:tt, pedantic, $description:tt } => {
131         declare_tool_lint! {
132             $(#[$attr])* pub clippy::$name, Allow, $description, report_in_external_macro: true
133         }
134     };
135     { $(#[$attr:meta])* pub $name:tt, restriction, $description:tt } => {
136         declare_tool_lint! {
137             $(#[$attr])* pub clippy::$name, Allow, $description, report_in_external_macro: true
138         }
139     };
140     { $(#[$attr:meta])* pub $name:tt, cargo, $description:tt } => {
141         declare_tool_lint! {
142             $(#[$attr])* pub clippy::$name, Allow, $description, report_in_external_macro: true
143         }
144     };
145     { $(#[$attr:meta])* pub $name:tt, nursery, $description:tt } => {
146         declare_tool_lint! {
147             $(#[$attr])* pub clippy::$name, Allow, $description, report_in_external_macro: true
148         }
149     };
150     { $(#[$attr:meta])* pub $name:tt, internal, $description:tt } => {
151         declare_tool_lint! {
152             $(#[$attr])* pub clippy::$name, Allow, $description, report_in_external_macro: true
153         }
154     };
155     { $(#[$attr:meta])* pub $name:tt, internal_warn, $description:tt } => {
156         declare_tool_lint! {
157             $(#[$attr])* pub clippy::$name, Warn, $description, report_in_external_macro: true
158         }
159     };
160 }
161
162 #[cfg(feature = "internal")]
163 mod deprecated_lints;
164 #[cfg_attr(feature = "internal", allow(clippy::missing_clippy_version_attribute))]
165 mod utils;
166
167 mod renamed_lints;
168
169 // begin lints modules, do not remove this comment, it’s used in `update_lints`
170 mod absurd_extreme_comparisons;
171 mod approx_const;
172 mod arithmetic;
173 mod as_conversions;
174 mod asm_syntax;
175 mod assertions_on_constants;
176 mod assign_ops;
177 mod async_yields_async;
178 mod attrs;
179 mod await_holding_invalid;
180 mod bit_mask;
181 mod blacklisted_name;
182 mod blocks_in_if_conditions;
183 mod bool_assert_comparison;
184 mod booleans;
185 mod borrow_as_ptr;
186 mod bytecount;
187 mod bytes_count_to_len;
188 mod cargo;
189 mod case_sensitive_file_extension_comparisons;
190 mod casts;
191 mod checked_conversions;
192 mod cognitive_complexity;
193 mod collapsible_if;
194 mod collapsible_match;
195 mod comparison_chain;
196 mod copies;
197 mod copy_iterator;
198 mod crate_in_macro_def;
199 mod create_dir;
200 mod dbg_macro;
201 mod default;
202 mod default_numeric_fallback;
203 mod default_union_representation;
204 mod dereference;
205 mod derivable_impls;
206 mod derive;
207 mod disallowed_methods;
208 mod disallowed_script_idents;
209 mod disallowed_types;
210 mod doc;
211 mod double_comparison;
212 mod double_parens;
213 mod drop_forget_ref;
214 mod duration_subsec;
215 mod else_if_without_else;
216 mod empty_drop;
217 mod empty_enum;
218 mod empty_structs_with_brackets;
219 mod entry;
220 mod enum_clike;
221 mod enum_variants;
222 mod eq_op;
223 mod equatable_if_let;
224 mod erasing_op;
225 mod escape;
226 mod eta_reduction;
227 mod eval_order_dependence;
228 mod excessive_bools;
229 mod exhaustive_items;
230 mod exit;
231 mod explicit_write;
232 mod fallible_impl_from;
233 mod float_equality_without_abs;
234 mod float_literal;
235 mod floating_point_arithmetic;
236 mod format;
237 mod format_args;
238 mod format_impl;
239 mod format_push_string;
240 mod formatting;
241 mod from_over_into;
242 mod from_str_radix_10;
243 mod functions;
244 mod future_not_send;
245 mod get_last_with_len;
246 mod identity_op;
247 mod if_let_mutex;
248 mod if_not_else;
249 mod if_then_some_else_none;
250 mod implicit_hasher;
251 mod implicit_return;
252 mod implicit_saturating_sub;
253 mod inconsistent_struct_constructor;
254 mod index_refutable_slice;
255 mod indexing_slicing;
256 mod infinite_iter;
257 mod inherent_impl;
258 mod inherent_to_string;
259 mod init_numbered_fields;
260 mod inline_fn_without_body;
261 mod int_plus_one;
262 mod integer_division;
263 mod invalid_upcast_comparisons;
264 mod items_after_statements;
265 mod iter_not_returning_iterator;
266 mod large_const_arrays;
267 mod large_enum_variant;
268 mod large_include_file;
269 mod large_stack_arrays;
270 mod len_zero;
271 mod let_if_seq;
272 mod let_underscore;
273 mod lifetimes;
274 mod literal_representation;
275 mod loops;
276 mod macro_use;
277 mod main_recursion;
278 mod manual_assert;
279 mod manual_async_fn;
280 mod manual_bits;
281 mod manual_map;
282 mod manual_non_exhaustive;
283 mod manual_ok_or;
284 mod manual_strip;
285 mod manual_unwrap_or;
286 mod map_clone;
287 mod map_err_ignore;
288 mod map_unit_fn;
289 mod match_on_vec_items;
290 mod match_result_ok;
291 mod match_str_case_mismatch;
292 mod matches;
293 mod mem_forget;
294 mod mem_replace;
295 mod methods;
296 mod minmax;
297 mod misc;
298 mod misc_early;
299 mod missing_const_for_fn;
300 mod missing_doc;
301 mod missing_enforced_import_rename;
302 mod missing_inline;
303 mod module_style;
304 mod modulo_arithmetic;
305 mod mut_key;
306 mod mut_mut;
307 mod mut_mutex_lock;
308 mod mut_reference;
309 mod mutable_debug_assertion;
310 mod mutex_atomic;
311 mod needless_arbitrary_self_type;
312 mod needless_bitwise_bool;
313 mod needless_bool;
314 mod needless_borrowed_ref;
315 mod needless_continue;
316 mod needless_for_each;
317 mod needless_late_init;
318 mod needless_pass_by_value;
319 mod needless_question_mark;
320 mod needless_update;
321 mod neg_cmp_op_on_partial_ord;
322 mod neg_multiply;
323 mod new_without_default;
324 mod no_effect;
325 mod non_copy_const;
326 mod non_expressive_names;
327 mod non_octal_unix_permissions;
328 mod non_send_fields_in_send_ty;
329 mod nonstandard_macro_braces;
330 mod octal_escapes;
331 mod only_used_in_recursion;
332 mod open_options;
333 mod option_env_unwrap;
334 mod option_if_let_else;
335 mod overflow_check_conditional;
336 mod panic_in_result_fn;
337 mod panic_unimplemented;
338 mod partialeq_ne_impl;
339 mod pass_by_ref_or_value;
340 mod path_buf_push_overwrite;
341 mod pattern_type_mismatch;
342 mod precedence;
343 mod ptr;
344 mod ptr_eq;
345 mod ptr_offset_with_cast;
346 mod pub_use;
347 mod question_mark;
348 mod ranges;
349 mod rc_clone_in_vec_init;
350 mod redundant_clone;
351 mod redundant_closure_call;
352 mod redundant_else;
353 mod redundant_field_names;
354 mod redundant_pub_crate;
355 mod redundant_slicing;
356 mod redundant_static_lifetimes;
357 mod ref_option_ref;
358 mod reference;
359 mod regex;
360 mod repeat_once;
361 mod return_self_not_must_use;
362 mod returns;
363 mod same_name_method;
364 mod self_assignment;
365 mod self_named_constructors;
366 mod semicolon_if_nothing_returned;
367 mod serde_api;
368 mod shadow;
369 mod single_char_lifetime_names;
370 mod single_component_path_imports;
371 mod size_of_in_element_count;
372 mod slow_vector_initialization;
373 mod stable_sort_primitive;
374 mod strings;
375 mod strlen_on_c_strings;
376 mod suspicious_operation_groupings;
377 mod suspicious_trait_impl;
378 mod swap;
379 mod tabs_in_doc_comments;
380 mod temporary_assignment;
381 mod to_digit_is_some;
382 mod trailing_empty_array;
383 mod trait_bounds;
384 mod transmute;
385 mod transmuting_null;
386 mod try_err;
387 mod types;
388 mod undocumented_unsafe_blocks;
389 mod unicode;
390 mod uninit_vec;
391 mod unit_hash;
392 mod unit_return_expecting_ord;
393 mod unit_types;
394 mod unnamed_address;
395 mod unnecessary_owned_empty_strings;
396 mod unnecessary_self_imports;
397 mod unnecessary_sort_by;
398 mod unnecessary_wraps;
399 mod unnested_or_patterns;
400 mod unsafe_removed_from_name;
401 mod unused_async;
402 mod unused_io_amount;
403 mod unused_self;
404 mod unused_unit;
405 mod unwrap;
406 mod unwrap_in_result;
407 mod upper_case_acronyms;
408 mod use_self;
409 mod useless_conversion;
410 mod vec;
411 mod vec_init_then_push;
412 mod vec_resize_to_zero;
413 mod verbose_file_reads;
414 mod wildcard_imports;
415 mod write;
416 mod zero_div_zero;
417 mod zero_sized_map_values;
418 // end lints modules, do not remove this comment, it’s used in `update_lints`
419
420 pub use crate::utils::conf::Conf;
421 use crate::utils::conf::TryConf;
422
423 /// Register all pre expansion lints
424 ///
425 /// Pre-expansion lints run before any macro expansion has happened.
426 ///
427 /// Note that due to the architecture of the compiler, currently `cfg_attr` attributes on crate
428 /// level (i.e `#![cfg_attr(...)]`) will still be expanded even when using a pre-expansion pass.
429 ///
430 /// Used in `./src/driver.rs`.
431 pub fn register_pre_expansion_lints(store: &mut rustc_lint::LintStore, sess: &Session, conf: &Conf) {
432     // NOTE: Do not add any more pre-expansion passes. These should be removed eventually.
433
434     let msrv = conf.msrv.as_ref().and_then(|s| {
435         parse_msrv(s, None, None).or_else(|| {
436             sess.err(&format!(
437                 "error reading Clippy's configuration file. `{}` is not a valid Rust version",
438                 s
439             ));
440             None
441         })
442     });
443
444     store.register_pre_expansion_pass(|| Box::new(write::Write::default()));
445     store.register_pre_expansion_pass(move || Box::new(attrs::EarlyAttributes { msrv }));
446 }
447
448 #[doc(hidden)]
449 pub fn read_conf(sess: &Session) -> Conf {
450     let file_name = match utils::conf::lookup_conf_file() {
451         Ok(Some(path)) => path,
452         Ok(None) => return Conf::default(),
453         Err(error) => {
454             sess.struct_err(&format!("error finding Clippy's configuration file: {}", error))
455                 .emit();
456             return Conf::default();
457         },
458     };
459
460     let TryConf { conf, errors } = utils::conf::read(&file_name);
461     // all conf errors are non-fatal, we just use the default conf in case of error
462     for error in errors {
463         sess.struct_err(&format!(
464             "error reading Clippy's configuration file `{}`: {}",
465             file_name.display(),
466             error
467         ))
468         .emit();
469     }
470
471     conf
472 }
473
474 /// Register all lints and lint groups with the rustc plugin registry
475 ///
476 /// Used in `./src/driver.rs`.
477 #[expect(clippy::too_many_lines)]
478 pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: &Conf) {
479     register_removed_non_tool_lints(store);
480
481     include!("lib.deprecated.rs");
482
483     include!("lib.register_lints.rs");
484     include!("lib.register_restriction.rs");
485     include!("lib.register_pedantic.rs");
486
487     #[cfg(feature = "internal")]
488     include!("lib.register_internal.rs");
489
490     include!("lib.register_all.rs");
491     include!("lib.register_style.rs");
492     include!("lib.register_complexity.rs");
493     include!("lib.register_correctness.rs");
494     include!("lib.register_suspicious.rs");
495     include!("lib.register_perf.rs");
496     include!("lib.register_cargo.rs");
497     include!("lib.register_nursery.rs");
498
499     #[cfg(feature = "internal")]
500     {
501         if std::env::var("ENABLE_METADATA_COLLECTION").eq(&Ok("1".to_string())) {
502             store.register_late_pass(|| Box::new(utils::internal_lints::metadata_collector::MetadataCollector::new()));
503             return;
504         }
505     }
506
507     // all the internal lints
508     #[cfg(feature = "internal")]
509     {
510         store.register_early_pass(|| Box::new(utils::internal_lints::ClippyLintsInternal));
511         store.register_early_pass(|| Box::new(utils::internal_lints::ProduceIce));
512         store.register_late_pass(|| Box::new(utils::internal_lints::CollapsibleCalls));
513         store.register_late_pass(|| Box::new(utils::internal_lints::CompilerLintFunctions::new()));
514         store.register_late_pass(|| Box::new(utils::internal_lints::IfChainStyle));
515         store.register_late_pass(|| Box::new(utils::internal_lints::InvalidPaths));
516         store.register_late_pass(|| Box::new(utils::internal_lints::InterningDefinedSymbol::default()));
517         store.register_late_pass(|| Box::new(utils::internal_lints::LintWithoutLintPass::default()));
518         store.register_late_pass(|| Box::new(utils::internal_lints::MatchTypeOnDiagItem));
519         store.register_late_pass(|| Box::new(utils::internal_lints::OuterExpnDataPass));
520         store.register_late_pass(|| Box::new(utils::internal_lints::MsrvAttrImpl));
521     }
522
523     store.register_late_pass(|| Box::new(utils::dump_hir::DumpHir));
524     store.register_late_pass(|| Box::new(utils::author::Author));
525     let await_holding_invalid_types = conf.await_holding_invalid_types.clone();
526     store.register_late_pass(move || {
527         Box::new(await_holding_invalid::AwaitHolding::new(
528             await_holding_invalid_types.clone(),
529         ))
530     });
531     store.register_late_pass(|| Box::new(serde_api::SerdeApi));
532     let vec_box_size_threshold = conf.vec_box_size_threshold;
533     let type_complexity_threshold = conf.type_complexity_threshold;
534     let avoid_breaking_exported_api = conf.avoid_breaking_exported_api;
535     store.register_late_pass(move || {
536         Box::new(types::Types::new(
537             vec_box_size_threshold,
538             type_complexity_threshold,
539             avoid_breaking_exported_api,
540         ))
541     });
542     store.register_late_pass(|| Box::new(booleans::NonminimalBool));
543     store.register_late_pass(|| Box::new(needless_bitwise_bool::NeedlessBitwiseBool));
544     store.register_late_pass(|| Box::new(eq_op::EqOp));
545     store.register_late_pass(|| Box::new(enum_clike::UnportableVariant));
546     store.register_late_pass(|| Box::new(float_literal::FloatLiteral));
547     let verbose_bit_mask_threshold = conf.verbose_bit_mask_threshold;
548     store.register_late_pass(move || Box::new(bit_mask::BitMask::new(verbose_bit_mask_threshold)));
549     store.register_late_pass(|| Box::new(ptr::Ptr));
550     store.register_late_pass(|| Box::new(ptr_eq::PtrEq));
551     store.register_late_pass(|| Box::new(needless_bool::NeedlessBool));
552     store.register_late_pass(|| Box::new(needless_bool::BoolComparison));
553     store.register_late_pass(|| Box::new(needless_for_each::NeedlessForEach));
554     store.register_late_pass(|| Box::new(misc::MiscLints));
555     store.register_late_pass(|| Box::new(eta_reduction::EtaReduction));
556     store.register_late_pass(|| Box::new(identity_op::IdentityOp));
557     store.register_late_pass(|| Box::new(erasing_op::ErasingOp));
558     store.register_late_pass(|| Box::new(mut_mut::MutMut));
559     store.register_late_pass(|| Box::new(mut_reference::UnnecessaryMutPassed));
560     store.register_late_pass(|| Box::new(len_zero::LenZero));
561     store.register_late_pass(|| Box::new(attrs::Attributes));
562     store.register_late_pass(|| Box::new(blocks_in_if_conditions::BlocksInIfConditions));
563     store.register_late_pass(|| Box::new(collapsible_match::CollapsibleMatch));
564     store.register_late_pass(|| Box::new(unicode::Unicode));
565     store.register_late_pass(|| Box::new(uninit_vec::UninitVec));
566     store.register_late_pass(|| Box::new(unit_hash::UnitHash));
567     store.register_late_pass(|| Box::new(unit_return_expecting_ord::UnitReturnExpectingOrd));
568     store.register_late_pass(|| Box::new(strings::StringAdd));
569     store.register_late_pass(|| Box::new(implicit_return::ImplicitReturn));
570     store.register_late_pass(|| Box::new(implicit_saturating_sub::ImplicitSaturatingSub));
571     store.register_late_pass(|| Box::new(default_numeric_fallback::DefaultNumericFallback));
572     store.register_late_pass(|| Box::new(inconsistent_struct_constructor::InconsistentStructConstructor));
573     store.register_late_pass(|| Box::new(non_octal_unix_permissions::NonOctalUnixPermissions));
574     store.register_early_pass(|| Box::new(unnecessary_self_imports::UnnecessarySelfImports));
575
576     let msrv = conf.msrv.as_ref().and_then(|s| {
577         parse_msrv(s, None, None).or_else(|| {
578             sess.err(&format!(
579                 "error reading Clippy's configuration file. `{}` is not a valid Rust version",
580                 s
581             ));
582             None
583         })
584     });
585
586     let avoid_breaking_exported_api = conf.avoid_breaking_exported_api;
587     let allow_expect_in_tests = conf.allow_expect_in_tests;
588     let allow_unwrap_in_tests = conf.allow_unwrap_in_tests;
589     store.register_late_pass(move || Box::new(approx_const::ApproxConstant::new(msrv)));
590     store.register_late_pass(move || {
591         Box::new(methods::Methods::new(
592             avoid_breaking_exported_api,
593             msrv,
594             allow_expect_in_tests,
595             allow_unwrap_in_tests,
596         ))
597     });
598     store.register_late_pass(move || Box::new(matches::Matches::new(msrv)));
599     store.register_early_pass(move || Box::new(manual_non_exhaustive::ManualNonExhaustiveStruct::new(msrv)));
600     store.register_late_pass(move || Box::new(manual_non_exhaustive::ManualNonExhaustiveEnum::new(msrv)));
601     store.register_late_pass(move || Box::new(manual_strip::ManualStrip::new(msrv)));
602     store.register_early_pass(move || Box::new(redundant_static_lifetimes::RedundantStaticLifetimes::new(msrv)));
603     store.register_early_pass(move || Box::new(redundant_field_names::RedundantFieldNames::new(msrv)));
604     store.register_late_pass(move || Box::new(checked_conversions::CheckedConversions::new(msrv)));
605     store.register_late_pass(move || Box::new(mem_replace::MemReplace::new(msrv)));
606     store.register_late_pass(move || Box::new(ranges::Ranges::new(msrv)));
607     store.register_late_pass(move || Box::new(from_over_into::FromOverInto::new(msrv)));
608     store.register_late_pass(move || Box::new(use_self::UseSelf::new(msrv)));
609     store.register_late_pass(move || Box::new(missing_const_for_fn::MissingConstForFn::new(msrv)));
610     store.register_late_pass(move || Box::new(needless_question_mark::NeedlessQuestionMark));
611     store.register_late_pass(move || Box::new(casts::Casts::new(msrv)));
612     store.register_early_pass(move || Box::new(unnested_or_patterns::UnnestedOrPatterns::new(msrv)));
613     store.register_late_pass(move || Box::new(map_clone::MapClone::new(msrv)));
614
615     store.register_late_pass(|| Box::new(size_of_in_element_count::SizeOfInElementCount));
616     store.register_late_pass(|| Box::new(same_name_method::SameNameMethod));
617     let max_suggested_slice_pattern_length = conf.max_suggested_slice_pattern_length;
618     store.register_late_pass(move || {
619         Box::new(index_refutable_slice::IndexRefutableSlice::new(
620             max_suggested_slice_pattern_length,
621             msrv,
622         ))
623     });
624     store.register_late_pass(|| Box::new(map_err_ignore::MapErrIgnore));
625     store.register_late_pass(|| Box::new(shadow::Shadow::default()));
626     store.register_late_pass(|| Box::new(unit_types::UnitTypes));
627     store.register_late_pass(|| Box::new(loops::Loops));
628     store.register_late_pass(|| Box::new(main_recursion::MainRecursion::default()));
629     store.register_late_pass(|| Box::new(lifetimes::Lifetimes));
630     store.register_late_pass(|| Box::new(entry::HashMapPass));
631     store.register_late_pass(|| Box::new(minmax::MinMaxPass));
632     store.register_late_pass(|| Box::new(open_options::OpenOptions));
633     store.register_late_pass(|| Box::new(zero_div_zero::ZeroDiv));
634     store.register_late_pass(|| Box::new(mutex_atomic::Mutex));
635     store.register_late_pass(|| Box::new(needless_update::NeedlessUpdate));
636     store.register_late_pass(|| Box::new(needless_borrowed_ref::NeedlessBorrowedRef));
637     store.register_late_pass(|| Box::new(no_effect::NoEffect));
638     store.register_late_pass(|| Box::new(temporary_assignment::TemporaryAssignment));
639     store.register_late_pass(|| Box::new(transmute::Transmute));
640     let cognitive_complexity_threshold = conf.cognitive_complexity_threshold;
641     store.register_late_pass(move || {
642         Box::new(cognitive_complexity::CognitiveComplexity::new(
643             cognitive_complexity_threshold,
644         ))
645     });
646     let too_large_for_stack = conf.too_large_for_stack;
647     store.register_late_pass(move || Box::new(escape::BoxedLocal { too_large_for_stack }));
648     store.register_late_pass(move || Box::new(vec::UselessVec { too_large_for_stack }));
649     store.register_late_pass(|| Box::new(panic_unimplemented::PanicUnimplemented));
650     store.register_late_pass(|| Box::new(strings::StringLitAsBytes));
651     store.register_late_pass(|| Box::new(derive::Derive));
652     store.register_late_pass(|| Box::new(derivable_impls::DerivableImpls));
653     store.register_late_pass(|| Box::new(get_last_with_len::GetLastWithLen));
654     store.register_late_pass(|| Box::new(drop_forget_ref::DropForgetRef));
655     store.register_late_pass(|| Box::new(empty_enum::EmptyEnum));
656     store.register_late_pass(|| Box::new(absurd_extreme_comparisons::AbsurdExtremeComparisons));
657     store.register_late_pass(|| Box::new(invalid_upcast_comparisons::InvalidUpcastComparisons));
658     store.register_late_pass(|| Box::new(regex::Regex));
659     store.register_late_pass(|| Box::new(copies::CopyAndPaste));
660     store.register_late_pass(|| Box::new(copy_iterator::CopyIterator));
661     store.register_late_pass(|| Box::new(format::UselessFormat));
662     store.register_late_pass(|| Box::new(swap::Swap));
663     store.register_late_pass(|| Box::new(overflow_check_conditional::OverflowCheckConditional));
664     store.register_late_pass(|| Box::new(new_without_default::NewWithoutDefault::default()));
665     let blacklisted_names = conf.blacklisted_names.iter().cloned().collect::<FxHashSet<_>>();
666     store.register_late_pass(move || Box::new(blacklisted_name::BlacklistedName::new(blacklisted_names.clone())));
667     let too_many_arguments_threshold = conf.too_many_arguments_threshold;
668     let too_many_lines_threshold = conf.too_many_lines_threshold;
669     store.register_late_pass(move || {
670         Box::new(functions::Functions::new(
671             too_many_arguments_threshold,
672             too_many_lines_threshold,
673         ))
674     });
675     let doc_valid_idents = conf.doc_valid_idents.iter().cloned().collect::<FxHashSet<_>>();
676     store.register_late_pass(move || Box::new(doc::DocMarkdown::new(doc_valid_idents.clone())));
677     store.register_late_pass(|| Box::new(neg_multiply::NegMultiply));
678     store.register_late_pass(|| Box::new(mem_forget::MemForget));
679     store.register_late_pass(|| Box::new(arithmetic::Arithmetic::default()));
680     store.register_late_pass(|| Box::new(assign_ops::AssignOps));
681     store.register_late_pass(|| Box::new(let_if_seq::LetIfSeq));
682     store.register_late_pass(|| Box::new(eval_order_dependence::EvalOrderDependence));
683     store.register_late_pass(|| Box::new(missing_doc::MissingDoc::new()));
684     store.register_late_pass(|| Box::new(missing_inline::MissingInline));
685     store.register_late_pass(move || Box::new(exhaustive_items::ExhaustiveItems));
686     store.register_late_pass(|| Box::new(match_result_ok::MatchResultOk));
687     store.register_late_pass(|| Box::new(partialeq_ne_impl::PartialEqNeImpl));
688     store.register_late_pass(|| Box::new(unused_io_amount::UnusedIoAmount));
689     let enum_variant_size_threshold = conf.enum_variant_size_threshold;
690     store.register_late_pass(move || Box::new(large_enum_variant::LargeEnumVariant::new(enum_variant_size_threshold)));
691     store.register_late_pass(|| Box::new(explicit_write::ExplicitWrite));
692     store.register_late_pass(|| Box::new(needless_pass_by_value::NeedlessPassByValue));
693     let pass_by_ref_or_value = pass_by_ref_or_value::PassByRefOrValue::new(
694         conf.trivial_copy_size_limit,
695         conf.pass_by_value_size_limit,
696         conf.avoid_breaking_exported_api,
697         &sess.target,
698     );
699     store.register_late_pass(move || Box::new(pass_by_ref_or_value));
700     store.register_late_pass(|| Box::new(ref_option_ref::RefOptionRef));
701     store.register_late_pass(|| Box::new(try_err::TryErr));
702     store.register_late_pass(|| Box::new(bytecount::ByteCount));
703     store.register_late_pass(|| Box::new(infinite_iter::InfiniteIter));
704     store.register_late_pass(|| Box::new(inline_fn_without_body::InlineFnWithoutBody));
705     store.register_late_pass(|| Box::new(useless_conversion::UselessConversion::default()));
706     store.register_late_pass(|| Box::new(implicit_hasher::ImplicitHasher));
707     store.register_late_pass(|| Box::new(fallible_impl_from::FallibleImplFrom));
708     store.register_late_pass(|| Box::new(double_comparison::DoubleComparisons));
709     store.register_late_pass(|| Box::new(question_mark::QuestionMark));
710     store.register_early_pass(|| Box::new(suspicious_operation_groupings::SuspiciousOperationGroupings));
711     store.register_late_pass(|| Box::new(suspicious_trait_impl::SuspiciousImpl));
712     store.register_late_pass(|| Box::new(map_unit_fn::MapUnit));
713     store.register_late_pass(|| Box::new(inherent_impl::MultipleInherentImpl));
714     store.register_late_pass(|| Box::new(neg_cmp_op_on_partial_ord::NoNegCompOpForPartialOrd));
715     store.register_late_pass(|| Box::new(unwrap::Unwrap));
716     store.register_late_pass(|| Box::new(duration_subsec::DurationSubsec));
717     store.register_late_pass(|| Box::new(indexing_slicing::IndexingSlicing));
718     store.register_late_pass(|| Box::new(non_copy_const::NonCopyConst));
719     store.register_late_pass(|| Box::new(ptr_offset_with_cast::PtrOffsetWithCast));
720     store.register_late_pass(|| Box::new(redundant_clone::RedundantClone));
721     store.register_late_pass(|| Box::new(slow_vector_initialization::SlowVectorInit));
722     store.register_late_pass(|| Box::new(unnecessary_sort_by::UnnecessarySortBy));
723     store.register_late_pass(move || Box::new(unnecessary_wraps::UnnecessaryWraps::new(avoid_breaking_exported_api)));
724     store.register_late_pass(|| Box::new(assertions_on_constants::AssertionsOnConstants));
725     store.register_late_pass(|| Box::new(transmuting_null::TransmutingNull));
726     store.register_late_pass(|| Box::new(path_buf_push_overwrite::PathBufPushOverwrite));
727     store.register_late_pass(|| Box::new(integer_division::IntegerDivision));
728     store.register_late_pass(|| Box::new(inherent_to_string::InherentToString));
729     let max_trait_bounds = conf.max_trait_bounds;
730     store.register_late_pass(move || Box::new(trait_bounds::TraitBounds::new(max_trait_bounds)));
731     store.register_late_pass(|| Box::new(comparison_chain::ComparisonChain));
732     store.register_late_pass(|| Box::new(mut_key::MutableKeyType));
733     store.register_late_pass(|| Box::new(modulo_arithmetic::ModuloArithmetic));
734     store.register_early_pass(|| Box::new(reference::DerefAddrOf));
735     store.register_early_pass(|| Box::new(double_parens::DoubleParens));
736     store.register_late_pass(|| Box::new(format_impl::FormatImpl::new()));
737     store.register_early_pass(|| Box::new(unsafe_removed_from_name::UnsafeNameRemoval));
738     store.register_early_pass(|| Box::new(else_if_without_else::ElseIfWithoutElse));
739     store.register_early_pass(|| Box::new(int_plus_one::IntPlusOne));
740     store.register_early_pass(|| Box::new(formatting::Formatting));
741     store.register_early_pass(|| Box::new(misc_early::MiscEarlyLints));
742     store.register_early_pass(|| Box::new(redundant_closure_call::RedundantClosureCall));
743     store.register_late_pass(|| Box::new(redundant_closure_call::RedundantClosureCall));
744     store.register_early_pass(|| Box::new(unused_unit::UnusedUnit));
745     store.register_late_pass(|| Box::new(returns::Return));
746     store.register_early_pass(|| Box::new(collapsible_if::CollapsibleIf));
747     store.register_early_pass(|| Box::new(items_after_statements::ItemsAfterStatements));
748     store.register_early_pass(|| Box::new(precedence::Precedence));
749     store.register_early_pass(|| Box::new(needless_continue::NeedlessContinue));
750     store.register_early_pass(|| Box::new(redundant_else::RedundantElse));
751     store.register_late_pass(|| Box::new(create_dir::CreateDir));
752     store.register_early_pass(|| Box::new(needless_arbitrary_self_type::NeedlessArbitrarySelfType));
753     let literal_representation_lint_fraction_readability = conf.unreadable_literal_lint_fractions;
754     store.register_early_pass(move || {
755         Box::new(literal_representation::LiteralDigitGrouping::new(
756             literal_representation_lint_fraction_readability,
757         ))
758     });
759     let literal_representation_threshold = conf.literal_representation_threshold;
760     store.register_early_pass(move || {
761         Box::new(literal_representation::DecimalLiteralRepresentation::new(
762             literal_representation_threshold,
763         ))
764     });
765     let enum_variant_name_threshold = conf.enum_variant_name_threshold;
766     store.register_late_pass(move || {
767         Box::new(enum_variants::EnumVariantNames::new(
768             enum_variant_name_threshold,
769             avoid_breaking_exported_api,
770         ))
771     });
772     store.register_early_pass(|| Box::new(tabs_in_doc_comments::TabsInDocComments));
773     let upper_case_acronyms_aggressive = conf.upper_case_acronyms_aggressive;
774     store.register_late_pass(move || {
775         Box::new(upper_case_acronyms::UpperCaseAcronyms::new(
776             avoid_breaking_exported_api,
777             upper_case_acronyms_aggressive,
778         ))
779     });
780     store.register_late_pass(|| Box::new(default::Default::default()));
781     store.register_late_pass(|| Box::new(unused_self::UnusedSelf));
782     store.register_late_pass(|| Box::new(mutable_debug_assertion::DebugAssertWithMutCall));
783     store.register_late_pass(|| Box::new(exit::Exit));
784     store.register_late_pass(|| Box::new(to_digit_is_some::ToDigitIsSome));
785     let array_size_threshold = conf.array_size_threshold;
786     store.register_late_pass(move || Box::new(large_stack_arrays::LargeStackArrays::new(array_size_threshold)));
787     store.register_late_pass(move || Box::new(large_const_arrays::LargeConstArrays::new(array_size_threshold)));
788     store.register_late_pass(|| Box::new(floating_point_arithmetic::FloatingPointArithmetic));
789     store.register_early_pass(|| Box::new(as_conversions::AsConversions));
790     store.register_late_pass(|| Box::new(let_underscore::LetUnderscore));
791     store.register_early_pass(|| Box::new(single_component_path_imports::SingleComponentPathImports));
792     let max_fn_params_bools = conf.max_fn_params_bools;
793     let max_struct_bools = conf.max_struct_bools;
794     store.register_early_pass(move || {
795         Box::new(excessive_bools::ExcessiveBools::new(
796             max_struct_bools,
797             max_fn_params_bools,
798         ))
799     });
800     store.register_early_pass(|| Box::new(option_env_unwrap::OptionEnvUnwrap));
801     let warn_on_all_wildcard_imports = conf.warn_on_all_wildcard_imports;
802     store.register_late_pass(move || Box::new(wildcard_imports::WildcardImports::new(warn_on_all_wildcard_imports)));
803     store.register_late_pass(|| Box::new(verbose_file_reads::VerboseFileReads));
804     store.register_late_pass(|| Box::new(redundant_pub_crate::RedundantPubCrate::default()));
805     store.register_late_pass(|| Box::new(unnamed_address::UnnamedAddress));
806     store.register_late_pass(|| Box::new(dereference::Dereferencing::default()));
807     store.register_late_pass(|| Box::new(option_if_let_else::OptionIfLetElse));
808     store.register_late_pass(|| Box::new(future_not_send::FutureNotSend));
809     store.register_late_pass(|| Box::new(if_let_mutex::IfLetMutex));
810     store.register_late_pass(|| Box::new(if_not_else::IfNotElse));
811     store.register_late_pass(|| Box::new(equatable_if_let::PatternEquality));
812     store.register_late_pass(|| Box::new(mut_mutex_lock::MutMutexLock));
813     store.register_late_pass(|| Box::new(match_on_vec_items::MatchOnVecItems));
814     store.register_late_pass(|| Box::new(manual_async_fn::ManualAsyncFn));
815     store.register_late_pass(|| Box::new(vec_resize_to_zero::VecResizeToZero));
816     store.register_late_pass(|| Box::new(panic_in_result_fn::PanicInResultFn));
817     let single_char_binding_names_threshold = conf.single_char_binding_names_threshold;
818     store.register_early_pass(move || {
819         Box::new(non_expressive_names::NonExpressiveNames {
820             single_char_binding_names_threshold,
821         })
822     });
823     let macro_matcher = conf.standard_macro_braces.iter().cloned().collect::<FxHashSet<_>>();
824     store.register_early_pass(move || Box::new(nonstandard_macro_braces::MacroBraces::new(&macro_matcher)));
825     store.register_late_pass(|| Box::new(macro_use::MacroUseImports::default()));
826     store.register_late_pass(|| Box::new(pattern_type_mismatch::PatternTypeMismatch));
827     store.register_late_pass(|| Box::new(stable_sort_primitive::StableSortPrimitive));
828     store.register_late_pass(|| Box::new(repeat_once::RepeatOnce));
829     store.register_late_pass(|| Box::new(unwrap_in_result::UnwrapInResult));
830     store.register_late_pass(|| Box::new(self_assignment::SelfAssignment));
831     store.register_late_pass(|| Box::new(manual_unwrap_or::ManualUnwrapOr));
832     store.register_late_pass(|| Box::new(manual_ok_or::ManualOkOr));
833     store.register_late_pass(|| Box::new(float_equality_without_abs::FloatEqualityWithoutAbs));
834     store.register_late_pass(|| Box::new(semicolon_if_nothing_returned::SemicolonIfNothingReturned));
835     store.register_late_pass(|| Box::new(async_yields_async::AsyncYieldsAsync));
836     let disallowed_methods = conf.disallowed_methods.clone();
837     store.register_late_pass(move || Box::new(disallowed_methods::DisallowedMethods::new(disallowed_methods.clone())));
838     store.register_early_pass(|| Box::new(asm_syntax::InlineAsmX86AttSyntax));
839     store.register_early_pass(|| Box::new(asm_syntax::InlineAsmX86IntelSyntax));
840     store.register_late_pass(|| Box::new(empty_drop::EmptyDrop));
841     store.register_late_pass(|| Box::new(strings::StrToString));
842     store.register_late_pass(|| Box::new(strings::StringToString));
843     store.register_late_pass(|| Box::new(zero_sized_map_values::ZeroSizedMapValues));
844     store.register_late_pass(|| Box::new(vec_init_then_push::VecInitThenPush::default()));
845     store.register_late_pass(|| {
846         Box::new(case_sensitive_file_extension_comparisons::CaseSensitiveFileExtensionComparisons)
847     });
848     store.register_late_pass(|| Box::new(redundant_slicing::RedundantSlicing));
849     store.register_late_pass(|| Box::new(from_str_radix_10::FromStrRadix10));
850     store.register_late_pass(|| Box::new(manual_map::ManualMap));
851     store.register_late_pass(move || Box::new(if_then_some_else_none::IfThenSomeElseNone::new(msrv)));
852     store.register_late_pass(|| Box::new(bool_assert_comparison::BoolAssertComparison));
853     store.register_early_pass(move || Box::new(module_style::ModStyle));
854     store.register_late_pass(|| Box::new(unused_async::UnusedAsync));
855     let disallowed_types = conf.disallowed_types.clone();
856     store.register_late_pass(move || Box::new(disallowed_types::DisallowedTypes::new(disallowed_types.clone())));
857     let import_renames = conf.enforced_import_renames.clone();
858     store.register_late_pass(move || {
859         Box::new(missing_enforced_import_rename::ImportRename::new(
860             import_renames.clone(),
861         ))
862     });
863     let scripts = conf.allowed_scripts.clone();
864     store.register_early_pass(move || Box::new(disallowed_script_idents::DisallowedScriptIdents::new(&scripts)));
865     store.register_late_pass(|| Box::new(strlen_on_c_strings::StrlenOnCStrings));
866     store.register_late_pass(move || Box::new(self_named_constructors::SelfNamedConstructors));
867     store.register_late_pass(move || Box::new(iter_not_returning_iterator::IterNotReturningIterator));
868     store.register_late_pass(move || Box::new(manual_assert::ManualAssert));
869     let enable_raw_pointer_heuristic_for_send = conf.enable_raw_pointer_heuristic_for_send;
870     store.register_late_pass(move || {
871         Box::new(non_send_fields_in_send_ty::NonSendFieldInSendTy::new(
872             enable_raw_pointer_heuristic_for_send,
873         ))
874     });
875     store.register_late_pass(move || Box::new(undocumented_unsafe_blocks::UndocumentedUnsafeBlocks));
876     store.register_late_pass(|| Box::new(match_str_case_mismatch::MatchStrCaseMismatch));
877     store.register_late_pass(move || Box::new(format_args::FormatArgs));
878     store.register_late_pass(|| Box::new(trailing_empty_array::TrailingEmptyArray));
879     store.register_early_pass(|| Box::new(octal_escapes::OctalEscapes));
880     store.register_late_pass(|| Box::new(needless_late_init::NeedlessLateInit));
881     store.register_late_pass(|| Box::new(return_self_not_must_use::ReturnSelfNotMustUse));
882     store.register_late_pass(|| Box::new(init_numbered_fields::NumberedFields));
883     store.register_early_pass(|| Box::new(single_char_lifetime_names::SingleCharLifetimeNames));
884     store.register_late_pass(move || Box::new(borrow_as_ptr::BorrowAsPtr::new(msrv)));
885     store.register_late_pass(move || Box::new(manual_bits::ManualBits::new(msrv)));
886     store.register_late_pass(|| Box::new(default_union_representation::DefaultUnionRepresentation));
887     store.register_late_pass(|| Box::new(only_used_in_recursion::OnlyUsedInRecursion));
888     store.register_late_pass(|| Box::new(dbg_macro::DbgMacro));
889     let cargo_ignore_publish = conf.cargo_ignore_publish;
890     store.register_late_pass(move || {
891         Box::new(cargo::Cargo {
892             ignore_publish: cargo_ignore_publish,
893         })
894     });
895     store.register_early_pass(|| Box::new(crate_in_macro_def::CrateInMacroDef));
896     store.register_early_pass(|| Box::new(empty_structs_with_brackets::EmptyStructsWithBrackets));
897     store.register_late_pass(|| Box::new(unnecessary_owned_empty_strings::UnnecessaryOwnedEmptyStrings));
898     store.register_early_pass(|| Box::new(pub_use::PubUse));
899     store.register_late_pass(|| Box::new(format_push_string::FormatPushString));
900     store.register_late_pass(|| Box::new(bytes_count_to_len::BytesCountToLen));
901     let max_include_file_size = conf.max_include_file_size;
902     store.register_late_pass(move || Box::new(large_include_file::LargeIncludeFile::new(max_include_file_size)));
903     store.register_late_pass(|| Box::new(strings::TrimSplitWhitespace));
904     store.register_late_pass(|| Box::new(rc_clone_in_vec_init::RcCloneInVecInit));
905     // add lints here, do not remove this comment, it's used in `new_lint`
906 }
907
908 #[rustfmt::skip]
909 fn register_removed_non_tool_lints(store: &mut rustc_lint::LintStore) {
910     store.register_removed(
911         "should_assert_eq",
912         "`assert!()` will be more flexible with RFC 2011",
913     );
914     store.register_removed(
915         "extend_from_slice",
916         "`.extend_from_slice(_)` is a faster way to extend a Vec by a slice",
917     );
918     store.register_removed(
919         "range_step_by_zero",
920         "`iterator.step_by(0)` panics nowadays",
921     );
922     store.register_removed(
923         "unstable_as_slice",
924         "`Vec::as_slice` has been stabilized in 1.7",
925     );
926     store.register_removed(
927         "unstable_as_mut_slice",
928         "`Vec::as_mut_slice` has been stabilized in 1.7",
929     );
930     store.register_removed(
931         "misaligned_transmute",
932         "this lint has been split into cast_ptr_alignment and transmute_ptr_to_ptr",
933     );
934     store.register_removed(
935         "assign_ops",
936         "using compound assignment operators (e.g., `+=`) is harmless",
937     );
938     store.register_removed(
939         "if_let_redundant_pattern_matching",
940         "this lint has been changed to redundant_pattern_matching",
941     );
942     store.register_removed(
943         "unsafe_vector_initialization",
944         "the replacement suggested by this lint had substantially different behavior",
945     );
946     store.register_removed(
947         "reverse_range_loop",
948         "this lint is now included in reversed_empty_ranges",
949     );
950 }
951
952 /// Register renamed lints.
953 ///
954 /// Used in `./src/driver.rs`.
955 pub fn register_renamed(ls: &mut rustc_lint::LintStore) {
956     for (old_name, new_name) in renamed_lints::RENAMED_LINTS {
957         ls.register_renamed(old_name, new_name);
958     }
959 }
960
961 // only exists to let the dogfood integration test works.
962 // Don't run clippy as an executable directly
963 #[allow(dead_code)]
964 fn main() {
965     panic!("Please use the cargo-clippy executable");
966 }