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