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