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