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