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