]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_lint/src/lib.rs
added a lint against function references
[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                 FunctionReferences: FunctionReferences,
198             ]
199         );
200     };
201 }
202
203 macro_rules! declare_combined_late_pass {
204     ([$v:vis $name:ident], $passes:tt) => (
205         late_lint_methods!(declare_combined_late_lint_pass, [$v $name, $passes], ['tcx]);
206     )
207 }
208
209 // FIXME: Make a separate lint type which do not require typeck tables
210 late_lint_passes!(declare_combined_late_pass, [pub BuiltinCombinedLateLintPass]);
211
212 late_lint_mod_passes!(declare_combined_late_pass, [BuiltinCombinedModuleLateLintPass]);
213
214 pub fn new_lint_store(no_interleave_lints: bool, internal_lints: bool) -> LintStore {
215     let mut lint_store = LintStore::new();
216
217     register_builtins(&mut lint_store, no_interleave_lints);
218     if internal_lints {
219         register_internals(&mut lint_store);
220     }
221
222     lint_store
223 }
224
225 /// Tell the `LintStore` about all the built-in lints (the ones
226 /// defined in this crate and the ones defined in
227 /// `rustc_session::lint::builtin`).
228 fn register_builtins(store: &mut LintStore, no_interleave_lints: bool) {
229     macro_rules! add_lint_group {
230         ($name:expr, $($lint:ident),*) => (
231             store.register_group(false, $name, None, vec![$(LintId::of($lint)),*]);
232         )
233     }
234
235     macro_rules! register_pass {
236         ($method:ident, $ty:ident, $constructor:expr) => {
237             store.register_lints(&$ty::get_lints());
238             store.$method(|| box $constructor);
239         };
240     }
241
242     macro_rules! register_passes {
243         ($method:ident, [$($passes:ident: $constructor:expr,)*]) => (
244             $(
245                 register_pass!($method, $passes, $constructor);
246             )*
247         )
248     }
249
250     if no_interleave_lints {
251         pre_expansion_lint_passes!(register_passes, register_pre_expansion_pass);
252         early_lint_passes!(register_passes, register_early_pass);
253         late_lint_passes!(register_passes, register_late_pass);
254         late_lint_mod_passes!(register_passes, register_late_mod_pass);
255     } else {
256         store.register_lints(&BuiltinCombinedPreExpansionLintPass::get_lints());
257         store.register_lints(&BuiltinCombinedEarlyLintPass::get_lints());
258         store.register_lints(&BuiltinCombinedModuleLateLintPass::get_lints());
259         store.register_lints(&BuiltinCombinedLateLintPass::get_lints());
260     }
261
262     add_lint_group!(
263         "nonstandard_style",
264         NON_CAMEL_CASE_TYPES,
265         NON_SNAKE_CASE,
266         NON_UPPER_CASE_GLOBALS
267     );
268
269     add_lint_group!(
270         "unused",
271         UNUSED_IMPORTS,
272         UNUSED_VARIABLES,
273         UNUSED_ASSIGNMENTS,
274         DEAD_CODE,
275         UNUSED_MUT,
276         UNREACHABLE_CODE,
277         UNREACHABLE_PATTERNS,
278         OVERLAPPING_PATTERNS,
279         UNUSED_MUST_USE,
280         UNUSED_UNSAFE,
281         PATH_STATEMENTS,
282         UNUSED_ATTRIBUTES,
283         UNUSED_MACROS,
284         UNUSED_ALLOCATION,
285         UNUSED_DOC_COMMENTS,
286         UNUSED_EXTERN_CRATES,
287         UNUSED_FEATURES,
288         UNUSED_LABELS,
289         UNUSED_PARENS,
290         UNUSED_BRACES,
291         REDUNDANT_SEMICOLONS
292     );
293
294     add_lint_group!(
295         "rust_2018_idioms",
296         BARE_TRAIT_OBJECTS,
297         UNUSED_EXTERN_CRATES,
298         ELLIPSIS_INCLUSIVE_RANGE_PATTERNS,
299         ELIDED_LIFETIMES_IN_PATHS,
300         EXPLICIT_OUTLIVES_REQUIREMENTS // FIXME(#52665, #47816) not always applicable and not all
301                                        // macros are ready for this yet.
302                                        // UNREACHABLE_PUB,
303
304                                        // FIXME macro crates are not up for this yet, too much
305                                        // breakage is seen if we try to encourage this lint.
306                                        // MACRO_USE_EXTERN_CRATE
307     );
308
309     add_lint_group!(
310         "rustdoc",
311         BROKEN_INTRA_DOC_LINKS,
312         PRIVATE_INTRA_DOC_LINKS,
313         INVALID_CODEBLOCK_ATTRIBUTES,
314         MISSING_DOC_CODE_EXAMPLES,
315         PRIVATE_DOC_TESTS,
316         INVALID_HTML_TAGS
317     );
318
319     // Register renamed and removed lints.
320     store.register_renamed("single_use_lifetime", "single_use_lifetimes");
321     store.register_renamed("elided_lifetime_in_path", "elided_lifetimes_in_paths");
322     store.register_renamed("bare_trait_object", "bare_trait_objects");
323     store.register_renamed("unstable_name_collision", "unstable_name_collisions");
324     store.register_renamed("unused_doc_comment", "unused_doc_comments");
325     store.register_renamed("async_idents", "keyword_idents");
326     store.register_renamed("exceeding_bitshifts", "arithmetic_overflow");
327     store.register_renamed("redundant_semicolon", "redundant_semicolons");
328     store.register_renamed("intra_doc_link_resolution_failure", "broken_intra_doc_links");
329     store.register_removed("unknown_features", "replaced by an error");
330     store.register_removed("unsigned_negation", "replaced by negate_unsigned feature gate");
331     store.register_removed("negate_unsigned", "cast a signed value instead");
332     store.register_removed("raw_pointer_derive", "using derive with raw pointers is ok");
333     // Register lint group aliases.
334     store.register_group_alias("nonstandard_style", "bad_style");
335     // This was renamed to `raw_pointer_derive`, which was then removed,
336     // so it is also considered removed.
337     store.register_removed("raw_pointer_deriving", "using derive with raw pointers is ok");
338     store.register_removed("drop_with_repr_extern", "drop flags have been removed");
339     store.register_removed("fat_ptr_transmutes", "was accidentally removed back in 2014");
340     store.register_removed("deprecated_attr", "use `deprecated` instead");
341     store.register_removed(
342         "transmute_from_fn_item_types",
343         "always cast functions before transmuting them",
344     );
345     store.register_removed(
346         "hr_lifetime_in_assoc_type",
347         "converted into hard error, see issue #33685 \
348          <https://github.com/rust-lang/rust/issues/33685> for more information",
349     );
350     store.register_removed(
351         "inaccessible_extern_crate",
352         "converted into hard error, see issue #36886 \
353          <https://github.com/rust-lang/rust/issues/36886> for more information",
354     );
355     store.register_removed(
356         "super_or_self_in_global_path",
357         "converted into hard error, see issue #36888 \
358          <https://github.com/rust-lang/rust/issues/36888> for more information",
359     );
360     store.register_removed(
361         "overlapping_inherent_impls",
362         "converted into hard error, see issue #36889 \
363          <https://github.com/rust-lang/rust/issues/36889> for more information",
364     );
365     store.register_removed(
366         "illegal_floating_point_constant_pattern",
367         "converted into hard error, see issue #36890 \
368          <https://github.com/rust-lang/rust/issues/36890> for more information",
369     );
370     store.register_removed(
371         "illegal_struct_or_enum_constant_pattern",
372         "converted into hard error, see issue #36891 \
373          <https://github.com/rust-lang/rust/issues/36891> for more information",
374     );
375     store.register_removed(
376         "lifetime_underscore",
377         "converted into hard error, see issue #36892 \
378          <https://github.com/rust-lang/rust/issues/36892> for more information",
379     );
380     store.register_removed(
381         "extra_requirement_in_impl",
382         "converted into hard error, see issue #37166 \
383          <https://github.com/rust-lang/rust/issues/37166> for more information",
384     );
385     store.register_removed(
386         "legacy_imports",
387         "converted into hard error, see issue #38260 \
388          <https://github.com/rust-lang/rust/issues/38260> for more information",
389     );
390     store.register_removed(
391         "coerce_never",
392         "converted into hard error, see issue #48950 \
393          <https://github.com/rust-lang/rust/issues/48950> for more information",
394     );
395     store.register_removed(
396         "resolve_trait_on_defaulted_unit",
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         "private_no_mangle_fns",
402         "no longer a warning, `#[no_mangle]` functions always exported",
403     );
404     store.register_removed(
405         "private_no_mangle_statics",
406         "no longer a warning, `#[no_mangle]` statics always exported",
407     );
408     store.register_removed("bad_repr", "replaced with a generic attribute input check");
409     store.register_removed(
410         "duplicate_matcher_binding_name",
411         "converted into hard error, see issue #57742 \
412          <https://github.com/rust-lang/rust/issues/57742> for more information",
413     );
414     store.register_removed(
415         "incoherent_fundamental_impls",
416         "converted into hard error, see issue #46205 \
417          <https://github.com/rust-lang/rust/issues/46205> for more information",
418     );
419     store.register_removed(
420         "legacy_constructor_visibility",
421         "converted into hard error, see issue #39207 \
422          <https://github.com/rust-lang/rust/issues/39207> for more information",
423     );
424     store.register_removed(
425         "legacy_directory_ownership",
426         "converted into hard error, see issue #37872 \
427          <https://github.com/rust-lang/rust/issues/37872> for more information",
428     );
429     store.register_removed(
430         "safe_extern_statics",
431         "converted into hard error, see issue #36247 \
432          <https://github.com/rust-lang/rust/issues/36247> for more information",
433     );
434     store.register_removed(
435         "parenthesized_params_in_types_and_modules",
436         "converted into hard error, see issue #42238 \
437          <https://github.com/rust-lang/rust/issues/42238> for more information",
438     );
439     store.register_removed(
440         "duplicate_macro_exports",
441         "converted into hard error, see issue #35896 \
442          <https://github.com/rust-lang/rust/issues/35896> for more information",
443     );
444     store.register_removed(
445         "nested_impl_trait",
446         "converted into hard error, see issue #59014 \
447          <https://github.com/rust-lang/rust/issues/59014> for more information",
448     );
449     store.register_removed("plugin_as_library", "plugins have been deprecated and retired");
450 }
451
452 fn register_internals(store: &mut LintStore) {
453     store.register_lints(&DefaultHashTypes::get_lints());
454     store.register_early_pass(|| box DefaultHashTypes::new());
455     store.register_lints(&LintPassImpl::get_lints());
456     store.register_early_pass(|| box LintPassImpl);
457     store.register_lints(&TyTyKind::get_lints());
458     store.register_late_pass(|| box TyTyKind);
459     store.register_group(
460         false,
461         "rustc::internal",
462         None,
463         vec![
464             LintId::of(DEFAULT_HASH_TYPES),
465             LintId::of(USAGE_OF_TY_TYKIND),
466             LintId::of(LINT_PASS_IMPL_WITHOUT_MACRO),
467             LintId::of(TY_PASS_BY_REFERENCE),
468             LintId::of(USAGE_OF_QUALIFIED_TY),
469         ],
470     );
471 }