]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_lint/src/lib.rs
Rollup merge of #93830 - camelid:cleanup-section-code, r=GuillaumeGomez
[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 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
29 #![feature(array_windows)]
30 #![feature(bool_to_option)]
31 #![feature(box_patterns)]
32 #![feature(crate_visibility_modifier)]
33 #![feature(if_let_guard)]
34 #![feature(iter_order_by)]
35 #![feature(let_else)]
36 #![feature(never_type)]
37 #![feature(nll)]
38 #![feature(control_flow_enum)]
39 #![recursion_limit = "256"]
40 #![cfg_attr(not(bootstrap), allow(rustc::potential_query_instability))]
41
42 #[macro_use]
43 extern crate rustc_middle;
44 #[macro_use]
45 extern crate rustc_session;
46
47 mod array_into_iter;
48 pub mod builtin;
49 mod context;
50 mod early;
51 mod enum_intrinsics_non_enums;
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, Symbol};
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;
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     *providers = Providers { lint_mod, ..*providers };
111 }
112
113 fn lint_mod(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
114     late::late_lint_mod(tcx, module_def_id, BuiltinCombinedModuleLateLintPass::new());
115 }
116
117 macro_rules! pre_expansion_lint_passes {
118     ($macro:path, $args:tt) => {
119         $macro!($args, [KeywordIdents: KeywordIdents,]);
120     };
121 }
122
123 macro_rules! early_lint_passes {
124     ($macro:path, $args:tt) => {
125         $macro!(
126             $args,
127             [
128                 UnusedParens: UnusedParens,
129                 UnusedBraces: UnusedBraces,
130                 UnusedImportBraces: UnusedImportBraces,
131                 UnsafeCode: UnsafeCode,
132                 AnonymousParameters: AnonymousParameters,
133                 EllipsisInclusiveRangePatterns: EllipsisInclusiveRangePatterns::default(),
134                 NonCamelCaseTypes: NonCamelCaseTypes,
135                 DeprecatedAttr: DeprecatedAttr::new(),
136                 WhileTrue: WhileTrue,
137                 NonAsciiIdents: NonAsciiIdents,
138                 HiddenUnicodeCodepoints: HiddenUnicodeCodepoints,
139                 IncompleteFeatures: IncompleteFeatures,
140                 RedundantSemicolons: RedundantSemicolons,
141                 UnusedDocComment: UnusedDocComment,
142             ]
143         );
144     };
145 }
146
147 macro_rules! declare_combined_early_pass {
148     ([$name:ident], $passes:tt) => (
149         early_lint_methods!(declare_combined_early_lint_pass, [pub $name, $passes]);
150     )
151 }
152
153 pre_expansion_lint_passes!(declare_combined_early_pass, [BuiltinCombinedPreExpansionLintPass]);
154 early_lint_passes!(declare_combined_early_pass, [BuiltinCombinedEarlyLintPass]);
155
156 macro_rules! late_lint_passes {
157     ($macro:path, $args:tt) => {
158         $macro!(
159             $args,
160             [
161                 // FIXME: Look into regression when this is used as a module lint
162                 // May Depend on constants elsewhere
163                 UnusedBrokenConst: UnusedBrokenConst,
164                 // Needs to run after UnusedAttributes as it marks all `feature` attributes as used.
165                 UnstableFeatures: UnstableFeatures,
166                 // Tracks state across modules
167                 UnnameableTestItems: UnnameableTestItems::new(),
168                 // Tracks attributes of parents
169                 MissingDoc: MissingDoc::new(),
170                 // Depends on access levels
171                 // FIXME: Turn the computation of types which implement Debug into a query
172                 // and change this to a module lint pass
173                 MissingDebugImplementations: MissingDebugImplementations::default(),
174                 ArrayIntoIter: ArrayIntoIter::default(),
175                 ClashingExternDeclarations: ClashingExternDeclarations::new(),
176                 DropTraitConstraints: DropTraitConstraints,
177                 TemporaryCStringAsPtr: TemporaryCStringAsPtr,
178                 NonPanicFmt: NonPanicFmt,
179                 NoopMethodCall: NoopMethodCall,
180                 EnumIntrinsicsNonEnums: EnumIntrinsicsNonEnums,
181                 InvalidAtomicOrdering: InvalidAtomicOrdering,
182                 NamedAsmLabels: NamedAsmLabels,
183             ]
184         );
185     };
186 }
187
188 macro_rules! late_lint_mod_passes {
189     ($macro:path, $args:tt) => {
190         $macro!(
191             $args,
192             [
193                 HardwiredLints: HardwiredLints,
194                 ImproperCTypesDeclarations: ImproperCTypesDeclarations,
195                 ImproperCTypesDefinitions: ImproperCTypesDefinitions,
196                 VariantSizeDifferences: VariantSizeDifferences,
197                 BoxPointers: BoxPointers,
198                 PathStatements: PathStatements,
199                 // Depends on referenced function signatures in expressions
200                 UnusedResults: UnusedResults,
201                 NonUpperCaseGlobals: NonUpperCaseGlobals,
202                 NonShorthandFieldPatterns: NonShorthandFieldPatterns,
203                 UnusedAllocation: UnusedAllocation,
204                 // Depends on types used in type definitions
205                 MissingCopyImplementations: MissingCopyImplementations,
206                 // Depends on referenced function signatures in expressions
207                 MutableTransmutes: MutableTransmutes,
208                 TypeAliasBounds: TypeAliasBounds,
209                 TrivialConstraints: TrivialConstraints,
210                 TypeLimits: TypeLimits::new(),
211                 NonSnakeCase: NonSnakeCase,
212                 InvalidNoMangleItems: InvalidNoMangleItems,
213                 // Depends on access levels
214                 UnreachablePub: UnreachablePub,
215                 ExplicitOutlivesRequirements: ExplicitOutlivesRequirements,
216                 InvalidValue: InvalidValue,
217                 DerefNullPtr: DerefNullPtr,
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_ALLOCATION,
304         UNUSED_DOC_COMMENTS,
305         UNUSED_EXTERN_CRATES,
306         UNUSED_FEATURES,
307         UNUSED_LABELS,
308         UNUSED_PARENS,
309         UNUSED_BRACES,
310         REDUNDANT_SEMICOLONS
311     );
312
313     add_lint_group!(
314         "rust_2018_idioms",
315         BARE_TRAIT_OBJECTS,
316         UNUSED_EXTERN_CRATES,
317         ELLIPSIS_INCLUSIVE_RANGE_PATTERNS,
318         ELIDED_LIFETIMES_IN_PATHS,
319         EXPLICIT_OUTLIVES_REQUIREMENTS // FIXME(#52665, #47816) not always applicable and not all
320                                        // macros are ready for this yet.
321                                        // UNREACHABLE_PUB,
322
323                                        // FIXME macro crates are not up for this yet, too much
324                                        // breakage is seen if we try to encourage this lint.
325                                        // MACRO_USE_EXTERN_CRATE
326     );
327
328     // Register renamed and removed lints.
329     store.register_renamed("single_use_lifetime", "single_use_lifetimes");
330     store.register_renamed("elided_lifetime_in_path", "elided_lifetimes_in_paths");
331     store.register_renamed("bare_trait_object", "bare_trait_objects");
332     store.register_renamed("unstable_name_collision", "unstable_name_collisions");
333     store.register_renamed("unused_doc_comment", "unused_doc_comments");
334     store.register_renamed("async_idents", "keyword_idents");
335     store.register_renamed("exceeding_bitshifts", "arithmetic_overflow");
336     store.register_renamed("redundant_semicolon", "redundant_semicolons");
337     store.register_renamed("overlapping_patterns", "overlapping_range_endpoints");
338     store.register_renamed("safe_packed_borrows", "unaligned_references");
339     store.register_renamed("disjoint_capture_migration", "rust_2021_incompatible_closure_captures");
340     store.register_renamed("or_patterns_back_compat", "rust_2021_incompatible_or_patterns");
341     store.register_renamed("non_fmt_panic", "non_fmt_panics");
342
343     // These were moved to tool lints, but rustc still sees them when compiling normally, before
344     // tool lints are registered, so `check_tool_name_for_backwards_compat` doesn't work. Use
345     // `register_removed` explicitly.
346     const RUSTDOC_LINTS: &[&str] = &[
347         "broken_intra_doc_links",
348         "private_intra_doc_links",
349         "missing_crate_level_docs",
350         "missing_doc_code_examples",
351         "private_doc_tests",
352         "invalid_codeblock_attributes",
353         "invalid_html_tags",
354         "non_autolinks",
355     ];
356     for rustdoc_lint in RUSTDOC_LINTS {
357         store.register_ignored(rustdoc_lint);
358     }
359     store.register_removed(
360         "intra_doc_link_resolution_failure",
361         "use `rustdoc::broken_intra_doc_links` instead",
362     );
363     store.register_removed("rustdoc", "use `rustdoc::all` instead");
364
365     store.register_removed("unknown_features", "replaced by an error");
366     store.register_removed("unsigned_negation", "replaced by negate_unsigned feature gate");
367     store.register_removed("negate_unsigned", "cast a signed value instead");
368     store.register_removed("raw_pointer_derive", "using derive with raw pointers is ok");
369     // Register lint group aliases.
370     store.register_group_alias("nonstandard_style", "bad_style");
371     // This was renamed to `raw_pointer_derive`, which was then removed,
372     // so it is also considered removed.
373     store.register_removed("raw_pointer_deriving", "using derive with raw pointers is ok");
374     store.register_removed("drop_with_repr_extern", "drop flags have been removed");
375     store.register_removed("fat_ptr_transmutes", "was accidentally removed back in 2014");
376     store.register_removed("deprecated_attr", "use `deprecated` instead");
377     store.register_removed(
378         "transmute_from_fn_item_types",
379         "always cast functions before transmuting them",
380     );
381     store.register_removed(
382         "hr_lifetime_in_assoc_type",
383         "converted into hard error, see issue #33685 \
384          <https://github.com/rust-lang/rust/issues/33685> for more information",
385     );
386     store.register_removed(
387         "inaccessible_extern_crate",
388         "converted into hard error, see issue #36886 \
389          <https://github.com/rust-lang/rust/issues/36886> for more information",
390     );
391     store.register_removed(
392         "super_or_self_in_global_path",
393         "converted into hard error, see issue #36888 \
394          <https://github.com/rust-lang/rust/issues/36888> for more information",
395     );
396     store.register_removed(
397         "overlapping_inherent_impls",
398         "converted into hard error, see issue #36889 \
399          <https://github.com/rust-lang/rust/issues/36889> for more information",
400     );
401     store.register_removed(
402         "illegal_floating_point_constant_pattern",
403         "converted into hard error, see issue #36890 \
404          <https://github.com/rust-lang/rust/issues/36890> for more information",
405     );
406     store.register_removed(
407         "illegal_struct_or_enum_constant_pattern",
408         "converted into hard error, see issue #36891 \
409          <https://github.com/rust-lang/rust/issues/36891> for more information",
410     );
411     store.register_removed(
412         "lifetime_underscore",
413         "converted into hard error, see issue #36892 \
414          <https://github.com/rust-lang/rust/issues/36892> for more information",
415     );
416     store.register_removed(
417         "extra_requirement_in_impl",
418         "converted into hard error, see issue #37166 \
419          <https://github.com/rust-lang/rust/issues/37166> for more information",
420     );
421     store.register_removed(
422         "legacy_imports",
423         "converted into hard error, see issue #38260 \
424          <https://github.com/rust-lang/rust/issues/38260> for more information",
425     );
426     store.register_removed(
427         "coerce_never",
428         "converted into hard error, see issue #48950 \
429          <https://github.com/rust-lang/rust/issues/48950> for more information",
430     );
431     store.register_removed(
432         "resolve_trait_on_defaulted_unit",
433         "converted into hard error, see issue #48950 \
434          <https://github.com/rust-lang/rust/issues/48950> for more information",
435     );
436     store.register_removed(
437         "private_no_mangle_fns",
438         "no longer a warning, `#[no_mangle]` functions always exported",
439     );
440     store.register_removed(
441         "private_no_mangle_statics",
442         "no longer a warning, `#[no_mangle]` statics always exported",
443     );
444     store.register_removed("bad_repr", "replaced with a generic attribute input check");
445     store.register_removed(
446         "duplicate_matcher_binding_name",
447         "converted into hard error, see issue #57742 \
448          <https://github.com/rust-lang/rust/issues/57742> for more information",
449     );
450     store.register_removed(
451         "incoherent_fundamental_impls",
452         "converted into hard error, see issue #46205 \
453          <https://github.com/rust-lang/rust/issues/46205> for more information",
454     );
455     store.register_removed(
456         "legacy_constructor_visibility",
457         "converted into hard error, see issue #39207 \
458          <https://github.com/rust-lang/rust/issues/39207> for more information",
459     );
460     store.register_removed(
461         "legacy_directory_ownership",
462         "converted into hard error, see issue #37872 \
463          <https://github.com/rust-lang/rust/issues/37872> for more information",
464     );
465     store.register_removed(
466         "safe_extern_statics",
467         "converted into hard error, see issue #36247 \
468          <https://github.com/rust-lang/rust/issues/36247> for more information",
469     );
470     store.register_removed(
471         "parenthesized_params_in_types_and_modules",
472         "converted into hard error, see issue #42238 \
473          <https://github.com/rust-lang/rust/issues/42238> for more information",
474     );
475     store.register_removed(
476         "duplicate_macro_exports",
477         "converted into hard error, see issue #35896 \
478          <https://github.com/rust-lang/rust/issues/35896> for more information",
479     );
480     store.register_removed(
481         "nested_impl_trait",
482         "converted into hard error, see issue #59014 \
483          <https://github.com/rust-lang/rust/issues/59014> for more information",
484     );
485     store.register_removed("plugin_as_library", "plugins have been deprecated and retired");
486     store.register_removed(
487         "unsupported_naked_functions",
488         "converted into hard error, see RFC 2972 \
489          <https://github.com/rust-lang/rfcs/blob/master/text/2972-constrained-naked.md> for more information",
490     );
491 }
492
493 fn register_internals(store: &mut LintStore) {
494     store.register_lints(&LintPassImpl::get_lints());
495     store.register_early_pass(|| Box::new(LintPassImpl));
496     store.register_lints(&DefaultHashTypes::get_lints());
497     store.register_late_pass(|| Box::new(DefaultHashTypes));
498     store.register_lints(&QueryStability::get_lints());
499     store.register_late_pass(|| Box::new(QueryStability));
500     store.register_lints(&ExistingDocKeyword::get_lints());
501     store.register_late_pass(|| Box::new(ExistingDocKeyword));
502     store.register_lints(&TyTyKind::get_lints());
503     store.register_late_pass(|| Box::new(TyTyKind));
504     store.register_lints(&PassByValue::get_lints());
505     store.register_late_pass(|| Box::new(PassByValue));
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         ],
519     );
520 }
521
522 #[cfg(test)]
523 mod tests;