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