1 //! Lints, aka compiler warnings.
3 //! A 'lint' check is a kind of miscellaneous constraint that a user _might_
4 //! want to enforce, but might reasonably want to permit as well, on a
5 //! module-by-module basis. They contrast with static constraints enforced by
6 //! other phases of the compiler, which are generally required to hold in order
7 //! to compile the program at all.
9 //! Most lints can be written as [LintPass] instances. These run after
10 //! all other analyses. The `LintPass`es built into rustc are defined
11 //! within [rustc_session::lint::builtin],
12 //! which has further comments on how to add such a lint.
13 //! rustc can also load user-defined lint plugins via the plugin mechanism.
15 //! Some of rustc's lints are defined elsewhere in the compiler and work by
16 //! calling `add_lint()` on the overall `Session` object. This works when
17 //! it happens before the main lint pass, which emits the lints stored by
18 //! `add_lint()`. To emit lints after the main lint pass (from codegen, for
19 //! example) requires more effort. See `emit_lint` and `GatherNodeLevels`
22 //! Some code also exists in [rustc_session::lint], [rustc_middle::lint].
26 //! This API is completely unstable and subject to change.
28 #![allow(rustc::potential_query_instability)]
29 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
30 #![feature(array_windows)]
31 #![feature(box_patterns)]
32 #![feature(control_flow_enum)]
33 #![feature(if_let_guard)]
34 #![feature(iter_intersperse)]
35 #![feature(iter_order_by)]
36 #![feature(let_chains)]
37 #![feature(min_specialization)]
38 #![feature(never_type)]
39 #![feature(rustc_attrs)]
40 #![recursion_limit = "256"]
43 extern crate rustc_middle;
45 extern crate rustc_session;
52 mod deref_into_dyn_supertrait;
54 mod enum_intrinsics_non_enums;
57 mod for_loops_over_fallibles;
58 pub mod hidden_unicode_codepoints;
66 mod nonstandard_style;
68 mod opaque_hidden_inferred_bound;
71 mod redundant_semicolon;
76 pub use array_into_iter::ARRAY_INTO_ITER;
80 use rustc_hir::def_id::LocalDefId;
81 use rustc_middle::ty::query::Providers;
82 use rustc_middle::ty::TyCtxt;
83 use rustc_session::lint::builtin::{
84 BARE_TRAIT_OBJECTS, ELIDED_LIFETIMES_IN_PATHS, EXPLICIT_OUTLIVES_REQUIREMENTS,
86 use rustc_span::symbol::Ident;
89 use array_into_iter::ArrayIntoIter;
91 use deref_into_dyn_supertrait::*;
92 use enum_intrinsics_non_enums::EnumIntrinsicsNonEnums;
93 use for_loops_over_fallibles::*;
94 use hidden_unicode_codepoints::*;
96 use let_underscore::*;
98 use non_ascii_idents::*;
99 use non_fmt_panic::NonPanicFmt;
100 use nonstandard_style::*;
101 use noop_method_call::*;
102 use opaque_hidden_inferred_bound::*;
103 use pass_by_value::*;
104 use redundant_semicolon::*;
109 /// Useful for other parts of the compiler / Clippy.
110 pub use builtin::SoftLints;
111 pub use context::{CheckLintNameResult, FindLintError, LintStore};
112 pub use context::{EarlyContext, LateContext, LintContext};
113 pub use early::{check_ast_node, EarlyCheckNode};
114 pub use late::{check_crate, unerased_lint_store};
115 pub use passes::{EarlyLintPass, LateLintPass};
116 pub use rustc_session::lint::Level::{self, *};
117 pub use rustc_session::lint::{BufferedEarlyLint, FutureIncompatibleInfo, Lint, LintId};
118 pub use rustc_session::lint::{LintArray, LintPass};
120 pub fn provide(providers: &mut Providers) {
121 levels::provide(providers);
122 expect::provide(providers);
123 *providers = Providers { lint_mod, ..*providers };
126 fn lint_mod(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
127 late::late_lint_mod(tcx, module_def_id, BuiltinCombinedModuleLateLintPass::new());
130 macro_rules! pre_expansion_lint_passes {
131 ($macro:path, $args:tt) => {
132 $macro!($args, [KeywordIdents: KeywordIdents,]);
136 macro_rules! early_lint_passes {
137 ($macro:path, $args:tt) => {
141 UnusedParens: UnusedParens,
142 UnusedBraces: UnusedBraces,
143 UnusedImportBraces: UnusedImportBraces,
144 UnsafeCode: UnsafeCode,
145 SpecialModuleName: SpecialModuleName,
146 AnonymousParameters: AnonymousParameters,
147 EllipsisInclusiveRangePatterns: EllipsisInclusiveRangePatterns::default(),
148 NonCamelCaseTypes: NonCamelCaseTypes,
149 DeprecatedAttr: DeprecatedAttr::new(),
150 WhileTrue: WhileTrue,
151 NonAsciiIdents: NonAsciiIdents,
152 HiddenUnicodeCodepoints: HiddenUnicodeCodepoints,
153 IncompleteFeatures: IncompleteFeatures,
154 RedundantSemicolons: RedundantSemicolons,
155 UnusedDocComment: UnusedDocComment,
156 UnexpectedCfgs: UnexpectedCfgs,
162 macro_rules! declare_combined_early_pass {
163 ([$name:ident], $passes:tt) => (
164 early_lint_methods!(declare_combined_early_lint_pass, [pub $name, $passes]);
168 pre_expansion_lint_passes!(declare_combined_early_pass, [BuiltinCombinedPreExpansionLintPass]);
169 early_lint_passes!(declare_combined_early_pass, [BuiltinCombinedEarlyLintPass]);
171 macro_rules! late_lint_passes {
172 ($macro:path, $args:tt) => {
176 // Tracks state across modules
177 UnnameableTestItems: UnnameableTestItems::new(),
178 // Tracks attributes of parents
179 MissingDoc: MissingDoc::new(),
180 // Builds a global list of all impls of `Debug`.
181 // FIXME: Turn the computation of types which implement Debug into a query
182 // and change this to a module lint pass
183 MissingDebugImplementations: MissingDebugImplementations::default(),
184 // Keeps a global list of foreign declarations.
185 ClashingExternDeclarations: ClashingExternDeclarations::new(),
191 macro_rules! late_lint_mod_passes {
192 ($macro:path, $args:tt) => {
196 ForLoopsOverFallibles: ForLoopsOverFallibles,
197 DerefIntoDynSupertrait: DerefIntoDynSupertrait,
198 HardwiredLints: HardwiredLints,
199 ImproperCTypesDeclarations: ImproperCTypesDeclarations,
200 ImproperCTypesDefinitions: ImproperCTypesDefinitions,
201 VariantSizeDifferences: VariantSizeDifferences,
202 BoxPointers: BoxPointers,
203 PathStatements: PathStatements,
204 LetUnderscore: LetUnderscore,
205 // Depends on referenced function signatures in expressions
206 UnusedResults: UnusedResults,
207 NonUpperCaseGlobals: NonUpperCaseGlobals,
208 NonShorthandFieldPatterns: NonShorthandFieldPatterns,
209 UnusedAllocation: UnusedAllocation,
210 // Depends on types used in type definitions
211 MissingCopyImplementations: MissingCopyImplementations,
212 // Depends on referenced function signatures in expressions
213 MutableTransmutes: MutableTransmutes,
214 TypeAliasBounds: TypeAliasBounds,
215 TrivialConstraints: TrivialConstraints,
216 TypeLimits: TypeLimits::new(),
217 NonSnakeCase: NonSnakeCase,
218 InvalidNoMangleItems: InvalidNoMangleItems,
219 // Depends on effective visibilities
220 UnreachablePub: UnreachablePub,
221 ExplicitOutlivesRequirements: ExplicitOutlivesRequirements,
222 InvalidValue: InvalidValue,
223 DerefNullPtr: DerefNullPtr,
224 // May Depend on constants elsewhere
225 UnusedBrokenConst: UnusedBrokenConst,
226 UnstableFeatures: UnstableFeatures,
227 ArrayIntoIter: ArrayIntoIter::default(),
228 DropTraitConstraints: DropTraitConstraints,
229 TemporaryCStringAsPtr: TemporaryCStringAsPtr,
230 NonPanicFmt: NonPanicFmt,
231 NoopMethodCall: NoopMethodCall,
232 EnumIntrinsicsNonEnums: EnumIntrinsicsNonEnums,
233 InvalidAtomicOrdering: InvalidAtomicOrdering,
234 NamedAsmLabels: NamedAsmLabels,
235 OpaqueHiddenInferredBound: OpaqueHiddenInferredBound,
241 macro_rules! declare_combined_late_pass {
242 ([$v:vis $name:ident], $passes:tt) => (
243 late_lint_methods!(declare_combined_late_lint_pass, [$v $name, $passes], ['tcx]);
247 // FIXME: Make a separate lint type which do not require typeck tables
248 late_lint_passes!(declare_combined_late_pass, [pub BuiltinCombinedLateLintPass]);
250 late_lint_mod_passes!(declare_combined_late_pass, [BuiltinCombinedModuleLateLintPass]);
252 pub fn new_lint_store(no_interleave_lints: bool, internal_lints: bool) -> LintStore {
253 let mut lint_store = LintStore::new();
255 register_builtins(&mut lint_store, no_interleave_lints);
257 register_internals(&mut lint_store);
263 /// Tell the `LintStore` about all the built-in lints (the ones
264 /// defined in this crate and the ones defined in
265 /// `rustc_session::lint::builtin`).
266 fn register_builtins(store: &mut LintStore, no_interleave_lints: bool) {
267 macro_rules! add_lint_group {
268 ($name:expr, $($lint:ident),*) => (
269 store.register_group(false, $name, None, vec![$(LintId::of($lint)),*]);
273 macro_rules! register_early_pass {
274 ($method:ident, $ty:ident, $constructor:expr) => {
275 store.register_lints(&$ty::get_lints());
276 store.$method(|| Box::new($constructor));
280 macro_rules! register_late_pass {
281 ($method:ident, $ty:ident, $constructor:expr) => {
282 store.register_lints(&$ty::get_lints());
283 store.$method(|_| Box::new($constructor));
287 macro_rules! register_early_passes {
288 ($method:ident, [$($passes:ident: $constructor:expr,)*]) => (
290 register_early_pass!($method, $passes, $constructor);
295 macro_rules! register_late_passes {
296 ($method:ident, [$($passes:ident: $constructor:expr,)*]) => (
298 register_late_pass!($method, $passes, $constructor);
303 if no_interleave_lints {
304 pre_expansion_lint_passes!(register_early_passes, register_pre_expansion_pass);
305 early_lint_passes!(register_early_passes, register_early_pass);
306 late_lint_passes!(register_late_passes, register_late_pass);
307 late_lint_mod_passes!(register_late_passes, register_late_mod_pass);
309 store.register_lints(&BuiltinCombinedPreExpansionLintPass::get_lints());
310 store.register_lints(&BuiltinCombinedEarlyLintPass::get_lints());
311 store.register_lints(&BuiltinCombinedModuleLateLintPass::get_lints());
312 store.register_lints(&BuiltinCombinedLateLintPass::get_lints());
317 NON_CAMEL_CASE_TYPES,
319 NON_UPPER_CASE_GLOBALS
330 UNREACHABLE_PATTERNS,
339 UNUSED_EXTERN_CRATES,
347 add_lint_group!("let_underscore", LET_UNDERSCORE_DROP, LET_UNDERSCORE_LOCK);
352 UNUSED_EXTERN_CRATES,
353 ELLIPSIS_INCLUSIVE_RANGE_PATTERNS,
354 ELIDED_LIFETIMES_IN_PATHS,
355 EXPLICIT_OUTLIVES_REQUIREMENTS // FIXME(#52665, #47816) not always applicable and not all
356 // macros are ready for this yet.
359 // FIXME macro crates are not up for this yet, too much
360 // breakage is seen if we try to encourage this lint.
361 // MACRO_USE_EXTERN_CRATE
364 // Register renamed and removed lints.
365 store.register_renamed("single_use_lifetime", "single_use_lifetimes");
366 store.register_renamed("elided_lifetime_in_path", "elided_lifetimes_in_paths");
367 store.register_renamed("bare_trait_object", "bare_trait_objects");
368 store.register_renamed("unstable_name_collision", "unstable_name_collisions");
369 store.register_renamed("unused_doc_comment", "unused_doc_comments");
370 store.register_renamed("async_idents", "keyword_idents");
371 store.register_renamed("exceeding_bitshifts", "arithmetic_overflow");
372 store.register_renamed("redundant_semicolon", "redundant_semicolons");
373 store.register_renamed("overlapping_patterns", "overlapping_range_endpoints");
374 store.register_renamed("safe_packed_borrows", "unaligned_references");
375 store.register_renamed("disjoint_capture_migration", "rust_2021_incompatible_closure_captures");
376 store.register_renamed("or_patterns_back_compat", "rust_2021_incompatible_or_patterns");
377 store.register_renamed("non_fmt_panic", "non_fmt_panics");
379 // These were moved to tool lints, but rustc still sees them when compiling normally, before
380 // tool lints are registered, so `check_tool_name_for_backwards_compat` doesn't work. Use
381 // `register_removed` explicitly.
382 const RUSTDOC_LINTS: &[&str] = &[
383 "broken_intra_doc_links",
384 "private_intra_doc_links",
385 "missing_crate_level_docs",
386 "missing_doc_code_examples",
388 "invalid_codeblock_attributes",
392 for rustdoc_lint in RUSTDOC_LINTS {
393 store.register_ignored(rustdoc_lint);
395 store.register_removed(
396 "intra_doc_link_resolution_failure",
397 "use `rustdoc::broken_intra_doc_links` instead",
399 store.register_removed("rustdoc", "use `rustdoc::all` instead");
401 store.register_removed("unknown_features", "replaced by an error");
402 store.register_removed("unsigned_negation", "replaced by negate_unsigned feature gate");
403 store.register_removed("negate_unsigned", "cast a signed value instead");
404 store.register_removed("raw_pointer_derive", "using derive with raw pointers is ok");
405 // Register lint group aliases.
406 store.register_group_alias("nonstandard_style", "bad_style");
407 // This was renamed to `raw_pointer_derive`, which was then removed,
408 // so it is also considered removed.
409 store.register_removed("raw_pointer_deriving", "using derive with raw pointers is ok");
410 store.register_removed("drop_with_repr_extern", "drop flags have been removed");
411 store.register_removed("fat_ptr_transmutes", "was accidentally removed back in 2014");
412 store.register_removed("deprecated_attr", "use `deprecated` instead");
413 store.register_removed(
414 "transmute_from_fn_item_types",
415 "always cast functions before transmuting them",
417 store.register_removed(
418 "hr_lifetime_in_assoc_type",
419 "converted into hard error, see issue #33685 \
420 <https://github.com/rust-lang/rust/issues/33685> for more information",
422 store.register_removed(
423 "inaccessible_extern_crate",
424 "converted into hard error, see issue #36886 \
425 <https://github.com/rust-lang/rust/issues/36886> for more information",
427 store.register_removed(
428 "super_or_self_in_global_path",
429 "converted into hard error, see issue #36888 \
430 <https://github.com/rust-lang/rust/issues/36888> for more information",
432 store.register_removed(
433 "overlapping_inherent_impls",
434 "converted into hard error, see issue #36889 \
435 <https://github.com/rust-lang/rust/issues/36889> for more information",
437 store.register_removed(
438 "illegal_floating_point_constant_pattern",
439 "converted into hard error, see issue #36890 \
440 <https://github.com/rust-lang/rust/issues/36890> for more information",
442 store.register_removed(
443 "illegal_struct_or_enum_constant_pattern",
444 "converted into hard error, see issue #36891 \
445 <https://github.com/rust-lang/rust/issues/36891> for more information",
447 store.register_removed(
448 "lifetime_underscore",
449 "converted into hard error, see issue #36892 \
450 <https://github.com/rust-lang/rust/issues/36892> for more information",
452 store.register_removed(
453 "extra_requirement_in_impl",
454 "converted into hard error, see issue #37166 \
455 <https://github.com/rust-lang/rust/issues/37166> for more information",
457 store.register_removed(
459 "converted into hard error, see issue #38260 \
460 <https://github.com/rust-lang/rust/issues/38260> for more information",
462 store.register_removed(
464 "converted into hard error, see issue #48950 \
465 <https://github.com/rust-lang/rust/issues/48950> for more information",
467 store.register_removed(
468 "resolve_trait_on_defaulted_unit",
469 "converted into hard error, see issue #48950 \
470 <https://github.com/rust-lang/rust/issues/48950> for more information",
472 store.register_removed(
473 "private_no_mangle_fns",
474 "no longer a warning, `#[no_mangle]` functions always exported",
476 store.register_removed(
477 "private_no_mangle_statics",
478 "no longer a warning, `#[no_mangle]` statics always exported",
480 store.register_removed("bad_repr", "replaced with a generic attribute input check");
481 store.register_removed(
482 "duplicate_matcher_binding_name",
483 "converted into hard error, see issue #57742 \
484 <https://github.com/rust-lang/rust/issues/57742> for more information",
486 store.register_removed(
487 "incoherent_fundamental_impls",
488 "converted into hard error, see issue #46205 \
489 <https://github.com/rust-lang/rust/issues/46205> for more information",
491 store.register_removed(
492 "legacy_constructor_visibility",
493 "converted into hard error, see issue #39207 \
494 <https://github.com/rust-lang/rust/issues/39207> for more information",
496 store.register_removed(
497 "legacy_directory_ownership",
498 "converted into hard error, see issue #37872 \
499 <https://github.com/rust-lang/rust/issues/37872> for more information",
501 store.register_removed(
502 "safe_extern_statics",
503 "converted into hard error, see issue #36247 \
504 <https://github.com/rust-lang/rust/issues/36247> for more information",
506 store.register_removed(
507 "parenthesized_params_in_types_and_modules",
508 "converted into hard error, see issue #42238 \
509 <https://github.com/rust-lang/rust/issues/42238> for more information",
511 store.register_removed(
512 "duplicate_macro_exports",
513 "converted into hard error, see issue #35896 \
514 <https://github.com/rust-lang/rust/issues/35896> for more information",
516 store.register_removed(
518 "converted into hard error, see issue #59014 \
519 <https://github.com/rust-lang/rust/issues/59014> for more information",
521 store.register_removed("plugin_as_library", "plugins have been deprecated and retired");
522 store.register_removed(
523 "unsupported_naked_functions",
524 "converted into hard error, see RFC 2972 \
525 <https://github.com/rust-lang/rfcs/blob/master/text/2972-constrained-naked.md> for more information",
527 store.register_removed(
528 "mutable_borrow_reservation_conflict",
529 "now allowed, see issue #59159 \
530 <https://github.com/rust-lang/rust/issues/59159> for more information",
532 store.register_removed(
534 "converted into hard error, see issue #71800 \
535 <https://github.com/rust-lang/rust/issues/71800> for more information",
539 fn register_internals(store: &mut LintStore) {
540 store.register_lints(&LintPassImpl::get_lints());
541 store.register_early_pass(|| Box::new(LintPassImpl));
542 store.register_lints(&DefaultHashTypes::get_lints());
543 store.register_late_pass(|_| Box::new(DefaultHashTypes));
544 store.register_lints(&QueryStability::get_lints());
545 store.register_late_pass(|_| Box::new(QueryStability));
546 store.register_lints(&ExistingDocKeyword::get_lints());
547 store.register_late_pass(|_| Box::new(ExistingDocKeyword));
548 store.register_lints(&TyTyKind::get_lints());
549 store.register_late_pass(|_| Box::new(TyTyKind));
550 store.register_lints(&Diagnostics::get_lints());
551 store.register_late_pass(|_| Box::new(Diagnostics));
552 store.register_lints(&BadOptAccess::get_lints());
553 store.register_late_pass(|_| Box::new(BadOptAccess));
554 store.register_lints(&PassByValue::get_lints());
555 store.register_late_pass(|_| Box::new(PassByValue));
556 // FIXME(davidtwco): deliberately do not include `UNTRANSLATABLE_DIAGNOSTIC` and
557 // `DIAGNOSTIC_OUTSIDE_OF_IMPL` here because `-Wrustc::internal` is provided to every crate and
558 // these lints will trigger all of the time - change this once migration to diagnostic structs
559 // and translation is completed
560 store.register_group(
565 LintId::of(DEFAULT_HASH_TYPES),
566 LintId::of(POTENTIAL_QUERY_INSTABILITY),
567 LintId::of(USAGE_OF_TY_TYKIND),
568 LintId::of(PASS_BY_VALUE),
569 LintId::of(LINT_PASS_IMPL_WITHOUT_MACRO),
570 LintId::of(USAGE_OF_QUALIFIED_TY),
571 LintId::of(EXISTING_DOC_KEYWORD),
572 LintId::of(BAD_OPT_ACCESS),