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