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