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