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