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