]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/lib.rs
Rollup merge of #97301 - semicoleon:unstable-reexport, r=petrochenkov
[rust.git] / src / tools / clippy / 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 almost_complete_letter_range;
172 mod approx_const;
173 mod as_conversions;
174 mod as_underscore;
175 mod asm_syntax;
176 mod assertions_on_constants;
177 mod assign_ops;
178 mod async_yields_async;
179 mod attrs;
180 mod await_holding_invalid;
181 mod bit_mask;
182 mod blacklisted_name;
183 mod blocks_in_if_conditions;
184 mod bool_assert_comparison;
185 mod booleans;
186 mod borrow_as_ptr;
187 mod borrow_deref_ref;
188 mod bytecount;
189 mod bytes_count_to_len;
190 mod cargo;
191 mod case_sensitive_file_extension_comparisons;
192 mod casts;
193 mod checked_conversions;
194 mod cognitive_complexity;
195 mod collapsible_if;
196 mod comparison_chain;
197 mod copies;
198 mod copy_iterator;
199 mod crate_in_macro_def;
200 mod create_dir;
201 mod dbg_macro;
202 mod default;
203 mod default_numeric_fallback;
204 mod default_union_representation;
205 mod dereference;
206 mod derivable_impls;
207 mod derive;
208 mod disallowed_methods;
209 mod disallowed_script_idents;
210 mod disallowed_types;
211 mod doc;
212 mod doc_link_with_quotes;
213 mod double_comparison;
214 mod double_parens;
215 mod drop_forget_ref;
216 mod duplicate_mod;
217 mod duration_subsec;
218 mod else_if_without_else;
219 mod empty_drop;
220 mod empty_enum;
221 mod empty_structs_with_brackets;
222 mod entry;
223 mod enum_clike;
224 mod enum_variants;
225 mod eq_op;
226 mod equatable_if_let;
227 mod erasing_op;
228 mod escape;
229 mod eta_reduction;
230 mod excessive_bools;
231 mod exhaustive_items;
232 mod exit;
233 mod explicit_write;
234 mod fallible_impl_from;
235 mod float_equality_without_abs;
236 mod float_literal;
237 mod floating_point_arithmetic;
238 mod format;
239 mod format_args;
240 mod format_impl;
241 mod format_push_string;
242 mod formatting;
243 mod from_over_into;
244 mod from_str_radix_10;
245 mod functions;
246 mod future_not_send;
247 mod get_first;
248 mod identity_op;
249 mod if_let_mutex;
250 mod if_not_else;
251 mod if_then_some_else_none;
252 mod implicit_hasher;
253 mod implicit_return;
254 mod implicit_saturating_sub;
255 mod inconsistent_struct_constructor;
256 mod index_refutable_slice;
257 mod indexing_slicing;
258 mod infinite_iter;
259 mod inherent_impl;
260 mod inherent_to_string;
261 mod init_numbered_fields;
262 mod inline_fn_without_body;
263 mod int_plus_one;
264 mod integer_division;
265 mod invalid_upcast_comparisons;
266 mod items_after_statements;
267 mod iter_not_returning_iterator;
268 mod large_const_arrays;
269 mod large_enum_variant;
270 mod large_include_file;
271 mod large_stack_arrays;
272 mod len_zero;
273 mod let_if_seq;
274 mod let_underscore;
275 mod lifetimes;
276 mod literal_representation;
277 mod loops;
278 mod macro_use;
279 mod main_recursion;
280 mod manual_assert;
281 mod manual_async_fn;
282 mod manual_bits;
283 mod manual_non_exhaustive;
284 mod manual_ok_or;
285 mod manual_strip;
286 mod map_clone;
287 mod map_err_ignore;
288 mod map_unit_fn;
289 mod match_result_ok;
290 mod matches;
291 mod mem_forget;
292 mod mem_replace;
293 mod methods;
294 mod minmax;
295 mod misc;
296 mod misc_early;
297 mod mismatching_type_param_order;
298 mod missing_const_for_fn;
299 mod missing_doc;
300 mod missing_enforced_import_rename;
301 mod missing_inline;
302 mod mixed_read_write_in_expression;
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 numeric_arithmetic;
331 mod octal_escapes;
332 mod only_used_in_recursion;
333 mod open_options;
334 mod option_env_unwrap;
335 mod option_if_let_else;
336 mod overflow_check_conditional;
337 mod panic_in_result_fn;
338 mod panic_unimplemented;
339 mod partialeq_ne_impl;
340 mod pass_by_ref_or_value;
341 mod path_buf_push_overwrite;
342 mod pattern_type_mismatch;
343 mod precedence;
344 mod ptr;
345 mod ptr_eq;
346 mod ptr_offset_with_cast;
347 mod pub_use;
348 mod question_mark;
349 mod ranges;
350 mod rc_clone_in_vec_init;
351 mod redundant_clone;
352 mod redundant_closure_call;
353 mod redundant_else;
354 mod redundant_field_names;
355 mod redundant_pub_crate;
356 mod redundant_slicing;
357 mod redundant_static_lifetimes;
358 mod ref_option_ref;
359 mod reference;
360 mod regex;
361 mod repeat_once;
362 mod return_self_not_must_use;
363 mod returns;
364 mod same_name_method;
365 mod self_assignment;
366 mod self_named_constructors;
367 mod semicolon_if_nothing_returned;
368 mod serde_api;
369 mod shadow;
370 mod single_char_lifetime_names;
371 mod single_component_path_imports;
372 mod size_of_in_element_count;
373 mod slow_vector_initialization;
374 mod stable_sort_primitive;
375 mod strings;
376 mod strlen_on_c_strings;
377 mod suspicious_operation_groupings;
378 mod suspicious_trait_impl;
379 mod swap;
380 mod swap_ptr_to_ref;
381 mod tabs_in_doc_comments;
382 mod temporary_assignment;
383 mod to_digit_is_some;
384 mod trailing_empty_array;
385 mod trait_bounds;
386 mod transmute;
387 mod transmuting_null;
388 mod types;
389 mod undocumented_unsafe_blocks;
390 mod unicode;
391 mod uninit_vec;
392 mod unit_hash;
393 mod unit_return_expecting_ord;
394 mod unit_types;
395 mod unnamed_address;
396 mod unnecessary_owned_empty_strings;
397 mod unnecessary_self_imports;
398 mod unnecessary_sort_by;
399 mod unnecessary_wraps;
400 mod unnested_or_patterns;
401 mod unsafe_removed_from_name;
402 mod unused_async;
403 mod unused_io_amount;
404 mod unused_rounding;
405 mod unused_self;
406 mod unused_unit;
407 mod unwrap;
408 mod unwrap_in_result;
409 mod upper_case_acronyms;
410 mod use_self;
411 mod useless_conversion;
412 mod vec;
413 mod vec_init_then_push;
414 mod vec_resize_to_zero;
415 mod verbose_file_reads;
416 mod wildcard_imports;
417 mod write;
418 mod zero_div_zero;
419 mod zero_sized_map_values;
420 // end lints modules, do not remove this comment, it’s used in `update_lints`
421
422 pub use crate::utils::conf::Conf;
423 use crate::utils::conf::{format_error, TryConf};
424
425 /// Register all pre expansion lints
426 ///
427 /// Pre-expansion lints run before any macro expansion has happened.
428 ///
429 /// Note that due to the architecture of the compiler, currently `cfg_attr` attributes on crate
430 /// level (i.e `#![cfg_attr(...)]`) will still be expanded even when using a pre-expansion pass.
431 ///
432 /// Used in `./src/driver.rs`.
433 pub fn register_pre_expansion_lints(store: &mut rustc_lint::LintStore, sess: &Session, conf: &Conf) {
434     // NOTE: Do not add any more pre-expansion passes. These should be removed eventually.
435
436     let msrv = conf.msrv.as_ref().and_then(|s| {
437         parse_msrv(s, None, None).or_else(|| {
438             sess.err(&format!(
439                 "error reading Clippy's configuration file. `{}` is not a valid Rust version",
440                 s
441             ));
442             None
443         })
444     });
445
446     store.register_pre_expansion_pass(|| Box::new(write::Write::default()));
447     store.register_pre_expansion_pass(move || Box::new(attrs::EarlyAttributes { msrv }));
448 }
449
450 #[doc(hidden)]
451 pub fn read_conf(sess: &Session) -> Conf {
452     let file_name = match utils::conf::lookup_conf_file() {
453         Ok(Some(path)) => path,
454         Ok(None) => return Conf::default(),
455         Err(error) => {
456             sess.struct_err(&format!("error finding Clippy's configuration file: {}", error))
457                 .emit();
458             return Conf::default();
459         },
460     };
461
462     let TryConf { conf, errors } = utils::conf::read(&file_name);
463     // all conf errors are non-fatal, we just use the default conf in case of error
464     for error in errors {
465         sess.struct_err(&format!(
466             "error reading Clippy's configuration file `{}`: {}",
467             file_name.display(),
468             format_error(error)
469         ))
470         .emit();
471     }
472
473     conf
474 }
475
476 /// Register all lints and lint groups with the rustc plugin registry
477 ///
478 /// Used in `./src/driver.rs`.
479 #[expect(clippy::too_many_lines)]
480 pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: &Conf) {
481     register_removed_non_tool_lints(store);
482
483     include!("lib.deprecated.rs");
484
485     include!("lib.register_lints.rs");
486     include!("lib.register_restriction.rs");
487     include!("lib.register_pedantic.rs");
488
489     #[cfg(feature = "internal")]
490     include!("lib.register_internal.rs");
491
492     include!("lib.register_all.rs");
493     include!("lib.register_style.rs");
494     include!("lib.register_complexity.rs");
495     include!("lib.register_correctness.rs");
496     include!("lib.register_suspicious.rs");
497     include!("lib.register_perf.rs");
498     include!("lib.register_cargo.rs");
499     include!("lib.register_nursery.rs");
500
501     #[cfg(feature = "internal")]
502     {
503         if std::env::var("ENABLE_METADATA_COLLECTION").eq(&Ok("1".to_string())) {
504             store.register_late_pass(|| Box::new(utils::internal_lints::metadata_collector::MetadataCollector::new()));
505             return;
506         }
507     }
508
509     // all the internal lints
510     #[cfg(feature = "internal")]
511     {
512         store.register_early_pass(|| Box::new(utils::internal_lints::ClippyLintsInternal));
513         store.register_early_pass(|| Box::new(utils::internal_lints::ProduceIce));
514         store.register_late_pass(|| Box::new(utils::internal_lints::CollapsibleCalls));
515         store.register_late_pass(|| Box::new(utils::internal_lints::CompilerLintFunctions::new()));
516         store.register_late_pass(|| Box::new(utils::internal_lints::IfChainStyle));
517         store.register_late_pass(|| Box::new(utils::internal_lints::InvalidPaths));
518         store.register_late_pass(|| Box::new(utils::internal_lints::InterningDefinedSymbol::default()));
519         store.register_late_pass(|| Box::new(utils::internal_lints::LintWithoutLintPass::default()));
520         store.register_late_pass(|| Box::new(utils::internal_lints::MatchTypeOnDiagItem));
521         store.register_late_pass(|| Box::new(utils::internal_lints::OuterExpnDataPass));
522         store.register_late_pass(|| Box::new(utils::internal_lints::MsrvAttrImpl));
523     }
524
525     store.register_late_pass(|| Box::new(utils::dump_hir::DumpHir));
526     store.register_late_pass(|| Box::new(utils::author::Author));
527     let await_holding_invalid_types = conf.await_holding_invalid_types.clone();
528     store.register_late_pass(move || {
529         Box::new(await_holding_invalid::AwaitHolding::new(
530             await_holding_invalid_types.clone(),
531         ))
532     });
533     store.register_late_pass(|| Box::new(serde_api::SerdeApi));
534     let vec_box_size_threshold = conf.vec_box_size_threshold;
535     let type_complexity_threshold = conf.type_complexity_threshold;
536     let avoid_breaking_exported_api = conf.avoid_breaking_exported_api;
537     store.register_late_pass(move || {
538         Box::new(types::Types::new(
539             vec_box_size_threshold,
540             type_complexity_threshold,
541             avoid_breaking_exported_api,
542         ))
543     });
544     store.register_late_pass(|| Box::new(booleans::NonminimalBool));
545     store.register_late_pass(|| Box::new(needless_bitwise_bool::NeedlessBitwiseBool));
546     store.register_late_pass(|| Box::new(eq_op::EqOp));
547     store.register_late_pass(|| Box::new(enum_clike::UnportableVariant));
548     store.register_late_pass(|| Box::new(float_literal::FloatLiteral));
549     let verbose_bit_mask_threshold = conf.verbose_bit_mask_threshold;
550     store.register_late_pass(move || Box::new(bit_mask::BitMask::new(verbose_bit_mask_threshold)));
551     store.register_late_pass(|| Box::new(ptr::Ptr));
552     store.register_late_pass(|| Box::new(ptr_eq::PtrEq));
553     store.register_late_pass(|| Box::new(needless_bool::NeedlessBool));
554     store.register_late_pass(|| Box::new(needless_bool::BoolComparison));
555     store.register_late_pass(|| Box::new(needless_for_each::NeedlessForEach));
556     store.register_late_pass(|| Box::new(misc::MiscLints));
557     store.register_late_pass(|| Box::new(eta_reduction::EtaReduction));
558     store.register_late_pass(|| Box::new(identity_op::IdentityOp));
559     store.register_late_pass(|| Box::new(erasing_op::ErasingOp));
560     store.register_late_pass(|| Box::new(mut_mut::MutMut));
561     store.register_late_pass(|| Box::new(mut_reference::UnnecessaryMutPassed));
562     store.register_late_pass(|| Box::new(len_zero::LenZero));
563     store.register_late_pass(|| Box::new(attrs::Attributes));
564     store.register_late_pass(|| Box::new(blocks_in_if_conditions::BlocksInIfConditions));
565     store.register_late_pass(|| Box::new(unicode::Unicode));
566     store.register_late_pass(|| Box::new(uninit_vec::UninitVec));
567     store.register_late_pass(|| Box::new(unit_hash::UnitHash));
568     store.register_late_pass(|| Box::new(unit_return_expecting_ord::UnitReturnExpectingOrd));
569     store.register_late_pass(|| Box::new(strings::StringAdd));
570     store.register_late_pass(|| Box::new(implicit_return::ImplicitReturn));
571     store.register_late_pass(|| Box::new(implicit_saturating_sub::ImplicitSaturatingSub));
572     store.register_late_pass(|| Box::new(default_numeric_fallback::DefaultNumericFallback));
573     store.register_late_pass(|| Box::new(inconsistent_struct_constructor::InconsistentStructConstructor));
574     store.register_late_pass(|| Box::new(non_octal_unix_permissions::NonOctalUnixPermissions));
575     store.register_early_pass(|| Box::new(unnecessary_self_imports::UnnecessarySelfImports));
576
577     let msrv = conf.msrv.as_ref().and_then(|s| {
578         parse_msrv(s, None, None).or_else(|| {
579             sess.err(&format!(
580                 "error reading Clippy's configuration file. `{}` is not a valid Rust version",
581                 s
582             ));
583             None
584         })
585     });
586
587     let avoid_breaking_exported_api = conf.avoid_breaking_exported_api;
588     let allow_expect_in_tests = conf.allow_expect_in_tests;
589     let allow_unwrap_in_tests = conf.allow_unwrap_in_tests;
590     store.register_late_pass(move || Box::new(approx_const::ApproxConstant::new(msrv)));
591     store.register_late_pass(move || {
592         Box::new(methods::Methods::new(
593             avoid_breaking_exported_api,
594             msrv,
595             allow_expect_in_tests,
596             allow_unwrap_in_tests,
597         ))
598     });
599     store.register_late_pass(move || Box::new(matches::Matches::new(msrv)));
600     store.register_early_pass(move || Box::new(manual_non_exhaustive::ManualNonExhaustiveStruct::new(msrv)));
601     store.register_late_pass(move || Box::new(manual_non_exhaustive::ManualNonExhaustiveEnum::new(msrv)));
602     store.register_late_pass(move || Box::new(manual_strip::ManualStrip::new(msrv)));
603     store.register_early_pass(move || Box::new(redundant_static_lifetimes::RedundantStaticLifetimes::new(msrv)));
604     store.register_early_pass(move || Box::new(redundant_field_names::RedundantFieldNames::new(msrv)));
605     store.register_late_pass(move || Box::new(checked_conversions::CheckedConversions::new(msrv)));
606     store.register_late_pass(move || Box::new(mem_replace::MemReplace::new(msrv)));
607     store.register_late_pass(move || Box::new(ranges::Ranges::new(msrv)));
608     store.register_late_pass(move || Box::new(from_over_into::FromOverInto::new(msrv)));
609     store.register_late_pass(move || Box::new(use_self::UseSelf::new(msrv)));
610     store.register_late_pass(move || Box::new(missing_const_for_fn::MissingConstForFn::new(msrv)));
611     store.register_late_pass(move || Box::new(needless_question_mark::NeedlessQuestionMark));
612     store.register_late_pass(move || Box::new(casts::Casts::new(msrv)));
613     store.register_early_pass(move || Box::new(unnested_or_patterns::UnnestedOrPatterns::new(msrv)));
614     store.register_late_pass(move || Box::new(map_clone::MapClone::new(msrv)));
615
616     store.register_late_pass(|| Box::new(size_of_in_element_count::SizeOfInElementCount));
617     store.register_late_pass(|| Box::new(same_name_method::SameNameMethod));
618     let max_suggested_slice_pattern_length = conf.max_suggested_slice_pattern_length;
619     store.register_late_pass(move || {
620         Box::new(index_refutable_slice::IndexRefutableSlice::new(
621             max_suggested_slice_pattern_length,
622             msrv,
623         ))
624     });
625     store.register_late_pass(|| Box::new(map_err_ignore::MapErrIgnore));
626     store.register_late_pass(|| Box::new(shadow::Shadow::default()));
627     store.register_late_pass(|| Box::new(unit_types::UnitTypes));
628     store.register_late_pass(|| Box::new(loops::Loops));
629     store.register_late_pass(|| Box::new(main_recursion::MainRecursion::default()));
630     store.register_late_pass(|| Box::new(lifetimes::Lifetimes));
631     store.register_late_pass(|| Box::new(entry::HashMapPass));
632     store.register_late_pass(|| Box::new(minmax::MinMaxPass));
633     store.register_late_pass(|| Box::new(open_options::OpenOptions));
634     store.register_late_pass(|| Box::new(zero_div_zero::ZeroDiv));
635     store.register_late_pass(|| Box::new(mutex_atomic::Mutex));
636     store.register_late_pass(|| Box::new(needless_update::NeedlessUpdate));
637     store.register_late_pass(|| Box::new(needless_borrowed_ref::NeedlessBorrowedRef));
638     store.register_late_pass(|| Box::new(borrow_deref_ref::BorrowDerefRef));
639     store.register_late_pass(|| Box::new(no_effect::NoEffect));
640     store.register_late_pass(|| Box::new(temporary_assignment::TemporaryAssignment));
641     store.register_late_pass(|| Box::new(transmute::Transmute));
642     let cognitive_complexity_threshold = conf.cognitive_complexity_threshold;
643     store.register_late_pass(move || {
644         Box::new(cognitive_complexity::CognitiveComplexity::new(
645             cognitive_complexity_threshold,
646         ))
647     });
648     let too_large_for_stack = conf.too_large_for_stack;
649     store.register_late_pass(move || Box::new(escape::BoxedLocal { too_large_for_stack }));
650     store.register_late_pass(move || Box::new(vec::UselessVec { too_large_for_stack }));
651     store.register_late_pass(|| Box::new(panic_unimplemented::PanicUnimplemented));
652     store.register_late_pass(|| Box::new(strings::StringLitAsBytes));
653     store.register_late_pass(|| Box::new(derive::Derive));
654     store.register_late_pass(|| Box::new(derivable_impls::DerivableImpls));
655     store.register_late_pass(|| Box::new(drop_forget_ref::DropForgetRef));
656     store.register_late_pass(|| Box::new(empty_enum::EmptyEnum));
657     store.register_late_pass(|| Box::new(absurd_extreme_comparisons::AbsurdExtremeComparisons));
658     store.register_late_pass(|| Box::new(invalid_upcast_comparisons::InvalidUpcastComparisons));
659     store.register_late_pass(|| Box::new(regex::Regex));
660     store.register_late_pass(|| Box::new(copies::CopyAndPaste));
661     store.register_late_pass(|| Box::new(copy_iterator::CopyIterator));
662     store.register_late_pass(|| Box::new(format::UselessFormat));
663     store.register_late_pass(|| Box::new(swap::Swap));
664     store.register_late_pass(|| Box::new(overflow_check_conditional::OverflowCheckConditional));
665     store.register_late_pass(|| Box::new(new_without_default::NewWithoutDefault::default()));
666     let blacklisted_names = conf.blacklisted_names.iter().cloned().collect::<FxHashSet<_>>();
667     store.register_late_pass(move || Box::new(blacklisted_name::BlacklistedName::new(blacklisted_names.clone())));
668     let too_many_arguments_threshold = conf.too_many_arguments_threshold;
669     let too_many_lines_threshold = conf.too_many_lines_threshold;
670     store.register_late_pass(move || {
671         Box::new(functions::Functions::new(
672             too_many_arguments_threshold,
673             too_many_lines_threshold,
674         ))
675     });
676     let doc_valid_idents = conf.doc_valid_idents.iter().cloned().collect::<FxHashSet<_>>();
677     store.register_late_pass(move || Box::new(doc::DocMarkdown::new(doc_valid_idents.clone())));
678     store.register_late_pass(|| Box::new(neg_multiply::NegMultiply));
679     store.register_late_pass(|| Box::new(mem_forget::MemForget));
680     store.register_late_pass(|| Box::new(numeric_arithmetic::NumericArithmetic::default()));
681     store.register_late_pass(|| Box::new(assign_ops::AssignOps));
682     store.register_late_pass(|| Box::new(let_if_seq::LetIfSeq));
683     store.register_late_pass(|| Box::new(mixed_read_write_in_expression::EvalOrderDependence));
684     store.register_late_pass(|| Box::new(missing_doc::MissingDoc::new()));
685     store.register_late_pass(|| Box::new(missing_inline::MissingInline));
686     store.register_late_pass(move || Box::new(exhaustive_items::ExhaustiveItems));
687     store.register_late_pass(|| Box::new(match_result_ok::MatchResultOk));
688     store.register_late_pass(|| Box::new(partialeq_ne_impl::PartialEqNeImpl));
689     store.register_late_pass(|| Box::new(unused_io_amount::UnusedIoAmount));
690     let enum_variant_size_threshold = conf.enum_variant_size_threshold;
691     store.register_late_pass(move || Box::new(large_enum_variant::LargeEnumVariant::new(enum_variant_size_threshold)));
692     store.register_late_pass(|| Box::new(explicit_write::ExplicitWrite));
693     store.register_late_pass(|| Box::new(needless_pass_by_value::NeedlessPassByValue));
694     let pass_by_ref_or_value = pass_by_ref_or_value::PassByRefOrValue::new(
695         conf.trivial_copy_size_limit,
696         conf.pass_by_value_size_limit,
697         conf.avoid_breaking_exported_api,
698         &sess.target,
699     );
700     store.register_late_pass(move || Box::new(pass_by_ref_or_value));
701     store.register_late_pass(|| Box::new(ref_option_ref::RefOptionRef));
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(manual_async_fn::ManualAsyncFn));
814     store.register_late_pass(|| Box::new(vec_resize_to_zero::VecResizeToZero));
815     store.register_late_pass(|| Box::new(panic_in_result_fn::PanicInResultFn));
816     let single_char_binding_names_threshold = conf.single_char_binding_names_threshold;
817     store.register_early_pass(move || {
818         Box::new(non_expressive_names::NonExpressiveNames {
819             single_char_binding_names_threshold,
820         })
821     });
822     let macro_matcher = conf.standard_macro_braces.iter().cloned().collect::<FxHashSet<_>>();
823     store.register_early_pass(move || Box::new(nonstandard_macro_braces::MacroBraces::new(&macro_matcher)));
824     store.register_late_pass(|| Box::new(macro_use::MacroUseImports::default()));
825     store.register_late_pass(|| Box::new(pattern_type_mismatch::PatternTypeMismatch));
826     store.register_late_pass(|| Box::new(stable_sort_primitive::StableSortPrimitive));
827     store.register_late_pass(|| Box::new(repeat_once::RepeatOnce));
828     store.register_late_pass(|| Box::new(unwrap_in_result::UnwrapInResult));
829     store.register_late_pass(|| Box::new(self_assignment::SelfAssignment));
830     store.register_late_pass(|| Box::new(manual_ok_or::ManualOkOr));
831     store.register_late_pass(|| Box::new(float_equality_without_abs::FloatEqualityWithoutAbs));
832     store.register_late_pass(|| Box::new(semicolon_if_nothing_returned::SemicolonIfNothingReturned));
833     store.register_late_pass(|| Box::new(async_yields_async::AsyncYieldsAsync));
834     let disallowed_methods = conf.disallowed_methods.clone();
835     store.register_late_pass(move || Box::new(disallowed_methods::DisallowedMethods::new(disallowed_methods.clone())));
836     store.register_early_pass(|| Box::new(asm_syntax::InlineAsmX86AttSyntax));
837     store.register_early_pass(|| Box::new(asm_syntax::InlineAsmX86IntelSyntax));
838     store.register_late_pass(|| Box::new(empty_drop::EmptyDrop));
839     store.register_late_pass(|| Box::new(strings::StrToString));
840     store.register_late_pass(|| Box::new(strings::StringToString));
841     store.register_late_pass(|| Box::new(zero_sized_map_values::ZeroSizedMapValues));
842     store.register_late_pass(|| Box::new(vec_init_then_push::VecInitThenPush::default()));
843     store.register_late_pass(|| {
844         Box::new(case_sensitive_file_extension_comparisons::CaseSensitiveFileExtensionComparisons)
845     });
846     store.register_late_pass(|| Box::new(redundant_slicing::RedundantSlicing));
847     store.register_late_pass(|| Box::new(from_str_radix_10::FromStrRadix10));
848     store.register_late_pass(move || Box::new(if_then_some_else_none::IfThenSomeElseNone::new(msrv)));
849     store.register_late_pass(|| Box::new(bool_assert_comparison::BoolAssertComparison));
850     store.register_early_pass(move || Box::new(module_style::ModStyle));
851     store.register_late_pass(|| Box::new(unused_async::UnusedAsync));
852     let disallowed_types = conf.disallowed_types.clone();
853     store.register_late_pass(move || Box::new(disallowed_types::DisallowedTypes::new(disallowed_types.clone())));
854     let import_renames = conf.enforced_import_renames.clone();
855     store.register_late_pass(move || {
856         Box::new(missing_enforced_import_rename::ImportRename::new(
857             import_renames.clone(),
858         ))
859     });
860     let scripts = conf.allowed_scripts.clone();
861     store.register_early_pass(move || Box::new(disallowed_script_idents::DisallowedScriptIdents::new(&scripts)));
862     store.register_late_pass(|| Box::new(strlen_on_c_strings::StrlenOnCStrings));
863     store.register_late_pass(move || Box::new(self_named_constructors::SelfNamedConstructors));
864     store.register_late_pass(move || Box::new(iter_not_returning_iterator::IterNotReturningIterator));
865     store.register_late_pass(move || Box::new(manual_assert::ManualAssert));
866     let enable_raw_pointer_heuristic_for_send = conf.enable_raw_pointer_heuristic_for_send;
867     store.register_late_pass(move || {
868         Box::new(non_send_fields_in_send_ty::NonSendFieldInSendTy::new(
869             enable_raw_pointer_heuristic_for_send,
870         ))
871     });
872     store.register_late_pass(move || Box::new(undocumented_unsafe_blocks::UndocumentedUnsafeBlocks));
873     store.register_late_pass(move || Box::new(format_args::FormatArgs));
874     store.register_late_pass(|| Box::new(trailing_empty_array::TrailingEmptyArray));
875     store.register_early_pass(|| Box::new(octal_escapes::OctalEscapes));
876     store.register_late_pass(|| Box::new(needless_late_init::NeedlessLateInit));
877     store.register_late_pass(|| Box::new(return_self_not_must_use::ReturnSelfNotMustUse));
878     store.register_late_pass(|| Box::new(init_numbered_fields::NumberedFields));
879     store.register_early_pass(|| Box::new(single_char_lifetime_names::SingleCharLifetimeNames));
880     store.register_late_pass(move || Box::new(borrow_as_ptr::BorrowAsPtr::new(msrv)));
881     store.register_late_pass(move || Box::new(manual_bits::ManualBits::new(msrv)));
882     store.register_late_pass(|| Box::new(default_union_representation::DefaultUnionRepresentation));
883     store.register_early_pass(|| Box::new(doc_link_with_quotes::DocLinkWithQuotes));
884     store.register_late_pass(|| Box::new(only_used_in_recursion::OnlyUsedInRecursion));
885     let allow_dbg_in_tests = conf.allow_dbg_in_tests;
886     store.register_late_pass(move || Box::new(dbg_macro::DbgMacro::new(allow_dbg_in_tests)));
887     let cargo_ignore_publish = conf.cargo_ignore_publish;
888     store.register_late_pass(move || {
889         Box::new(cargo::Cargo {
890             ignore_publish: cargo_ignore_publish,
891         })
892     });
893     store.register_early_pass(|| Box::new(crate_in_macro_def::CrateInMacroDef));
894     store.register_early_pass(|| Box::new(empty_structs_with_brackets::EmptyStructsWithBrackets));
895     store.register_late_pass(|| Box::new(unnecessary_owned_empty_strings::UnnecessaryOwnedEmptyStrings));
896     store.register_early_pass(|| Box::new(pub_use::PubUse));
897     store.register_late_pass(|| Box::new(format_push_string::FormatPushString));
898     store.register_late_pass(|| Box::new(bytes_count_to_len::BytesCountToLen));
899     let max_include_file_size = conf.max_include_file_size;
900     store.register_late_pass(move || Box::new(large_include_file::LargeIncludeFile::new(max_include_file_size)));
901     store.register_late_pass(|| Box::new(strings::TrimSplitWhitespace));
902     store.register_late_pass(|| Box::new(rc_clone_in_vec_init::RcCloneInVecInit));
903     store.register_early_pass(|| Box::new(duplicate_mod::DuplicateMod::default()));
904     store.register_late_pass(|| Box::new(get_first::GetFirst));
905     store.register_early_pass(|| Box::new(unused_rounding::UnusedRounding));
906     store.register_early_pass(move || Box::new(almost_complete_letter_range::AlmostCompleteLetterRange::new(msrv)));
907     store.register_late_pass(|| Box::new(swap_ptr_to_ref::SwapPtrToRef));
908     store.register_late_pass(|| Box::new(mismatching_type_param_order::TypeParamMismatch));
909     store.register_late_pass(|| Box::new(as_underscore::AsUnderscore));
910     // add lints here, do not remove this comment, it's used in `new_lint`
911 }
912
913 #[rustfmt::skip]
914 fn register_removed_non_tool_lints(store: &mut rustc_lint::LintStore) {
915     store.register_removed(
916         "should_assert_eq",
917         "`assert!()` will be more flexible with RFC 2011",
918     );
919     store.register_removed(
920         "extend_from_slice",
921         "`.extend_from_slice(_)` is a faster way to extend a Vec by a slice",
922     );
923     store.register_removed(
924         "range_step_by_zero",
925         "`iterator.step_by(0)` panics nowadays",
926     );
927     store.register_removed(
928         "unstable_as_slice",
929         "`Vec::as_slice` has been stabilized in 1.7",
930     );
931     store.register_removed(
932         "unstable_as_mut_slice",
933         "`Vec::as_mut_slice` has been stabilized in 1.7",
934     );
935     store.register_removed(
936         "misaligned_transmute",
937         "this lint has been split into cast_ptr_alignment and transmute_ptr_to_ptr",
938     );
939     store.register_removed(
940         "assign_ops",
941         "using compound assignment operators (e.g., `+=`) is harmless",
942     );
943     store.register_removed(
944         "if_let_redundant_pattern_matching",
945         "this lint has been changed to redundant_pattern_matching",
946     );
947     store.register_removed(
948         "unsafe_vector_initialization",
949         "the replacement suggested by this lint had substantially different behavior",
950     );
951     store.register_removed(
952         "reverse_range_loop",
953         "this lint is now included in reversed_empty_ranges",
954     );
955 }
956
957 /// Register renamed lints.
958 ///
959 /// Used in `./src/driver.rs`.
960 pub fn register_renamed(ls: &mut rustc_lint::LintStore) {
961     for (old_name, new_name) in renamed_lints::RENAMED_LINTS {
962         ls.register_renamed(old_name, new_name);
963     }
964 }
965
966 // only exists to let the dogfood integration test works.
967 // Don't run clippy as an executable directly
968 #[allow(dead_code)]
969 fn main() {
970     panic!("Please use the cargo-clippy executable");
971 }