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::source_map::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"
111 "stable features found in #[feature] directive"
115 pub UNKNOWN_CRATE_TYPES,
117 "unknown crate type found in #[crate_type] directive"
123 "detects trivial casts which could be removed"
127 pub TRIVIAL_NUMERIC_CASTS,
129 "detects trivial casts of numeric types which could be removed"
133 pub PRIVATE_IN_PUBLIC,
135 "detect private items in public interfaces not caught by the old implementation"
139 pub PUB_USE_OF_PRIVATE_EXTERN_CRATE,
141 "detect public re-exports of private extern crates"
145 pub INVALID_TYPE_PARAM_DEFAULT,
147 "type parameter default erroneously allowed in invalid location"
151 pub RENAMED_AND_REMOVED_LINTS,
153 "lints that have been renamed or removed"
157 pub SAFE_EXTERN_STATICS,
159 "safe access to extern statics was erroneously allowed"
163 pub SAFE_PACKED_BORROWS,
165 "safe borrows of fields of packed structs were was erroneously allowed"
169 pub PATTERNS_IN_FNS_WITHOUT_BODY,
171 "patterns in functions without body were erroneously allowed"
175 pub LEGACY_DIRECTORY_OWNERSHIP,
177 "non-inline, non-`#[path]` modules (e.g. `mod foo;`) were erroneously allowed in some files \
182 pub LEGACY_CONSTRUCTOR_VISIBILITY,
184 "detects use of struct constructors that would be invisible with new visibility rules"
188 pub MISSING_FRAGMENT_SPECIFIER,
190 "detects missing fragment specifiers in unused `macro_rules!` patterns"
194 pub PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
196 "detects parenthesized generic parameters in type and module names"
200 pub LATE_BOUND_LIFETIME_ARGUMENTS,
202 "detects generic lifetime arguments in path segments with late bound lifetime parameters"
206 pub INCOHERENT_FUNDAMENTAL_IMPLS,
208 "potentially-conflicting impls were erroneously allowed"
214 "detects incorrect use of `repr` attribute"
220 "detects use of deprecated items",
221 report_in_external_macro: true
227 "unnecessary use of an `unsafe` block"
233 "detect mut variables which don't need to be mutable"
237 pub SINGLE_USE_LIFETIMES,
239 "detects lifetime parameters that are only used once"
243 pub UNUSED_LIFETIMES,
245 "detects lifetime parameters that are never used"
249 pub TYVAR_BEHIND_RAW_POINTER,
251 "raw pointer to an inference variable"
255 pub ELIDED_LIFETIMES_IN_PATHS,
257 "hidden lifetime parameters in types are deprecated"
261 pub BARE_TRAIT_OBJECTS,
263 "suggest using `dyn Trait` for trait objects"
267 pub ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE,
269 "fully qualified paths that start with a module name \
270 instead of `crate`, `self`, or an extern crate name"
274 pub ILLEGAL_FLOATING_POINT_LITERAL_PATTERN,
276 "floating-point literals cannot be used in patterns"
280 pub UNSTABLE_NAME_COLLISIONS,
282 "detects name collision with an existing but unstable method"
286 pub IRREFUTABLE_LET_PATTERNS,
288 "detects irrefutable patterns in if-let and while-let statements"
294 "detects labels that are never used"
298 pub DUPLICATE_ASSOCIATED_TYPE_BINDINGS,
300 "warns about duplicate associated type bindings in generics"
304 pub DUPLICATE_MACRO_EXPORTS,
306 "detects duplicate macro exports"
310 pub INTRA_DOC_LINK_RESOLUTION_FAILURE,
312 "warn about documentation intra links resolution failure"
316 pub WHERE_CLAUSES_OBJECT_SAFETY,
318 "checks the object safety of where clauses"
322 pub PROC_MACRO_DERIVE_RESOLUTION_FALLBACK,
324 "detects proc macro derives using inaccessible names from parent modules"
328 pub MACRO_USE_EXTERN_CRATE,
330 "the `#[macro_use]` attribute is now deprecated in favor of using macros \
331 via the module system"
335 pub MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS,
337 "macro-expanded `macro_export` macros from the current crate \
338 cannot be referred to by absolute paths"
342 pub EXPLICIT_OUTLIVES_REQUIREMENTS,
344 "outlives requirements can be inferred"
347 /// Some lints that are buffered from `libsyntax`. See `syntax::early_buffered_lints`.
350 pub QUESTION_MARK_MACRO_SEP,
352 "detects the use of `?` as a macro separator"
356 /// Does nothing as a lint pass, but registers some `Lint`s
357 /// which are used by other parts of the compiler.
358 #[derive(Copy, Clone)]
359 pub struct HardwiredLints;
361 impl LintPass for HardwiredLints {
362 fn get_lints(&self) -> LintArray {
364 ILLEGAL_FLOATING_POINT_LITERAL_PATTERN,
367 UNUSED_EXTERN_CRATES,
368 UNUSED_QUALIFICATIONS,
374 UNREACHABLE_PATTERNS,
381 TRIVIAL_NUMERIC_CASTS,
383 PUB_USE_OF_PRIVATE_EXTERN_CRATE,
384 INVALID_TYPE_PARAM_DEFAULT,
386 RENAMED_AND_REMOVED_LINTS,
389 PATTERNS_IN_FNS_WITHOUT_BODY,
390 LEGACY_DIRECTORY_OWNERSHIP,
391 LEGACY_CONSTRUCTOR_VISIBILITY,
392 MISSING_FRAGMENT_SPECIFIER,
393 PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
394 LATE_BOUND_LIFETIME_ARGUMENTS,
395 INCOHERENT_FUNDAMENTAL_IMPLS,
399 SINGLE_USE_LIFETIMES,
402 TYVAR_BEHIND_RAW_POINTER,
403 ELIDED_LIFETIMES_IN_PATHS,
405 ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE,
406 UNSTABLE_NAME_COLLISIONS,
407 IRREFUTABLE_LET_PATTERNS,
408 DUPLICATE_ASSOCIATED_TYPE_BINDINGS,
409 DUPLICATE_MACRO_EXPORTS,
410 INTRA_DOC_LINK_RESOLUTION_FAILURE,
411 WHERE_CLAUSES_OBJECT_SAFETY,
412 PROC_MACRO_DERIVE_RESOLUTION_FALLBACK,
413 MACRO_USE_EXTERN_CRATE,
414 MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS,
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 MacroExpandedMacroExportsAccessedByAbsolutePaths(Span),
430 ElidedLifetimesInPaths(usize, Span, bool, Span, String),
431 UnknownCrateTypes(Span, String, String),
434 impl BuiltinLintDiagnostics {
435 pub fn run(self, sess: &Session, db: &mut DiagnosticBuilder<'_>) {
437 BuiltinLintDiagnostics::Normal => (),
438 BuiltinLintDiagnostics::BareTraitObject(span, is_global) => {
439 let (sugg, app) = match sess.source_map().span_to_snippet(span) {
440 Ok(ref s) if is_global => (format!("dyn ({})", s),
441 Applicability::MachineApplicable),
442 Ok(s) => (format!("dyn {}", s), Applicability::MachineApplicable),
443 Err(_) => ("dyn <type>".to_string(), Applicability::HasPlaceholders)
445 db.span_suggestion_with_applicability(span, "use `dyn`", sugg, app);
447 BuiltinLintDiagnostics::AbsPathWithModule(span) => {
448 let (sugg, app) = match sess.source_map().span_to_snippet(span) {
450 // FIXME(Manishearth) ideally the emitting code
451 // can tell us whether or not this is global
452 let opt_colon = if s.trim_left().starts_with("::") {
458 (format!("crate{}{}", opt_colon, s), Applicability::MachineApplicable)
460 Err(_) => ("crate::<path>".to_string(), Applicability::HasPlaceholders)
462 db.span_suggestion_with_applicability(span, "use `crate`", sugg, app);
464 BuiltinLintDiagnostics::DuplicatedMacroExports(ident, earlier_span, later_span) => {
465 db.span_label(later_span, format!("`{}` already exported", ident));
466 db.span_note(earlier_span, "previous macro export is now shadowed");
468 BuiltinLintDiagnostics::ProcMacroDeriveResolutionFallback(span) => {
469 db.span_label(span, "names from parent modules are not \
470 accessible without an explicit import");
472 BuiltinLintDiagnostics::MacroExpandedMacroExportsAccessedByAbsolutePaths(span_def) => {
473 db.span_note(span_def, "the macro is defined here");
475 BuiltinLintDiagnostics::ElidedLifetimesInPaths(
476 n, path_span, incl_angl_brckt, insertion_span, anon_lts
478 let (replace_span, suggestion) = if incl_angl_brckt {
479 (insertion_span, anon_lts)
481 // When possible, prefer a suggestion that replaces the whole
482 // `Path<T>` expression with `Path<'_, T>`, rather than inserting `'_, `
483 // at a point (which makes for an ugly/confusing label)
484 if let Ok(snippet) = sess.source_map().span_to_snippet(path_span) {
485 // But our spans can get out of whack due to macros; if the place we think
486 // we want to insert `'_` isn't even within the path expression's span, we
487 // should bail out of making any suggestion rather than panicking on a
488 // subtract-with-overflow or string-slice-out-out-bounds (!)
489 // FIXME: can we do better?
490 if insertion_span.lo().0 < path_span.lo().0 {
493 let insertion_index = (insertion_span.lo().0 - path_span.lo().0) as usize;
494 if insertion_index > snippet.len() {
497 let (before, after) = snippet.split_at(insertion_index);
498 (path_span, format!("{}{}{}", before, anon_lts, after))
500 (insertion_span, anon_lts)
503 db.span_suggestion_with_applicability(
505 &format!("indicate the anonymous lifetime{}", if n >= 2 { "s" } else { "" }),
507 Applicability::MachineApplicable
510 BuiltinLintDiagnostics::UnknownCrateTypes(span, note, sugg) => {
511 db.span_suggestion_with_applicability(
515 Applicability::MaybeIncorrect
522 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for HardwiredLints {}