]> git.lizzy.rs Git - rust.git/blob - src/librustc/lint/builtin.rs
2301055e5cec2a509105d617d5673ac55006bd32
[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::codemap::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 UNKNOWN_FEATURES,
110     Deny,
111     "unknown features found in crate-level #[feature] directives"
112 }
113
114 declare_lint! {
115     pub DUPLICATE_FEATURES,
116     Deny,
117     "duplicate features found in crate-level #[feature] directives"
118 }
119
120 declare_lint! {
121     pub STABLE_FEATURES,
122     Warn,
123     "stable features found in #[feature] directive"
124 }
125
126 declare_lint! {
127     pub UNKNOWN_CRATE_TYPES,
128     Deny,
129     "unknown crate type found in #[crate_type] directive"
130 }
131
132 declare_lint! {
133     pub TRIVIAL_CASTS,
134     Allow,
135     "detects trivial casts which could be removed"
136 }
137
138 declare_lint! {
139     pub TRIVIAL_NUMERIC_CASTS,
140     Allow,
141     "detects trivial casts of numeric types which could be removed"
142 }
143
144 declare_lint! {
145     pub PRIVATE_IN_PUBLIC,
146     Warn,
147     "detect private items in public interfaces not caught by the old implementation"
148 }
149
150 declare_lint! {
151     pub PUB_USE_OF_PRIVATE_EXTERN_CRATE,
152     Deny,
153     "detect public re-exports of private extern crates"
154 }
155
156 declare_lint! {
157     pub INVALID_TYPE_PARAM_DEFAULT,
158     Deny,
159     "type parameter default erroneously allowed in invalid location"
160 }
161
162 declare_lint! {
163     pub RENAMED_AND_REMOVED_LINTS,
164     Warn,
165     "lints that have been renamed or removed"
166 }
167
168 declare_lint! {
169     pub SAFE_EXTERN_STATICS,
170     Deny,
171     "safe access to extern statics was erroneously allowed"
172 }
173
174 declare_lint! {
175     pub SAFE_PACKED_BORROWS,
176     Warn,
177     "safe borrows of fields of packed structs were was erroneously allowed"
178 }
179
180 declare_lint! {
181     pub PATTERNS_IN_FNS_WITHOUT_BODY,
182     Warn,
183     "patterns in functions without body were erroneously allowed"
184 }
185
186 declare_lint! {
187     pub LEGACY_DIRECTORY_OWNERSHIP,
188     Deny,
189     "non-inline, non-`#[path]` modules (e.g. `mod foo;`) were erroneously allowed in some files \
190      not named `mod.rs`"
191 }
192
193 declare_lint! {
194     pub LEGACY_CONSTRUCTOR_VISIBILITY,
195     Deny,
196     "detects use of struct constructors that would be invisible with new visibility rules"
197 }
198
199 declare_lint! {
200     pub MISSING_FRAGMENT_SPECIFIER,
201     Deny,
202     "detects missing fragment specifiers in unused `macro_rules!` patterns"
203 }
204
205 declare_lint! {
206     pub PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
207     Deny,
208     "detects parenthesized generic parameters in type and module names"
209 }
210
211 declare_lint! {
212     pub LATE_BOUND_LIFETIME_ARGUMENTS,
213     Warn,
214     "detects generic lifetime arguments in path segments with late bound lifetime parameters"
215 }
216
217 declare_lint! {
218     pub INCOHERENT_FUNDAMENTAL_IMPLS,
219     Deny,
220     "potentially-conflicting impls were erroneously allowed"
221 }
222
223 declare_lint! {
224     pub BAD_REPR,
225     Warn,
226     "detects incorrect use of `repr` attribute"
227 }
228
229 declare_lint! {
230     pub DEPRECATED,
231     Warn,
232     "detects use of deprecated items",
233     report_in_external_macro: true
234 }
235
236 declare_lint! {
237     pub UNUSED_UNSAFE,
238     Warn,
239     "unnecessary use of an `unsafe` block"
240 }
241
242 declare_lint! {
243     pub UNUSED_MUT,
244     Warn,
245     "detect mut variables which don't need to be mutable"
246 }
247
248 declare_lint! {
249     pub SINGLE_USE_LIFETIMES,
250     Allow,
251     "detects lifetime parameters that are only used once"
252 }
253
254 declare_lint! {
255     pub UNUSED_LIFETIMES,
256     Allow,
257     "detects lifetime parameters that are never used"
258 }
259
260 declare_lint! {
261     pub TYVAR_BEHIND_RAW_POINTER,
262     Warn,
263     "raw pointer to an inference variable"
264 }
265
266 declare_lint! {
267     pub ELIDED_LIFETIMES_IN_PATHS,
268     Allow,
269     "hidden lifetime parameters in types are deprecated"
270 }
271
272 declare_lint! {
273     pub BARE_TRAIT_OBJECTS,
274     Allow,
275     "suggest using `dyn Trait` for trait objects"
276 }
277
278 declare_lint! {
279     pub ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE,
280     Allow,
281     "fully qualified paths that start with a module name \
282      instead of `crate`, `self`, or an extern crate name"
283 }
284
285 declare_lint! {
286     pub ILLEGAL_FLOATING_POINT_LITERAL_PATTERN,
287     Warn,
288     "floating-point literals cannot be used in patterns"
289 }
290
291 declare_lint! {
292     pub UNSTABLE_NAME_COLLISIONS,
293     Warn,
294     "detects name collision with an existing but unstable method"
295 }
296
297 declare_lint! {
298     pub IRREFUTABLE_LET_PATTERNS,
299     Deny,
300     "detects irrefutable patterns in if-let and while-let statements"
301 }
302
303 declare_lint! {
304     pub UNUSED_LABELS,
305     Allow,
306     "detects labels that are never used"
307 }
308
309 declare_lint! {
310     pub DUPLICATE_ASSOCIATED_TYPE_BINDINGS,
311     Warn,
312     "warns about duplicate associated type bindings in generics"
313 }
314
315 declare_lint! {
316     pub DUPLICATE_MACRO_EXPORTS,
317     Deny,
318     "detects duplicate macro exports"
319 }
320
321 declare_lint! {
322     pub INTRA_DOC_LINK_RESOLUTION_FAILURE,
323     Warn,
324     "warn about documentation intra links resolution failure"
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 /// Some lints that are buffered from `libsyntax`. See `syntax::early_buffered_lints`.
347 pub mod parser {
348     declare_lint! {
349         pub QUESTION_MARK_MACRO_SEP,
350         Allow,
351         "detects the use of `?` as a macro separator"
352     }
353 }
354
355 /// Does nothing as a lint pass, but registers some `Lint`s
356 /// which are used by other parts of the compiler.
357 #[derive(Copy, Clone)]
358 pub struct HardwiredLints;
359
360 impl LintPass for HardwiredLints {
361     fn get_lints(&self) -> LintArray {
362         lint_array!(
363             ILLEGAL_FLOATING_POINT_LITERAL_PATTERN,
364             EXCEEDING_BITSHIFTS,
365             UNUSED_IMPORTS,
366             UNUSED_EXTERN_CRATES,
367             UNUSED_QUALIFICATIONS,
368             UNKNOWN_LINTS,
369             UNUSED_VARIABLES,
370             UNUSED_ASSIGNMENTS,
371             DEAD_CODE,
372             UNREACHABLE_CODE,
373             UNREACHABLE_PATTERNS,
374             UNUSED_MACROS,
375             WARNINGS,
376             UNUSED_FEATURES,
377             UNKNOWN_FEATURES,
378             DUPLICATE_FEATURES,
379             STABLE_FEATURES,
380             UNKNOWN_CRATE_TYPES,
381             TRIVIAL_CASTS,
382             TRIVIAL_NUMERIC_CASTS,
383             PRIVATE_IN_PUBLIC,
384             PUB_USE_OF_PRIVATE_EXTERN_CRATE,
385             INVALID_TYPE_PARAM_DEFAULT,
386             CONST_ERR,
387             RENAMED_AND_REMOVED_LINTS,
388             SAFE_EXTERN_STATICS,
389             SAFE_PACKED_BORROWS,
390             PATTERNS_IN_FNS_WITHOUT_BODY,
391             LEGACY_DIRECTORY_OWNERSHIP,
392             LEGACY_CONSTRUCTOR_VISIBILITY,
393             MISSING_FRAGMENT_SPECIFIER,
394             PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
395             LATE_BOUND_LIFETIME_ARGUMENTS,
396             INCOHERENT_FUNDAMENTAL_IMPLS,
397             DEPRECATED,
398             UNUSED_UNSAFE,
399             UNUSED_MUT,
400             SINGLE_USE_LIFETIMES,
401             UNUSED_LIFETIMES,
402             UNUSED_LABELS,
403             TYVAR_BEHIND_RAW_POINTER,
404             ELIDED_LIFETIMES_IN_PATHS,
405             BARE_TRAIT_OBJECTS,
406             ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE,
407             UNSTABLE_NAME_COLLISIONS,
408             IRREFUTABLE_LET_PATTERNS,
409             DUPLICATE_ASSOCIATED_TYPE_BINDINGS,
410             DUPLICATE_MACRO_EXPORTS,
411             INTRA_DOC_LINK_RESOLUTION_FAILURE,
412             WHERE_CLAUSES_OBJECT_SAFETY,
413             PROC_MACRO_DERIVE_RESOLUTION_FALLBACK,
414             MACRO_USE_EXTERN_CRATE,
415             parser::QUESTION_MARK_MACRO_SEP,
416         )
417     }
418 }
419
420 // this could be a closure, but then implementing derive traits
421 // becomes hacky (and it gets allocated)
422 #[derive(PartialEq, RustcEncodable, RustcDecodable, Debug)]
423 pub enum BuiltinLintDiagnostics {
424     Normal,
425     BareTraitObject(Span, /* is_global */ bool),
426     AbsPathWithModule(Span),
427     DuplicatedMacroExports(ast::Ident, Span, Span),
428     ProcMacroDeriveResolutionFallback(Span),
429     ElidedLifetimesInPaths(usize, Span, bool, Span, String),
430 }
431
432 impl BuiltinLintDiagnostics {
433     pub fn run(self, sess: &Session, db: &mut DiagnosticBuilder) {
434         match self {
435             BuiltinLintDiagnostics::Normal => (),
436             BuiltinLintDiagnostics::BareTraitObject(span, is_global) => {
437                 let (sugg, app) = match sess.codemap().span_to_snippet(span) {
438                     Ok(ref s) if is_global => (format!("dyn ({})", s),
439                                                Applicability::MachineApplicable),
440                     Ok(s) => (format!("dyn {}", s), Applicability::MachineApplicable),
441                     Err(_) => ("dyn <type>".to_string(), Applicability::HasPlaceholders)
442                 };
443                 db.span_suggestion_with_applicability(span, "use `dyn`", sugg, app);
444             }
445             BuiltinLintDiagnostics::AbsPathWithModule(span) => {
446                 let (sugg, app) = match sess.codemap().span_to_snippet(span) {
447                     Ok(ref s) => {
448                         // FIXME(Manishearth) ideally the emitting code
449                         // can tell us whether or not this is global
450                         let opt_colon = if s.trim_left().starts_with("::") {
451                             ""
452                         } else {
453                             "::"
454                         };
455
456                         (format!("crate{}{}", opt_colon, s), Applicability::MachineApplicable)
457                     }
458                     Err(_) => ("crate::<path>".to_string(), Applicability::HasPlaceholders)
459                 };
460                 db.span_suggestion_with_applicability(span, "use `crate`", sugg, app);
461             }
462             BuiltinLintDiagnostics::DuplicatedMacroExports(ident, earlier_span, later_span) => {
463                 db.span_label(later_span, format!("`{}` already exported", ident));
464                 db.span_note(earlier_span, "previous macro export is now shadowed");
465             }
466             BuiltinLintDiagnostics::ProcMacroDeriveResolutionFallback(span) => {
467                 db.span_label(span, "names from parent modules are not \
468                                      accessible without an explicit import");
469             }
470             BuiltinLintDiagnostics::ElidedLifetimesInPaths(
471                 n, path_span, incl_angl_brckt, insertion_span, anon_lts
472             ) => {
473                 let (replace_span, suggestion) = if incl_angl_brckt {
474                     (insertion_span, anon_lts)
475                 } else {
476                     // When possible, prefer a suggestion that replaces the whole
477                     // `Path<T>` expression with `Path<'_, T>`, rather than inserting `'_, `
478                     // at a point (which makes for an ugly/confusing label)
479                     if let Ok(snippet) = sess.codemap().span_to_snippet(path_span) {
480                         // But our spans can get out of whack due to macros; if the place we think
481                         // we want to insert `'_` isn't even within the path expression's span, we
482                         // should bail out of making any suggestion rather than panicking on a
483                         // subtract-with-overflow or string-slice-out-out-bounds (!)
484                         // FIXME: can we do better?
485                         if insertion_span.lo().0 < path_span.lo().0 {
486                             return;
487                         }
488                         let insertion_index = (insertion_span.lo().0 - path_span.lo().0) as usize;
489                         if insertion_index > snippet.len() {
490                             return;
491                         }
492                         let (before, after) = snippet.split_at(insertion_index);
493                         (path_span, format!("{}{}{}", before, anon_lts, after))
494                     } else {
495                         (insertion_span, anon_lts)
496                     }
497                 };
498                 db.span_suggestion_with_applicability(
499                     replace_span,
500                     &format!("indicate the anonymous lifetime{}", if n >= 2 { "s" } else { "" }),
501                     suggestion,
502                     Applicability::MachineApplicable
503                 );
504             }
505         }
506     }
507 }
508
509 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for HardwiredLints {}