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