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());
131 declare_combined_early_lint_pass,
133 pub BuiltinCombinedPreExpansionLintPass,
135 KeywordIdents: KeywordIdents,
141 declare_combined_early_lint_pass,
143 pub BuiltinCombinedEarlyLintPass,
145 UnusedParens: UnusedParens,
146 UnusedBraces: UnusedBraces,
147 UnusedImportBraces: UnusedImportBraces,
148 UnsafeCode: UnsafeCode,
149 SpecialModuleName: SpecialModuleName,
150 AnonymousParameters: AnonymousParameters,
151 EllipsisInclusiveRangePatterns: EllipsisInclusiveRangePatterns::default(),
152 NonCamelCaseTypes: NonCamelCaseTypes,
153 DeprecatedAttr: DeprecatedAttr::new(),
154 WhileTrue: WhileTrue,
155 NonAsciiIdents: NonAsciiIdents,
156 HiddenUnicodeCodepoints: HiddenUnicodeCodepoints,
157 IncompleteFeatures: IncompleteFeatures,
158 RedundantSemicolons: RedundantSemicolons,
159 UnusedDocComment: UnusedDocComment,
160 UnexpectedCfgs: UnexpectedCfgs,
165 // FIXME: Make a separate lint type which do not require typeck tables
167 declare_combined_late_lint_pass,
169 pub BuiltinCombinedLateLintPass,
171 // Tracks state across modules
172 UnnameableTestItems: UnnameableTestItems::new(),
173 // Tracks attributes of parents
174 MissingDoc: MissingDoc::new(),
175 // Builds a global list of all impls of `Debug`.
176 // FIXME: Turn the computation of types which implement Debug into a query
177 // and change this to a module lint pass
178 MissingDebugImplementations: MissingDebugImplementations::default(),
179 // Keeps a global list of foreign declarations.
180 ClashingExternDeclarations: ClashingExternDeclarations::new(),
187 declare_combined_late_lint_pass,
189 BuiltinCombinedModuleLateLintPass,
191 ForLoopsOverFallibles: ForLoopsOverFallibles,
192 DerefIntoDynSupertrait: DerefIntoDynSupertrait,
193 HardwiredLints: HardwiredLints,
194 ImproperCTypesDeclarations: ImproperCTypesDeclarations,
195 ImproperCTypesDefinitions: ImproperCTypesDefinitions,
196 VariantSizeDifferences: VariantSizeDifferences,
197 BoxPointers: BoxPointers,
198 PathStatements: PathStatements,
199 LetUnderscore: LetUnderscore,
200 // Depends on referenced function signatures in expressions
201 UnusedResults: UnusedResults,
202 NonUpperCaseGlobals: NonUpperCaseGlobals,
203 NonShorthandFieldPatterns: NonShorthandFieldPatterns,
204 UnusedAllocation: UnusedAllocation,
205 // Depends on types used in type definitions
206 MissingCopyImplementations: MissingCopyImplementations,
207 // Depends on referenced function signatures in expressions
208 MutableTransmutes: MutableTransmutes,
209 TypeAliasBounds: TypeAliasBounds,
210 TrivialConstraints: TrivialConstraints,
211 TypeLimits: TypeLimits::new(),
212 NonSnakeCase: NonSnakeCase,
213 InvalidNoMangleItems: InvalidNoMangleItems,
214 // Depends on effective visibilities
215 UnreachablePub: UnreachablePub,
216 ExplicitOutlivesRequirements: ExplicitOutlivesRequirements,
217 InvalidValue: InvalidValue,
218 DerefNullPtr: DerefNullPtr,
219 // May Depend on constants elsewhere
220 UnusedBrokenConst: UnusedBrokenConst,
221 UnstableFeatures: UnstableFeatures,
222 ArrayIntoIter: ArrayIntoIter::default(),
223 DropTraitConstraints: DropTraitConstraints,
224 TemporaryCStringAsPtr: TemporaryCStringAsPtr,
225 NonPanicFmt: NonPanicFmt,
226 NoopMethodCall: NoopMethodCall,
227 EnumIntrinsicsNonEnums: EnumIntrinsicsNonEnums,
228 InvalidAtomicOrdering: InvalidAtomicOrdering,
229 NamedAsmLabels: NamedAsmLabels,
230 OpaqueHiddenInferredBound: OpaqueHiddenInferredBound,
236 pub fn new_lint_store(internal_lints: bool) -> LintStore {
237 let mut lint_store = LintStore::new();
239 register_builtins(&mut lint_store);
241 register_internals(&mut lint_store);
247 /// Tell the `LintStore` about all the built-in lints (the ones
248 /// defined in this crate and the ones defined in
249 /// `rustc_session::lint::builtin`).
250 fn register_builtins(store: &mut LintStore) {
251 macro_rules! add_lint_group {
252 ($name:expr, $($lint:ident),*) => (
253 store.register_group(false, $name, None, vec![$(LintId::of($lint)),*]);
257 store.register_lints(&BuiltinCombinedPreExpansionLintPass::get_lints());
258 store.register_lints(&BuiltinCombinedEarlyLintPass::get_lints());
259 store.register_lints(&BuiltinCombinedModuleLateLintPass::get_lints());
260 store.register_lints(&BuiltinCombinedLateLintPass::get_lints());
264 NON_CAMEL_CASE_TYPES,
266 NON_UPPER_CASE_GLOBALS
277 UNREACHABLE_PATTERNS,
286 UNUSED_EXTERN_CRATES,
294 add_lint_group!("let_underscore", LET_UNDERSCORE_DROP, LET_UNDERSCORE_LOCK);
299 UNUSED_EXTERN_CRATES,
300 ELLIPSIS_INCLUSIVE_RANGE_PATTERNS,
301 ELIDED_LIFETIMES_IN_PATHS,
302 EXPLICIT_OUTLIVES_REQUIREMENTS // FIXME(#52665, #47816) not always applicable and not all
303 // macros are ready for this yet.
306 // FIXME macro crates are not up for this yet, too much
307 // breakage is seen if we try to encourage this lint.
308 // MACRO_USE_EXTERN_CRATE
311 // Register renamed and removed lints.
312 store.register_renamed("single_use_lifetime", "single_use_lifetimes");
313 store.register_renamed("elided_lifetime_in_path", "elided_lifetimes_in_paths");
314 store.register_renamed("bare_trait_object", "bare_trait_objects");
315 store.register_renamed("unstable_name_collision", "unstable_name_collisions");
316 store.register_renamed("unused_doc_comment", "unused_doc_comments");
317 store.register_renamed("async_idents", "keyword_idents");
318 store.register_renamed("exceeding_bitshifts", "arithmetic_overflow");
319 store.register_renamed("redundant_semicolon", "redundant_semicolons");
320 store.register_renamed("overlapping_patterns", "overlapping_range_endpoints");
321 store.register_renamed("safe_packed_borrows", "unaligned_references");
322 store.register_renamed("disjoint_capture_migration", "rust_2021_incompatible_closure_captures");
323 store.register_renamed("or_patterns_back_compat", "rust_2021_incompatible_or_patterns");
324 store.register_renamed("non_fmt_panic", "non_fmt_panics");
326 // These were moved to tool lints, but rustc still sees them when compiling normally, before
327 // tool lints are registered, so `check_tool_name_for_backwards_compat` doesn't work. Use
328 // `register_removed` explicitly.
329 const RUSTDOC_LINTS: &[&str] = &[
330 "broken_intra_doc_links",
331 "private_intra_doc_links",
332 "missing_crate_level_docs",
333 "missing_doc_code_examples",
335 "invalid_codeblock_attributes",
339 for rustdoc_lint in RUSTDOC_LINTS {
340 store.register_ignored(rustdoc_lint);
342 store.register_removed(
343 "intra_doc_link_resolution_failure",
344 "use `rustdoc::broken_intra_doc_links` instead",
346 store.register_removed("rustdoc", "use `rustdoc::all` instead");
348 store.register_removed("unknown_features", "replaced by an error");
349 store.register_removed("unsigned_negation", "replaced by negate_unsigned feature gate");
350 store.register_removed("negate_unsigned", "cast a signed value instead");
351 store.register_removed("raw_pointer_derive", "using derive with raw pointers is ok");
352 // Register lint group aliases.
353 store.register_group_alias("nonstandard_style", "bad_style");
354 // This was renamed to `raw_pointer_derive`, which was then removed,
355 // so it is also considered removed.
356 store.register_removed("raw_pointer_deriving", "using derive with raw pointers is ok");
357 store.register_removed("drop_with_repr_extern", "drop flags have been removed");
358 store.register_removed("fat_ptr_transmutes", "was accidentally removed back in 2014");
359 store.register_removed("deprecated_attr", "use `deprecated` instead");
360 store.register_removed(
361 "transmute_from_fn_item_types",
362 "always cast functions before transmuting them",
364 store.register_removed(
365 "hr_lifetime_in_assoc_type",
366 "converted into hard error, see issue #33685 \
367 <https://github.com/rust-lang/rust/issues/33685> for more information",
369 store.register_removed(
370 "inaccessible_extern_crate",
371 "converted into hard error, see issue #36886 \
372 <https://github.com/rust-lang/rust/issues/36886> for more information",
374 store.register_removed(
375 "super_or_self_in_global_path",
376 "converted into hard error, see issue #36888 \
377 <https://github.com/rust-lang/rust/issues/36888> for more information",
379 store.register_removed(
380 "overlapping_inherent_impls",
381 "converted into hard error, see issue #36889 \
382 <https://github.com/rust-lang/rust/issues/36889> for more information",
384 store.register_removed(
385 "illegal_floating_point_constant_pattern",
386 "converted into hard error, see issue #36890 \
387 <https://github.com/rust-lang/rust/issues/36890> for more information",
389 store.register_removed(
390 "illegal_struct_or_enum_constant_pattern",
391 "converted into hard error, see issue #36891 \
392 <https://github.com/rust-lang/rust/issues/36891> for more information",
394 store.register_removed(
395 "lifetime_underscore",
396 "converted into hard error, see issue #36892 \
397 <https://github.com/rust-lang/rust/issues/36892> for more information",
399 store.register_removed(
400 "extra_requirement_in_impl",
401 "converted into hard error, see issue #37166 \
402 <https://github.com/rust-lang/rust/issues/37166> for more information",
404 store.register_removed(
406 "converted into hard error, see issue #38260 \
407 <https://github.com/rust-lang/rust/issues/38260> for more information",
409 store.register_removed(
411 "converted into hard error, see issue #48950 \
412 <https://github.com/rust-lang/rust/issues/48950> for more information",
414 store.register_removed(
415 "resolve_trait_on_defaulted_unit",
416 "converted into hard error, see issue #48950 \
417 <https://github.com/rust-lang/rust/issues/48950> for more information",
419 store.register_removed(
420 "private_no_mangle_fns",
421 "no longer a warning, `#[no_mangle]` functions always exported",
423 store.register_removed(
424 "private_no_mangle_statics",
425 "no longer a warning, `#[no_mangle]` statics always exported",
427 store.register_removed("bad_repr", "replaced with a generic attribute input check");
428 store.register_removed(
429 "duplicate_matcher_binding_name",
430 "converted into hard error, see issue #57742 \
431 <https://github.com/rust-lang/rust/issues/57742> for more information",
433 store.register_removed(
434 "incoherent_fundamental_impls",
435 "converted into hard error, see issue #46205 \
436 <https://github.com/rust-lang/rust/issues/46205> for more information",
438 store.register_removed(
439 "legacy_constructor_visibility",
440 "converted into hard error, see issue #39207 \
441 <https://github.com/rust-lang/rust/issues/39207> for more information",
443 store.register_removed(
444 "legacy_directory_ownership",
445 "converted into hard error, see issue #37872 \
446 <https://github.com/rust-lang/rust/issues/37872> for more information",
448 store.register_removed(
449 "safe_extern_statics",
450 "converted into hard error, see issue #36247 \
451 <https://github.com/rust-lang/rust/issues/36247> for more information",
453 store.register_removed(
454 "parenthesized_params_in_types_and_modules",
455 "converted into hard error, see issue #42238 \
456 <https://github.com/rust-lang/rust/issues/42238> for more information",
458 store.register_removed(
459 "duplicate_macro_exports",
460 "converted into hard error, see issue #35896 \
461 <https://github.com/rust-lang/rust/issues/35896> for more information",
463 store.register_removed(
465 "converted into hard error, see issue #59014 \
466 <https://github.com/rust-lang/rust/issues/59014> for more information",
468 store.register_removed("plugin_as_library", "plugins have been deprecated and retired");
469 store.register_removed(
470 "unsupported_naked_functions",
471 "converted into hard error, see RFC 2972 \
472 <https://github.com/rust-lang/rfcs/blob/master/text/2972-constrained-naked.md> for more information",
474 store.register_removed(
475 "mutable_borrow_reservation_conflict",
476 "now allowed, see issue #59159 \
477 <https://github.com/rust-lang/rust/issues/59159> for more information",
479 store.register_removed(
481 "converted into hard error, see issue #71800 \
482 <https://github.com/rust-lang/rust/issues/71800> for more information",
486 fn register_internals(store: &mut LintStore) {
487 store.register_lints(&LintPassImpl::get_lints());
488 store.register_early_pass(|| Box::new(LintPassImpl));
489 store.register_lints(&DefaultHashTypes::get_lints());
490 store.register_late_pass(|_| Box::new(DefaultHashTypes));
491 store.register_lints(&QueryStability::get_lints());
492 store.register_late_pass(|_| Box::new(QueryStability));
493 store.register_lints(&ExistingDocKeyword::get_lints());
494 store.register_late_pass(|_| Box::new(ExistingDocKeyword));
495 store.register_lints(&TyTyKind::get_lints());
496 store.register_late_pass(|_| Box::new(TyTyKind));
497 store.register_lints(&Diagnostics::get_lints());
498 store.register_late_pass(|_| Box::new(Diagnostics));
499 store.register_lints(&BadOptAccess::get_lints());
500 store.register_late_pass(|_| Box::new(BadOptAccess));
501 store.register_lints(&PassByValue::get_lints());
502 store.register_late_pass(|_| Box::new(PassByValue));
503 // FIXME(davidtwco): deliberately do not include `UNTRANSLATABLE_DIAGNOSTIC` and
504 // `DIAGNOSTIC_OUTSIDE_OF_IMPL` here because `-Wrustc::internal` is provided to every crate and
505 // these lints will trigger all of the time - change this once migration to diagnostic structs
506 // and translation is completed
507 store.register_group(
512 LintId::of(DEFAULT_HASH_TYPES),
513 LintId::of(POTENTIAL_QUERY_INSTABILITY),
514 LintId::of(USAGE_OF_TY_TYKIND),
515 LintId::of(PASS_BY_VALUE),
516 LintId::of(LINT_PASS_IMPL_WITHOUT_MACRO),
517 LintId::of(USAGE_OF_QUALIFIED_TY),
518 LintId::of(EXISTING_DOC_KEYWORD),
519 LintId::of(BAD_OPT_ACCESS),