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