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