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