]> git.lizzy.rs Git - rust.git/blob - src/librustc/lint/builtin.rs
22f2023eefbd874693121105c5deefbe6a9c39e8
[rust.git] / src / librustc / lint / builtin.rs
1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Some lints that are built in to the compiler.
12 //!
13 //! These are the built-in lints that are emitted direct in the main
14 //! compiler code, rather than using their own custom pass. Those
15 //! lints are all available in `rustc_lint::builtin`.
16
17 use errors::{Applicability, DiagnosticBuilder};
18 use lint::{LintPass, LateLintPass, LintArray};
19 use session::Session;
20 use syntax::ast;
21 use syntax::source_map::Span;
22
23 declare_lint! {
24     pub EXCEEDING_BITSHIFTS,
25     Deny,
26     "shift exceeds the type's number of bits"
27 }
28
29 declare_lint! {
30     pub CONST_ERR,
31     Deny,
32     "constant evaluation detected erroneous expression"
33 }
34
35 declare_lint! {
36     pub UNUSED_IMPORTS,
37     Warn,
38     "imports that are never used"
39 }
40
41 declare_lint! {
42     pub UNUSED_EXTERN_CRATES,
43     Allow,
44     "extern crates that are never used"
45 }
46
47 declare_lint! {
48     pub UNUSED_QUALIFICATIONS,
49     Allow,
50     "detects unnecessarily qualified names"
51 }
52
53 declare_lint! {
54     pub UNKNOWN_LINTS,
55     Warn,
56     "unrecognized lint attribute"
57 }
58
59 declare_lint! {
60     pub UNUSED_VARIABLES,
61     Warn,
62     "detect variables which are not used in any way"
63 }
64
65 declare_lint! {
66     pub UNUSED_ASSIGNMENTS,
67     Warn,
68     "detect assignments that will never be read"
69 }
70
71 declare_lint! {
72     pub DEAD_CODE,
73     Warn,
74     "detect unused, unexported items"
75 }
76
77 declare_lint! {
78     pub UNREACHABLE_CODE,
79     Warn,
80     "detects unreachable code paths",
81     report_in_external_macro: true
82 }
83
84 declare_lint! {
85     pub UNREACHABLE_PATTERNS,
86     Warn,
87     "detects unreachable patterns"
88 }
89
90 declare_lint! {
91     pub UNUSED_MACROS,
92     Warn,
93     "detects macros that were not used"
94 }
95
96 declare_lint! {
97     pub WARNINGS,
98     Warn,
99     "mass-change the level for lints which produce warnings"
100 }
101
102 declare_lint! {
103     pub UNUSED_FEATURES,
104     Warn,
105     "unused features found in crate-level #[feature] directives"
106 }
107
108 declare_lint! {
109     pub STABLE_FEATURES,
110     Warn,
111     "stable features found in #[feature] directive"
112 }
113
114 declare_lint! {
115     pub UNKNOWN_CRATE_TYPES,
116     Deny,
117     "unknown crate type found in #[crate_type] directive"
118 }
119
120 declare_lint! {
121     pub TRIVIAL_CASTS,
122     Allow,
123     "detects trivial casts which could be removed"
124 }
125
126 declare_lint! {
127     pub TRIVIAL_NUMERIC_CASTS,
128     Allow,
129     "detects trivial casts of numeric types which could be removed"
130 }
131
132 declare_lint! {
133     pub PRIVATE_IN_PUBLIC,
134     Warn,
135     "detect private items in public interfaces not caught by the old implementation"
136 }
137
138 declare_lint! {
139     pub PUB_USE_OF_PRIVATE_EXTERN_CRATE,
140     Deny,
141     "detect public re-exports of private extern crates"
142 }
143
144 declare_lint! {
145     pub INVALID_TYPE_PARAM_DEFAULT,
146     Deny,
147     "type parameter default erroneously allowed in invalid location"
148 }
149
150 declare_lint! {
151     pub RENAMED_AND_REMOVED_LINTS,
152     Warn,
153     "lints that have been renamed or removed"
154 }
155
156 declare_lint! {
157     pub SAFE_EXTERN_STATICS,
158     Deny,
159     "safe access to extern statics was erroneously allowed"
160 }
161
162 declare_lint! {
163     pub SAFE_PACKED_BORROWS,
164     Warn,
165     "safe borrows of fields of packed structs were was erroneously allowed"
166 }
167
168 declare_lint! {
169     pub PATTERNS_IN_FNS_WITHOUT_BODY,
170     Warn,
171     "patterns in functions without body were erroneously allowed"
172 }
173
174 declare_lint! {
175     pub LEGACY_DIRECTORY_OWNERSHIP,
176     Deny,
177     "non-inline, non-`#[path]` modules (e.g. `mod foo;`) were erroneously allowed in some files \
178      not named `mod.rs`"
179 }
180
181 declare_lint! {
182     pub LEGACY_CONSTRUCTOR_VISIBILITY,
183     Deny,
184     "detects use of struct constructors that would be invisible with new visibility rules"
185 }
186
187 declare_lint! {
188     pub MISSING_FRAGMENT_SPECIFIER,
189     Deny,
190     "detects missing fragment specifiers in unused `macro_rules!` patterns"
191 }
192
193 declare_lint! {
194     pub PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
195     Deny,
196     "detects parenthesized generic parameters in type and module names"
197 }
198
199 declare_lint! {
200     pub LATE_BOUND_LIFETIME_ARGUMENTS,
201     Warn,
202     "detects generic lifetime arguments in path segments with late bound lifetime parameters"
203 }
204
205 declare_lint! {
206     pub INCOHERENT_FUNDAMENTAL_IMPLS,
207     Deny,
208     "potentially-conflicting impls were erroneously allowed"
209 }
210
211 declare_lint! {
212     pub BAD_REPR,
213     Warn,
214     "detects incorrect use of `repr` attribute"
215 }
216
217 declare_lint! {
218     pub DEPRECATED,
219     Warn,
220     "detects use of deprecated items",
221     report_in_external_macro: true
222 }
223
224 declare_lint! {
225     pub UNUSED_UNSAFE,
226     Warn,
227     "unnecessary use of an `unsafe` block"
228 }
229
230 declare_lint! {
231     pub UNUSED_MUT,
232     Warn,
233     "detect mut variables which don't need to be mutable"
234 }
235
236 declare_lint! {
237     pub UNCONDITIONAL_RECURSION,
238     Warn,
239     "functions that cannot return without calling themselves"
240 }
241
242 declare_lint! {
243     pub SINGLE_USE_LIFETIMES,
244     Allow,
245     "detects lifetime parameters that are only used once"
246 }
247
248 declare_lint! {
249     pub UNUSED_LIFETIMES,
250     Allow,
251     "detects lifetime parameters that are never used"
252 }
253
254 declare_lint! {
255     pub TYVAR_BEHIND_RAW_POINTER,
256     Warn,
257     "raw pointer to an inference variable"
258 }
259
260 declare_lint! {
261     pub ELIDED_LIFETIMES_IN_PATHS,
262     Allow,
263     "hidden lifetime parameters in types are deprecated"
264 }
265
266 declare_lint! {
267     pub BARE_TRAIT_OBJECTS,
268     Allow,
269     "suggest using `dyn Trait` for trait objects"
270 }
271
272 declare_lint! {
273     pub ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE,
274     Allow,
275     "fully qualified paths that start with a module name \
276      instead of `crate`, `self`, or an extern crate name"
277 }
278
279 declare_lint! {
280     pub ILLEGAL_FLOATING_POINT_LITERAL_PATTERN,
281     Warn,
282     "floating-point literals cannot be used in patterns"
283 }
284
285 declare_lint! {
286     pub UNSTABLE_NAME_COLLISIONS,
287     Warn,
288     "detects name collision with an existing but unstable method"
289 }
290
291 declare_lint! {
292     pub IRREFUTABLE_LET_PATTERNS,
293     Deny,
294     "detects irrefutable patterns in if-let and while-let statements"
295 }
296
297 declare_lint! {
298     pub UNUSED_LABELS,
299     Allow,
300     "detects labels that are never used"
301 }
302
303 declare_lint! {
304     pub DUPLICATE_MACRO_EXPORTS,
305     Deny,
306     "detects duplicate macro exports"
307 }
308
309 declare_lint! {
310     pub INTRA_DOC_LINK_RESOLUTION_FAILURE,
311     Warn,
312     "warn about documentation intra links resolution failure"
313 }
314
315 declare_lint! {
316     pub MISSING_DOC_CODE_EXAMPLES,
317     Allow,
318     "warn about missing code example in an item's documentation"
319 }
320
321 declare_lint! {
322     pub PRIVATE_DOC_TESTS,
323     Allow,
324     "warn about doc test in private item"
325 }
326
327 declare_lint! {
328     pub WHERE_CLAUSES_OBJECT_SAFETY,
329     Warn,
330     "checks the object safety of where clauses"
331 }
332
333 declare_lint! {
334     pub PROC_MACRO_DERIVE_RESOLUTION_FALLBACK,
335     Warn,
336     "detects proc macro derives using inaccessible names from parent modules"
337 }
338
339 declare_lint! {
340     pub MACRO_USE_EXTERN_CRATE,
341     Allow,
342     "the `#[macro_use]` attribute is now deprecated in favor of using macros \
343      via the module system"
344 }
345
346 declare_lint! {
347     pub MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS,
348     Deny,
349     "macro-expanded `macro_export` macros from the current crate \
350      cannot be referred to by absolute paths"
351 }
352
353 declare_lint! {
354     pub EXPLICIT_OUTLIVES_REQUIREMENTS,
355     Allow,
356     "outlives requirements can be inferred"
357 }
358
359 /// Some lints that are buffered from `libsyntax`. See `syntax::early_buffered_lints`.
360 pub mod parser {
361     declare_lint! {
362         pub QUESTION_MARK_MACRO_SEP,
363         Allow,
364         "detects the use of `?` as a macro separator"
365     }
366 }
367
368 /// Does nothing as a lint pass, but registers some `Lint`s
369 /// which are used by other parts of the compiler.
370 #[derive(Copy, Clone)]
371 pub struct HardwiredLints;
372
373 impl LintPass for HardwiredLints {
374     fn get_lints(&self) -> LintArray {
375         lint_array!(
376             ILLEGAL_FLOATING_POINT_LITERAL_PATTERN,
377             EXCEEDING_BITSHIFTS,
378             UNUSED_IMPORTS,
379             UNUSED_EXTERN_CRATES,
380             UNUSED_QUALIFICATIONS,
381             UNKNOWN_LINTS,
382             UNUSED_VARIABLES,
383             UNUSED_ASSIGNMENTS,
384             DEAD_CODE,
385             UNREACHABLE_CODE,
386             UNREACHABLE_PATTERNS,
387             UNUSED_MACROS,
388             WARNINGS,
389             UNUSED_FEATURES,
390             STABLE_FEATURES,
391             UNKNOWN_CRATE_TYPES,
392             TRIVIAL_CASTS,
393             TRIVIAL_NUMERIC_CASTS,
394             PRIVATE_IN_PUBLIC,
395             PUB_USE_OF_PRIVATE_EXTERN_CRATE,
396             INVALID_TYPE_PARAM_DEFAULT,
397             CONST_ERR,
398             RENAMED_AND_REMOVED_LINTS,
399             SAFE_EXTERN_STATICS,
400             SAFE_PACKED_BORROWS,
401             PATTERNS_IN_FNS_WITHOUT_BODY,
402             LEGACY_DIRECTORY_OWNERSHIP,
403             LEGACY_CONSTRUCTOR_VISIBILITY,
404             MISSING_FRAGMENT_SPECIFIER,
405             PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
406             LATE_BOUND_LIFETIME_ARGUMENTS,
407             INCOHERENT_FUNDAMENTAL_IMPLS,
408             DEPRECATED,
409             UNUSED_UNSAFE,
410             UNUSED_MUT,
411             UNCONDITIONAL_RECURSION,
412             SINGLE_USE_LIFETIMES,
413             UNUSED_LIFETIMES,
414             UNUSED_LABELS,
415             TYVAR_BEHIND_RAW_POINTER,
416             ELIDED_LIFETIMES_IN_PATHS,
417             BARE_TRAIT_OBJECTS,
418             ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE,
419             UNSTABLE_NAME_COLLISIONS,
420             IRREFUTABLE_LET_PATTERNS,
421             DUPLICATE_MACRO_EXPORTS,
422             INTRA_DOC_LINK_RESOLUTION_FAILURE,
423             MISSING_DOC_CODE_EXAMPLES,
424             PRIVATE_DOC_TESTS,
425             WHERE_CLAUSES_OBJECT_SAFETY,
426             PROC_MACRO_DERIVE_RESOLUTION_FALLBACK,
427             MACRO_USE_EXTERN_CRATE,
428             MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS,
429             parser::QUESTION_MARK_MACRO_SEP,
430         )
431     }
432 }
433
434 // this could be a closure, but then implementing derive traits
435 // becomes hacky (and it gets allocated)
436 #[derive(PartialEq, RustcEncodable, RustcDecodable, Debug)]
437 pub enum BuiltinLintDiagnostics {
438     Normal,
439     BareTraitObject(Span, /* is_global */ bool),
440     AbsPathWithModule(Span),
441     DuplicatedMacroExports(ast::Ident, Span, Span),
442     ProcMacroDeriveResolutionFallback(Span),
443     MacroExpandedMacroExportsAccessedByAbsolutePaths(Span),
444     ElidedLifetimesInPaths(usize, Span, bool, Span, String),
445     UnknownCrateTypes(Span, String, String),
446 }
447
448 impl BuiltinLintDiagnostics {
449     pub fn run(self, sess: &Session, db: &mut DiagnosticBuilder<'_>) {
450         match self {
451             BuiltinLintDiagnostics::Normal => (),
452             BuiltinLintDiagnostics::BareTraitObject(span, is_global) => {
453                 let (sugg, app) = match sess.source_map().span_to_snippet(span) {
454                     Ok(ref s) if is_global => (format!("dyn ({})", s),
455                                                Applicability::MachineApplicable),
456                     Ok(s) => (format!("dyn {}", s), Applicability::MachineApplicable),
457                     Err(_) => ("dyn <type>".to_string(), Applicability::HasPlaceholders)
458                 };
459                 db.span_suggestion_with_applicability(span, "use `dyn`", sugg, app);
460             }
461             BuiltinLintDiagnostics::AbsPathWithModule(span) => {
462                 let (sugg, app) = match sess.source_map().span_to_snippet(span) {
463                     Ok(ref s) => {
464                         // FIXME(Manishearth) ideally the emitting code
465                         // can tell us whether or not this is global
466                         let opt_colon = if s.trim_left().starts_with("::") {
467                             ""
468                         } else {
469                             "::"
470                         };
471
472                         (format!("crate{}{}", opt_colon, s), Applicability::MachineApplicable)
473                     }
474                     Err(_) => ("crate::<path>".to_string(), Applicability::HasPlaceholders)
475                 };
476                 db.span_suggestion_with_applicability(span, "use `crate`", sugg, app);
477             }
478             BuiltinLintDiagnostics::DuplicatedMacroExports(ident, earlier_span, later_span) => {
479                 db.span_label(later_span, format!("`{}` already exported", ident));
480                 db.span_note(earlier_span, "previous macro export is now shadowed");
481             }
482             BuiltinLintDiagnostics::ProcMacroDeriveResolutionFallback(span) => {
483                 db.span_label(span, "names from parent modules are not \
484                                      accessible without an explicit import");
485             }
486             BuiltinLintDiagnostics::MacroExpandedMacroExportsAccessedByAbsolutePaths(span_def) => {
487                 db.span_note(span_def, "the macro is defined here");
488             }
489             BuiltinLintDiagnostics::ElidedLifetimesInPaths(
490                 n, path_span, incl_angl_brckt, insertion_span, anon_lts
491             ) => {
492                 let (replace_span, suggestion) = if incl_angl_brckt {
493                     (insertion_span, anon_lts)
494                 } else {
495                     // When possible, prefer a suggestion that replaces the whole
496                     // `Path<T>` expression with `Path<'_, T>`, rather than inserting `'_, `
497                     // at a point (which makes for an ugly/confusing label)
498                     if let Ok(snippet) = sess.source_map().span_to_snippet(path_span) {
499                         // But our spans can get out of whack due to macros; if the place we think
500                         // we want to insert `'_` isn't even within the path expression's span, we
501                         // should bail out of making any suggestion rather than panicking on a
502                         // subtract-with-overflow or string-slice-out-out-bounds (!)
503                         // FIXME: can we do better?
504                         if insertion_span.lo().0 < path_span.lo().0 {
505                             return;
506                         }
507                         let insertion_index = (insertion_span.lo().0 - path_span.lo().0) as usize;
508                         if insertion_index > snippet.len() {
509                             return;
510                         }
511                         let (before, after) = snippet.split_at(insertion_index);
512                         (path_span, format!("{}{}{}", before, anon_lts, after))
513                     } else {
514                         (insertion_span, anon_lts)
515                     }
516                 };
517                 db.span_suggestion_with_applicability(
518                     replace_span,
519                     &format!("indicate the anonymous lifetime{}", if n >= 2 { "s" } else { "" }),
520                     suggestion,
521                     Applicability::MachineApplicable
522                 );
523             }
524             BuiltinLintDiagnostics::UnknownCrateTypes(span, note, sugg) => {
525                 db.span_suggestion_with_applicability(
526                     span,
527                     &note,
528                     sugg,
529                     Applicability::MaybeIncorrect
530                 );
531             }
532         }
533     }
534 }
535
536 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for HardwiredLints {}