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