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