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