]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_lint/src/lib.rs
Rollup merge of #93192 - theidexisted:patch-1, r=wesleywiser
[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 #![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)]
34 #![feature(let_else)]
35 #![feature(never_type)]
36 #![feature(nll)]
37 #![feature(control_flow_enum)]
38 #![recursion_limit = "256"]
39
40 #[macro_use]
41 extern crate rustc_middle;
42 #[macro_use]
43 extern crate rustc_session;
44
45 mod array_into_iter;
46 pub mod builtin;
47 mod context;
48 mod early;
49 mod enum_intrinsics_non_enums;
50 pub mod hidden_unicode_codepoints;
51 mod internal;
52 mod late;
53 mod levels;
54 mod methods;
55 mod non_ascii_idents;
56 mod non_fmt_panic;
57 mod nonstandard_style;
58 mod noop_method_call;
59 mod pass_by_value;
60 mod passes;
61 mod redundant_semicolon;
62 mod traits;
63 mod types;
64 mod unused;
65
66 pub use array_into_iter::ARRAY_INTO_ITER;
67
68 use rustc_ast as ast;
69 use rustc_hir as hir;
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,
75 };
76 use rustc_span::symbol::{Ident, Symbol};
77 use rustc_span::Span;
78
79 use array_into_iter::ArrayIntoIter;
80 use builtin::*;
81 use enum_intrinsics_non_enums::EnumIntrinsicsNonEnums;
82 use hidden_unicode_codepoints::*;
83 use internal::*;
84 use methods::*;
85 use non_ascii_idents::*;
86 use non_fmt_panic::NonPanicFmt;
87 use nonstandard_style::*;
88 use noop_method_call::*;
89 use pass_by_value::*;
90 use redundant_semicolon::*;
91 use traits::*;
92 use types::*;
93 use unused::*;
94
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};
105
106 pub fn provide(providers: &mut Providers) {
107     levels::provide(providers);
108     *providers = Providers { lint_mod, ..*providers };
109 }
110
111 fn lint_mod(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
112     late::late_lint_mod(tcx, module_def_id, BuiltinCombinedModuleLateLintPass::new());
113 }
114
115 macro_rules! pre_expansion_lint_passes {
116     ($macro:path, $args:tt) => {
117         $macro!($args, [KeywordIdents: KeywordIdents,]);
118     };
119 }
120
121 macro_rules! early_lint_passes {
122     ($macro:path, $args:tt) => {
123         $macro!(
124             $args,
125             [
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,
140             ]
141         );
142     };
143 }
144
145 macro_rules! declare_combined_early_pass {
146     ([$name:ident], $passes:tt) => (
147         early_lint_methods!(declare_combined_early_lint_pass, [pub $name, $passes]);
148     )
149 }
150
151 pre_expansion_lint_passes!(declare_combined_early_pass, [BuiltinCombinedPreExpansionLintPass]);
152 early_lint_passes!(declare_combined_early_pass, [BuiltinCombinedEarlyLintPass]);
153
154 macro_rules! late_lint_passes {
155     ($macro:path, $args:tt) => {
156         $macro!(
157             $args,
158             [
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,
181             ]
182         );
183     };
184 }
185
186 macro_rules! late_lint_mod_passes {
187     ($macro:path, $args:tt) => {
188         $macro!(
189             $args,
190             [
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,
216             ]
217         );
218     };
219 }
220
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]);
224     )
225 }
226
227 // FIXME: Make a separate lint type which do not require typeck tables
228 late_lint_passes!(declare_combined_late_pass, [pub BuiltinCombinedLateLintPass]);
229
230 late_lint_mod_passes!(declare_combined_late_pass, [BuiltinCombinedModuleLateLintPass]);
231
232 pub fn new_lint_store(no_interleave_lints: bool, internal_lints: bool) -> LintStore {
233     let mut lint_store = LintStore::new();
234
235     register_builtins(&mut lint_store, no_interleave_lints);
236     if internal_lints {
237         register_internals(&mut lint_store);
238     }
239
240     lint_store
241 }
242
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)),*]);
250         )
251     }
252
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));
257         };
258     }
259
260     macro_rules! register_passes {
261         ($method:ident, [$($passes:ident: $constructor:expr,)*]) => (
262             $(
263                 register_pass!($method, $passes, $constructor);
264             )*
265         )
266     }
267
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);
273     } else {
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());
278     }
279
280     add_lint_group!(
281         "nonstandard_style",
282         NON_CAMEL_CASE_TYPES,
283         NON_SNAKE_CASE,
284         NON_UPPER_CASE_GLOBALS
285     );
286
287     add_lint_group!(
288         "unused",
289         UNUSED_IMPORTS,
290         UNUSED_VARIABLES,
291         UNUSED_ASSIGNMENTS,
292         DEAD_CODE,
293         UNUSED_MUT,
294         UNREACHABLE_CODE,
295         UNREACHABLE_PATTERNS,
296         UNUSED_MUST_USE,
297         UNUSED_UNSAFE,
298         PATH_STATEMENTS,
299         UNUSED_ATTRIBUTES,
300         UNUSED_MACROS,
301         UNUSED_ALLOCATION,
302         UNUSED_DOC_COMMENTS,
303         UNUSED_EXTERN_CRATES,
304         UNUSED_FEATURES,
305         UNUSED_LABELS,
306         UNUSED_PARENS,
307         UNUSED_BRACES,
308         REDUNDANT_SEMICOLONS
309     );
310
311     add_lint_group!(
312         "rust_2018_idioms",
313         BARE_TRAIT_OBJECTS,
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.
319                                        // UNREACHABLE_PUB,
320
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
324     );
325
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");
340
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",
349         "private_doc_tests",
350         "invalid_codeblock_attributes",
351         "invalid_html_tags",
352         "non_autolinks",
353     ];
354     for rustdoc_lint in RUSTDOC_LINTS {
355         store.register_ignored(rustdoc_lint);
356     }
357     store.register_removed(
358         "intra_doc_link_resolution_failure",
359         "use `rustdoc::broken_intra_doc_links` instead",
360     );
361     store.register_removed("rustdoc", "use `rustdoc::all` instead");
362
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",
378     );
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",
383     );
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",
388     );
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",
393     );
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",
398     );
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",
403     );
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",
408     );
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",
413     );
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",
418     );
419     store.register_removed(
420         "legacy_imports",
421         "converted into hard error, see issue #38260 \
422          <https://github.com/rust-lang/rust/issues/38260> for more information",
423     );
424     store.register_removed(
425         "coerce_never",
426         "converted into hard error, see issue #48950 \
427          <https://github.com/rust-lang/rust/issues/48950> for more information",
428     );
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",
433     );
434     store.register_removed(
435         "private_no_mangle_fns",
436         "no longer a warning, `#[no_mangle]` functions always exported",
437     );
438     store.register_removed(
439         "private_no_mangle_statics",
440         "no longer a warning, `#[no_mangle]` statics always exported",
441     );
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",
447     );
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",
452     );
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",
457     );
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",
462     );
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",
467     );
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",
472     );
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",
477     );
478     store.register_removed(
479         "nested_impl_trait",
480         "converted into hard error, see issue #59014 \
481          <https://github.com/rust-lang/rust/issues/59014> for more information",
482     );
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",
488     );
489 }
490
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(
503         false,
504         "rustc::internal",
505         None,
506         vec![
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),
513         ],
514     );
515 }
516
517 #[cfg(test)]
518 mod tests;