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