]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_lint/src/lib.rs
Rollup merge of #90333 - jsha:flashy-searchbar, r=GuillaumeGomez
[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(format_args_capture)]
34 #![feature(iter_order_by)]
35 #![feature(iter_zip)]
36 #![feature(never_type)]
37 #![feature(nll)]
38 #![feature(control_flow_enum)]
39 #![recursion_limit = "256"]
40
41 #[macro_use]
42 extern crate rustc_middle;
43 #[macro_use]
44 extern crate rustc_session;
45
46 mod array_into_iter;
47 pub mod builtin;
48 mod context;
49 mod early;
50 mod enum_intrinsics_non_enums;
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 passes;
60 mod redundant_semicolon;
61 mod traits;
62 mod types;
63 mod unused;
64
65 pub use array_into_iter::ARRAY_INTO_ITER;
66
67 use rustc_ast as ast;
68 use rustc_hir as hir;
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,
74 };
75 use rustc_span::symbol::{Ident, Symbol};
76 use rustc_span::Span;
77
78 use array_into_iter::ArrayIntoIter;
79 use builtin::*;
80 use enum_intrinsics_non_enums::EnumIntrinsicsNonEnums;
81 use internal::*;
82 use methods::*;
83 use non_ascii_idents::*;
84 use non_fmt_panic::NonPanicFmt;
85 use nonstandard_style::*;
86 use noop_method_call::*;
87 use redundant_semicolon::*;
88 use traits::*;
89 use types::*;
90 use unused::*;
91
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};
101
102 pub fn provide(providers: &mut Providers) {
103     levels::provide(providers);
104     *providers = Providers { lint_mod, ..*providers };
105 }
106
107 fn lint_mod(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
108     late::late_lint_mod(tcx, module_def_id, BuiltinCombinedModuleLateLintPass::new());
109 }
110
111 macro_rules! pre_expansion_lint_passes {
112     ($macro:path, $args:tt) => {
113         $macro!($args, [KeywordIdents: KeywordIdents,]);
114     };
115 }
116
117 macro_rules! early_lint_passes {
118     ($macro:path, $args:tt) => {
119         $macro!(
120             $args,
121             [
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,
135             ]
136         );
137     };
138 }
139
140 macro_rules! declare_combined_early_pass {
141     ([$name:ident], $passes:tt) => (
142         early_lint_methods!(declare_combined_early_lint_pass, [pub $name, $passes]);
143     )
144 }
145
146 pre_expansion_lint_passes!(declare_combined_early_pass, [BuiltinCombinedPreExpansionLintPass]);
147 early_lint_passes!(declare_combined_early_pass, [BuiltinCombinedEarlyLintPass]);
148
149 macro_rules! late_lint_passes {
150     ($macro:path, $args:tt) => {
151         $macro!(
152             $args,
153             [
154                 // FIXME: Look into regression when this is used as a module lint
155                 // May Depend on constants elsewhere
156                 UnusedBrokenConst: UnusedBrokenConst,
157                 // Needs to run after UnusedAttributes as it marks all `feature` attributes as used.
158                 UnstableFeatures: UnstableFeatures,
159                 // Tracks state across modules
160                 UnnameableTestItems: UnnameableTestItems::new(),
161                 // Tracks attributes of parents
162                 MissingDoc: MissingDoc::new(),
163                 // Depends on access levels
164                 // FIXME: Turn the computation of types which implement Debug into a query
165                 // and change this to a module lint pass
166                 MissingDebugImplementations: MissingDebugImplementations::default(),
167                 ArrayIntoIter: ArrayIntoIter::default(),
168                 ClashingExternDeclarations: ClashingExternDeclarations::new(),
169                 DropTraitConstraints: DropTraitConstraints,
170                 TemporaryCStringAsPtr: TemporaryCStringAsPtr,
171                 NonPanicFmt: NonPanicFmt,
172                 NoopMethodCall: NoopMethodCall,
173                 EnumIntrinsicsNonEnums: EnumIntrinsicsNonEnums,
174                 InvalidAtomicOrdering: InvalidAtomicOrdering,
175                 NamedAsmLabels: NamedAsmLabels,
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             ]
212         );
213     };
214 }
215
216 macro_rules! declare_combined_late_pass {
217     ([$v:vis $name:ident], $passes:tt) => (
218         late_lint_methods!(declare_combined_late_lint_pass, [$v $name, $passes], ['tcx]);
219     )
220 }
221
222 // FIXME: Make a separate lint type which do not require typeck tables
223 late_lint_passes!(declare_combined_late_pass, [pub BuiltinCombinedLateLintPass]);
224
225 late_lint_mod_passes!(declare_combined_late_pass, [BuiltinCombinedModuleLateLintPass]);
226
227 pub fn new_lint_store(no_interleave_lints: bool, internal_lints: bool) -> LintStore {
228     let mut lint_store = LintStore::new();
229
230     register_builtins(&mut lint_store, no_interleave_lints);
231     if internal_lints {
232         register_internals(&mut lint_store);
233     }
234
235     lint_store
236 }
237
238 /// Tell the `LintStore` about all the built-in lints (the ones
239 /// defined in this crate and the ones defined in
240 /// `rustc_session::lint::builtin`).
241 fn register_builtins(store: &mut LintStore, no_interleave_lints: bool) {
242     macro_rules! add_lint_group {
243         ($name:expr, $($lint:ident),*) => (
244             store.register_group(false, $name, None, vec![$(LintId::of($lint)),*]);
245         )
246     }
247
248     macro_rules! register_pass {
249         ($method:ident, $ty:ident, $constructor:expr) => {
250             store.register_lints(&$ty::get_lints());
251             store.$method(|| Box::new($constructor));
252         };
253     }
254
255     macro_rules! register_passes {
256         ($method:ident, [$($passes:ident: $constructor:expr,)*]) => (
257             $(
258                 register_pass!($method, $passes, $constructor);
259             )*
260         )
261     }
262
263     if no_interleave_lints {
264         pre_expansion_lint_passes!(register_passes, register_pre_expansion_pass);
265         early_lint_passes!(register_passes, register_early_pass);
266         late_lint_passes!(register_passes, register_late_pass);
267         late_lint_mod_passes!(register_passes, register_late_mod_pass);
268     } else {
269         store.register_lints(&BuiltinCombinedPreExpansionLintPass::get_lints());
270         store.register_lints(&BuiltinCombinedEarlyLintPass::get_lints());
271         store.register_lints(&BuiltinCombinedModuleLateLintPass::get_lints());
272         store.register_lints(&BuiltinCombinedLateLintPass::get_lints());
273     }
274
275     add_lint_group!(
276         "nonstandard_style",
277         NON_CAMEL_CASE_TYPES,
278         NON_SNAKE_CASE,
279         NON_UPPER_CASE_GLOBALS
280     );
281
282     add_lint_group!(
283         "unused",
284         UNUSED_IMPORTS,
285         UNUSED_VARIABLES,
286         UNUSED_ASSIGNMENTS,
287         DEAD_CODE,
288         UNUSED_MUT,
289         UNREACHABLE_CODE,
290         UNREACHABLE_PATTERNS,
291         UNUSED_MUST_USE,
292         UNUSED_UNSAFE,
293         PATH_STATEMENTS,
294         UNUSED_ATTRIBUTES,
295         UNUSED_MACROS,
296         UNUSED_ALLOCATION,
297         UNUSED_DOC_COMMENTS,
298         UNUSED_EXTERN_CRATES,
299         UNUSED_FEATURES,
300         UNUSED_LABELS,
301         UNUSED_PARENS,
302         UNUSED_BRACES,
303         REDUNDANT_SEMICOLONS
304     );
305
306     add_lint_group!(
307         "rust_2018_idioms",
308         BARE_TRAIT_OBJECTS,
309         UNUSED_EXTERN_CRATES,
310         ELLIPSIS_INCLUSIVE_RANGE_PATTERNS,
311         ELIDED_LIFETIMES_IN_PATHS,
312         EXPLICIT_OUTLIVES_REQUIREMENTS // FIXME(#52665, #47816) not always applicable and not all
313                                        // macros are ready for this yet.
314                                        // UNREACHABLE_PUB,
315
316                                        // FIXME macro crates are not up for this yet, too much
317                                        // breakage is seen if we try to encourage this lint.
318                                        // MACRO_USE_EXTERN_CRATE
319     );
320
321     // Register renamed and removed lints.
322     store.register_renamed("single_use_lifetime", "single_use_lifetimes");
323     store.register_renamed("elided_lifetime_in_path", "elided_lifetimes_in_paths");
324     store.register_renamed("bare_trait_object", "bare_trait_objects");
325     store.register_renamed("unstable_name_collision", "unstable_name_collisions");
326     store.register_renamed("unused_doc_comment", "unused_doc_comments");
327     store.register_renamed("async_idents", "keyword_idents");
328     store.register_renamed("exceeding_bitshifts", "arithmetic_overflow");
329     store.register_renamed("redundant_semicolon", "redundant_semicolons");
330     store.register_renamed("overlapping_patterns", "overlapping_range_endpoints");
331     store.register_renamed("safe_packed_borrows", "unaligned_references");
332     store.register_renamed("disjoint_capture_migration", "rust_2021_incompatible_closure_captures");
333     store.register_renamed("or_patterns_back_compat", "rust_2021_incompatible_or_patterns");
334     store.register_renamed("non_fmt_panic", "non_fmt_panics");
335
336     // These were moved to tool lints, but rustc still sees them when compiling normally, before
337     // tool lints are registered, so `check_tool_name_for_backwards_compat` doesn't work. Use
338     // `register_removed` explicitly.
339     const RUSTDOC_LINTS: &[&str] = &[
340         "broken_intra_doc_links",
341         "private_intra_doc_links",
342         "missing_crate_level_docs",
343         "missing_doc_code_examples",
344         "private_doc_tests",
345         "invalid_codeblock_attributes",
346         "invalid_html_tags",
347         "non_autolinks",
348     ];
349     for rustdoc_lint in RUSTDOC_LINTS {
350         store.register_ignored(rustdoc_lint);
351     }
352     store.register_removed(
353         "intra_doc_link_resolution_failure",
354         "use `rustdoc::broken_intra_doc_links` instead",
355     );
356     store.register_removed("rustdoc", "use `rustdoc::all` instead");
357
358     store.register_removed("unknown_features", "replaced by an error");
359     store.register_removed("unsigned_negation", "replaced by negate_unsigned feature gate");
360     store.register_removed("negate_unsigned", "cast a signed value instead");
361     store.register_removed("raw_pointer_derive", "using derive with raw pointers is ok");
362     // Register lint group aliases.
363     store.register_group_alias("nonstandard_style", "bad_style");
364     // This was renamed to `raw_pointer_derive`, which was then removed,
365     // so it is also considered removed.
366     store.register_removed("raw_pointer_deriving", "using derive with raw pointers is ok");
367     store.register_removed("drop_with_repr_extern", "drop flags have been removed");
368     store.register_removed("fat_ptr_transmutes", "was accidentally removed back in 2014");
369     store.register_removed("deprecated_attr", "use `deprecated` instead");
370     store.register_removed(
371         "transmute_from_fn_item_types",
372         "always cast functions before transmuting them",
373     );
374     store.register_removed(
375         "hr_lifetime_in_assoc_type",
376         "converted into hard error, see issue #33685 \
377          <https://github.com/rust-lang/rust/issues/33685> for more information",
378     );
379     store.register_removed(
380         "inaccessible_extern_crate",
381         "converted into hard error, see issue #36886 \
382          <https://github.com/rust-lang/rust/issues/36886> for more information",
383     );
384     store.register_removed(
385         "super_or_self_in_global_path",
386         "converted into hard error, see issue #36888 \
387          <https://github.com/rust-lang/rust/issues/36888> for more information",
388     );
389     store.register_removed(
390         "overlapping_inherent_impls",
391         "converted into hard error, see issue #36889 \
392          <https://github.com/rust-lang/rust/issues/36889> for more information",
393     );
394     store.register_removed(
395         "illegal_floating_point_constant_pattern",
396         "converted into hard error, see issue #36890 \
397          <https://github.com/rust-lang/rust/issues/36890> for more information",
398     );
399     store.register_removed(
400         "illegal_struct_or_enum_constant_pattern",
401         "converted into hard error, see issue #36891 \
402          <https://github.com/rust-lang/rust/issues/36891> for more information",
403     );
404     store.register_removed(
405         "lifetime_underscore",
406         "converted into hard error, see issue #36892 \
407          <https://github.com/rust-lang/rust/issues/36892> for more information",
408     );
409     store.register_removed(
410         "extra_requirement_in_impl",
411         "converted into hard error, see issue #37166 \
412          <https://github.com/rust-lang/rust/issues/37166> for more information",
413     );
414     store.register_removed(
415         "legacy_imports",
416         "converted into hard error, see issue #38260 \
417          <https://github.com/rust-lang/rust/issues/38260> for more information",
418     );
419     store.register_removed(
420         "coerce_never",
421         "converted into hard error, see issue #48950 \
422          <https://github.com/rust-lang/rust/issues/48950> for more information",
423     );
424     store.register_removed(
425         "resolve_trait_on_defaulted_unit",
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         "private_no_mangle_fns",
431         "no longer a warning, `#[no_mangle]` functions always exported",
432     );
433     store.register_removed(
434         "private_no_mangle_statics",
435         "no longer a warning, `#[no_mangle]` statics always exported",
436     );
437     store.register_removed("bad_repr", "replaced with a generic attribute input check");
438     store.register_removed(
439         "duplicate_matcher_binding_name",
440         "converted into hard error, see issue #57742 \
441          <https://github.com/rust-lang/rust/issues/57742> for more information",
442     );
443     store.register_removed(
444         "incoherent_fundamental_impls",
445         "converted into hard error, see issue #46205 \
446          <https://github.com/rust-lang/rust/issues/46205> for more information",
447     );
448     store.register_removed(
449         "legacy_constructor_visibility",
450         "converted into hard error, see issue #39207 \
451          <https://github.com/rust-lang/rust/issues/39207> for more information",
452     );
453     store.register_removed(
454         "legacy_directory_ownership",
455         "converted into hard error, see issue #37872 \
456          <https://github.com/rust-lang/rust/issues/37872> for more information",
457     );
458     store.register_removed(
459         "safe_extern_statics",
460         "converted into hard error, see issue #36247 \
461          <https://github.com/rust-lang/rust/issues/36247> for more information",
462     );
463     store.register_removed(
464         "parenthesized_params_in_types_and_modules",
465         "converted into hard error, see issue #42238 \
466          <https://github.com/rust-lang/rust/issues/42238> for more information",
467     );
468     store.register_removed(
469         "duplicate_macro_exports",
470         "converted into hard error, see issue #35896 \
471          <https://github.com/rust-lang/rust/issues/35896> for more information",
472     );
473     store.register_removed(
474         "nested_impl_trait",
475         "converted into hard error, see issue #59014 \
476          <https://github.com/rust-lang/rust/issues/59014> for more information",
477     );
478     store.register_removed("plugin_as_library", "plugins have been deprecated and retired");
479 }
480
481 fn register_internals(store: &mut LintStore) {
482     store.register_lints(&LintPassImpl::get_lints());
483     store.register_early_pass(|| Box::new(LintPassImpl));
484     store.register_lints(&DefaultHashTypes::get_lints());
485     store.register_late_pass(|| Box::new(DefaultHashTypes));
486     store.register_lints(&ExistingDocKeyword::get_lints());
487     store.register_late_pass(|| Box::new(ExistingDocKeyword));
488     store.register_lints(&TyTyKind::get_lints());
489     store.register_late_pass(|| Box::new(TyTyKind));
490     store.register_group(
491         false,
492         "rustc::internal",
493         None,
494         vec![
495             LintId::of(DEFAULT_HASH_TYPES),
496             LintId::of(USAGE_OF_TY_TYKIND),
497             LintId::of(LINT_PASS_IMPL_WITHOUT_MACRO),
498             LintId::of(TY_PASS_BY_REFERENCE),
499             LintId::of(USAGE_OF_QUALIFIED_TY),
500             LintId::of(EXISTING_DOC_KEYWORD),
501         ],
502     );
503 }
504
505 #[cfg(test)]
506 mod tests;