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)]
38 #![feature(never_type)]
39 #![recursion_limit = "256"]
42 extern crate rustc_middle;
44 extern crate rustc_session;
50 mod enum_intrinsics_non_enums;
53 pub mod hidden_unicode_codepoints;
60 mod nonstandard_style;
64 mod redundant_semicolon;
69 pub use array_into_iter::ARRAY_INTO_ITER;
73 use rustc_hir::def_id::LocalDefId;
74 use rustc_middle::ty::query::Providers;
75 use rustc_middle::ty::TyCtxt;
76 use rustc_session::lint::builtin::{
77 BARE_TRAIT_OBJECTS, ELIDED_LIFETIMES_IN_PATHS, EXPLICIT_OUTLIVES_REQUIREMENTS,
79 use rustc_span::symbol::Ident;
82 use array_into_iter::ArrayIntoIter;
84 use enum_intrinsics_non_enums::EnumIntrinsicsNonEnums;
85 use hidden_unicode_codepoints::*;
88 use non_ascii_idents::*;
89 use non_fmt_panic::NonPanicFmt;
90 use nonstandard_style::*;
91 use noop_method_call::*;
93 use redundant_semicolon::*;
98 /// Useful for other parts of the compiler / Clippy.
99 pub use builtin::SoftLints;
100 pub use context::{CheckLintNameResult, FindLintError, LintStore};
101 pub use context::{EarlyContext, LateContext, LintContext};
102 pub use early::{check_ast_node, EarlyCheckNode};
103 pub use late::{check_crate, unerased_lint_store};
104 pub use passes::{EarlyLintPass, LateLintPass};
105 pub use rustc_session::lint::Level::{self, *};
106 pub use rustc_session::lint::{BufferedEarlyLint, FutureIncompatibleInfo, Lint, LintId};
107 pub use rustc_session::lint::{LintArray, LintPass};
109 pub fn provide(providers: &mut Providers) {
110 levels::provide(providers);
111 expect::provide(providers);
112 *providers = Providers { lint_mod, ..*providers };
115 fn lint_mod(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
116 late::late_lint_mod(tcx, module_def_id, BuiltinCombinedModuleLateLintPass::new());
119 macro_rules! pre_expansion_lint_passes {
120 ($macro:path, $args:tt) => {
121 $macro!($args, [KeywordIdents: KeywordIdents,]);
125 macro_rules! early_lint_passes {
126 ($macro:path, $args:tt) => {
130 UnusedParens: UnusedParens,
131 UnusedBraces: UnusedBraces,
132 UnusedImportBraces: UnusedImportBraces,
133 UnsafeCode: UnsafeCode,
134 AnonymousParameters: AnonymousParameters,
135 EllipsisInclusiveRangePatterns: EllipsisInclusiveRangePatterns::default(),
136 NonCamelCaseTypes: NonCamelCaseTypes,
137 DeprecatedAttr: DeprecatedAttr::new(),
138 WhileTrue: WhileTrue,
139 NonAsciiIdents: NonAsciiIdents,
140 HiddenUnicodeCodepoints: HiddenUnicodeCodepoints,
141 IncompleteFeatures: IncompleteFeatures,
142 RedundantSemicolons: RedundantSemicolons,
143 UnusedDocComment: UnusedDocComment,
149 macro_rules! declare_combined_early_pass {
150 ([$name:ident], $passes:tt) => (
151 early_lint_methods!(declare_combined_early_lint_pass, [pub $name, $passes]);
155 pre_expansion_lint_passes!(declare_combined_early_pass, [BuiltinCombinedPreExpansionLintPass]);
156 early_lint_passes!(declare_combined_early_pass, [BuiltinCombinedEarlyLintPass]);
158 macro_rules! late_lint_passes {
159 ($macro:path, $args:tt) => {
163 // Tracks state across modules
164 UnnameableTestItems: UnnameableTestItems::new(),
165 // Tracks attributes of parents
166 MissingDoc: MissingDoc::new(),
167 // Builds a global list of all impls of `Debug`.
168 // FIXME: Turn the computation of types which implement Debug into a query
169 // and change this to a module lint pass
170 MissingDebugImplementations: MissingDebugImplementations::default(),
171 // Keeps a global list of foreign declarations.
172 ClashingExternDeclarations: ClashingExternDeclarations::new(),
178 macro_rules! late_lint_mod_passes {
179 ($macro:path, $args:tt) => {
183 HardwiredLints: HardwiredLints,
184 ImproperCTypesDeclarations: ImproperCTypesDeclarations,
185 ImproperCTypesDefinitions: ImproperCTypesDefinitions,
186 VariantSizeDifferences: VariantSizeDifferences,
187 BoxPointers: BoxPointers,
188 PathStatements: PathStatements,
189 // Depends on referenced function signatures in expressions
190 UnusedResults: UnusedResults,
191 NonUpperCaseGlobals: NonUpperCaseGlobals,
192 NonShorthandFieldPatterns: NonShorthandFieldPatterns,
193 UnusedAllocation: UnusedAllocation,
194 // Depends on types used in type definitions
195 MissingCopyImplementations: MissingCopyImplementations,
196 // Depends on referenced function signatures in expressions
197 MutableTransmutes: MutableTransmutes,
198 TypeAliasBounds: TypeAliasBounds,
199 TrivialConstraints: TrivialConstraints,
200 TypeLimits: TypeLimits::new(),
201 NonSnakeCase: NonSnakeCase,
202 InvalidNoMangleItems: InvalidNoMangleItems,
203 // Depends on access levels
204 UnreachablePub: UnreachablePub,
205 ExplicitOutlivesRequirements: ExplicitOutlivesRequirements,
206 InvalidValue: InvalidValue,
207 DerefNullPtr: DerefNullPtr,
208 // May Depend on constants elsewhere
209 UnusedBrokenConst: UnusedBrokenConst,
210 UnstableFeatures: UnstableFeatures,
211 ArrayIntoIter: ArrayIntoIter::default(),
212 DropTraitConstraints: DropTraitConstraints,
213 TemporaryCStringAsPtr: TemporaryCStringAsPtr,
214 NonPanicFmt: NonPanicFmt,
215 NoopMethodCall: NoopMethodCall,
216 EnumIntrinsicsNonEnums: EnumIntrinsicsNonEnums,
217 InvalidAtomicOrdering: InvalidAtomicOrdering,
218 NamedAsmLabels: NamedAsmLabels,
224 macro_rules! declare_combined_late_pass {
225 ([$v:vis $name:ident], $passes:tt) => (
226 late_lint_methods!(declare_combined_late_lint_pass, [$v $name, $passes], ['tcx]);
230 // FIXME: Make a separate lint type which do not require typeck tables
231 late_lint_passes!(declare_combined_late_pass, [pub BuiltinCombinedLateLintPass]);
233 late_lint_mod_passes!(declare_combined_late_pass, [BuiltinCombinedModuleLateLintPass]);
235 pub fn new_lint_store(no_interleave_lints: bool, internal_lints: bool) -> LintStore {
236 let mut lint_store = LintStore::new();
238 register_builtins(&mut lint_store, no_interleave_lints);
240 register_internals(&mut lint_store);
246 /// Tell the `LintStore` about all the built-in lints (the ones
247 /// defined in this crate and the ones defined in
248 /// `rustc_session::lint::builtin`).
249 fn register_builtins(store: &mut LintStore, no_interleave_lints: bool) {
250 macro_rules! add_lint_group {
251 ($name:expr, $($lint:ident),*) => (
252 store.register_group(false, $name, None, vec![$(LintId::of($lint)),*]);
256 macro_rules! register_pass {
257 ($method:ident, $ty:ident, $constructor:expr) => {
258 store.register_lints(&$ty::get_lints());
259 store.$method(|| Box::new($constructor));
263 macro_rules! register_passes {
264 ($method:ident, [$($passes:ident: $constructor:expr,)*]) => (
266 register_pass!($method, $passes, $constructor);
271 if no_interleave_lints {
272 pre_expansion_lint_passes!(register_passes, register_pre_expansion_pass);
273 early_lint_passes!(register_passes, register_early_pass);
274 late_lint_passes!(register_passes, register_late_pass);
275 late_lint_mod_passes!(register_passes, register_late_mod_pass);
277 store.register_lints(&BuiltinCombinedPreExpansionLintPass::get_lints());
278 store.register_lints(&BuiltinCombinedEarlyLintPass::get_lints());
279 store.register_lints(&BuiltinCombinedModuleLateLintPass::get_lints());
280 store.register_lints(&BuiltinCombinedLateLintPass::get_lints());
285 NON_CAMEL_CASE_TYPES,
287 NON_UPPER_CASE_GLOBALS
298 UNREACHABLE_PATTERNS,
307 UNUSED_EXTERN_CRATES,
318 UNUSED_EXTERN_CRATES,
319 ELLIPSIS_INCLUSIVE_RANGE_PATTERNS,
320 ELIDED_LIFETIMES_IN_PATHS,
321 EXPLICIT_OUTLIVES_REQUIREMENTS // FIXME(#52665, #47816) not always applicable and not all
322 // macros are ready for this yet.
325 // FIXME macro crates are not up for this yet, too much
326 // breakage is seen if we try to encourage this lint.
327 // MACRO_USE_EXTERN_CRATE
330 // Register renamed and removed lints.
331 store.register_renamed("single_use_lifetime", "single_use_lifetimes");
332 store.register_renamed("elided_lifetime_in_path", "elided_lifetimes_in_paths");
333 store.register_renamed("bare_trait_object", "bare_trait_objects");
334 store.register_renamed("unstable_name_collision", "unstable_name_collisions");
335 store.register_renamed("unused_doc_comment", "unused_doc_comments");
336 store.register_renamed("async_idents", "keyword_idents");
337 store.register_renamed("exceeding_bitshifts", "arithmetic_overflow");
338 store.register_renamed("redundant_semicolon", "redundant_semicolons");
339 store.register_renamed("overlapping_patterns", "overlapping_range_endpoints");
340 store.register_renamed("safe_packed_borrows", "unaligned_references");
341 store.register_renamed("disjoint_capture_migration", "rust_2021_incompatible_closure_captures");
342 store.register_renamed("or_patterns_back_compat", "rust_2021_incompatible_or_patterns");
343 store.register_renamed("non_fmt_panic", "non_fmt_panics");
345 // These were moved to tool lints, but rustc still sees them when compiling normally, before
346 // tool lints are registered, so `check_tool_name_for_backwards_compat` doesn't work. Use
347 // `register_removed` explicitly.
348 const RUSTDOC_LINTS: &[&str] = &[
349 "broken_intra_doc_links",
350 "private_intra_doc_links",
351 "missing_crate_level_docs",
352 "missing_doc_code_examples",
354 "invalid_codeblock_attributes",
358 for rustdoc_lint in RUSTDOC_LINTS {
359 store.register_ignored(rustdoc_lint);
361 store.register_removed(
362 "intra_doc_link_resolution_failure",
363 "use `rustdoc::broken_intra_doc_links` instead",
365 store.register_removed("rustdoc", "use `rustdoc::all` instead");
367 store.register_removed("unknown_features", "replaced by an error");
368 store.register_removed("unsigned_negation", "replaced by negate_unsigned feature gate");
369 store.register_removed("negate_unsigned", "cast a signed value instead");
370 store.register_removed("raw_pointer_derive", "using derive with raw pointers is ok");
371 // Register lint group aliases.
372 store.register_group_alias("nonstandard_style", "bad_style");
373 // This was renamed to `raw_pointer_derive`, which was then removed,
374 // so it is also considered removed.
375 store.register_removed("raw_pointer_deriving", "using derive with raw pointers is ok");
376 store.register_removed("drop_with_repr_extern", "drop flags have been removed");
377 store.register_removed("fat_ptr_transmutes", "was accidentally removed back in 2014");
378 store.register_removed("deprecated_attr", "use `deprecated` instead");
379 store.register_removed(
380 "transmute_from_fn_item_types",
381 "always cast functions before transmuting them",
383 store.register_removed(
384 "hr_lifetime_in_assoc_type",
385 "converted into hard error, see issue #33685 \
386 <https://github.com/rust-lang/rust/issues/33685> for more information",
388 store.register_removed(
389 "inaccessible_extern_crate",
390 "converted into hard error, see issue #36886 \
391 <https://github.com/rust-lang/rust/issues/36886> for more information",
393 store.register_removed(
394 "super_or_self_in_global_path",
395 "converted into hard error, see issue #36888 \
396 <https://github.com/rust-lang/rust/issues/36888> for more information",
398 store.register_removed(
399 "overlapping_inherent_impls",
400 "converted into hard error, see issue #36889 \
401 <https://github.com/rust-lang/rust/issues/36889> for more information",
403 store.register_removed(
404 "illegal_floating_point_constant_pattern",
405 "converted into hard error, see issue #36890 \
406 <https://github.com/rust-lang/rust/issues/36890> for more information",
408 store.register_removed(
409 "illegal_struct_or_enum_constant_pattern",
410 "converted into hard error, see issue #36891 \
411 <https://github.com/rust-lang/rust/issues/36891> for more information",
413 store.register_removed(
414 "lifetime_underscore",
415 "converted into hard error, see issue #36892 \
416 <https://github.com/rust-lang/rust/issues/36892> for more information",
418 store.register_removed(
419 "extra_requirement_in_impl",
420 "converted into hard error, see issue #37166 \
421 <https://github.com/rust-lang/rust/issues/37166> for more information",
423 store.register_removed(
425 "converted into hard error, see issue #38260 \
426 <https://github.com/rust-lang/rust/issues/38260> for more information",
428 store.register_removed(
430 "converted into hard error, see issue #48950 \
431 <https://github.com/rust-lang/rust/issues/48950> for more information",
433 store.register_removed(
434 "resolve_trait_on_defaulted_unit",
435 "converted into hard error, see issue #48950 \
436 <https://github.com/rust-lang/rust/issues/48950> for more information",
438 store.register_removed(
439 "private_no_mangle_fns",
440 "no longer a warning, `#[no_mangle]` functions always exported",
442 store.register_removed(
443 "private_no_mangle_statics",
444 "no longer a warning, `#[no_mangle]` statics always exported",
446 store.register_removed("bad_repr", "replaced with a generic attribute input check");
447 store.register_removed(
448 "duplicate_matcher_binding_name",
449 "converted into hard error, see issue #57742 \
450 <https://github.com/rust-lang/rust/issues/57742> for more information",
452 store.register_removed(
453 "incoherent_fundamental_impls",
454 "converted into hard error, see issue #46205 \
455 <https://github.com/rust-lang/rust/issues/46205> for more information",
457 store.register_removed(
458 "legacy_constructor_visibility",
459 "converted into hard error, see issue #39207 \
460 <https://github.com/rust-lang/rust/issues/39207> for more information",
462 store.register_removed(
463 "legacy_directory_ownership",
464 "converted into hard error, see issue #37872 \
465 <https://github.com/rust-lang/rust/issues/37872> for more information",
467 store.register_removed(
468 "safe_extern_statics",
469 "converted into hard error, see issue #36247 \
470 <https://github.com/rust-lang/rust/issues/36247> for more information",
472 store.register_removed(
473 "parenthesized_params_in_types_and_modules",
474 "converted into hard error, see issue #42238 \
475 <https://github.com/rust-lang/rust/issues/42238> for more information",
477 store.register_removed(
478 "duplicate_macro_exports",
479 "converted into hard error, see issue #35896 \
480 <https://github.com/rust-lang/rust/issues/35896> for more information",
482 store.register_removed(
484 "converted into hard error, see issue #59014 \
485 <https://github.com/rust-lang/rust/issues/59014> for more information",
487 store.register_removed("plugin_as_library", "plugins have been deprecated and retired");
488 store.register_removed(
489 "unsupported_naked_functions",
490 "converted into hard error, see RFC 2972 \
491 <https://github.com/rust-lang/rfcs/blob/master/text/2972-constrained-naked.md> for more information",
493 store.register_removed(
494 "mutable_borrow_reservation_conflict",
495 "now allowed, see issue #59159 \
496 <https://github.com/rust-lang/rust/issues/59159> for more information",
500 fn register_internals(store: &mut LintStore) {
501 store.register_lints(&LintPassImpl::get_lints());
502 store.register_early_pass(|| Box::new(LintPassImpl));
503 store.register_lints(&DefaultHashTypes::get_lints());
504 store.register_late_pass(|| Box::new(DefaultHashTypes));
505 store.register_lints(&QueryStability::get_lints());
506 store.register_late_pass(|| Box::new(QueryStability));
507 store.register_lints(&ExistingDocKeyword::get_lints());
508 store.register_late_pass(|| Box::new(ExistingDocKeyword));
509 store.register_lints(&TyTyKind::get_lints());
510 store.register_late_pass(|| Box::new(TyTyKind));
511 store.register_lints(&Diagnostics::get_lints());
512 store.register_late_pass(|| Box::new(Diagnostics));
513 store.register_lints(&BadOptAccess::get_lints());
514 store.register_late_pass(|| Box::new(BadOptAccess));
515 store.register_lints(&PassByValue::get_lints());
516 store.register_late_pass(|| Box::new(PassByValue));
517 // FIXME(davidtwco): deliberately do not include `UNTRANSLATABLE_DIAGNOSTIC` and
518 // `DIAGNOSTIC_OUTSIDE_OF_IMPL` here because `-Wrustc::internal` is provided to every crate and
519 // these lints will trigger all of the time - change this once migration to diagnostic structs
520 // and translation is completed
521 store.register_group(
526 LintId::of(DEFAULT_HASH_TYPES),
527 LintId::of(POTENTIAL_QUERY_INSTABILITY),
528 LintId::of(USAGE_OF_TY_TYKIND),
529 LintId::of(PASS_BY_VALUE),
530 LintId::of(LINT_PASS_IMPL_WITHOUT_MACRO),
531 LintId::of(USAGE_OF_QUALIFIED_TY),
532 LintId::of(EXISTING_DOC_KEYWORD),
533 LintId::of(BAD_OPT_ACCESS),