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