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