1 //! Lints, aka compiler warnings.
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.
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.
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`
22 //! Some code also exists in [rustc_session::lint], [rustc_middle::lint].
26 //! This API is completely unstable and subject to change.
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(crate_visibility_modifier)]
34 #![feature(iter_order_by)]
35 #![feature(never_type)]
37 #![feature(or_patterns)]
38 #![feature(half_open_range_patterns)]
39 #![feature(exclusive_range_pattern)]
40 #![feature(control_flow_enum)]
41 #![recursion_limit = "256"]
44 extern crate rustc_middle;
46 extern crate rustc_session;
57 mod nonstandard_style;
59 mod redundant_semicolon;
66 use rustc_hir::def_id::LocalDefId;
67 use rustc_middle::ty::query::Providers;
68 use rustc_middle::ty::TyCtxt;
69 use rustc_session::lint::builtin::{
70 BARE_TRAIT_OBJECTS, BROKEN_INTRA_DOC_LINKS, ELIDED_LIFETIMES_IN_PATHS,
71 EXPLICIT_OUTLIVES_REQUIREMENTS, INVALID_CODEBLOCK_ATTRIBUTES, INVALID_HTML_TAGS,
72 MISSING_DOC_CODE_EXAMPLES, NON_AUTOLINKS, PRIVATE_DOC_TESTS,
74 use rustc_span::symbol::{Ident, Symbol};
77 use array_into_iter::ArrayIntoIter;
81 use non_ascii_idents::*;
82 use nonstandard_style::*;
83 use redundant_semicolon::*;
88 /// Useful for other parts of the compiler / Clippy.
89 pub use builtin::SoftLints;
90 pub use context::{CheckLintNameResult, EarlyContext, LateContext, LintContext, LintStore};
91 pub use early::check_ast_crate;
92 pub use late::check_crate;
93 pub use passes::{EarlyLintPass, LateLintPass};
94 pub use rustc_session::lint::Level::{self, *};
95 pub use rustc_session::lint::{BufferedEarlyLint, FutureIncompatibleInfo, Lint, LintId};
96 pub use rustc_session::lint::{LintArray, LintPass};
98 pub fn provide(providers: &mut Providers) {
99 levels::provide(providers);
100 *providers = Providers { lint_mod, ..*providers };
103 fn lint_mod(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
104 late::late_lint_mod(tcx, module_def_id, BuiltinCombinedModuleLateLintPass::new());
107 macro_rules! pre_expansion_lint_passes {
108 ($macro:path, $args:tt) => {
109 $macro!($args, [KeywordIdents: KeywordIdents,]);
113 macro_rules! early_lint_passes {
114 ($macro:path, $args:tt) => {
118 UnusedParens: UnusedParens,
119 UnusedBraces: UnusedBraces,
120 UnusedImportBraces: UnusedImportBraces,
121 UnsafeCode: UnsafeCode,
122 AnonymousParameters: AnonymousParameters,
123 EllipsisInclusiveRangePatterns: EllipsisInclusiveRangePatterns::default(),
124 NonCamelCaseTypes: NonCamelCaseTypes,
125 DeprecatedAttr: DeprecatedAttr::new(),
126 WhileTrue: WhileTrue,
127 NonAsciiIdents: NonAsciiIdents,
128 IncompleteFeatures: IncompleteFeatures,
129 RedundantSemicolons: RedundantSemicolons,
130 UnusedDocComment: UnusedDocComment,
136 macro_rules! declare_combined_early_pass {
137 ([$name:ident], $passes:tt) => (
138 early_lint_methods!(declare_combined_early_lint_pass, [pub $name, $passes]);
142 pre_expansion_lint_passes!(declare_combined_early_pass, [BuiltinCombinedPreExpansionLintPass]);
143 early_lint_passes!(declare_combined_early_pass, [BuiltinCombinedEarlyLintPass]);
145 macro_rules! late_lint_passes {
146 ($macro:path, $args:tt) => {
150 // FIXME: Look into regression when this is used as a module lint
151 // May Depend on constants elsewhere
152 UnusedBrokenConst: UnusedBrokenConst,
153 // Uses attr::is_used which is untracked, can't be an incremental module pass.
154 UnusedAttributes: UnusedAttributes::new(),
155 // Needs to run after UnusedAttributes as it marks all `feature` attributes as used.
156 UnstableFeatures: UnstableFeatures,
157 // Tracks state across modules
158 UnnameableTestItems: UnnameableTestItems::new(),
159 // Tracks attributes of parents
160 MissingDoc: MissingDoc::new(),
161 // Depends on access levels
162 // FIXME: Turn the computation of types which implement Debug into a query
163 // and change this to a module lint pass
164 MissingDebugImplementations: MissingDebugImplementations::default(),
165 ArrayIntoIter: ArrayIntoIter,
166 ClashingExternDeclarations: ClashingExternDeclarations::new(),
167 DropTraitConstraints: DropTraitConstraints,
168 TemporaryCStringAsPtr: TemporaryCStringAsPtr,
174 macro_rules! late_lint_mod_passes {
175 ($macro:path, $args:tt) => {
179 HardwiredLints: HardwiredLints,
180 ImproperCTypesDeclarations: ImproperCTypesDeclarations,
181 ImproperCTypesDefinitions: ImproperCTypesDefinitions,
182 VariantSizeDifferences: VariantSizeDifferences,
183 BoxPointers: BoxPointers,
184 PathStatements: PathStatements,
185 // Depends on referenced function signatures in expressions
186 UnusedResults: UnusedResults,
187 NonUpperCaseGlobals: NonUpperCaseGlobals,
188 NonShorthandFieldPatterns: NonShorthandFieldPatterns,
189 UnusedAllocation: UnusedAllocation,
190 // Depends on types used in type definitions
191 MissingCopyImplementations: MissingCopyImplementations,
192 // Depends on referenced function signatures in expressions
193 MutableTransmutes: MutableTransmutes,
194 TypeAliasBounds: TypeAliasBounds,
195 TrivialConstraints: TrivialConstraints,
196 TypeLimits: TypeLimits::new(),
197 NonSnakeCase: NonSnakeCase,
198 InvalidNoMangleItems: InvalidNoMangleItems,
199 // Depends on access levels
200 UnreachablePub: UnreachablePub,
201 ExplicitOutlivesRequirements: ExplicitOutlivesRequirements,
202 InvalidValue: InvalidValue,
208 macro_rules! declare_combined_late_pass {
209 ([$v:vis $name:ident], $passes:tt) => (
210 late_lint_methods!(declare_combined_late_lint_pass, [$v $name, $passes], ['tcx]);
214 // FIXME: Make a separate lint type which do not require typeck tables
215 late_lint_passes!(declare_combined_late_pass, [pub BuiltinCombinedLateLintPass]);
217 late_lint_mod_passes!(declare_combined_late_pass, [BuiltinCombinedModuleLateLintPass]);
219 pub fn new_lint_store(no_interleave_lints: bool, internal_lints: bool) -> LintStore {
220 let mut lint_store = LintStore::new();
222 register_builtins(&mut lint_store, no_interleave_lints);
224 register_internals(&mut lint_store);
230 /// Tell the `LintStore` about all the built-in lints (the ones
231 /// defined in this crate and the ones defined in
232 /// `rustc_session::lint::builtin`).
233 fn register_builtins(store: &mut LintStore, no_interleave_lints: bool) {
234 macro_rules! add_lint_group {
235 ($name:expr, $($lint:ident),*) => (
236 store.register_group(false, $name, None, vec![$(LintId::of($lint)),*]);
240 macro_rules! register_pass {
241 ($method:ident, $ty:ident, $constructor:expr) => {
242 store.register_lints(&$ty::get_lints());
243 store.$method(|| box $constructor);
247 macro_rules! register_passes {
248 ($method:ident, [$($passes:ident: $constructor:expr,)*]) => (
250 register_pass!($method, $passes, $constructor);
255 if no_interleave_lints {
256 pre_expansion_lint_passes!(register_passes, register_pre_expansion_pass);
257 early_lint_passes!(register_passes, register_early_pass);
258 late_lint_passes!(register_passes, register_late_pass);
259 late_lint_mod_passes!(register_passes, register_late_mod_pass);
261 store.register_lints(&BuiltinCombinedPreExpansionLintPass::get_lints());
262 store.register_lints(&BuiltinCombinedEarlyLintPass::get_lints());
263 store.register_lints(&BuiltinCombinedModuleLateLintPass::get_lints());
264 store.register_lints(&BuiltinCombinedLateLintPass::get_lints());
269 NON_CAMEL_CASE_TYPES,
271 NON_UPPER_CASE_GLOBALS
282 UNREACHABLE_PATTERNS,
283 OVERLAPPING_PATTERNS,
291 UNUSED_EXTERN_CRATES,
302 UNUSED_EXTERN_CRATES,
303 ELLIPSIS_INCLUSIVE_RANGE_PATTERNS,
304 ELIDED_LIFETIMES_IN_PATHS,
305 EXPLICIT_OUTLIVES_REQUIREMENTS // FIXME(#52665, #47816) not always applicable and not all
306 // macros are ready for this yet.
309 // FIXME macro crates are not up for this yet, too much
310 // breakage is seen if we try to encourage this lint.
311 // MACRO_USE_EXTERN_CRATE
317 BROKEN_INTRA_DOC_LINKS,
318 PRIVATE_INTRA_DOC_LINKS,
319 INVALID_CODEBLOCK_ATTRIBUTES,
320 MISSING_DOC_CODE_EXAMPLES,
325 // Register renamed and removed lints.
326 store.register_renamed("single_use_lifetime", "single_use_lifetimes");
327 store.register_renamed("elided_lifetime_in_path", "elided_lifetimes_in_paths");
328 store.register_renamed("bare_trait_object", "bare_trait_objects");
329 store.register_renamed("unstable_name_collision", "unstable_name_collisions");
330 store.register_renamed("unused_doc_comment", "unused_doc_comments");
331 store.register_renamed("async_idents", "keyword_idents");
332 store.register_renamed("exceeding_bitshifts", "arithmetic_overflow");
333 store.register_renamed("redundant_semicolon", "redundant_semicolons");
334 store.register_renamed("intra_doc_link_resolution_failure", "broken_intra_doc_links");
335 store.register_removed("unknown_features", "replaced by an error");
336 store.register_removed("unsigned_negation", "replaced by negate_unsigned feature gate");
337 store.register_removed("negate_unsigned", "cast a signed value instead");
338 store.register_removed("raw_pointer_derive", "using derive with raw pointers is ok");
339 // Register lint group aliases.
340 store.register_group_alias("nonstandard_style", "bad_style");
341 // This was renamed to `raw_pointer_derive`, which was then removed,
342 // so it is also considered removed.
343 store.register_removed("raw_pointer_deriving", "using derive with raw pointers is ok");
344 store.register_removed("drop_with_repr_extern", "drop flags have been removed");
345 store.register_removed("fat_ptr_transmutes", "was accidentally removed back in 2014");
346 store.register_removed("deprecated_attr", "use `deprecated` instead");
347 store.register_removed(
348 "transmute_from_fn_item_types",
349 "always cast functions before transmuting them",
351 store.register_removed(
352 "hr_lifetime_in_assoc_type",
353 "converted into hard error, see issue #33685 \
354 <https://github.com/rust-lang/rust/issues/33685> for more information",
356 store.register_removed(
357 "inaccessible_extern_crate",
358 "converted into hard error, see issue #36886 \
359 <https://github.com/rust-lang/rust/issues/36886> for more information",
361 store.register_removed(
362 "super_or_self_in_global_path",
363 "converted into hard error, see issue #36888 \
364 <https://github.com/rust-lang/rust/issues/36888> for more information",
366 store.register_removed(
367 "overlapping_inherent_impls",
368 "converted into hard error, see issue #36889 \
369 <https://github.com/rust-lang/rust/issues/36889> for more information",
371 store.register_removed(
372 "illegal_floating_point_constant_pattern",
373 "converted into hard error, see issue #36890 \
374 <https://github.com/rust-lang/rust/issues/36890> for more information",
376 store.register_removed(
377 "illegal_struct_or_enum_constant_pattern",
378 "converted into hard error, see issue #36891 \
379 <https://github.com/rust-lang/rust/issues/36891> for more information",
381 store.register_removed(
382 "lifetime_underscore",
383 "converted into hard error, see issue #36892 \
384 <https://github.com/rust-lang/rust/issues/36892> for more information",
386 store.register_removed(
387 "extra_requirement_in_impl",
388 "converted into hard error, see issue #37166 \
389 <https://github.com/rust-lang/rust/issues/37166> for more information",
391 store.register_removed(
393 "converted into hard error, see issue #38260 \
394 <https://github.com/rust-lang/rust/issues/38260> for more information",
396 store.register_removed(
398 "converted into hard error, see issue #48950 \
399 <https://github.com/rust-lang/rust/issues/48950> for more information",
401 store.register_removed(
402 "resolve_trait_on_defaulted_unit",
403 "converted into hard error, see issue #48950 \
404 <https://github.com/rust-lang/rust/issues/48950> for more information",
406 store.register_removed(
407 "private_no_mangle_fns",
408 "no longer a warning, `#[no_mangle]` functions always exported",
410 store.register_removed(
411 "private_no_mangle_statics",
412 "no longer a warning, `#[no_mangle]` statics always exported",
414 store.register_removed("bad_repr", "replaced with a generic attribute input check");
415 store.register_removed(
416 "duplicate_matcher_binding_name",
417 "converted into hard error, see issue #57742 \
418 <https://github.com/rust-lang/rust/issues/57742> for more information",
420 store.register_removed(
421 "incoherent_fundamental_impls",
422 "converted into hard error, see issue #46205 \
423 <https://github.com/rust-lang/rust/issues/46205> for more information",
425 store.register_removed(
426 "legacy_constructor_visibility",
427 "converted into hard error, see issue #39207 \
428 <https://github.com/rust-lang/rust/issues/39207> for more information",
430 store.register_removed(
431 "legacy_directory_ownership",
432 "converted into hard error, see issue #37872 \
433 <https://github.com/rust-lang/rust/issues/37872> for more information",
435 store.register_removed(
436 "safe_extern_statics",
437 "converted into hard error, see issue #36247 \
438 <https://github.com/rust-lang/rust/issues/36247> for more information",
440 store.register_removed(
441 "parenthesized_params_in_types_and_modules",
442 "converted into hard error, see issue #42238 \
443 <https://github.com/rust-lang/rust/issues/42238> for more information",
445 store.register_removed(
446 "duplicate_macro_exports",
447 "converted into hard error, see issue #35896 \
448 <https://github.com/rust-lang/rust/issues/35896> for more information",
450 store.register_removed(
452 "converted into hard error, see issue #59014 \
453 <https://github.com/rust-lang/rust/issues/59014> for more information",
455 store.register_removed("plugin_as_library", "plugins have been deprecated and retired");
458 fn register_internals(store: &mut LintStore) {
459 store.register_lints(&DefaultHashTypes::get_lints());
460 store.register_early_pass(|| box DefaultHashTypes::new());
461 store.register_lints(&LintPassImpl::get_lints());
462 store.register_early_pass(|| box LintPassImpl);
463 store.register_lints(&TyTyKind::get_lints());
464 store.register_late_pass(|| box TyTyKind);
465 store.register_group(
470 LintId::of(DEFAULT_HASH_TYPES),
471 LintId::of(USAGE_OF_TY_TYKIND),
472 LintId::of(LINT_PASS_IMPL_WITHOUT_MACRO),
473 LintId::of(TY_PASS_BY_REFERENCE),
474 LintId::of(USAGE_OF_QUALIFIED_TY),