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(spec_option_partial_eq)]
38 #![feature(min_specialization)]
39 #![feature(never_type)]
40 #![recursion_limit = "256"]
43 extern crate rustc_middle;
45 extern crate rustc_session;
53 mod enum_intrinsics_non_enums;
56 mod for_loops_over_fallibles;
57 pub mod hidden_unicode_codepoints;
65 mod nonstandard_style;
67 mod opaque_hidden_inferred_bound;
70 mod redundant_semicolon;
75 pub use array_into_iter::ARRAY_INTO_ITER;
79 use rustc_hir::def_id::LocalDefId;
80 use rustc_middle::ty::query::Providers;
81 use rustc_middle::ty::TyCtxt;
82 use rustc_session::lint::builtin::{
83 BARE_TRAIT_OBJECTS, ELIDED_LIFETIMES_IN_PATHS, EXPLICIT_OUTLIVES_REQUIREMENTS,
85 use rustc_span::symbol::Ident;
88 use array_into_iter::ArrayIntoIter;
90 use enum_intrinsics_non_enums::EnumIntrinsicsNonEnums;
91 use for_loops_over_fallibles::*;
92 use hidden_unicode_codepoints::*;
94 use let_underscore::*;
96 use non_ascii_idents::*;
97 use non_fmt_panic::NonPanicFmt;
98 use nonstandard_style::*;
99 use noop_method_call::*;
100 use opaque_hidden_inferred_bound::*;
101 use pass_by_value::*;
102 use redundant_semicolon::*;
107 /// Useful for other parts of the compiler / Clippy.
108 pub use builtin::SoftLints;
109 pub use context::{CheckLintNameResult, FindLintError, LintStore};
110 pub use context::{EarlyContext, LateContext, LintContext};
111 pub use early::{check_ast_node, EarlyCheckNode};
112 pub use late::{check_crate, unerased_lint_store};
113 pub use passes::{EarlyLintPass, LateLintPass};
114 pub use rustc_session::lint::Level::{self, *};
115 pub use rustc_session::lint::{BufferedEarlyLint, FutureIncompatibleInfo, Lint, LintId};
116 pub use rustc_session::lint::{LintArray, LintPass};
118 pub fn provide(providers: &mut Providers) {
119 levels::provide(providers);
120 expect::provide(providers);
121 *providers = Providers { lint_mod, ..*providers };
124 fn lint_mod(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
125 late::late_lint_mod(tcx, module_def_id, BuiltinCombinedModuleLateLintPass::new());
128 macro_rules! pre_expansion_lint_passes {
129 ($macro:path, $args:tt) => {
130 $macro!($args, [KeywordIdents: KeywordIdents,]);
134 macro_rules! early_lint_passes {
135 ($macro:path, $args:tt) => {
139 UnusedParens: UnusedParens,
140 UnusedBraces: UnusedBraces,
141 UnusedImportBraces: UnusedImportBraces,
142 UnsafeCode: UnsafeCode,
143 SpecialModuleName: SpecialModuleName,
144 AnonymousParameters: AnonymousParameters,
145 EllipsisInclusiveRangePatterns: EllipsisInclusiveRangePatterns::default(),
146 NonCamelCaseTypes: NonCamelCaseTypes,
147 DeprecatedAttr: DeprecatedAttr::new(),
148 WhileTrue: WhileTrue,
149 NonAsciiIdents: NonAsciiIdents,
150 HiddenUnicodeCodepoints: HiddenUnicodeCodepoints,
151 IncompleteFeatures: IncompleteFeatures,
152 RedundantSemicolons: RedundantSemicolons,
153 UnusedDocComment: UnusedDocComment,
154 UnexpectedCfgs: UnexpectedCfgs,
160 macro_rules! declare_combined_early_pass {
161 ([$name:ident], $passes:tt) => (
162 early_lint_methods!(declare_combined_early_lint_pass, [pub $name, $passes]);
166 pre_expansion_lint_passes!(declare_combined_early_pass, [BuiltinCombinedPreExpansionLintPass]);
167 early_lint_passes!(declare_combined_early_pass, [BuiltinCombinedEarlyLintPass]);
169 macro_rules! late_lint_passes {
170 ($macro:path, $args:tt) => {
174 // Tracks state across modules
175 UnnameableTestItems: UnnameableTestItems::new(),
176 // Tracks attributes of parents
177 MissingDoc: MissingDoc::new(),
178 // Builds a global list of all impls of `Debug`.
179 // FIXME: Turn the computation of types which implement Debug into a query
180 // and change this to a module lint pass
181 MissingDebugImplementations: MissingDebugImplementations::default(),
182 // Keeps a global list of foreign declarations.
183 ClashingExternDeclarations: ClashingExternDeclarations::new(),
189 macro_rules! late_lint_mod_passes {
190 ($macro:path, $args:tt) => {
194 ForLoopsOverFallibles: ForLoopsOverFallibles,
195 HardwiredLints: HardwiredLints,
196 ImproperCTypesDeclarations: ImproperCTypesDeclarations,
197 ImproperCTypesDefinitions: ImproperCTypesDefinitions,
198 VariantSizeDifferences: VariantSizeDifferences,
199 BoxPointers: BoxPointers,
200 PathStatements: PathStatements,
201 LetUnderscore: LetUnderscore,
202 // Depends on referenced function signatures in expressions
203 UnusedResults: UnusedResults,
204 NonUpperCaseGlobals: NonUpperCaseGlobals,
205 NonShorthandFieldPatterns: NonShorthandFieldPatterns,
206 UnusedAllocation: UnusedAllocation,
207 // Depends on types used in type definitions
208 MissingCopyImplementations: MissingCopyImplementations,
209 // Depends on referenced function signatures in expressions
210 MutableTransmutes: MutableTransmutes,
211 TypeAliasBounds: TypeAliasBounds,
212 TrivialConstraints: TrivialConstraints,
213 TypeLimits: TypeLimits::new(),
214 NonSnakeCase: NonSnakeCase,
215 InvalidNoMangleItems: InvalidNoMangleItems,
216 // Depends on effective visibilities
217 UnreachablePub: UnreachablePub,
218 ExplicitOutlivesRequirements: ExplicitOutlivesRequirements,
219 InvalidValue: InvalidValue,
220 DerefNullPtr: DerefNullPtr,
221 // May Depend on constants elsewhere
222 UnusedBrokenConst: UnusedBrokenConst,
223 UnstableFeatures: UnstableFeatures,
224 ArrayIntoIter: ArrayIntoIter::default(),
225 DropTraitConstraints: DropTraitConstraints,
226 TemporaryCStringAsPtr: TemporaryCStringAsPtr,
227 NonPanicFmt: NonPanicFmt,
228 NoopMethodCall: NoopMethodCall,
229 EnumIntrinsicsNonEnums: EnumIntrinsicsNonEnums,
230 InvalidAtomicOrdering: InvalidAtomicOrdering,
231 NamedAsmLabels: NamedAsmLabels,
232 OpaqueHiddenInferredBound: OpaqueHiddenInferredBound,
238 macro_rules! declare_combined_late_pass {
239 ([$v:vis $name:ident], $passes:tt) => (
240 late_lint_methods!(declare_combined_late_lint_pass, [$v $name, $passes], ['tcx]);
244 // FIXME: Make a separate lint type which do not require typeck tables
245 late_lint_passes!(declare_combined_late_pass, [pub BuiltinCombinedLateLintPass]);
247 late_lint_mod_passes!(declare_combined_late_pass, [BuiltinCombinedModuleLateLintPass]);
249 pub fn new_lint_store(no_interleave_lints: bool, internal_lints: bool) -> LintStore {
250 let mut lint_store = LintStore::new();
252 register_builtins(&mut lint_store, no_interleave_lints);
254 register_internals(&mut lint_store);
260 /// Tell the `LintStore` about all the built-in lints (the ones
261 /// defined in this crate and the ones defined in
262 /// `rustc_session::lint::builtin`).
263 fn register_builtins(store: &mut LintStore, no_interleave_lints: bool) {
264 macro_rules! add_lint_group {
265 ($name:expr, $($lint:ident),*) => (
266 store.register_group(false, $name, None, vec![$(LintId::of($lint)),*]);
270 macro_rules! register_early_pass {
271 ($method:ident, $ty:ident, $constructor:expr) => {
272 store.register_lints(&$ty::get_lints());
273 store.$method(|| Box::new($constructor));
277 macro_rules! register_late_pass {
278 ($method:ident, $ty:ident, $constructor:expr) => {
279 store.register_lints(&$ty::get_lints());
280 store.$method(|_| Box::new($constructor));
284 macro_rules! register_early_passes {
285 ($method:ident, [$($passes:ident: $constructor:expr,)*]) => (
287 register_early_pass!($method, $passes, $constructor);
292 macro_rules! register_late_passes {
293 ($method:ident, [$($passes:ident: $constructor:expr,)*]) => (
295 register_late_pass!($method, $passes, $constructor);
300 if no_interleave_lints {
301 pre_expansion_lint_passes!(register_early_passes, register_pre_expansion_pass);
302 early_lint_passes!(register_early_passes, register_early_pass);
303 late_lint_passes!(register_late_passes, register_late_pass);
304 late_lint_mod_passes!(register_late_passes, register_late_mod_pass);
306 store.register_lints(&BuiltinCombinedPreExpansionLintPass::get_lints());
307 store.register_lints(&BuiltinCombinedEarlyLintPass::get_lints());
308 store.register_lints(&BuiltinCombinedModuleLateLintPass::get_lints());
309 store.register_lints(&BuiltinCombinedLateLintPass::get_lints());
314 NON_CAMEL_CASE_TYPES,
316 NON_UPPER_CASE_GLOBALS
327 UNREACHABLE_PATTERNS,
336 UNUSED_EXTERN_CRATES,
344 add_lint_group!("let_underscore", LET_UNDERSCORE_DROP, LET_UNDERSCORE_LOCK);
349 UNUSED_EXTERN_CRATES,
350 ELLIPSIS_INCLUSIVE_RANGE_PATTERNS,
351 ELIDED_LIFETIMES_IN_PATHS,
352 EXPLICIT_OUTLIVES_REQUIREMENTS // FIXME(#52665, #47816) not always applicable and not all
353 // macros are ready for this yet.
356 // FIXME macro crates are not up for this yet, too much
357 // breakage is seen if we try to encourage this lint.
358 // MACRO_USE_EXTERN_CRATE
361 // Register renamed and removed lints.
362 store.register_renamed("single_use_lifetime", "single_use_lifetimes");
363 store.register_renamed("elided_lifetime_in_path", "elided_lifetimes_in_paths");
364 store.register_renamed("bare_trait_object", "bare_trait_objects");
365 store.register_renamed("unstable_name_collision", "unstable_name_collisions");
366 store.register_renamed("unused_doc_comment", "unused_doc_comments");
367 store.register_renamed("async_idents", "keyword_idents");
368 store.register_renamed("exceeding_bitshifts", "arithmetic_overflow");
369 store.register_renamed("redundant_semicolon", "redundant_semicolons");
370 store.register_renamed("overlapping_patterns", "overlapping_range_endpoints");
371 store.register_renamed("safe_packed_borrows", "unaligned_references");
372 store.register_renamed("disjoint_capture_migration", "rust_2021_incompatible_closure_captures");
373 store.register_renamed("or_patterns_back_compat", "rust_2021_incompatible_or_patterns");
374 store.register_renamed("non_fmt_panic", "non_fmt_panics");
376 // These were moved to tool lints, but rustc still sees them when compiling normally, before
377 // tool lints are registered, so `check_tool_name_for_backwards_compat` doesn't work. Use
378 // `register_removed` explicitly.
379 const RUSTDOC_LINTS: &[&str] = &[
380 "broken_intra_doc_links",
381 "private_intra_doc_links",
382 "missing_crate_level_docs",
383 "missing_doc_code_examples",
385 "invalid_codeblock_attributes",
389 for rustdoc_lint in RUSTDOC_LINTS {
390 store.register_ignored(rustdoc_lint);
392 store.register_removed(
393 "intra_doc_link_resolution_failure",
394 "use `rustdoc::broken_intra_doc_links` instead",
396 store.register_removed("rustdoc", "use `rustdoc::all` instead");
398 store.register_removed("unknown_features", "replaced by an error");
399 store.register_removed("unsigned_negation", "replaced by negate_unsigned feature gate");
400 store.register_removed("negate_unsigned", "cast a signed value instead");
401 store.register_removed("raw_pointer_derive", "using derive with raw pointers is ok");
402 // Register lint group aliases.
403 store.register_group_alias("nonstandard_style", "bad_style");
404 // This was renamed to `raw_pointer_derive`, which was then removed,
405 // so it is also considered removed.
406 store.register_removed("raw_pointer_deriving", "using derive with raw pointers is ok");
407 store.register_removed("drop_with_repr_extern", "drop flags have been removed");
408 store.register_removed("fat_ptr_transmutes", "was accidentally removed back in 2014");
409 store.register_removed("deprecated_attr", "use `deprecated` instead");
410 store.register_removed(
411 "transmute_from_fn_item_types",
412 "always cast functions before transmuting them",
414 store.register_removed(
415 "hr_lifetime_in_assoc_type",
416 "converted into hard error, see issue #33685 \
417 <https://github.com/rust-lang/rust/issues/33685> for more information",
419 store.register_removed(
420 "inaccessible_extern_crate",
421 "converted into hard error, see issue #36886 \
422 <https://github.com/rust-lang/rust/issues/36886> for more information",
424 store.register_removed(
425 "super_or_self_in_global_path",
426 "converted into hard error, see issue #36888 \
427 <https://github.com/rust-lang/rust/issues/36888> for more information",
429 store.register_removed(
430 "overlapping_inherent_impls",
431 "converted into hard error, see issue #36889 \
432 <https://github.com/rust-lang/rust/issues/36889> for more information",
434 store.register_removed(
435 "illegal_floating_point_constant_pattern",
436 "converted into hard error, see issue #36890 \
437 <https://github.com/rust-lang/rust/issues/36890> for more information",
439 store.register_removed(
440 "illegal_struct_or_enum_constant_pattern",
441 "converted into hard error, see issue #36891 \
442 <https://github.com/rust-lang/rust/issues/36891> for more information",
444 store.register_removed(
445 "lifetime_underscore",
446 "converted into hard error, see issue #36892 \
447 <https://github.com/rust-lang/rust/issues/36892> for more information",
449 store.register_removed(
450 "extra_requirement_in_impl",
451 "converted into hard error, see issue #37166 \
452 <https://github.com/rust-lang/rust/issues/37166> for more information",
454 store.register_removed(
456 "converted into hard error, see issue #38260 \
457 <https://github.com/rust-lang/rust/issues/38260> for more information",
459 store.register_removed(
461 "converted into hard error, see issue #48950 \
462 <https://github.com/rust-lang/rust/issues/48950> for more information",
464 store.register_removed(
465 "resolve_trait_on_defaulted_unit",
466 "converted into hard error, see issue #48950 \
467 <https://github.com/rust-lang/rust/issues/48950> for more information",
469 store.register_removed(
470 "private_no_mangle_fns",
471 "no longer a warning, `#[no_mangle]` functions always exported",
473 store.register_removed(
474 "private_no_mangle_statics",
475 "no longer a warning, `#[no_mangle]` statics always exported",
477 store.register_removed("bad_repr", "replaced with a generic attribute input check");
478 store.register_removed(
479 "duplicate_matcher_binding_name",
480 "converted into hard error, see issue #57742 \
481 <https://github.com/rust-lang/rust/issues/57742> for more information",
483 store.register_removed(
484 "incoherent_fundamental_impls",
485 "converted into hard error, see issue #46205 \
486 <https://github.com/rust-lang/rust/issues/46205> for more information",
488 store.register_removed(
489 "legacy_constructor_visibility",
490 "converted into hard error, see issue #39207 \
491 <https://github.com/rust-lang/rust/issues/39207> for more information",
493 store.register_removed(
494 "legacy_directory_ownership",
495 "converted into hard error, see issue #37872 \
496 <https://github.com/rust-lang/rust/issues/37872> for more information",
498 store.register_removed(
499 "safe_extern_statics",
500 "converted into hard error, see issue #36247 \
501 <https://github.com/rust-lang/rust/issues/36247> for more information",
503 store.register_removed(
504 "parenthesized_params_in_types_and_modules",
505 "converted into hard error, see issue #42238 \
506 <https://github.com/rust-lang/rust/issues/42238> for more information",
508 store.register_removed(
509 "duplicate_macro_exports",
510 "converted into hard error, see issue #35896 \
511 <https://github.com/rust-lang/rust/issues/35896> for more information",
513 store.register_removed(
515 "converted into hard error, see issue #59014 \
516 <https://github.com/rust-lang/rust/issues/59014> for more information",
518 store.register_removed("plugin_as_library", "plugins have been deprecated and retired");
519 store.register_removed(
520 "unsupported_naked_functions",
521 "converted into hard error, see RFC 2972 \
522 <https://github.com/rust-lang/rfcs/blob/master/text/2972-constrained-naked.md> for more information",
524 store.register_removed(
525 "mutable_borrow_reservation_conflict",
526 "now allowed, see issue #59159 \
527 <https://github.com/rust-lang/rust/issues/59159> for more information",
529 store.register_removed(
531 "converted into hard error, see issue #71800 \
532 <https://github.com/rust-lang/rust/issues/71800> for more information",
536 fn register_internals(store: &mut LintStore) {
537 store.register_lints(&LintPassImpl::get_lints());
538 store.register_early_pass(|| Box::new(LintPassImpl));
539 store.register_lints(&DefaultHashTypes::get_lints());
540 store.register_late_pass(|_| Box::new(DefaultHashTypes));
541 store.register_lints(&QueryStability::get_lints());
542 store.register_late_pass(|_| Box::new(QueryStability));
543 store.register_lints(&ExistingDocKeyword::get_lints());
544 store.register_late_pass(|_| Box::new(ExistingDocKeyword));
545 store.register_lints(&TyTyKind::get_lints());
546 store.register_late_pass(|_| Box::new(TyTyKind));
547 store.register_lints(&Diagnostics::get_lints());
548 store.register_late_pass(|_| Box::new(Diagnostics));
549 store.register_lints(&BadOptAccess::get_lints());
550 store.register_late_pass(|_| Box::new(BadOptAccess));
551 store.register_lints(&PassByValue::get_lints());
552 store.register_late_pass(|_| Box::new(PassByValue));
553 // FIXME(davidtwco): deliberately do not include `UNTRANSLATABLE_DIAGNOSTIC` and
554 // `DIAGNOSTIC_OUTSIDE_OF_IMPL` here because `-Wrustc::internal` is provided to every crate and
555 // these lints will trigger all of the time - change this once migration to diagnostic structs
556 // and translation is completed
557 store.register_group(
562 LintId::of(DEFAULT_HASH_TYPES),
563 LintId::of(POTENTIAL_QUERY_INSTABILITY),
564 LintId::of(USAGE_OF_TY_TYKIND),
565 LintId::of(PASS_BY_VALUE),
566 LintId::of(LINT_PASS_IMPL_WITHOUT_MACRO),
567 LintId::of(USAGE_OF_QUALIFIED_TY),
568 LintId::of(EXISTING_DOC_KEYWORD),
569 LintId::of(BAD_OPT_ACCESS),