]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_lint/src/lib.rs
Rollup merge of #106980 - Nilstrieb:_use_mk_manual_debug_impl_instead, r=lcnr
[rust.git] / compiler / rustc_lint / src / lib.rs
1 //! Lints, aka compiler warnings.
2 //!
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.
8 //!
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.
14 //!
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`
20 //! in `context.rs`.
21 //!
22 //! Some code also exists in [rustc_session::lint], [rustc_middle::lint].
23 //!
24 //! ## Note
25 //!
26 //! This API is completely unstable and subject to change.
27
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"]
41 #![deny(rustc::untranslatable_diagnostic)]
42 #![deny(rustc::diagnostic_outside_of_impl)]
43
44 #[macro_use]
45 extern crate rustc_middle;
46 #[macro_use]
47 extern crate rustc_session;
48 #[macro_use]
49 extern crate tracing;
50
51 mod array_into_iter;
52 pub mod builtin;
53 mod context;
54 mod deref_into_dyn_supertrait;
55 mod early;
56 mod enum_intrinsics_non_enums;
57 mod errors;
58 mod expect;
59 mod for_loops_over_fallibles;
60 pub mod hidden_unicode_codepoints;
61 mod internal;
62 mod late;
63 mod let_underscore;
64 mod levels;
65 mod lints;
66 mod methods;
67 mod non_ascii_idents;
68 mod non_fmt_panic;
69 mod nonstandard_style;
70 mod noop_method_call;
71 mod opaque_hidden_inferred_bound;
72 mod pass_by_value;
73 mod passes;
74 mod redundant_semicolon;
75 mod traits;
76 mod types;
77 mod unused;
78
79 pub use array_into_iter::ARRAY_INTO_ITER;
80
81 use rustc_ast as ast;
82 use rustc_hir as hir;
83 use rustc_hir::def_id::LocalDefId;
84 use rustc_middle::ty::query::Providers;
85 use rustc_middle::ty::TyCtxt;
86 use rustc_session::lint::builtin::{
87     BARE_TRAIT_OBJECTS, ELIDED_LIFETIMES_IN_PATHS, EXPLICIT_OUTLIVES_REQUIREMENTS,
88 };
89 use rustc_span::symbol::Ident;
90 use rustc_span::Span;
91
92 use array_into_iter::ArrayIntoIter;
93 use builtin::*;
94 use deref_into_dyn_supertrait::*;
95 use enum_intrinsics_non_enums::EnumIntrinsicsNonEnums;
96 use for_loops_over_fallibles::*;
97 use hidden_unicode_codepoints::*;
98 use internal::*;
99 use let_underscore::*;
100 use methods::*;
101 use non_ascii_idents::*;
102 use non_fmt_panic::NonPanicFmt;
103 use nonstandard_style::*;
104 use noop_method_call::*;
105 use opaque_hidden_inferred_bound::*;
106 use pass_by_value::*;
107 use redundant_semicolon::*;
108 use traits::*;
109 use types::*;
110 use unused::*;
111
112 /// Useful for other parts of the compiler / Clippy.
113 pub use builtin::SoftLints;
114 pub use context::{CheckLintNameResult, FindLintError, LintStore};
115 pub use context::{EarlyContext, LateContext, LintContext};
116 pub use early::{check_ast_node, EarlyCheckNode};
117 pub use late::{check_crate, unerased_lint_store};
118 pub use passes::{EarlyLintPass, LateLintPass};
119 pub use rustc_session::lint::Level::{self, *};
120 pub use rustc_session::lint::{BufferedEarlyLint, FutureIncompatibleInfo, Lint, LintId};
121 pub use rustc_session::lint::{LintArray, LintPass};
122
123 pub fn provide(providers: &mut Providers) {
124     levels::provide(providers);
125     expect::provide(providers);
126     *providers = Providers { lint_mod, ..*providers };
127 }
128
129 fn lint_mod(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
130     late::late_lint_mod(tcx, module_def_id, BuiltinCombinedModuleLateLintPass::new());
131 }
132
133 early_lint_methods!(
134     declare_combined_early_lint_pass,
135     [
136         pub BuiltinCombinedPreExpansionLintPass,
137         [
138             KeywordIdents: KeywordIdents,
139         ]
140     ]
141 );
142
143 early_lint_methods!(
144     declare_combined_early_lint_pass,
145     [
146         pub BuiltinCombinedEarlyLintPass,
147         [
148             UnusedParens: UnusedParens::new(),
149             UnusedBraces: UnusedBraces,
150             UnusedImportBraces: UnusedImportBraces,
151             UnsafeCode: UnsafeCode,
152             SpecialModuleName: SpecialModuleName,
153             AnonymousParameters: AnonymousParameters,
154             EllipsisInclusiveRangePatterns: EllipsisInclusiveRangePatterns::default(),
155             NonCamelCaseTypes: NonCamelCaseTypes,
156             DeprecatedAttr: DeprecatedAttr::new(),
157             WhileTrue: WhileTrue,
158             NonAsciiIdents: NonAsciiIdents,
159             HiddenUnicodeCodepoints: HiddenUnicodeCodepoints,
160             IncompleteFeatures: IncompleteFeatures,
161             RedundantSemicolons: RedundantSemicolons,
162             UnusedDocComment: UnusedDocComment,
163             UnexpectedCfgs: UnexpectedCfgs,
164         ]
165     ]
166 );
167
168 // FIXME: Make a separate lint type which does not require typeck tables.
169
170 late_lint_methods!(
171     declare_combined_late_lint_pass,
172     [
173         pub BuiltinCombinedLateLintPass,
174         [
175             // Tracks state across modules
176             UnnameableTestItems: UnnameableTestItems::new(),
177             // Tracks attributes of parents
178             MissingDoc: MissingDoc::new(),
179             // Builds a global list of all impls of `Debug`.
180             // FIXME: Turn the computation of types which implement Debug into a query
181             // and change this to a module lint pass
182             MissingDebugImplementations: MissingDebugImplementations::default(),
183             // Keeps a global list of foreign declarations.
184             ClashingExternDeclarations: ClashingExternDeclarations::new(),
185         ]
186     ]
187 );
188
189 late_lint_methods!(
190     declare_combined_late_lint_pass,
191     [
192         BuiltinCombinedModuleLateLintPass,
193         [
194             ForLoopsOverFallibles: ForLoopsOverFallibles,
195             DerefIntoDynSupertrait: DerefIntoDynSupertrait,
196             HardwiredLints: HardwiredLints,
197             ImproperCTypesDeclarations: ImproperCTypesDeclarations,
198             ImproperCTypesDefinitions: ImproperCTypesDefinitions,
199             VariantSizeDifferences: VariantSizeDifferences,
200             BoxPointers: BoxPointers,
201             PathStatements: PathStatements,
202             LetUnderscore: LetUnderscore,
203             // Depends on referenced function signatures in expressions
204             UnusedResults: UnusedResults,
205             NonUpperCaseGlobals: NonUpperCaseGlobals,
206             NonShorthandFieldPatterns: NonShorthandFieldPatterns,
207             UnusedAllocation: UnusedAllocation,
208             // Depends on types used in type definitions
209             MissingCopyImplementations: MissingCopyImplementations,
210             // Depends on referenced function signatures in expressions
211             MutableTransmutes: MutableTransmutes,
212             TypeAliasBounds: TypeAliasBounds,
213             TrivialConstraints: TrivialConstraints,
214             TypeLimits: TypeLimits::new(),
215             NonSnakeCase: NonSnakeCase,
216             InvalidNoMangleItems: InvalidNoMangleItems,
217             // Depends on effective visibilities
218             UnreachablePub: UnreachablePub,
219             ExplicitOutlivesRequirements: ExplicitOutlivesRequirements,
220             InvalidValue: InvalidValue,
221             DerefNullPtr: DerefNullPtr,
222             // May Depend on constants elsewhere
223             UnusedBrokenConst: UnusedBrokenConst,
224             UnstableFeatures: UnstableFeatures,
225             UngatedAsyncFnTrackCaller: UngatedAsyncFnTrackCaller,
226             ArrayIntoIter: ArrayIntoIter::default(),
227             DropTraitConstraints: DropTraitConstraints,
228             TemporaryCStringAsPtr: TemporaryCStringAsPtr,
229             NonPanicFmt: NonPanicFmt,
230             NoopMethodCall: NoopMethodCall,
231             EnumIntrinsicsNonEnums: EnumIntrinsicsNonEnums,
232             InvalidAtomicOrdering: InvalidAtomicOrdering,
233             NamedAsmLabels: NamedAsmLabels,
234             OpaqueHiddenInferredBound: OpaqueHiddenInferredBound,
235         ]
236     ]
237 );
238
239 pub fn new_lint_store(internal_lints: bool) -> LintStore {
240     let mut lint_store = LintStore::new();
241
242     register_builtins(&mut lint_store);
243     if internal_lints {
244         register_internals(&mut lint_store);
245     }
246
247     lint_store
248 }
249
250 /// Tell the `LintStore` about all the built-in lints (the ones
251 /// defined in this crate and the ones defined in
252 /// `rustc_session::lint::builtin`).
253 fn register_builtins(store: &mut LintStore) {
254     macro_rules! add_lint_group {
255         ($name:expr, $($lint:ident),*) => (
256             store.register_group(false, $name, None, vec![$(LintId::of($lint)),*]);
257         )
258     }
259
260     store.register_lints(&BuiltinCombinedPreExpansionLintPass::get_lints());
261     store.register_lints(&BuiltinCombinedEarlyLintPass::get_lints());
262     store.register_lints(&BuiltinCombinedModuleLateLintPass::get_lints());
263     store.register_lints(&BuiltinCombinedLateLintPass::get_lints());
264
265     add_lint_group!(
266         "nonstandard_style",
267         NON_CAMEL_CASE_TYPES,
268         NON_SNAKE_CASE,
269         NON_UPPER_CASE_GLOBALS
270     );
271
272     add_lint_group!(
273         "unused",
274         UNUSED_IMPORTS,
275         UNUSED_VARIABLES,
276         UNUSED_ASSIGNMENTS,
277         DEAD_CODE,
278         UNUSED_MUT,
279         UNREACHABLE_CODE,
280         UNREACHABLE_PATTERNS,
281         UNUSED_MUST_USE,
282         UNUSED_UNSAFE,
283         PATH_STATEMENTS,
284         UNUSED_ATTRIBUTES,
285         UNUSED_MACROS,
286         UNUSED_MACRO_RULES,
287         UNUSED_ALLOCATION,
288         UNUSED_DOC_COMMENTS,
289         UNUSED_EXTERN_CRATES,
290         UNUSED_FEATURES,
291         UNUSED_LABELS,
292         UNUSED_PARENS,
293         UNUSED_BRACES,
294         REDUNDANT_SEMICOLONS
295     );
296
297     add_lint_group!("let_underscore", LET_UNDERSCORE_DROP, LET_UNDERSCORE_LOCK);
298
299     add_lint_group!(
300         "rust_2018_idioms",
301         BARE_TRAIT_OBJECTS,
302         UNUSED_EXTERN_CRATES,
303         ELLIPSIS_INCLUSIVE_RANGE_PATTERNS,
304         ELIDED_LIFETIMES_IN_PATHS,
305         EXPLICIT_OUTLIVES_REQUIREMENTS // FIXME(#52665, #47816) not always applicable and not all
306                                        // macros are ready for this yet.
307                                        // UNREACHABLE_PUB,
308
309                                        // FIXME macro crates are not up for this yet, too much
310                                        // breakage is seen if we try to encourage this lint.
311                                        // MACRO_USE_EXTERN_CRATE
312     );
313
314     // Register renamed and removed lints.
315     store.register_renamed("single_use_lifetime", "single_use_lifetimes");
316     store.register_renamed("elided_lifetime_in_path", "elided_lifetimes_in_paths");
317     store.register_renamed("bare_trait_object", "bare_trait_objects");
318     store.register_renamed("unstable_name_collision", "unstable_name_collisions");
319     store.register_renamed("unused_doc_comment", "unused_doc_comments");
320     store.register_renamed("async_idents", "keyword_idents");
321     store.register_renamed("exceeding_bitshifts", "arithmetic_overflow");
322     store.register_renamed("redundant_semicolon", "redundant_semicolons");
323     store.register_renamed("overlapping_patterns", "overlapping_range_endpoints");
324     store.register_renamed("safe_packed_borrows", "unaligned_references");
325     store.register_renamed("disjoint_capture_migration", "rust_2021_incompatible_closure_captures");
326     store.register_renamed("or_patterns_back_compat", "rust_2021_incompatible_or_patterns");
327     store.register_renamed("non_fmt_panic", "non_fmt_panics");
328
329     // These were moved to tool lints, but rustc still sees them when compiling normally, before
330     // tool lints are registered, so `check_tool_name_for_backwards_compat` doesn't work. Use
331     // `register_removed` explicitly.
332     const RUSTDOC_LINTS: &[&str] = &[
333         "broken_intra_doc_links",
334         "private_intra_doc_links",
335         "missing_crate_level_docs",
336         "missing_doc_code_examples",
337         "private_doc_tests",
338         "invalid_codeblock_attributes",
339         "invalid_html_tags",
340         "non_autolinks",
341     ];
342     for rustdoc_lint in RUSTDOC_LINTS {
343         store.register_ignored(rustdoc_lint);
344     }
345     store.register_removed(
346         "intra_doc_link_resolution_failure",
347         "use `rustdoc::broken_intra_doc_links` instead",
348     );
349     store.register_removed("rustdoc", "use `rustdoc::all` instead");
350
351     store.register_removed("unknown_features", "replaced by an error");
352     store.register_removed("unsigned_negation", "replaced by negate_unsigned feature gate");
353     store.register_removed("negate_unsigned", "cast a signed value instead");
354     store.register_removed("raw_pointer_derive", "using derive with raw pointers is ok");
355     // Register lint group aliases.
356     store.register_group_alias("nonstandard_style", "bad_style");
357     // This was renamed to `raw_pointer_derive`, which was then removed,
358     // so it is also considered removed.
359     store.register_removed("raw_pointer_deriving", "using derive with raw pointers is ok");
360     store.register_removed("drop_with_repr_extern", "drop flags have been removed");
361     store.register_removed("fat_ptr_transmutes", "was accidentally removed back in 2014");
362     store.register_removed("deprecated_attr", "use `deprecated` instead");
363     store.register_removed(
364         "transmute_from_fn_item_types",
365         "always cast functions before transmuting them",
366     );
367     store.register_removed(
368         "hr_lifetime_in_assoc_type",
369         "converted into hard error, see issue #33685 \
370          <https://github.com/rust-lang/rust/issues/33685> for more information",
371     );
372     store.register_removed(
373         "inaccessible_extern_crate",
374         "converted into hard error, see issue #36886 \
375          <https://github.com/rust-lang/rust/issues/36886> for more information",
376     );
377     store.register_removed(
378         "super_or_self_in_global_path",
379         "converted into hard error, see issue #36888 \
380          <https://github.com/rust-lang/rust/issues/36888> for more information",
381     );
382     store.register_removed(
383         "overlapping_inherent_impls",
384         "converted into hard error, see issue #36889 \
385          <https://github.com/rust-lang/rust/issues/36889> for more information",
386     );
387     store.register_removed(
388         "illegal_floating_point_constant_pattern",
389         "converted into hard error, see issue #36890 \
390          <https://github.com/rust-lang/rust/issues/36890> for more information",
391     );
392     store.register_removed(
393         "illegal_struct_or_enum_constant_pattern",
394         "converted into hard error, see issue #36891 \
395          <https://github.com/rust-lang/rust/issues/36891> for more information",
396     );
397     store.register_removed(
398         "lifetime_underscore",
399         "converted into hard error, see issue #36892 \
400          <https://github.com/rust-lang/rust/issues/36892> for more information",
401     );
402     store.register_removed(
403         "extra_requirement_in_impl",
404         "converted into hard error, see issue #37166 \
405          <https://github.com/rust-lang/rust/issues/37166> for more information",
406     );
407     store.register_removed(
408         "legacy_imports",
409         "converted into hard error, see issue #38260 \
410          <https://github.com/rust-lang/rust/issues/38260> for more information",
411     );
412     store.register_removed(
413         "coerce_never",
414         "converted into hard error, see issue #48950 \
415          <https://github.com/rust-lang/rust/issues/48950> for more information",
416     );
417     store.register_removed(
418         "resolve_trait_on_defaulted_unit",
419         "converted into hard error, see issue #48950 \
420          <https://github.com/rust-lang/rust/issues/48950> for more information",
421     );
422     store.register_removed(
423         "private_no_mangle_fns",
424         "no longer a warning, `#[no_mangle]` functions always exported",
425     );
426     store.register_removed(
427         "private_no_mangle_statics",
428         "no longer a warning, `#[no_mangle]` statics always exported",
429     );
430     store.register_removed("bad_repr", "replaced with a generic attribute input check");
431     store.register_removed(
432         "duplicate_matcher_binding_name",
433         "converted into hard error, see issue #57742 \
434          <https://github.com/rust-lang/rust/issues/57742> for more information",
435     );
436     store.register_removed(
437         "incoherent_fundamental_impls",
438         "converted into hard error, see issue #46205 \
439          <https://github.com/rust-lang/rust/issues/46205> for more information",
440     );
441     store.register_removed(
442         "legacy_constructor_visibility",
443         "converted into hard error, see issue #39207 \
444          <https://github.com/rust-lang/rust/issues/39207> for more information",
445     );
446     store.register_removed(
447         "legacy_directory_ownership",
448         "converted into hard error, see issue #37872 \
449          <https://github.com/rust-lang/rust/issues/37872> for more information",
450     );
451     store.register_removed(
452         "safe_extern_statics",
453         "converted into hard error, see issue #36247 \
454          <https://github.com/rust-lang/rust/issues/36247> for more information",
455     );
456     store.register_removed(
457         "parenthesized_params_in_types_and_modules",
458         "converted into hard error, see issue #42238 \
459          <https://github.com/rust-lang/rust/issues/42238> for more information",
460     );
461     store.register_removed(
462         "duplicate_macro_exports",
463         "converted into hard error, see issue #35896 \
464          <https://github.com/rust-lang/rust/issues/35896> for more information",
465     );
466     store.register_removed(
467         "nested_impl_trait",
468         "converted into hard error, see issue #59014 \
469          <https://github.com/rust-lang/rust/issues/59014> for more information",
470     );
471     store.register_removed("plugin_as_library", "plugins have been deprecated and retired");
472     store.register_removed(
473         "unsupported_naked_functions",
474         "converted into hard error, see RFC 2972 \
475          <https://github.com/rust-lang/rfcs/blob/master/text/2972-constrained-naked.md> for more information",
476     );
477     store.register_removed(
478         "mutable_borrow_reservation_conflict",
479         "now allowed, see issue #59159 \
480          <https://github.com/rust-lang/rust/issues/59159> for more information",
481     );
482     store.register_removed(
483         "const_err",
484         "converted into hard error, see issue #71800 \
485          <https://github.com/rust-lang/rust/issues/71800> for more information",
486     );
487 }
488
489 fn register_internals(store: &mut LintStore) {
490     store.register_lints(&LintPassImpl::get_lints());
491     store.register_early_pass(|| Box::new(LintPassImpl));
492     store.register_lints(&DefaultHashTypes::get_lints());
493     store.register_late_pass(|_| Box::new(DefaultHashTypes));
494     store.register_lints(&QueryStability::get_lints());
495     store.register_late_pass(|_| Box::new(QueryStability));
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(&Diagnostics::get_lints());
501     store.register_late_pass(|_| Box::new(Diagnostics));
502     store.register_lints(&BadOptAccess::get_lints());
503     store.register_late_pass(|_| Box::new(BadOptAccess));
504     store.register_lints(&PassByValue::get_lints());
505     store.register_late_pass(|_| Box::new(PassByValue));
506     // FIXME(davidtwco): deliberately do not include `UNTRANSLATABLE_DIAGNOSTIC` and
507     // `DIAGNOSTIC_OUTSIDE_OF_IMPL` here because `-Wrustc::internal` is provided to every crate and
508     // these lints will trigger all of the time - change this once migration to diagnostic structs
509     // and translation is completed
510     store.register_group(
511         false,
512         "rustc::internal",
513         None,
514         vec![
515             LintId::of(DEFAULT_HASH_TYPES),
516             LintId::of(POTENTIAL_QUERY_INSTABILITY),
517             LintId::of(USAGE_OF_TY_TYKIND),
518             LintId::of(PASS_BY_VALUE),
519             LintId::of(LINT_PASS_IMPL_WITHOUT_MACRO),
520             LintId::of(USAGE_OF_QUALIFIED_TY),
521             LintId::of(EXISTING_DOC_KEYWORD),
522             LintId::of(BAD_OPT_ACCESS),
523         ],
524     );
525 }
526
527 #[cfg(test)]
528 mod tests;