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