]> git.lizzy.rs Git - rust.git/blob - src/librustc_lint/lib.rs
Rollup merge of #72461 - GuillaumeGomez:cleanup-e0600, r=Dylan-DPC
[rust.git] / src / librustc_lint / 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/")]
29 #![cfg_attr(test, feature(test))]
30 #![feature(bool_to_option)]
31 #![feature(box_syntax)]
32 #![feature(crate_visibility_modifier)]
33 #![feature(never_type)]
34 #![feature(nll)]
35 #![feature(or_patterns)]
36 #![recursion_limit = "256"]
37
38 #[macro_use]
39 extern crate rustc_middle;
40 #[macro_use]
41 extern crate rustc_session;
42
43 mod array_into_iter;
44 pub mod builtin;
45 mod context;
46 mod early;
47 mod internal;
48 mod late;
49 mod levels;
50 mod non_ascii_idents;
51 mod nonstandard_style;
52 mod passes;
53 mod redundant_semicolon;
54 mod types;
55 mod unused;
56
57 use rustc_ast::ast;
58 use rustc_hir as hir;
59 use rustc_hir::def_id::LocalDefId;
60 use rustc_middle::ty::query::Providers;
61 use rustc_middle::ty::TyCtxt;
62 use rustc_session::lint::builtin::{
63     BARE_TRAIT_OBJECTS, ELIDED_LIFETIMES_IN_PATHS, EXPLICIT_OUTLIVES_REQUIREMENTS,
64     INTRA_DOC_LINK_RESOLUTION_FAILURE, INVALID_CODEBLOCK_ATTRIBUTE, MISSING_DOC_CODE_EXAMPLES,
65     PRIVATE_DOC_TESTS,
66 };
67 use rustc_span::symbol::{Ident, Symbol};
68 use rustc_span::Span;
69
70 use array_into_iter::ArrayIntoIter;
71 use builtin::*;
72 use internal::*;
73 use non_ascii_idents::*;
74 use nonstandard_style::*;
75 use redundant_semicolon::*;
76 use types::*;
77 use unused::*;
78
79 /// Useful for other parts of the compiler / Clippy.
80 pub use builtin::SoftLints;
81 pub use context::{CheckLintNameResult, EarlyContext, LateContext, LintContext, LintStore};
82 pub use early::check_ast_crate;
83 pub use late::check_crate;
84 pub use passes::{EarlyLintPass, LateLintPass};
85 pub use rustc_session::lint::Level::{self, *};
86 pub use rustc_session::lint::{BufferedEarlyLint, FutureIncompatibleInfo, Lint, LintId};
87 pub use rustc_session::lint::{LintArray, LintPass};
88
89 pub fn provide(providers: &mut Providers<'_>) {
90     levels::provide(providers);
91     *providers = Providers { lint_mod, ..*providers };
92 }
93
94 fn lint_mod(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
95     late::late_lint_mod(tcx, module_def_id, BuiltinCombinedModuleLateLintPass::new());
96 }
97
98 macro_rules! pre_expansion_lint_passes {
99     ($macro:path, $args:tt) => {
100         $macro!($args, [KeywordIdents: KeywordIdents,]);
101     };
102 }
103
104 macro_rules! early_lint_passes {
105     ($macro:path, $args:tt) => {
106         $macro!(
107             $args,
108             [
109                 UnusedParens: UnusedParens,
110                 UnusedBraces: UnusedBraces,
111                 UnusedImportBraces: UnusedImportBraces,
112                 UnsafeCode: UnsafeCode,
113                 AnonymousParameters: AnonymousParameters,
114                 EllipsisInclusiveRangePatterns: EllipsisInclusiveRangePatterns::default(),
115                 NonCamelCaseTypes: NonCamelCaseTypes,
116                 DeprecatedAttr: DeprecatedAttr::new(),
117                 WhileTrue: WhileTrue,
118                 NonAsciiIdents: NonAsciiIdents,
119                 IncompleteFeatures: IncompleteFeatures,
120                 RedundantSemicolons: RedundantSemicolons,
121                 UnusedDocComment: UnusedDocComment,
122             ]
123         );
124     };
125 }
126
127 macro_rules! declare_combined_early_pass {
128     ([$name:ident], $passes:tt) => (
129         early_lint_methods!(declare_combined_early_lint_pass, [pub $name, $passes]);
130     )
131 }
132
133 pre_expansion_lint_passes!(declare_combined_early_pass, [BuiltinCombinedPreExpansionLintPass]);
134 early_lint_passes!(declare_combined_early_pass, [BuiltinCombinedEarlyLintPass]);
135
136 macro_rules! late_lint_passes {
137     ($macro:path, $args:tt) => {
138         $macro!(
139             $args,
140             [
141                 // FIXME: Look into regression when this is used as a module lint
142                 // May Depend on constants elsewhere
143                 UnusedBrokenConst: UnusedBrokenConst,
144                 // Uses attr::is_used which is untracked, can't be an incremental module pass.
145                 UnusedAttributes: UnusedAttributes::new(),
146                 // Needs to run after UnusedAttributes as it marks all `feature` attributes as used.
147                 UnstableFeatures: UnstableFeatures,
148                 // Tracks state across modules
149                 UnnameableTestItems: UnnameableTestItems::new(),
150                 // Tracks attributes of parents
151                 MissingDoc: MissingDoc::new(),
152                 // Depends on access levels
153                 // FIXME: Turn the computation of types which implement Debug into a query
154                 // and change this to a module lint pass
155                 MissingDebugImplementations: MissingDebugImplementations::default(),
156                 ArrayIntoIter: ArrayIntoIter,
157             ]
158         );
159     };
160 }
161
162 macro_rules! late_lint_mod_passes {
163     ($macro:path, $args:tt) => {
164         $macro!(
165             $args,
166             [
167                 HardwiredLints: HardwiredLints,
168                 ImproperCTypes: ImproperCTypes,
169                 VariantSizeDifferences: VariantSizeDifferences,
170                 BoxPointers: BoxPointers,
171                 PathStatements: PathStatements,
172                 // Depends on referenced function signatures in expressions
173                 UnusedResults: UnusedResults,
174                 NonUpperCaseGlobals: NonUpperCaseGlobals,
175                 NonShorthandFieldPatterns: NonShorthandFieldPatterns,
176                 UnusedAllocation: UnusedAllocation,
177                 // Depends on types used in type definitions
178                 MissingCopyImplementations: MissingCopyImplementations,
179                 // Depends on referenced function signatures in expressions
180                 MutableTransmutes: MutableTransmutes,
181                 TypeAliasBounds: TypeAliasBounds,
182                 TrivialConstraints: TrivialConstraints,
183                 TypeLimits: TypeLimits::new(),
184                 NonSnakeCase: NonSnakeCase,
185                 InvalidNoMangleItems: InvalidNoMangleItems,
186                 // Depends on access levels
187                 UnreachablePub: UnreachablePub,
188                 ExplicitOutlivesRequirements: ExplicitOutlivesRequirements,
189                 InvalidValue: InvalidValue,
190             ]
191         );
192     };
193 }
194
195 macro_rules! declare_combined_late_pass {
196     ([$v:vis $name:ident], $passes:tt) => (
197         late_lint_methods!(declare_combined_late_lint_pass, [$v $name, $passes], ['tcx]);
198     )
199 }
200
201 // FIXME: Make a separate lint type which do not require typeck tables
202 late_lint_passes!(declare_combined_late_pass, [pub BuiltinCombinedLateLintPass]);
203
204 late_lint_mod_passes!(declare_combined_late_pass, [BuiltinCombinedModuleLateLintPass]);
205
206 pub fn new_lint_store(no_interleave_lints: bool, internal_lints: bool) -> LintStore {
207     let mut lint_store = LintStore::new();
208
209     register_builtins(&mut lint_store, no_interleave_lints);
210     if internal_lints {
211         register_internals(&mut lint_store);
212     }
213
214     lint_store
215 }
216
217 /// Tell the `LintStore` about all the built-in lints (the ones
218 /// defined in this crate and the ones defined in
219 /// `rustc::lint::builtin`).
220 fn register_builtins(store: &mut LintStore, no_interleave_lints: bool) {
221     macro_rules! add_lint_group {
222         ($name:expr, $($lint:ident),*) => (
223             store.register_group(false, $name, None, vec![$(LintId::of($lint)),*]);
224         )
225     }
226
227     macro_rules! register_pass {
228         ($method:ident, $ty:ident, $constructor:expr) => {
229             store.register_lints(&$ty::get_lints());
230             store.$method(|| box $constructor);
231         };
232     }
233
234     macro_rules! register_passes {
235         ($method:ident, [$($passes:ident: $constructor:expr,)*]) => (
236             $(
237                 register_pass!($method, $passes, $constructor);
238             )*
239         )
240     }
241
242     if no_interleave_lints {
243         pre_expansion_lint_passes!(register_passes, register_pre_expansion_pass);
244         early_lint_passes!(register_passes, register_early_pass);
245         late_lint_passes!(register_passes, register_late_pass);
246         late_lint_mod_passes!(register_passes, register_late_mod_pass);
247     } else {
248         store.register_lints(&BuiltinCombinedPreExpansionLintPass::get_lints());
249         store.register_lints(&BuiltinCombinedEarlyLintPass::get_lints());
250         store.register_lints(&BuiltinCombinedModuleLateLintPass::get_lints());
251         store.register_lints(&BuiltinCombinedLateLintPass::get_lints());
252     }
253
254     add_lint_group!(
255         "nonstandard_style",
256         NON_CAMEL_CASE_TYPES,
257         NON_SNAKE_CASE,
258         NON_UPPER_CASE_GLOBALS
259     );
260
261     add_lint_group!(
262         "unused",
263         UNUSED_IMPORTS,
264         UNUSED_VARIABLES,
265         UNUSED_ASSIGNMENTS,
266         DEAD_CODE,
267         UNUSED_MUT,
268         UNREACHABLE_CODE,
269         UNREACHABLE_PATTERNS,
270         OVERLAPPING_PATTERNS,
271         UNUSED_MUST_USE,
272         UNUSED_UNSAFE,
273         PATH_STATEMENTS,
274         UNUSED_ATTRIBUTES,
275         UNUSED_MACROS,
276         UNUSED_ALLOCATION,
277         UNUSED_DOC_COMMENTS,
278         UNUSED_EXTERN_CRATES,
279         UNUSED_FEATURES,
280         UNUSED_LABELS,
281         UNUSED_PARENS,
282         UNUSED_BRACES,
283         REDUNDANT_SEMICOLONS
284     );
285
286     add_lint_group!(
287         "rust_2018_idioms",
288         BARE_TRAIT_OBJECTS,
289         UNUSED_EXTERN_CRATES,
290         ELLIPSIS_INCLUSIVE_RANGE_PATTERNS,
291         ELIDED_LIFETIMES_IN_PATHS,
292         EXPLICIT_OUTLIVES_REQUIREMENTS // FIXME(#52665, #47816) not always applicable and not all
293                                        // macros are ready for this yet.
294                                        // UNREACHABLE_PUB,
295
296                                        // FIXME macro crates are not up for this yet, too much
297                                        // breakage is seen if we try to encourage this lint.
298                                        // MACRO_USE_EXTERN_CRATE
299     );
300
301     add_lint_group!(
302         "rustdoc",
303         INTRA_DOC_LINK_RESOLUTION_FAILURE,
304         INVALID_CODEBLOCK_ATTRIBUTE,
305         MISSING_DOC_CODE_EXAMPLES,
306         PRIVATE_DOC_TESTS
307     );
308
309     // Register renamed and removed lints.
310     store.register_renamed("single_use_lifetime", "single_use_lifetimes");
311     store.register_renamed("elided_lifetime_in_path", "elided_lifetimes_in_paths");
312     store.register_renamed("bare_trait_object", "bare_trait_objects");
313     store.register_renamed("unstable_name_collision", "unstable_name_collisions");
314     store.register_renamed("unused_doc_comment", "unused_doc_comments");
315     store.register_renamed("async_idents", "keyword_idents");
316     store.register_renamed("exceeding_bitshifts", "arithmetic_overflow");
317     store.register_renamed("redundant_semicolon", "redundant_semicolons");
318     store.register_removed("unknown_features", "replaced by an error");
319     store.register_removed("unsigned_negation", "replaced by negate_unsigned feature gate");
320     store.register_removed("negate_unsigned", "cast a signed value instead");
321     store.register_removed("raw_pointer_derive", "using derive with raw pointers is ok");
322     // Register lint group aliases.
323     store.register_group_alias("nonstandard_style", "bad_style");
324     // This was renamed to `raw_pointer_derive`, which was then removed,
325     // so it is also considered removed.
326     store.register_removed("raw_pointer_deriving", "using derive with raw pointers is ok");
327     store.register_removed("drop_with_repr_extern", "drop flags have been removed");
328     store.register_removed("fat_ptr_transmutes", "was accidentally removed back in 2014");
329     store.register_removed("deprecated_attr", "use `deprecated` instead");
330     store.register_removed(
331         "transmute_from_fn_item_types",
332         "always cast functions before transmuting them",
333     );
334     store.register_removed(
335         "hr_lifetime_in_assoc_type",
336         "converted into hard error, see issue #33685 \
337          <https://github.com/rust-lang/rust/issues/33685> for more information",
338     );
339     store.register_removed(
340         "inaccessible_extern_crate",
341         "converted into hard error, see issue #36886 \
342          <https://github.com/rust-lang/rust/issues/36886> for more information",
343     );
344     store.register_removed(
345         "super_or_self_in_global_path",
346         "converted into hard error, see issue #36888 \
347          <https://github.com/rust-lang/rust/issues/36888> for more information",
348     );
349     store.register_removed(
350         "overlapping_inherent_impls",
351         "converted into hard error, see issue #36889 \
352          <https://github.com/rust-lang/rust/issues/36889> for more information",
353     );
354     store.register_removed(
355         "illegal_floating_point_constant_pattern",
356         "converted into hard error, see issue #36890 \
357          <https://github.com/rust-lang/rust/issues/36890> for more information",
358     );
359     store.register_removed(
360         "illegal_struct_or_enum_constant_pattern",
361         "converted into hard error, see issue #36891 \
362          <https://github.com/rust-lang/rust/issues/36891> for more information",
363     );
364     store.register_removed(
365         "lifetime_underscore",
366         "converted into hard error, see issue #36892 \
367          <https://github.com/rust-lang/rust/issues/36892> for more information",
368     );
369     store.register_removed(
370         "extra_requirement_in_impl",
371         "converted into hard error, see issue #37166 \
372          <https://github.com/rust-lang/rust/issues/37166> for more information",
373     );
374     store.register_removed(
375         "legacy_imports",
376         "converted into hard error, see issue #38260 \
377          <https://github.com/rust-lang/rust/issues/38260> for more information",
378     );
379     store.register_removed(
380         "coerce_never",
381         "converted into hard error, see issue #48950 \
382          <https://github.com/rust-lang/rust/issues/48950> for more information",
383     );
384     store.register_removed(
385         "resolve_trait_on_defaulted_unit",
386         "converted into hard error, see issue #48950 \
387          <https://github.com/rust-lang/rust/issues/48950> for more information",
388     );
389     store.register_removed(
390         "private_no_mangle_fns",
391         "no longer a warning, `#[no_mangle]` functions always exported",
392     );
393     store.register_removed(
394         "private_no_mangle_statics",
395         "no longer a warning, `#[no_mangle]` statics always exported",
396     );
397     store.register_removed("bad_repr", "replaced with a generic attribute input check");
398     store.register_removed(
399         "duplicate_matcher_binding_name",
400         "converted into hard error, see issue #57742 \
401          <https://github.com/rust-lang/rust/issues/57742> for more information",
402     );
403     store.register_removed(
404         "incoherent_fundamental_impls",
405         "converted into hard error, see issue #46205 \
406          <https://github.com/rust-lang/rust/issues/46205> for more information",
407     );
408     store.register_removed(
409         "legacy_constructor_visibility",
410         "converted into hard error, see issue #39207 \
411          <https://github.com/rust-lang/rust/issues/39207> for more information",
412     );
413     store.register_removed(
414         "legacy_directory_ownership",
415         "converted into hard error, see issue #37872 \
416          <https://github.com/rust-lang/rust/issues/37872> for more information",
417     );
418     store.register_removed(
419         "safe_extern_statics",
420         "converted into hard error, see issue #36247 \
421          <https://github.com/rust-lang/rust/issues/36247> for more information",
422     );
423     store.register_removed(
424         "parenthesized_params_in_types_and_modules",
425         "converted into hard error, see issue #42238 \
426          <https://github.com/rust-lang/rust/issues/42238> for more information",
427     );
428     store.register_removed(
429         "duplicate_macro_exports",
430         "converted into hard error, see issue #35896 \
431          <https://github.com/rust-lang/rust/issues/35896> for more information",
432     );
433     store.register_removed(
434         "nested_impl_trait",
435         "converted into hard error, see issue #59014 \
436          <https://github.com/rust-lang/rust/issues/59014> for more information",
437     );
438     store.register_removed("plugin_as_library", "plugins have been deprecated and retired");
439 }
440
441 fn register_internals(store: &mut LintStore) {
442     store.register_lints(&DefaultHashTypes::get_lints());
443     store.register_early_pass(|| box DefaultHashTypes::new());
444     store.register_lints(&LintPassImpl::get_lints());
445     store.register_early_pass(|| box LintPassImpl);
446     store.register_lints(&TyTyKind::get_lints());
447     store.register_late_pass(|| box TyTyKind);
448     store.register_group(
449         false,
450         "rustc::internal",
451         None,
452         vec![
453             LintId::of(DEFAULT_HASH_TYPES),
454             LintId::of(USAGE_OF_TY_TYKIND),
455             LintId::of(LINT_PASS_IMPL_WITHOUT_MACRO),
456             LintId::of(TY_PASS_BY_REFERENCE),
457             LintId::of(USAGE_OF_QUALIFIED_TY),
458         ],
459     );
460 }