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;
60 mod redundant_semicolon;
67 use rustc_hir::def_id::LocalDefId;
68 use rustc_middle::ty::query::Providers;
69 use rustc_middle::ty::TyCtxt;
70 use rustc_session::lint::builtin::{
71 BARE_TRAIT_OBJECTS, BROKEN_INTRA_DOC_LINKS, ELIDED_LIFETIMES_IN_PATHS,
72 EXPLICIT_OUTLIVES_REQUIREMENTS, INVALID_CODEBLOCK_ATTRIBUTES, INVALID_HTML_TAGS,
73 MISSING_DOC_CODE_EXAMPLES, NON_AUTOLINKS, PRIVATE_DOC_TESTS,
75 use rustc_span::symbol::{Ident, Symbol};
78 use array_into_iter::ArrayIntoIter;
82 use non_ascii_idents::*;
83 use nonstandard_style::*;
84 use panic_fmt::PanicFmt;
85 use redundant_semicolon::*;
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};
100 pub fn provide(providers: &mut Providers) {
101 levels::provide(providers);
102 *providers = Providers { lint_mod, ..*providers };
105 fn lint_mod(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
106 late::late_lint_mod(tcx, module_def_id, BuiltinCombinedModuleLateLintPass::new());
109 macro_rules! pre_expansion_lint_passes {
110 ($macro:path, $args:tt) => {
111 $macro!($args, [KeywordIdents: KeywordIdents,]);
115 macro_rules! early_lint_passes {
116 ($macro:path, $args:tt) => {
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,
138 macro_rules! declare_combined_early_pass {
139 ([$name:ident], $passes:tt) => (
140 early_lint_methods!(declare_combined_early_lint_pass, [pub $name, $passes]);
144 pre_expansion_lint_passes!(declare_combined_early_pass, [BuiltinCombinedPreExpansionLintPass]);
145 early_lint_passes!(declare_combined_early_pass, [BuiltinCombinedEarlyLintPass]);
147 macro_rules! late_lint_passes {
148 ($macro:path, $args:tt) => {
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,
168 ClashingExternDeclarations: ClashingExternDeclarations::new(),
169 DropTraitConstraints: DropTraitConstraints,
170 TemporaryCStringAsPtr: TemporaryCStringAsPtr,
177 macro_rules! late_lint_mod_passes {
178 ($macro:path, $args:tt) => {
182 HardwiredLints: HardwiredLints,
183 ImproperCTypesDeclarations: ImproperCTypesDeclarations,
184 ImproperCTypesDefinitions: ImproperCTypesDefinitions,
185 VariantSizeDifferences: VariantSizeDifferences,
186 BoxPointers: BoxPointers,
187 PathStatements: PathStatements,
188 // Depends on referenced function signatures in expressions
189 UnusedResults: UnusedResults,
190 NonUpperCaseGlobals: NonUpperCaseGlobals,
191 NonShorthandFieldPatterns: NonShorthandFieldPatterns,
192 UnusedAllocation: UnusedAllocation,
193 // Depends on types used in type definitions
194 MissingCopyImplementations: MissingCopyImplementations,
195 // Depends on referenced function signatures in expressions
196 MutableTransmutes: MutableTransmutes,
197 TypeAliasBounds: TypeAliasBounds,
198 TrivialConstraints: TrivialConstraints,
199 TypeLimits: TypeLimits::new(),
200 NonSnakeCase: NonSnakeCase,
201 InvalidNoMangleItems: InvalidNoMangleItems,
202 // Depends on access levels
203 UnreachablePub: UnreachablePub,
204 ExplicitOutlivesRequirements: ExplicitOutlivesRequirements,
205 InvalidValue: InvalidValue,
211 macro_rules! declare_combined_late_pass {
212 ([$v:vis $name:ident], $passes:tt) => (
213 late_lint_methods!(declare_combined_late_lint_pass, [$v $name, $passes], ['tcx]);
217 // FIXME: Make a separate lint type which do not require typeck tables
218 late_lint_passes!(declare_combined_late_pass, [pub BuiltinCombinedLateLintPass]);
220 late_lint_mod_passes!(declare_combined_late_pass, [BuiltinCombinedModuleLateLintPass]);
222 pub fn new_lint_store(no_interleave_lints: bool, internal_lints: bool) -> LintStore {
223 let mut lint_store = LintStore::new();
225 register_builtins(&mut lint_store, no_interleave_lints);
227 register_internals(&mut lint_store);
233 /// Tell the `LintStore` about all the built-in lints (the ones
234 /// defined in this crate and the ones defined in
235 /// `rustc_session::lint::builtin`).
236 fn register_builtins(store: &mut LintStore, no_interleave_lints: bool) {
237 macro_rules! add_lint_group {
238 ($name:expr, $($lint:ident),*) => (
239 store.register_group(false, $name, None, vec![$(LintId::of($lint)),*]);
243 macro_rules! register_pass {
244 ($method:ident, $ty:ident, $constructor:expr) => {
245 store.register_lints(&$ty::get_lints());
246 store.$method(|| box $constructor);
250 macro_rules! register_passes {
251 ($method:ident, [$($passes:ident: $constructor:expr,)*]) => (
253 register_pass!($method, $passes, $constructor);
258 if no_interleave_lints {
259 pre_expansion_lint_passes!(register_passes, register_pre_expansion_pass);
260 early_lint_passes!(register_passes, register_early_pass);
261 late_lint_passes!(register_passes, register_late_pass);
262 late_lint_mod_passes!(register_passes, register_late_mod_pass);
264 store.register_lints(&BuiltinCombinedPreExpansionLintPass::get_lints());
265 store.register_lints(&BuiltinCombinedEarlyLintPass::get_lints());
266 store.register_lints(&BuiltinCombinedModuleLateLintPass::get_lints());
267 store.register_lints(&BuiltinCombinedLateLintPass::get_lints());
272 NON_CAMEL_CASE_TYPES,
274 NON_UPPER_CASE_GLOBALS
285 UNREACHABLE_PATTERNS,
293 UNUSED_EXTERN_CRATES,
304 UNUSED_EXTERN_CRATES,
305 ELLIPSIS_INCLUSIVE_RANGE_PATTERNS,
306 ELIDED_LIFETIMES_IN_PATHS,
307 EXPLICIT_OUTLIVES_REQUIREMENTS // FIXME(#52665, #47816) not always applicable and not all
308 // macros are ready for this yet.
311 // FIXME macro crates are not up for this yet, too much
312 // breakage is seen if we try to encourage this lint.
313 // MACRO_USE_EXTERN_CRATE
319 BROKEN_INTRA_DOC_LINKS,
320 PRIVATE_INTRA_DOC_LINKS,
321 INVALID_CODEBLOCK_ATTRIBUTES,
322 MISSING_DOC_CODE_EXAMPLES,
327 // Register renamed and removed lints.
328 store.register_renamed("single_use_lifetime", "single_use_lifetimes");
329 store.register_renamed("elided_lifetime_in_path", "elided_lifetimes_in_paths");
330 store.register_renamed("bare_trait_object", "bare_trait_objects");
331 store.register_renamed("unstable_name_collision", "unstable_name_collisions");
332 store.register_renamed("unused_doc_comment", "unused_doc_comments");
333 store.register_renamed("async_idents", "keyword_idents");
334 store.register_renamed("exceeding_bitshifts", "arithmetic_overflow");
335 store.register_renamed("redundant_semicolon", "redundant_semicolons");
336 store.register_renamed("intra_doc_link_resolution_failure", "broken_intra_doc_links");
337 store.register_renamed("overlapping_patterns", "overlapping_range_endpoints");
338 store.register_removed("unknown_features", "replaced by an error");
339 store.register_removed("unsigned_negation", "replaced by negate_unsigned feature gate");
340 store.register_removed("negate_unsigned", "cast a signed value instead");
341 store.register_removed("raw_pointer_derive", "using derive with raw pointers is ok");
342 // Register lint group aliases.
343 store.register_group_alias("nonstandard_style", "bad_style");
344 // This was renamed to `raw_pointer_derive`, which was then removed,
345 // so it is also considered removed.
346 store.register_removed("raw_pointer_deriving", "using derive with raw pointers is ok");
347 store.register_removed("drop_with_repr_extern", "drop flags have been removed");
348 store.register_removed("fat_ptr_transmutes", "was accidentally removed back in 2014");
349 store.register_removed("deprecated_attr", "use `deprecated` instead");
350 store.register_removed(
351 "transmute_from_fn_item_types",
352 "always cast functions before transmuting them",
354 store.register_removed(
355 "hr_lifetime_in_assoc_type",
356 "converted into hard error, see issue #33685 \
357 <https://github.com/rust-lang/rust/issues/33685> for more information",
359 store.register_removed(
360 "inaccessible_extern_crate",
361 "converted into hard error, see issue #36886 \
362 <https://github.com/rust-lang/rust/issues/36886> for more information",
364 store.register_removed(
365 "super_or_self_in_global_path",
366 "converted into hard error, see issue #36888 \
367 <https://github.com/rust-lang/rust/issues/36888> for more information",
369 store.register_removed(
370 "overlapping_inherent_impls",
371 "converted into hard error, see issue #36889 \
372 <https://github.com/rust-lang/rust/issues/36889> for more information",
374 store.register_removed(
375 "illegal_floating_point_constant_pattern",
376 "converted into hard error, see issue #36890 \
377 <https://github.com/rust-lang/rust/issues/36890> for more information",
379 store.register_removed(
380 "illegal_struct_or_enum_constant_pattern",
381 "converted into hard error, see issue #36891 \
382 <https://github.com/rust-lang/rust/issues/36891> for more information",
384 store.register_removed(
385 "lifetime_underscore",
386 "converted into hard error, see issue #36892 \
387 <https://github.com/rust-lang/rust/issues/36892> for more information",
389 store.register_removed(
390 "extra_requirement_in_impl",
391 "converted into hard error, see issue #37166 \
392 <https://github.com/rust-lang/rust/issues/37166> for more information",
394 store.register_removed(
396 "converted into hard error, see issue #38260 \
397 <https://github.com/rust-lang/rust/issues/38260> for more information",
399 store.register_removed(
401 "converted into hard error, see issue #48950 \
402 <https://github.com/rust-lang/rust/issues/48950> for more information",
404 store.register_removed(
405 "resolve_trait_on_defaulted_unit",
406 "converted into hard error, see issue #48950 \
407 <https://github.com/rust-lang/rust/issues/48950> for more information",
409 store.register_removed(
410 "private_no_mangle_fns",
411 "no longer a warning, `#[no_mangle]` functions always exported",
413 store.register_removed(
414 "private_no_mangle_statics",
415 "no longer a warning, `#[no_mangle]` statics always exported",
417 store.register_removed("bad_repr", "replaced with a generic attribute input check");
418 store.register_removed(
419 "duplicate_matcher_binding_name",
420 "converted into hard error, see issue #57742 \
421 <https://github.com/rust-lang/rust/issues/57742> for more information",
423 store.register_removed(
424 "incoherent_fundamental_impls",
425 "converted into hard error, see issue #46205 \
426 <https://github.com/rust-lang/rust/issues/46205> for more information",
428 store.register_removed(
429 "legacy_constructor_visibility",
430 "converted into hard error, see issue #39207 \
431 <https://github.com/rust-lang/rust/issues/39207> for more information",
433 store.register_removed(
434 "legacy_directory_ownership",
435 "converted into hard error, see issue #37872 \
436 <https://github.com/rust-lang/rust/issues/37872> for more information",
438 store.register_removed(
439 "safe_extern_statics",
440 "converted into hard error, see issue #36247 \
441 <https://github.com/rust-lang/rust/issues/36247> for more information",
443 store.register_removed(
444 "parenthesized_params_in_types_and_modules",
445 "converted into hard error, see issue #42238 \
446 <https://github.com/rust-lang/rust/issues/42238> for more information",
448 store.register_removed(
449 "duplicate_macro_exports",
450 "converted into hard error, see issue #35896 \
451 <https://github.com/rust-lang/rust/issues/35896> for more information",
453 store.register_removed(
455 "converted into hard error, see issue #59014 \
456 <https://github.com/rust-lang/rust/issues/59014> for more information",
458 store.register_removed("plugin_as_library", "plugins have been deprecated and retired");
461 fn register_internals(store: &mut LintStore) {
462 store.register_lints(&DefaultHashTypes::get_lints());
463 store.register_early_pass(|| box DefaultHashTypes::new());
464 store.register_lints(&LintPassImpl::get_lints());
465 store.register_early_pass(|| box LintPassImpl);
466 store.register_lints(&ExistingDocKeyword::get_lints());
467 store.register_late_pass(|| box ExistingDocKeyword);
468 store.register_lints(&TyTyKind::get_lints());
469 store.register_late_pass(|| box TyTyKind);
470 store.register_group(
475 LintId::of(DEFAULT_HASH_TYPES),
476 LintId::of(USAGE_OF_TY_TYKIND),
477 LintId::of(LINT_PASS_IMPL_WITHOUT_MACRO),
478 LintId::of(TY_PASS_BY_REFERENCE),
479 LintId::of(USAGE_OF_QUALIFIED_TY),
480 LintId::of(EXISTING_DOC_KEYWORD),