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.
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.
11 //! Some lints that are built in to the compiler.
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`.
17 use errors::{Applicability, DiagnosticBuilder};
18 use lint::{LintPass, LateLintPass, LintArray};
21 use syntax::codemap::Span;
24 pub EXCEEDING_BITSHIFTS,
26 "shift exceeds the type's number of bits"
32 "constant evaluation detected erroneous expression"
38 "imports that are never used"
42 pub UNUSED_EXTERN_CRATES,
44 "extern crates that are never used"
48 pub UNUSED_QUALIFICATIONS,
50 "detects unnecessarily qualified names"
56 "unrecognized lint attribute"
62 "detect variables which are not used in any way"
66 pub UNUSED_ASSIGNMENTS,
68 "detect assignments that will never be read"
74 "detect unused, unexported items"
80 "detects unreachable code paths",
81 report_in_external_macro: true
85 pub UNREACHABLE_PATTERNS,
87 "detects unreachable patterns"
93 "detects macros that were not used"
99 "mass-change the level for lints which produce warnings"
105 "unused features found in crate-level #[feature] directives"
109 pub UNKNOWN_FEATURES,
111 "unknown features found in crate-level #[feature] directives"
115 pub DUPLICATE_FEATURES,
117 "duplicate features found in crate-level #[feature] directives"
123 "stable features found in #[feature] directive"
127 pub UNKNOWN_CRATE_TYPES,
129 "unknown crate type found in #[crate_type] directive"
135 "detects trivial casts which could be removed"
139 pub TRIVIAL_NUMERIC_CASTS,
141 "detects trivial casts of numeric types which could be removed"
145 pub PRIVATE_IN_PUBLIC,
147 "detect private items in public interfaces not caught by the old implementation"
151 pub PUB_USE_OF_PRIVATE_EXTERN_CRATE,
153 "detect public re-exports of private extern crates"
157 pub INVALID_TYPE_PARAM_DEFAULT,
159 "type parameter default erroneously allowed in invalid location"
163 pub RENAMED_AND_REMOVED_LINTS,
165 "lints that have been renamed or removed"
169 pub SAFE_EXTERN_STATICS,
171 "safe access to extern statics was erroneously allowed"
175 pub SAFE_PACKED_BORROWS,
177 "safe borrows of fields of packed structs were was erroneously allowed"
181 pub PATTERNS_IN_FNS_WITHOUT_BODY,
183 "patterns in functions without body were erroneously allowed"
187 pub LEGACY_DIRECTORY_OWNERSHIP,
189 "non-inline, non-`#[path]` modules (e.g. `mod foo;`) were erroneously allowed in some files \
194 pub LEGACY_CONSTRUCTOR_VISIBILITY,
196 "detects use of struct constructors that would be invisible with new visibility rules"
200 pub MISSING_FRAGMENT_SPECIFIER,
202 "detects missing fragment specifiers in unused `macro_rules!` patterns"
206 pub PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
208 "detects parenthesized generic parameters in type and module names"
212 pub LATE_BOUND_LIFETIME_ARGUMENTS,
214 "detects generic lifetime arguments in path segments with late bound lifetime parameters"
218 pub INCOHERENT_FUNDAMENTAL_IMPLS,
220 "potentially-conflicting impls were erroneously allowed"
226 "detects incorrect use of `repr` attribute"
232 "detects use of deprecated items",
233 report_in_external_macro: true
239 "unnecessary use of an `unsafe` block"
245 "detect mut variables which don't need to be mutable"
249 pub SINGLE_USE_LIFETIMES,
251 "detects lifetime parameters that are only used once"
255 pub UNUSED_LIFETIMES,
257 "detects lifetime parameters that are never used"
261 pub TYVAR_BEHIND_RAW_POINTER,
263 "raw pointer to an inference variable"
267 pub ELIDED_LIFETIMES_IN_PATHS,
269 "hidden lifetime parameters in types are deprecated"
273 pub BARE_TRAIT_OBJECTS,
275 "suggest using `dyn Trait` for trait objects"
279 pub ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE,
281 "fully qualified paths that start with a module name \
282 instead of `crate`, `self`, or an extern crate name"
286 pub ILLEGAL_FLOATING_POINT_LITERAL_PATTERN,
288 "floating-point literals cannot be used in patterns"
292 pub UNSTABLE_NAME_COLLISIONS,
294 "detects name collision with an existing but unstable method"
298 pub IRREFUTABLE_LET_PATTERNS,
300 "detects irrefutable patterns in if-let and while-let statements"
306 "detects labels that are never used"
310 pub DUPLICATE_ASSOCIATED_TYPE_BINDINGS,
312 "warns about duplicate associated type bindings in generics"
316 pub DUPLICATE_MACRO_EXPORTS,
318 "detects duplicate macro exports"
322 pub INTRA_DOC_LINK_RESOLUTION_FAILURE,
324 "warn about documentation intra links resolution failure"
328 pub WHERE_CLAUSES_OBJECT_SAFETY,
330 "checks the object safety of where clauses"
334 pub PROC_MACRO_DERIVE_RESOLUTION_FALLBACK,
336 "detects proc macro derives using inaccessible names from parent modules"
340 pub MACRO_USE_EXTERN_CRATE,
342 "the `#[macro_use]` attribute is now deprecated in favor of using macros \
343 via the module system"
346 /// Some lints that are buffered from `libsyntax`. See `syntax::early_buffered_lints`.
349 pub QUESTION_MARK_MACRO_SEP,
351 "detects the use of `?` as a macro separator"
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;
360 impl LintPass for HardwiredLints {
361 fn get_lints(&self) -> LintArray {
363 ILLEGAL_FLOATING_POINT_LITERAL_PATTERN,
366 UNUSED_EXTERN_CRATES,
367 UNUSED_QUALIFICATIONS,
373 UNREACHABLE_PATTERNS,
382 TRIVIAL_NUMERIC_CASTS,
384 PUB_USE_OF_PRIVATE_EXTERN_CRATE,
385 INVALID_TYPE_PARAM_DEFAULT,
387 RENAMED_AND_REMOVED_LINTS,
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,
400 SINGLE_USE_LIFETIMES,
403 TYVAR_BEHIND_RAW_POINTER,
404 ELIDED_LIFETIMES_IN_PATHS,
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,
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 {
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),
432 impl BuiltinLintDiagnostics {
433 pub fn run(self, sess: &Session, db: &mut DiagnosticBuilder) {
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)
443 db.span_suggestion_with_applicability(span, "use `dyn`", sugg, app);
445 BuiltinLintDiagnostics::AbsPathWithModule(span) => {
446 let (sugg, app) = match sess.codemap().span_to_snippet(span) {
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("::") {
456 (format!("crate{}{}", opt_colon, s), Applicability::MachineApplicable)
458 Err(_) => ("crate::<path>".to_string(), Applicability::HasPlaceholders)
460 db.span_suggestion_with_applicability(span, "use `crate`", sugg, app);
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");
466 BuiltinLintDiagnostics::ProcMacroDeriveResolutionFallback(span) => {
467 db.span_label(span, "names from parent modules are not \
468 accessible without an explicit import");
470 BuiltinLintDiagnostics::ElidedLifetimesInPaths(
471 n, path_span, incl_angl_brckt, insertion_span, anon_lts
473 let (replace_span, suggestion) = if incl_angl_brckt {
474 (insertion_span, anon_lts)
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 {
488 let insertion_index = (insertion_span.lo().0 - path_span.lo().0) as usize;
489 if insertion_index > snippet.len() {
492 let (before, after) = snippet.split_at(insertion_index);
493 (path_span, format!("{}{}{}", before, anon_lts, after))
495 (insertion_span, anon_lts)
498 db.span_suggestion_with_applicability(
500 &format!("indicate the anonymous lifetime{}", if n >= 2 { "s" } else { "" }),
502 Applicability::MachineApplicable
509 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for HardwiredLints {}