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;
60 mod redundant_semicolon;
65 pub use array_into_iter::ARRAY_INTO_ITER;
69 use rustc_hir::def_id::LocalDefId;
70 use rustc_middle::ty::query::Providers;
71 use rustc_middle::ty::TyCtxt;
72 use rustc_session::lint::builtin::{
73 BARE_TRAIT_OBJECTS, ELIDED_LIFETIMES_IN_PATHS, EXPLICIT_OUTLIVES_REQUIREMENTS,
75 use rustc_span::symbol::{Ident, Symbol};
78 use array_into_iter::ArrayIntoIter;
80 use enum_intrinsics_non_enums::EnumIntrinsicsNonEnums;
81 use hidden_unicode_codepoints::*;
84 use non_ascii_idents::*;
85 use non_fmt_panic::NonPanicFmt;
86 use nonstandard_style::*;
87 use noop_method_call::*;
88 use redundant_semicolon::*;
93 /// Useful for other parts of the compiler / Clippy.
94 pub use builtin::SoftLints;
95 pub use context::{CheckLintNameResult, EarlyContext, LateContext, LintContext, LintStore};
96 pub use early::check_ast_crate;
97 pub use late::check_crate;
98 pub use passes::{EarlyLintPass, LateLintPass};
99 pub use rustc_session::lint::Level::{self, *};
100 pub use rustc_session::lint::{BufferedEarlyLint, FutureIncompatibleInfo, Lint, LintId};
101 pub use rustc_session::lint::{LintArray, LintPass};
103 pub fn provide(providers: &mut Providers) {
104 levels::provide(providers);
105 *providers = Providers { lint_mod, ..*providers };
108 fn lint_mod(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
109 late::late_lint_mod(tcx, module_def_id, BuiltinCombinedModuleLateLintPass::new());
112 macro_rules! pre_expansion_lint_passes {
113 ($macro:path, $args:tt) => {
114 $macro!($args, [KeywordIdents: KeywordIdents,]);
118 macro_rules! early_lint_passes {
119 ($macro:path, $args:tt) => {
123 UnusedParens: UnusedParens,
124 UnusedBraces: UnusedBraces,
125 UnusedImportBraces: UnusedImportBraces,
126 UnsafeCode: UnsafeCode,
127 AnonymousParameters: AnonymousParameters,
128 EllipsisInclusiveRangePatterns: EllipsisInclusiveRangePatterns::default(),
129 NonCamelCaseTypes: NonCamelCaseTypes,
130 DeprecatedAttr: DeprecatedAttr::new(),
131 WhileTrue: WhileTrue,
132 NonAsciiIdents: NonAsciiIdents,
133 HiddenUnicodeCodepoints: HiddenUnicodeCodepoints,
134 IncompleteFeatures: IncompleteFeatures,
135 RedundantSemicolons: RedundantSemicolons,
136 UnusedDocComment: UnusedDocComment,
142 macro_rules! declare_combined_early_pass {
143 ([$name:ident], $passes:tt) => (
144 early_lint_methods!(declare_combined_early_lint_pass, [pub $name, $passes]);
148 pre_expansion_lint_passes!(declare_combined_early_pass, [BuiltinCombinedPreExpansionLintPass]);
149 early_lint_passes!(declare_combined_early_pass, [BuiltinCombinedEarlyLintPass]);
151 macro_rules! late_lint_passes {
152 ($macro:path, $args:tt) => {
156 // FIXME: Look into regression when this is used as a module lint
157 // May Depend on constants elsewhere
158 UnusedBrokenConst: UnusedBrokenConst,
159 // Needs to run after UnusedAttributes as it marks all `feature` attributes as used.
160 UnstableFeatures: UnstableFeatures,
161 // Tracks state across modules
162 UnnameableTestItems: UnnameableTestItems::new(),
163 // Tracks attributes of parents
164 MissingDoc: MissingDoc::new(),
165 // Depends on access levels
166 // FIXME: Turn the computation of types which implement Debug into a query
167 // and change this to a module lint pass
168 MissingDebugImplementations: MissingDebugImplementations::default(),
169 ArrayIntoIter: ArrayIntoIter::default(),
170 ClashingExternDeclarations: ClashingExternDeclarations::new(),
171 DropTraitConstraints: DropTraitConstraints,
172 TemporaryCStringAsPtr: TemporaryCStringAsPtr,
173 NonPanicFmt: NonPanicFmt,
174 NoopMethodCall: NoopMethodCall,
175 EnumIntrinsicsNonEnums: EnumIntrinsicsNonEnums,
176 InvalidAtomicOrdering: InvalidAtomicOrdering,
177 NamedAsmLabels: NamedAsmLabels,
183 macro_rules! late_lint_mod_passes {
184 ($macro:path, $args:tt) => {
188 HardwiredLints: HardwiredLints,
189 ImproperCTypesDeclarations: ImproperCTypesDeclarations,
190 ImproperCTypesDefinitions: ImproperCTypesDefinitions,
191 VariantSizeDifferences: VariantSizeDifferences,
192 BoxPointers: BoxPointers,
193 PathStatements: PathStatements,
194 // Depends on referenced function signatures in expressions
195 UnusedResults: UnusedResults,
196 NonUpperCaseGlobals: NonUpperCaseGlobals,
197 NonShorthandFieldPatterns: NonShorthandFieldPatterns,
198 UnusedAllocation: UnusedAllocation,
199 // Depends on types used in type definitions
200 MissingCopyImplementations: MissingCopyImplementations,
201 // Depends on referenced function signatures in expressions
202 MutableTransmutes: MutableTransmutes,
203 TypeAliasBounds: TypeAliasBounds,
204 TrivialConstraints: TrivialConstraints,
205 TypeLimits: TypeLimits::new(),
206 NonSnakeCase: NonSnakeCase,
207 InvalidNoMangleItems: InvalidNoMangleItems,
208 // Depends on access levels
209 UnreachablePub: UnreachablePub,
210 ExplicitOutlivesRequirements: ExplicitOutlivesRequirements,
211 InvalidValue: InvalidValue,
212 DerefNullPtr: DerefNullPtr,
218 macro_rules! declare_combined_late_pass {
219 ([$v:vis $name:ident], $passes:tt) => (
220 late_lint_methods!(declare_combined_late_lint_pass, [$v $name, $passes], ['tcx]);
224 // FIXME: Make a separate lint type which do not require typeck tables
225 late_lint_passes!(declare_combined_late_pass, [pub BuiltinCombinedLateLintPass]);
227 late_lint_mod_passes!(declare_combined_late_pass, [BuiltinCombinedModuleLateLintPass]);
229 pub fn new_lint_store(no_interleave_lints: bool, internal_lints: bool) -> LintStore {
230 let mut lint_store = LintStore::new();
232 register_builtins(&mut lint_store, no_interleave_lints);
234 register_internals(&mut lint_store);
240 /// Tell the `LintStore` about all the built-in lints (the ones
241 /// defined in this crate and the ones defined in
242 /// `rustc_session::lint::builtin`).
243 fn register_builtins(store: &mut LintStore, no_interleave_lints: bool) {
244 macro_rules! add_lint_group {
245 ($name:expr, $($lint:ident),*) => (
246 store.register_group(false, $name, None, vec![$(LintId::of($lint)),*]);
250 macro_rules! register_pass {
251 ($method:ident, $ty:ident, $constructor:expr) => {
252 store.register_lints(&$ty::get_lints());
253 store.$method(|| Box::new($constructor));
257 macro_rules! register_passes {
258 ($method:ident, [$($passes:ident: $constructor:expr,)*]) => (
260 register_pass!($method, $passes, $constructor);
265 if no_interleave_lints {
266 pre_expansion_lint_passes!(register_passes, register_pre_expansion_pass);
267 early_lint_passes!(register_passes, register_early_pass);
268 late_lint_passes!(register_passes, register_late_pass);
269 late_lint_mod_passes!(register_passes, register_late_mod_pass);
271 store.register_lints(&BuiltinCombinedPreExpansionLintPass::get_lints());
272 store.register_lints(&BuiltinCombinedEarlyLintPass::get_lints());
273 store.register_lints(&BuiltinCombinedModuleLateLintPass::get_lints());
274 store.register_lints(&BuiltinCombinedLateLintPass::get_lints());
279 NON_CAMEL_CASE_TYPES,
281 NON_UPPER_CASE_GLOBALS
292 UNREACHABLE_PATTERNS,
300 UNUSED_EXTERN_CRATES,
311 UNUSED_EXTERN_CRATES,
312 ELLIPSIS_INCLUSIVE_RANGE_PATTERNS,
313 ELIDED_LIFETIMES_IN_PATHS,
314 EXPLICIT_OUTLIVES_REQUIREMENTS // FIXME(#52665, #47816) not always applicable and not all
315 // macros are ready for this yet.
318 // FIXME macro crates are not up for this yet, too much
319 // breakage is seen if we try to encourage this lint.
320 // MACRO_USE_EXTERN_CRATE
323 // Register renamed and removed lints.
324 store.register_renamed("single_use_lifetime", "single_use_lifetimes");
325 store.register_renamed("elided_lifetime_in_path", "elided_lifetimes_in_paths");
326 store.register_renamed("bare_trait_object", "bare_trait_objects");
327 store.register_renamed("unstable_name_collision", "unstable_name_collisions");
328 store.register_renamed("unused_doc_comment", "unused_doc_comments");
329 store.register_renamed("async_idents", "keyword_idents");
330 store.register_renamed("exceeding_bitshifts", "arithmetic_overflow");
331 store.register_renamed("redundant_semicolon", "redundant_semicolons");
332 store.register_renamed("overlapping_patterns", "overlapping_range_endpoints");
333 store.register_renamed("safe_packed_borrows", "unaligned_references");
334 store.register_renamed("disjoint_capture_migration", "rust_2021_incompatible_closure_captures");
335 store.register_renamed("or_patterns_back_compat", "rust_2021_incompatible_or_patterns");
336 store.register_renamed("non_fmt_panic", "non_fmt_panics");
338 // These were moved to tool lints, but rustc still sees them when compiling normally, before
339 // tool lints are registered, so `check_tool_name_for_backwards_compat` doesn't work. Use
340 // `register_removed` explicitly.
341 const RUSTDOC_LINTS: &[&str] = &[
342 "broken_intra_doc_links",
343 "private_intra_doc_links",
344 "missing_crate_level_docs",
345 "missing_doc_code_examples",
347 "invalid_codeblock_attributes",
351 for rustdoc_lint in RUSTDOC_LINTS {
352 store.register_ignored(rustdoc_lint);
354 store.register_removed(
355 "intra_doc_link_resolution_failure",
356 "use `rustdoc::broken_intra_doc_links` instead",
358 store.register_removed("rustdoc", "use `rustdoc::all` instead");
360 store.register_removed("unknown_features", "replaced by an error");
361 store.register_removed("unsigned_negation", "replaced by negate_unsigned feature gate");
362 store.register_removed("negate_unsigned", "cast a signed value instead");
363 store.register_removed("raw_pointer_derive", "using derive with raw pointers is ok");
364 // Register lint group aliases.
365 store.register_group_alias("nonstandard_style", "bad_style");
366 // This was renamed to `raw_pointer_derive`, which was then removed,
367 // so it is also considered removed.
368 store.register_removed("raw_pointer_deriving", "using derive with raw pointers is ok");
369 store.register_removed("drop_with_repr_extern", "drop flags have been removed");
370 store.register_removed("fat_ptr_transmutes", "was accidentally removed back in 2014");
371 store.register_removed("deprecated_attr", "use `deprecated` instead");
372 store.register_removed(
373 "transmute_from_fn_item_types",
374 "always cast functions before transmuting them",
376 store.register_removed(
377 "hr_lifetime_in_assoc_type",
378 "converted into hard error, see issue #33685 \
379 <https://github.com/rust-lang/rust/issues/33685> for more information",
381 store.register_removed(
382 "inaccessible_extern_crate",
383 "converted into hard error, see issue #36886 \
384 <https://github.com/rust-lang/rust/issues/36886> for more information",
386 store.register_removed(
387 "super_or_self_in_global_path",
388 "converted into hard error, see issue #36888 \
389 <https://github.com/rust-lang/rust/issues/36888> for more information",
391 store.register_removed(
392 "overlapping_inherent_impls",
393 "converted into hard error, see issue #36889 \
394 <https://github.com/rust-lang/rust/issues/36889> for more information",
396 store.register_removed(
397 "illegal_floating_point_constant_pattern",
398 "converted into hard error, see issue #36890 \
399 <https://github.com/rust-lang/rust/issues/36890> for more information",
401 store.register_removed(
402 "illegal_struct_or_enum_constant_pattern",
403 "converted into hard error, see issue #36891 \
404 <https://github.com/rust-lang/rust/issues/36891> for more information",
406 store.register_removed(
407 "lifetime_underscore",
408 "converted into hard error, see issue #36892 \
409 <https://github.com/rust-lang/rust/issues/36892> for more information",
411 store.register_removed(
412 "extra_requirement_in_impl",
413 "converted into hard error, see issue #37166 \
414 <https://github.com/rust-lang/rust/issues/37166> for more information",
416 store.register_removed(
418 "converted into hard error, see issue #38260 \
419 <https://github.com/rust-lang/rust/issues/38260> for more information",
421 store.register_removed(
423 "converted into hard error, see issue #48950 \
424 <https://github.com/rust-lang/rust/issues/48950> for more information",
426 store.register_removed(
427 "resolve_trait_on_defaulted_unit",
428 "converted into hard error, see issue #48950 \
429 <https://github.com/rust-lang/rust/issues/48950> for more information",
431 store.register_removed(
432 "private_no_mangle_fns",
433 "no longer a warning, `#[no_mangle]` functions always exported",
435 store.register_removed(
436 "private_no_mangle_statics",
437 "no longer a warning, `#[no_mangle]` statics always exported",
439 store.register_removed("bad_repr", "replaced with a generic attribute input check");
440 store.register_removed(
441 "duplicate_matcher_binding_name",
442 "converted into hard error, see issue #57742 \
443 <https://github.com/rust-lang/rust/issues/57742> for more information",
445 store.register_removed(
446 "incoherent_fundamental_impls",
447 "converted into hard error, see issue #46205 \
448 <https://github.com/rust-lang/rust/issues/46205> for more information",
450 store.register_removed(
451 "legacy_constructor_visibility",
452 "converted into hard error, see issue #39207 \
453 <https://github.com/rust-lang/rust/issues/39207> for more information",
455 store.register_removed(
456 "legacy_directory_ownership",
457 "converted into hard error, see issue #37872 \
458 <https://github.com/rust-lang/rust/issues/37872> for more information",
460 store.register_removed(
461 "safe_extern_statics",
462 "converted into hard error, see issue #36247 \
463 <https://github.com/rust-lang/rust/issues/36247> for more information",
465 store.register_removed(
466 "parenthesized_params_in_types_and_modules",
467 "converted into hard error, see issue #42238 \
468 <https://github.com/rust-lang/rust/issues/42238> for more information",
470 store.register_removed(
471 "duplicate_macro_exports",
472 "converted into hard error, see issue #35896 \
473 <https://github.com/rust-lang/rust/issues/35896> for more information",
475 store.register_removed(
477 "converted into hard error, see issue #59014 \
478 <https://github.com/rust-lang/rust/issues/59014> for more information",
480 store.register_removed("plugin_as_library", "plugins have been deprecated and retired");
483 fn register_internals(store: &mut LintStore) {
484 store.register_lints(&LintPassImpl::get_lints());
485 store.register_early_pass(|| Box::new(LintPassImpl));
486 store.register_lints(&DefaultHashTypes::get_lints());
487 store.register_late_pass(|| Box::new(DefaultHashTypes));
488 store.register_lints(&ExistingDocKeyword::get_lints());
489 store.register_late_pass(|| Box::new(ExistingDocKeyword));
490 store.register_lints(&TyTyKind::get_lints());
491 store.register_late_pass(|| Box::new(TyTyKind));
492 store.register_group(
497 LintId::of(DEFAULT_HASH_TYPES),
498 LintId::of(USAGE_OF_TY_TYKIND),
499 LintId::of(LINT_PASS_IMPL_WITHOUT_MACRO),
500 LintId::of(TY_PASS_BY_REFERENCE),
501 LintId::of(USAGE_OF_QUALIFIED_TY),
502 LintId::of(EXISTING_DOC_KEYWORD),