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