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