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