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 #![cfg_attr(test, feature(test))]
30 #![feature(array_windows)]
31 #![feature(bool_to_option)]
32 #![feature(box_syntax)]
33 #![feature(box_patterns)]
34 #![feature(crate_visibility_modifier)]
35 #![feature(iter_order_by)]
37 #![feature(never_type)]
39 #![cfg_attr(bootstrap, feature(or_patterns))]
40 #![feature(half_open_range_patterns)]
41 #![feature(exclusive_range_pattern)]
42 #![feature(control_flow_enum)]
43 #![recursion_limit = "256"]
46 extern crate rustc_middle;
48 extern crate rustc_session;
60 mod nonstandard_style;
63 mod redundant_semicolon;
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;
83 use non_ascii_idents::*;
84 use non_fmt_panic::NonPanicFmt;
85 use nonstandard_style::*;
86 use noop_method_call::*;
87 use redundant_semicolon::*;
92 /// Useful for other parts of the compiler / Clippy.
93 pub use builtin::SoftLints;
94 pub use context::{CheckLintNameResult, EarlyContext, LateContext, LintContext, LintStore};
95 pub use early::check_ast_crate;
96 pub use late::check_crate;
97 pub use passes::{EarlyLintPass, LateLintPass};
98 pub use rustc_session::lint::Level::{self, *};
99 pub use rustc_session::lint::{BufferedEarlyLint, FutureIncompatibleInfo, Lint, LintId};
100 pub use rustc_session::lint::{LintArray, LintPass};
102 pub fn provide(providers: &mut Providers) {
103 levels::provide(providers);
104 *providers = Providers { lint_mod, ..*providers };
107 fn lint_mod(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
108 late::late_lint_mod(tcx, module_def_id, BuiltinCombinedModuleLateLintPass::new());
111 macro_rules! pre_expansion_lint_passes {
112 ($macro:path, $args:tt) => {
113 $macro!($args, [KeywordIdents: KeywordIdents,]);
117 macro_rules! early_lint_passes {
118 ($macro:path, $args:tt) => {
122 UnusedParens: UnusedParens,
123 UnusedBraces: UnusedBraces,
124 UnusedImportBraces: UnusedImportBraces,
125 UnsafeCode: UnsafeCode,
126 AnonymousParameters: AnonymousParameters,
127 EllipsisInclusiveRangePatterns: EllipsisInclusiveRangePatterns::default(),
128 NonCamelCaseTypes: NonCamelCaseTypes,
129 DeprecatedAttr: DeprecatedAttr::new(),
130 WhileTrue: WhileTrue,
131 NonAsciiIdents: NonAsciiIdents,
132 IncompleteFeatures: IncompleteFeatures,
133 RedundantSemicolons: RedundantSemicolons,
134 UnusedDocComment: UnusedDocComment,
140 macro_rules! declare_combined_early_pass {
141 ([$name:ident], $passes:tt) => (
142 early_lint_methods!(declare_combined_early_lint_pass, [pub $name, $passes]);
146 pre_expansion_lint_passes!(declare_combined_early_pass, [BuiltinCombinedPreExpansionLintPass]);
147 early_lint_passes!(declare_combined_early_pass, [BuiltinCombinedEarlyLintPass]);
149 macro_rules! late_lint_passes {
150 ($macro:path, $args:tt) => {
154 // FIXME: Look into regression when this is used as a module lint
155 // May Depend on constants elsewhere
156 UnusedBrokenConst: UnusedBrokenConst,
157 // Uses attr::is_used which is untracked, can't be an incremental module pass.
158 UnusedAttributes: UnusedAttributes::new(),
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,
170 ClashingExternDeclarations: ClashingExternDeclarations::new(),
171 DropTraitConstraints: DropTraitConstraints,
172 TemporaryCStringAsPtr: TemporaryCStringAsPtr,
173 NonPanicFmt: NonPanicFmt,
174 NoopMethodCall: NoopMethodCall,
180 macro_rules! late_lint_mod_passes {
181 ($macro:path, $args:tt) => {
185 HardwiredLints: HardwiredLints,
186 ImproperCTypesDeclarations: ImproperCTypesDeclarations,
187 ImproperCTypesDefinitions: ImproperCTypesDefinitions,
188 VariantSizeDifferences: VariantSizeDifferences,
189 BoxPointers: BoxPointers,
190 PathStatements: PathStatements,
191 // Depends on referenced function signatures in expressions
192 UnusedResults: UnusedResults,
193 NonUpperCaseGlobals: NonUpperCaseGlobals,
194 NonShorthandFieldPatterns: NonShorthandFieldPatterns,
195 UnusedAllocation: UnusedAllocation,
196 // Depends on types used in type definitions
197 MissingCopyImplementations: MissingCopyImplementations,
198 // Depends on referenced function signatures in expressions
199 MutableTransmutes: MutableTransmutes,
200 TypeAliasBounds: TypeAliasBounds,
201 TrivialConstraints: TrivialConstraints,
202 TypeLimits: TypeLimits::new(),
203 NonSnakeCase: NonSnakeCase,
204 InvalidNoMangleItems: InvalidNoMangleItems,
205 // Depends on access levels
206 UnreachablePub: UnreachablePub,
207 ExplicitOutlivesRequirements: ExplicitOutlivesRequirements,
208 InvalidValue: InvalidValue,
209 DerefNullPtr: DerefNullPtr,
215 macro_rules! declare_combined_late_pass {
216 ([$v:vis $name:ident], $passes:tt) => (
217 late_lint_methods!(declare_combined_late_lint_pass, [$v $name, $passes], ['tcx]);
221 // FIXME: Make a separate lint type which do not require typeck tables
222 late_lint_passes!(declare_combined_late_pass, [pub BuiltinCombinedLateLintPass]);
224 late_lint_mod_passes!(declare_combined_late_pass, [BuiltinCombinedModuleLateLintPass]);
226 pub fn new_lint_store(no_interleave_lints: bool, internal_lints: bool) -> LintStore {
227 let mut lint_store = LintStore::new();
229 register_builtins(&mut lint_store, no_interleave_lints);
231 register_internals(&mut lint_store);
237 /// Tell the `LintStore` about all the built-in lints (the ones
238 /// defined in this crate and the ones defined in
239 /// `rustc_session::lint::builtin`).
240 fn register_builtins(store: &mut LintStore, no_interleave_lints: bool) {
241 macro_rules! add_lint_group {
242 ($name:expr, $($lint:ident),*) => (
243 store.register_group(false, $name, None, vec![$(LintId::of($lint)),*]);
247 macro_rules! register_pass {
248 ($method:ident, $ty:ident, $constructor:expr) => {
249 store.register_lints(&$ty::get_lints());
250 store.$method(|| box $constructor);
254 macro_rules! register_passes {
255 ($method:ident, [$($passes:ident: $constructor:expr,)*]) => (
257 register_pass!($method, $passes, $constructor);
262 if no_interleave_lints {
263 pre_expansion_lint_passes!(register_passes, register_pre_expansion_pass);
264 early_lint_passes!(register_passes, register_early_pass);
265 late_lint_passes!(register_passes, register_late_pass);
266 late_lint_mod_passes!(register_passes, register_late_mod_pass);
268 store.register_lints(&BuiltinCombinedPreExpansionLintPass::get_lints());
269 store.register_lints(&BuiltinCombinedEarlyLintPass::get_lints());
270 store.register_lints(&BuiltinCombinedModuleLateLintPass::get_lints());
271 store.register_lints(&BuiltinCombinedLateLintPass::get_lints());
276 NON_CAMEL_CASE_TYPES,
278 NON_UPPER_CASE_GLOBALS
289 UNREACHABLE_PATTERNS,
297 UNUSED_EXTERN_CRATES,
308 UNUSED_EXTERN_CRATES,
309 ELLIPSIS_INCLUSIVE_RANGE_PATTERNS,
310 ELIDED_LIFETIMES_IN_PATHS,
311 EXPLICIT_OUTLIVES_REQUIREMENTS // FIXME(#52665, #47816) not always applicable and not all
312 // macros are ready for this yet.
315 // FIXME macro crates are not up for this yet, too much
316 // breakage is seen if we try to encourage this lint.
317 // MACRO_USE_EXTERN_CRATE
320 // Register renamed and removed lints.
321 store.register_renamed("single_use_lifetime", "single_use_lifetimes");
322 store.register_renamed("elided_lifetime_in_path", "elided_lifetimes_in_paths");
323 store.register_renamed("bare_trait_object", "bare_trait_objects");
324 store.register_renamed("unstable_name_collision", "unstable_name_collisions");
325 store.register_renamed("unused_doc_comment", "unused_doc_comments");
326 store.register_renamed("async_idents", "keyword_idents");
327 store.register_renamed("exceeding_bitshifts", "arithmetic_overflow");
328 store.register_renamed("redundant_semicolon", "redundant_semicolons");
329 store.register_renamed("overlapping_patterns", "overlapping_range_endpoints");
330 store.register_renamed("safe_packed_borrows", "unaligned_references");
332 // These were moved to tool lints, but rustc still sees them when compiling normally, before
333 // tool lints are registered, so `check_tool_name_for_backwards_compat` doesn't work. Use
334 // `register_removed` explicitly.
335 const RUSTDOC_LINTS: &[&str] = &[
336 "broken_intra_doc_links",
337 "private_intra_doc_links",
338 "missing_crate_level_docs",
339 "missing_doc_code_examples",
341 "invalid_codeblock_attributes",
345 for rustdoc_lint in RUSTDOC_LINTS {
346 store.register_ignored(rustdoc_lint);
348 store.register_removed(
349 "intra_doc_link_resolution_failure",
350 "use `rustdoc::broken_intra_doc_links` instead",
352 store.register_removed("rustdoc", "use `rustdoc::all` instead");
354 store.register_removed("unknown_features", "replaced by an error");
355 store.register_removed("unsigned_negation", "replaced by negate_unsigned feature gate");
356 store.register_removed("negate_unsigned", "cast a signed value instead");
357 store.register_removed("raw_pointer_derive", "using derive with raw pointers is ok");
358 // Register lint group aliases.
359 store.register_group_alias("nonstandard_style", "bad_style");
360 // This was renamed to `raw_pointer_derive`, which was then removed,
361 // so it is also considered removed.
362 store.register_removed("raw_pointer_deriving", "using derive with raw pointers is ok");
363 store.register_removed("drop_with_repr_extern", "drop flags have been removed");
364 store.register_removed("fat_ptr_transmutes", "was accidentally removed back in 2014");
365 store.register_removed("deprecated_attr", "use `deprecated` instead");
366 store.register_removed(
367 "transmute_from_fn_item_types",
368 "always cast functions before transmuting them",
370 store.register_removed(
371 "hr_lifetime_in_assoc_type",
372 "converted into hard error, see issue #33685 \
373 <https://github.com/rust-lang/rust/issues/33685> for more information",
375 store.register_removed(
376 "inaccessible_extern_crate",
377 "converted into hard error, see issue #36886 \
378 <https://github.com/rust-lang/rust/issues/36886> for more information",
380 store.register_removed(
381 "super_or_self_in_global_path",
382 "converted into hard error, see issue #36888 \
383 <https://github.com/rust-lang/rust/issues/36888> for more information",
385 store.register_removed(
386 "overlapping_inherent_impls",
387 "converted into hard error, see issue #36889 \
388 <https://github.com/rust-lang/rust/issues/36889> for more information",
390 store.register_removed(
391 "illegal_floating_point_constant_pattern",
392 "converted into hard error, see issue #36890 \
393 <https://github.com/rust-lang/rust/issues/36890> for more information",
395 store.register_removed(
396 "illegal_struct_or_enum_constant_pattern",
397 "converted into hard error, see issue #36891 \
398 <https://github.com/rust-lang/rust/issues/36891> for more information",
400 store.register_removed(
401 "lifetime_underscore",
402 "converted into hard error, see issue #36892 \
403 <https://github.com/rust-lang/rust/issues/36892> for more information",
405 store.register_removed(
406 "extra_requirement_in_impl",
407 "converted into hard error, see issue #37166 \
408 <https://github.com/rust-lang/rust/issues/37166> for more information",
410 store.register_removed(
412 "converted into hard error, see issue #38260 \
413 <https://github.com/rust-lang/rust/issues/38260> for more information",
415 store.register_removed(
417 "converted into hard error, see issue #48950 \
418 <https://github.com/rust-lang/rust/issues/48950> for more information",
420 store.register_removed(
421 "resolve_trait_on_defaulted_unit",
422 "converted into hard error, see issue #48950 \
423 <https://github.com/rust-lang/rust/issues/48950> for more information",
425 store.register_removed(
426 "private_no_mangle_fns",
427 "no longer a warning, `#[no_mangle]` functions always exported",
429 store.register_removed(
430 "private_no_mangle_statics",
431 "no longer a warning, `#[no_mangle]` statics always exported",
433 store.register_removed("bad_repr", "replaced with a generic attribute input check");
434 store.register_removed(
435 "duplicate_matcher_binding_name",
436 "converted into hard error, see issue #57742 \
437 <https://github.com/rust-lang/rust/issues/57742> for more information",
439 store.register_removed(
440 "incoherent_fundamental_impls",
441 "converted into hard error, see issue #46205 \
442 <https://github.com/rust-lang/rust/issues/46205> for more information",
444 store.register_removed(
445 "legacy_constructor_visibility",
446 "converted into hard error, see issue #39207 \
447 <https://github.com/rust-lang/rust/issues/39207> for more information",
449 store.register_removed(
450 "legacy_directory_ownership",
451 "converted into hard error, see issue #37872 \
452 <https://github.com/rust-lang/rust/issues/37872> for more information",
454 store.register_removed(
455 "safe_extern_statics",
456 "converted into hard error, see issue #36247 \
457 <https://github.com/rust-lang/rust/issues/36247> for more information",
459 store.register_removed(
460 "parenthesized_params_in_types_and_modules",
461 "converted into hard error, see issue #42238 \
462 <https://github.com/rust-lang/rust/issues/42238> for more information",
464 store.register_removed(
465 "duplicate_macro_exports",
466 "converted into hard error, see issue #35896 \
467 <https://github.com/rust-lang/rust/issues/35896> for more information",
469 store.register_removed(
471 "converted into hard error, see issue #59014 \
472 <https://github.com/rust-lang/rust/issues/59014> for more information",
474 store.register_removed("plugin_as_library", "plugins have been deprecated and retired");
477 fn register_internals(store: &mut LintStore) {
478 store.register_lints(&DefaultHashTypes::get_lints());
479 store.register_early_pass(|| box DefaultHashTypes::new());
480 store.register_lints(&LintPassImpl::get_lints());
481 store.register_early_pass(|| box LintPassImpl);
482 store.register_lints(&ExistingDocKeyword::get_lints());
483 store.register_late_pass(|| box ExistingDocKeyword);
484 store.register_lints(&TyTyKind::get_lints());
485 store.register_late_pass(|| box TyTyKind);
486 store.register_group(
491 LintId::of(DEFAULT_HASH_TYPES),
492 LintId::of(USAGE_OF_TY_TYKIND),
493 LintId::of(LINT_PASS_IMPL_WITHOUT_MACRO),
494 LintId::of(TY_PASS_BY_REFERENCE),
495 LintId::of(USAGE_OF_QUALIFIED_TY),
496 LintId::of(EXISTING_DOC_KEYWORD),