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 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
29 #![feature(array_windows)]
30 #![feature(bool_to_option)]
31 #![feature(box_patterns)]
32 #![feature(crate_visibility_modifier)]
33 #![feature(iter_order_by)]
35 #![feature(never_type)]
37 #![feature(control_flow_enum)]
38 #![recursion_limit = "256"]
41 extern crate rustc_middle;
43 extern crate rustc_session;
49 mod enum_intrinsics_non_enums;
50 pub mod hidden_unicode_codepoints;
57 mod nonstandard_style;
61 mod redundant_semicolon;
66 pub use array_into_iter::ARRAY_INTO_ITER;
70 use rustc_hir::def_id::LocalDefId;
71 use rustc_middle::ty::query::Providers;
72 use rustc_middle::ty::TyCtxt;
73 use rustc_session::lint::builtin::{
74 BARE_TRAIT_OBJECTS, ELIDED_LIFETIMES_IN_PATHS, EXPLICIT_OUTLIVES_REQUIREMENTS,
76 use rustc_span::symbol::{Ident, Symbol};
79 use array_into_iter::ArrayIntoIter;
81 use enum_intrinsics_non_enums::EnumIntrinsicsNonEnums;
82 use hidden_unicode_codepoints::*;
85 use non_ascii_idents::*;
86 use non_fmt_panic::NonPanicFmt;
87 use nonstandard_style::*;
88 use noop_method_call::*;
90 use redundant_semicolon::*;
95 /// Useful for other parts of the compiler / Clippy.
96 pub use builtin::SoftLints;
97 pub use context::{CheckLintNameResult, FindLintError, LintStore};
98 pub use context::{EarlyContext, LateContext, LintContext};
99 pub use early::{check_ast_node, EarlyCheckNode};
100 pub use late::check_crate;
101 pub use passes::{EarlyLintPass, LateLintPass};
102 pub use rustc_session::lint::Level::{self, *};
103 pub use rustc_session::lint::{BufferedEarlyLint, FutureIncompatibleInfo, Lint, LintId};
104 pub use rustc_session::lint::{LintArray, LintPass};
106 pub fn provide(providers: &mut Providers) {
107 levels::provide(providers);
108 *providers = Providers { lint_mod, ..*providers };
111 fn lint_mod(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
112 late::late_lint_mod(tcx, module_def_id, BuiltinCombinedModuleLateLintPass::new());
115 macro_rules! pre_expansion_lint_passes {
116 ($macro:path, $args:tt) => {
117 $macro!($args, [KeywordIdents: KeywordIdents,]);
121 macro_rules! early_lint_passes {
122 ($macro:path, $args:tt) => {
126 UnusedParens: UnusedParens,
127 UnusedBraces: UnusedBraces,
128 UnusedImportBraces: UnusedImportBraces,
129 UnsafeCode: UnsafeCode,
130 AnonymousParameters: AnonymousParameters,
131 EllipsisInclusiveRangePatterns: EllipsisInclusiveRangePatterns::default(),
132 NonCamelCaseTypes: NonCamelCaseTypes,
133 DeprecatedAttr: DeprecatedAttr::new(),
134 WhileTrue: WhileTrue,
135 NonAsciiIdents: NonAsciiIdents,
136 HiddenUnicodeCodepoints: HiddenUnicodeCodepoints,
137 IncompleteFeatures: IncompleteFeatures,
138 RedundantSemicolons: RedundantSemicolons,
139 UnusedDocComment: UnusedDocComment,
145 macro_rules! declare_combined_early_pass {
146 ([$name:ident], $passes:tt) => (
147 early_lint_methods!(declare_combined_early_lint_pass, [pub $name, $passes]);
151 pre_expansion_lint_passes!(declare_combined_early_pass, [BuiltinCombinedPreExpansionLintPass]);
152 early_lint_passes!(declare_combined_early_pass, [BuiltinCombinedEarlyLintPass]);
154 macro_rules! late_lint_passes {
155 ($macro:path, $args:tt) => {
159 // FIXME: Look into regression when this is used as a module lint
160 // May Depend on constants elsewhere
161 UnusedBrokenConst: UnusedBrokenConst,
162 // Needs to run after UnusedAttributes as it marks all `feature` attributes as used.
163 UnstableFeatures: UnstableFeatures,
164 // Tracks state across modules
165 UnnameableTestItems: UnnameableTestItems::new(),
166 // Tracks attributes of parents
167 MissingDoc: MissingDoc::new(),
168 // Depends on access levels
169 // FIXME: Turn the computation of types which implement Debug into a query
170 // and change this to a module lint pass
171 MissingDebugImplementations: MissingDebugImplementations::default(),
172 ArrayIntoIter: ArrayIntoIter::default(),
173 ClashingExternDeclarations: ClashingExternDeclarations::new(),
174 DropTraitConstraints: DropTraitConstraints,
175 TemporaryCStringAsPtr: TemporaryCStringAsPtr,
176 NonPanicFmt: NonPanicFmt,
177 NoopMethodCall: NoopMethodCall,
178 EnumIntrinsicsNonEnums: EnumIntrinsicsNonEnums,
179 InvalidAtomicOrdering: InvalidAtomicOrdering,
180 NamedAsmLabels: NamedAsmLabels,
186 macro_rules! late_lint_mod_passes {
187 ($macro:path, $args:tt) => {
191 HardwiredLints: HardwiredLints,
192 ImproperCTypesDeclarations: ImproperCTypesDeclarations,
193 ImproperCTypesDefinitions: ImproperCTypesDefinitions,
194 VariantSizeDifferences: VariantSizeDifferences,
195 BoxPointers: BoxPointers,
196 PathStatements: PathStatements,
197 // Depends on referenced function signatures in expressions
198 UnusedResults: UnusedResults,
199 NonUpperCaseGlobals: NonUpperCaseGlobals,
200 NonShorthandFieldPatterns: NonShorthandFieldPatterns,
201 UnusedAllocation: UnusedAllocation,
202 // Depends on types used in type definitions
203 MissingCopyImplementations: MissingCopyImplementations,
204 // Depends on referenced function signatures in expressions
205 MutableTransmutes: MutableTransmutes,
206 TypeAliasBounds: TypeAliasBounds,
207 TrivialConstraints: TrivialConstraints,
208 TypeLimits: TypeLimits::new(),
209 NonSnakeCase: NonSnakeCase,
210 InvalidNoMangleItems: InvalidNoMangleItems,
211 // Depends on access levels
212 UnreachablePub: UnreachablePub,
213 ExplicitOutlivesRequirements: ExplicitOutlivesRequirements,
214 InvalidValue: InvalidValue,
215 DerefNullPtr: DerefNullPtr,
221 macro_rules! declare_combined_late_pass {
222 ([$v:vis $name:ident], $passes:tt) => (
223 late_lint_methods!(declare_combined_late_lint_pass, [$v $name, $passes], ['tcx]);
227 // FIXME: Make a separate lint type which do not require typeck tables
228 late_lint_passes!(declare_combined_late_pass, [pub BuiltinCombinedLateLintPass]);
230 late_lint_mod_passes!(declare_combined_late_pass, [BuiltinCombinedModuleLateLintPass]);
232 pub fn new_lint_store(no_interleave_lints: bool, internal_lints: bool) -> LintStore {
233 let mut lint_store = LintStore::new();
235 register_builtins(&mut lint_store, no_interleave_lints);
237 register_internals(&mut lint_store);
243 /// Tell the `LintStore` about all the built-in lints (the ones
244 /// defined in this crate and the ones defined in
245 /// `rustc_session::lint::builtin`).
246 fn register_builtins(store: &mut LintStore, no_interleave_lints: bool) {
247 macro_rules! add_lint_group {
248 ($name:expr, $($lint:ident),*) => (
249 store.register_group(false, $name, None, vec![$(LintId::of($lint)),*]);
253 macro_rules! register_pass {
254 ($method:ident, $ty:ident, $constructor:expr) => {
255 store.register_lints(&$ty::get_lints());
256 store.$method(|| Box::new($constructor));
260 macro_rules! register_passes {
261 ($method:ident, [$($passes:ident: $constructor:expr,)*]) => (
263 register_pass!($method, $passes, $constructor);
268 if no_interleave_lints {
269 pre_expansion_lint_passes!(register_passes, register_pre_expansion_pass);
270 early_lint_passes!(register_passes, register_early_pass);
271 late_lint_passes!(register_passes, register_late_pass);
272 late_lint_mod_passes!(register_passes, register_late_mod_pass);
274 store.register_lints(&BuiltinCombinedPreExpansionLintPass::get_lints());
275 store.register_lints(&BuiltinCombinedEarlyLintPass::get_lints());
276 store.register_lints(&BuiltinCombinedModuleLateLintPass::get_lints());
277 store.register_lints(&BuiltinCombinedLateLintPass::get_lints());
282 NON_CAMEL_CASE_TYPES,
284 NON_UPPER_CASE_GLOBALS
295 UNREACHABLE_PATTERNS,
303 UNUSED_EXTERN_CRATES,
314 UNUSED_EXTERN_CRATES,
315 ELLIPSIS_INCLUSIVE_RANGE_PATTERNS,
316 ELIDED_LIFETIMES_IN_PATHS,
317 EXPLICIT_OUTLIVES_REQUIREMENTS // FIXME(#52665, #47816) not always applicable and not all
318 // macros are ready for this yet.
321 // FIXME macro crates are not up for this yet, too much
322 // breakage is seen if we try to encourage this lint.
323 // MACRO_USE_EXTERN_CRATE
326 // Register renamed and removed lints.
327 store.register_renamed("single_use_lifetime", "single_use_lifetimes");
328 store.register_renamed("elided_lifetime_in_path", "elided_lifetimes_in_paths");
329 store.register_renamed("bare_trait_object", "bare_trait_objects");
330 store.register_renamed("unstable_name_collision", "unstable_name_collisions");
331 store.register_renamed("unused_doc_comment", "unused_doc_comments");
332 store.register_renamed("async_idents", "keyword_idents");
333 store.register_renamed("exceeding_bitshifts", "arithmetic_overflow");
334 store.register_renamed("redundant_semicolon", "redundant_semicolons");
335 store.register_renamed("overlapping_patterns", "overlapping_range_endpoints");
336 store.register_renamed("safe_packed_borrows", "unaligned_references");
337 store.register_renamed("disjoint_capture_migration", "rust_2021_incompatible_closure_captures");
338 store.register_renamed("or_patterns_back_compat", "rust_2021_incompatible_or_patterns");
339 store.register_renamed("non_fmt_panic", "non_fmt_panics");
341 // These were moved to tool lints, but rustc still sees them when compiling normally, before
342 // tool lints are registered, so `check_tool_name_for_backwards_compat` doesn't work. Use
343 // `register_removed` explicitly.
344 const RUSTDOC_LINTS: &[&str] = &[
345 "broken_intra_doc_links",
346 "private_intra_doc_links",
347 "missing_crate_level_docs",
348 "missing_doc_code_examples",
350 "invalid_codeblock_attributes",
354 for rustdoc_lint in RUSTDOC_LINTS {
355 store.register_ignored(rustdoc_lint);
357 store.register_removed(
358 "intra_doc_link_resolution_failure",
359 "use `rustdoc::broken_intra_doc_links` instead",
361 store.register_removed("rustdoc", "use `rustdoc::all` instead");
363 store.register_removed("unknown_features", "replaced by an error");
364 store.register_removed("unsigned_negation", "replaced by negate_unsigned feature gate");
365 store.register_removed("negate_unsigned", "cast a signed value instead");
366 store.register_removed("raw_pointer_derive", "using derive with raw pointers is ok");
367 // Register lint group aliases.
368 store.register_group_alias("nonstandard_style", "bad_style");
369 // This was renamed to `raw_pointer_derive`, which was then removed,
370 // so it is also considered removed.
371 store.register_removed("raw_pointer_deriving", "using derive with raw pointers is ok");
372 store.register_removed("drop_with_repr_extern", "drop flags have been removed");
373 store.register_removed("fat_ptr_transmutes", "was accidentally removed back in 2014");
374 store.register_removed("deprecated_attr", "use `deprecated` instead");
375 store.register_removed(
376 "transmute_from_fn_item_types",
377 "always cast functions before transmuting them",
379 store.register_removed(
380 "hr_lifetime_in_assoc_type",
381 "converted into hard error, see issue #33685 \
382 <https://github.com/rust-lang/rust/issues/33685> for more information",
384 store.register_removed(
385 "inaccessible_extern_crate",
386 "converted into hard error, see issue #36886 \
387 <https://github.com/rust-lang/rust/issues/36886> for more information",
389 store.register_removed(
390 "super_or_self_in_global_path",
391 "converted into hard error, see issue #36888 \
392 <https://github.com/rust-lang/rust/issues/36888> for more information",
394 store.register_removed(
395 "overlapping_inherent_impls",
396 "converted into hard error, see issue #36889 \
397 <https://github.com/rust-lang/rust/issues/36889> for more information",
399 store.register_removed(
400 "illegal_floating_point_constant_pattern",
401 "converted into hard error, see issue #36890 \
402 <https://github.com/rust-lang/rust/issues/36890> for more information",
404 store.register_removed(
405 "illegal_struct_or_enum_constant_pattern",
406 "converted into hard error, see issue #36891 \
407 <https://github.com/rust-lang/rust/issues/36891> for more information",
409 store.register_removed(
410 "lifetime_underscore",
411 "converted into hard error, see issue #36892 \
412 <https://github.com/rust-lang/rust/issues/36892> for more information",
414 store.register_removed(
415 "extra_requirement_in_impl",
416 "converted into hard error, see issue #37166 \
417 <https://github.com/rust-lang/rust/issues/37166> for more information",
419 store.register_removed(
421 "converted into hard error, see issue #38260 \
422 <https://github.com/rust-lang/rust/issues/38260> for more information",
424 store.register_removed(
426 "converted into hard error, see issue #48950 \
427 <https://github.com/rust-lang/rust/issues/48950> for more information",
429 store.register_removed(
430 "resolve_trait_on_defaulted_unit",
431 "converted into hard error, see issue #48950 \
432 <https://github.com/rust-lang/rust/issues/48950> for more information",
434 store.register_removed(
435 "private_no_mangle_fns",
436 "no longer a warning, `#[no_mangle]` functions always exported",
438 store.register_removed(
439 "private_no_mangle_statics",
440 "no longer a warning, `#[no_mangle]` statics always exported",
442 store.register_removed("bad_repr", "replaced with a generic attribute input check");
443 store.register_removed(
444 "duplicate_matcher_binding_name",
445 "converted into hard error, see issue #57742 \
446 <https://github.com/rust-lang/rust/issues/57742> for more information",
448 store.register_removed(
449 "incoherent_fundamental_impls",
450 "converted into hard error, see issue #46205 \
451 <https://github.com/rust-lang/rust/issues/46205> for more information",
453 store.register_removed(
454 "legacy_constructor_visibility",
455 "converted into hard error, see issue #39207 \
456 <https://github.com/rust-lang/rust/issues/39207> for more information",
458 store.register_removed(
459 "legacy_directory_ownership",
460 "converted into hard error, see issue #37872 \
461 <https://github.com/rust-lang/rust/issues/37872> for more information",
463 store.register_removed(
464 "safe_extern_statics",
465 "converted into hard error, see issue #36247 \
466 <https://github.com/rust-lang/rust/issues/36247> for more information",
468 store.register_removed(
469 "parenthesized_params_in_types_and_modules",
470 "converted into hard error, see issue #42238 \
471 <https://github.com/rust-lang/rust/issues/42238> for more information",
473 store.register_removed(
474 "duplicate_macro_exports",
475 "converted into hard error, see issue #35896 \
476 <https://github.com/rust-lang/rust/issues/35896> for more information",
478 store.register_removed(
480 "converted into hard error, see issue #59014 \
481 <https://github.com/rust-lang/rust/issues/59014> for more information",
483 store.register_removed("plugin_as_library", "plugins have been deprecated and retired");
484 store.register_removed(
485 "unsupported_naked_functions",
486 "converted into hard error, see RFC 2972 \
487 <https://github.com/rust-lang/rfcs/blob/master/text/2972-constrained-naked.md> for more information",
491 fn register_internals(store: &mut LintStore) {
492 store.register_lints(&LintPassImpl::get_lints());
493 store.register_early_pass(|| Box::new(LintPassImpl));
494 store.register_lints(&DefaultHashTypes::get_lints());
495 store.register_late_pass(|| Box::new(DefaultHashTypes));
496 store.register_lints(&ExistingDocKeyword::get_lints());
497 store.register_late_pass(|| Box::new(ExistingDocKeyword));
498 store.register_lints(&TyTyKind::get_lints());
499 store.register_late_pass(|| Box::new(TyTyKind));
500 store.register_lints(&PassByValue::get_lints());
501 store.register_late_pass(|| Box::new(PassByValue));
502 store.register_group(
507 LintId::of(DEFAULT_HASH_TYPES),
508 LintId::of(USAGE_OF_TY_TYKIND),
509 LintId::of(PASS_BY_VALUE),
510 LintId::of(LINT_PASS_IMPL_WITHOUT_MACRO),
511 LintId::of(USAGE_OF_QUALIFIED_TY),
512 LintId::of(EXISTING_DOC_KEYWORD),