]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_lint/src/lib.rs
Merge commit '4f3ab69ea0a0908260944443c739426cc384ae1a' into clippyup
[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
42 #[macro_use]
43 extern crate rustc_middle;
44 #[macro_use]
45 extern crate rustc_session;
46 #[macro_use]
47 extern crate tracing;
48
49 mod array_into_iter;
50 pub mod builtin;
51 mod context;
52 mod deref_into_dyn_supertrait;
53 mod early;
54 mod enum_intrinsics_non_enums;
55 mod errors;
56 mod expect;
57 mod for_loops_over_fallibles;
58 pub mod hidden_unicode_codepoints;
59 mod internal;
60 mod late;
61 mod let_underscore;
62 mod levels;
63 mod methods;
64 mod multiple_supertrait_upcastable;
65 mod non_ascii_idents;
66 mod non_fmt_panic;
67 mod nonstandard_style;
68 mod noop_method_call;
69 mod opaque_hidden_inferred_bound;
70 mod pass_by_value;
71 mod passes;
72 mod redundant_semicolon;
73 mod traits;
74 mod types;
75 mod unused;
76
77 pub use array_into_iter::ARRAY_INTO_ITER;
78
79 use rustc_ast as ast;
80 use rustc_hir as hir;
81 use rustc_hir::def_id::LocalDefId;
82 use rustc_middle::ty::query::Providers;
83 use rustc_middle::ty::TyCtxt;
84 use rustc_session::lint::builtin::{
85     BARE_TRAIT_OBJECTS, ELIDED_LIFETIMES_IN_PATHS, EXPLICIT_OUTLIVES_REQUIREMENTS,
86 };
87 use rustc_span::symbol::Ident;
88 use rustc_span::Span;
89
90 use array_into_iter::ArrayIntoIter;
91 use builtin::*;
92 use deref_into_dyn_supertrait::*;
93 use enum_intrinsics_non_enums::EnumIntrinsicsNonEnums;
94 use for_loops_over_fallibles::*;
95 use hidden_unicode_codepoints::*;
96 use internal::*;
97 use let_underscore::*;
98 use methods::*;
99 use multiple_supertrait_upcastable::*;
100 use non_ascii_idents::*;
101 use non_fmt_panic::NonPanicFmt;
102 use nonstandard_style::*;
103 use noop_method_call::*;
104 use opaque_hidden_inferred_bound::*;
105 use pass_by_value::*;
106 use redundant_semicolon::*;
107 use traits::*;
108 use types::*;
109 use unused::*;
110
111 /// Useful for other parts of the compiler / Clippy.
112 pub use builtin::SoftLints;
113 pub use context::{CheckLintNameResult, FindLintError, LintStore};
114 pub use context::{EarlyContext, LateContext, LintContext};
115 pub use early::{check_ast_node, EarlyCheckNode};
116 pub use late::{check_crate, unerased_lint_store};
117 pub use passes::{EarlyLintPass, LateLintPass};
118 pub use rustc_session::lint::Level::{self, *};
119 pub use rustc_session::lint::{BufferedEarlyLint, FutureIncompatibleInfo, Lint, LintId};
120 pub use rustc_session::lint::{LintArray, LintPass};
121
122 pub fn provide(providers: &mut Providers) {
123     levels::provide(providers);
124     expect::provide(providers);
125     *providers = Providers { lint_mod, ..*providers };
126 }
127
128 fn lint_mod(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
129     late::late_lint_mod(tcx, module_def_id, BuiltinCombinedModuleLateLintPass::new());
130 }
131
132 early_lint_methods!(
133     declare_combined_early_lint_pass,
134     [
135         pub BuiltinCombinedPreExpansionLintPass,
136         [
137             KeywordIdents: KeywordIdents,
138         ]
139     ]
140 );
141
142 early_lint_methods!(
143     declare_combined_early_lint_pass,
144     [
145         pub BuiltinCombinedEarlyLintPass,
146         [
147             UnusedParens: UnusedParens,
148             UnusedBraces: UnusedBraces,
149             UnusedImportBraces: UnusedImportBraces,
150             UnsafeCode: UnsafeCode,
151             SpecialModuleName: SpecialModuleName,
152             AnonymousParameters: AnonymousParameters,
153             EllipsisInclusiveRangePatterns: EllipsisInclusiveRangePatterns::default(),
154             NonCamelCaseTypes: NonCamelCaseTypes,
155             DeprecatedAttr: DeprecatedAttr::new(),
156             WhileTrue: WhileTrue,
157             NonAsciiIdents: NonAsciiIdents,
158             HiddenUnicodeCodepoints: HiddenUnicodeCodepoints,
159             IncompleteFeatures: IncompleteFeatures,
160             RedundantSemicolons: RedundantSemicolons,
161             UnusedDocComment: UnusedDocComment,
162             UnexpectedCfgs: UnexpectedCfgs,
163         ]
164     ]
165 );
166
167 // FIXME: Make a separate lint type which does not require typeck tables.
168
169 late_lint_methods!(
170     declare_combined_late_lint_pass,
171     [
172         pub BuiltinCombinedLateLintPass,
173         [
174             // Tracks state across modules
175             UnnameableTestItems: UnnameableTestItems::new(),
176             // Tracks attributes of parents
177             MissingDoc: MissingDoc::new(),
178             // Builds a global list of all impls of `Debug`.
179             // FIXME: Turn the computation of types which implement Debug into a query
180             // and change this to a module lint pass
181             MissingDebugImplementations: MissingDebugImplementations::default(),
182             // Keeps a global list of foreign declarations.
183             ClashingExternDeclarations: ClashingExternDeclarations::new(),
184         ]
185     ]
186 );
187
188 late_lint_methods!(
189     declare_combined_late_lint_pass,
190     [
191         BuiltinCombinedModuleLateLintPass,
192         [
193             ForLoopsOverFallibles: ForLoopsOverFallibles,
194             DerefIntoDynSupertrait: DerefIntoDynSupertrait,
195             HardwiredLints: HardwiredLints,
196             ImproperCTypesDeclarations: ImproperCTypesDeclarations,
197             ImproperCTypesDefinitions: ImproperCTypesDefinitions,
198             VariantSizeDifferences: VariantSizeDifferences,
199             BoxPointers: BoxPointers,
200             PathStatements: PathStatements,
201             LetUnderscore: LetUnderscore,
202             // Depends on referenced function signatures in expressions
203             UnusedResults: UnusedResults,
204             NonUpperCaseGlobals: NonUpperCaseGlobals,
205             NonShorthandFieldPatterns: NonShorthandFieldPatterns,
206             UnusedAllocation: UnusedAllocation,
207             // Depends on types used in type definitions
208             MissingCopyImplementations: MissingCopyImplementations,
209             // Depends on referenced function signatures in expressions
210             MutableTransmutes: MutableTransmutes,
211             TypeAliasBounds: TypeAliasBounds,
212             TrivialConstraints: TrivialConstraints,
213             TypeLimits: TypeLimits::new(),
214             NonSnakeCase: NonSnakeCase,
215             InvalidNoMangleItems: InvalidNoMangleItems,
216             // Depends on effective visibilities
217             UnreachablePub: UnreachablePub,
218             ExplicitOutlivesRequirements: ExplicitOutlivesRequirements,
219             InvalidValue: InvalidValue,
220             DerefNullPtr: DerefNullPtr,
221             // May Depend on constants elsewhere
222             UnusedBrokenConst: UnusedBrokenConst,
223             UnstableFeatures: UnstableFeatures,
224             UngatedAsyncFnTrackCaller: UngatedAsyncFnTrackCaller,
225             ArrayIntoIter: ArrayIntoIter::default(),
226             DropTraitConstraints: DropTraitConstraints,
227             TemporaryCStringAsPtr: TemporaryCStringAsPtr,
228             NonPanicFmt: NonPanicFmt,
229             NoopMethodCall: NoopMethodCall,
230             EnumIntrinsicsNonEnums: EnumIntrinsicsNonEnums,
231             InvalidAtomicOrdering: InvalidAtomicOrdering,
232             NamedAsmLabels: NamedAsmLabels,
233             OpaqueHiddenInferredBound: OpaqueHiddenInferredBound,
234             MultipleSupertraitUpcastable: MultipleSupertraitUpcastable,
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;