1 //! Some lints that are built in to the compiler.
3 //! These are the built-in lints that are emitted direct in the main
4 //! compiler code, rather than using their own custom pass. Those
5 //! lints are all available in `rustc_lint::builtin`.
7 use crate::lint::{LintPass, LateLintPass, LintArray};
8 use crate::session::Session;
9 use errors::{Applicability, DiagnosticBuilder};
11 use syntax::source_map::Span;
14 pub EXCEEDING_BITSHIFTS,
16 "shift exceeds the type's number of bits"
22 "constant evaluation detected erroneous expression"
28 "imports that are never used"
32 pub UNUSED_EXTERN_CRATES,
34 "extern crates that are never used"
38 pub UNUSED_QUALIFICATIONS,
40 "detects unnecessarily qualified names"
46 "unrecognized lint attribute"
52 "detect variables which are not used in any way"
56 pub UNUSED_ASSIGNMENTS,
58 "detect assignments that will never be read"
64 "detect unused, unexported items"
70 "detects unreachable code paths",
71 report_in_external_macro: true
75 pub UNREACHABLE_PATTERNS,
77 "detects unreachable patterns"
83 "detects macros that were not used"
89 "mass-change the level for lints which produce warnings"
95 "unused features found in crate-level #[feature] directives"
101 "stable features found in #[feature] directive"
105 pub UNKNOWN_CRATE_TYPES,
107 "unknown crate type found in #[crate_type] directive"
113 "detects trivial casts which could be removed"
117 pub TRIVIAL_NUMERIC_CASTS,
119 "detects trivial casts of numeric types which could be removed"
123 pub PRIVATE_IN_PUBLIC,
125 "detect private items in public interfaces not caught by the old implementation"
129 pub EXPORTED_PRIVATE_DEPENDENCIES,
131 "public interface leaks type from a private dependency"
135 pub PUB_USE_OF_PRIVATE_EXTERN_CRATE,
137 "detect public re-exports of private extern crates"
141 pub INVALID_TYPE_PARAM_DEFAULT,
143 "type parameter default erroneously allowed in invalid location"
147 pub RENAMED_AND_REMOVED_LINTS,
149 "lints that have been renamed or removed"
153 pub SAFE_EXTERN_STATICS,
155 "safe access to extern statics was erroneously allowed"
159 pub SAFE_PACKED_BORROWS,
161 "safe borrows of fields of packed structs were was erroneously allowed"
165 pub PATTERNS_IN_FNS_WITHOUT_BODY,
167 "patterns in functions without body were erroneously allowed"
171 pub LEGACY_DIRECTORY_OWNERSHIP,
173 "non-inline, non-`#[path]` modules (e.g., `mod foo;`) were erroneously allowed in some files \
178 pub LEGACY_CONSTRUCTOR_VISIBILITY,
180 "detects use of struct constructors that would be invisible with new visibility rules"
184 pub MISSING_FRAGMENT_SPECIFIER,
186 "detects missing fragment specifiers in unused `macro_rules!` patterns"
190 pub PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
192 "detects parenthesized generic parameters in type and module names"
196 pub LATE_BOUND_LIFETIME_ARGUMENTS,
198 "detects generic lifetime arguments in path segments with late bound lifetime parameters"
202 pub ORDER_DEPENDENT_TRAIT_OBJECTS,
204 "trait-object types were treated as different depending on marker-trait order"
210 "detects use of deprecated items",
211 report_in_external_macro: true
217 "unnecessary use of an `unsafe` block"
223 "detect mut variables which don't need to be mutable"
227 pub UNCONDITIONAL_RECURSION,
229 "functions that cannot return without calling themselves"
233 pub SINGLE_USE_LIFETIMES,
235 "detects lifetime parameters that are only used once"
239 pub UNUSED_LIFETIMES,
241 "detects lifetime parameters that are never used"
245 pub TYVAR_BEHIND_RAW_POINTER,
247 "raw pointer to an inference variable"
251 pub ELIDED_LIFETIMES_IN_PATHS,
253 "hidden lifetime parameters in types are deprecated"
257 pub BARE_TRAIT_OBJECTS,
259 "suggest using `dyn Trait` for trait objects"
263 pub ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE,
265 "fully qualified paths that start with a module name \
266 instead of `crate`, `self`, or an extern crate name"
270 pub ILLEGAL_FLOATING_POINT_LITERAL_PATTERN,
272 "floating-point literals cannot be used in patterns"
276 pub UNSTABLE_NAME_COLLISIONS,
278 "detects name collision with an existing but unstable method"
282 pub IRREFUTABLE_LET_PATTERNS,
284 "detects irrefutable patterns in if-let and while-let statements"
290 "detects labels that are never used"
294 pub DUPLICATE_MACRO_EXPORTS,
296 "detects duplicate macro exports"
300 pub INTRA_DOC_LINK_RESOLUTION_FAILURE,
302 "failures in resolving intra-doc link targets"
306 pub MISSING_DOC_CODE_EXAMPLES,
308 "detects publicly-exported items without code samples in their documentation"
312 pub PRIVATE_DOC_TESTS,
314 "detects code samples in docs of private items not documented by rustdoc"
318 pub WHERE_CLAUSES_OBJECT_SAFETY,
320 "checks the object safety of where clauses"
324 pub PROC_MACRO_DERIVE_RESOLUTION_FALLBACK,
326 "detects proc macro derives using inaccessible names from parent modules"
330 pub MACRO_USE_EXTERN_CRATE,
332 "the `#[macro_use]` attribute is now deprecated in favor of using macros \
333 via the module system"
337 pub MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS,
339 "macro-expanded `macro_export` macros from the current crate \
340 cannot be referred to by absolute paths"
344 pub EXPLICIT_OUTLIVES_REQUIREMENTS,
346 "outlives requirements can be inferred"
349 /// Some lints that are buffered from `libsyntax`. See `syntax::early_buffered_lints`.
352 pub QUESTION_MARK_MACRO_SEP,
354 "detects the use of `?` as a macro separator"
358 pub ILL_FORMED_ATTRIBUTE_INPUT,
360 "ill-formed attribute inputs that were previously accepted and used in practice"
365 pub DEPRECATED_IN_FUTURE,
367 "detects use of items that will be deprecated in a future version",
368 report_in_external_macro: true
372 pub AMBIGUOUS_ASSOCIATED_ITEMS,
374 "ambiguous associated items"
378 pub NESTED_IMPL_TRAIT,
380 "nested occurrence of `impl Trait` type"
384 pub MUTABLE_BORROW_RESERVATION_CONFLICT,
386 "reservation of a two-phased borrow conflicts with other shared borrows"
390 /// Does nothing as a lint pass, but registers some `Lint`s
391 /// that are used by other parts of the compiler.
393 ILLEGAL_FLOATING_POINT_LITERAL_PATTERN,
396 UNUSED_EXTERN_CRATES,
397 UNUSED_QUALIFICATIONS,
403 UNREACHABLE_PATTERNS,
410 TRIVIAL_NUMERIC_CASTS,
412 EXPORTED_PRIVATE_DEPENDENCIES,
413 PUB_USE_OF_PRIVATE_EXTERN_CRATE,
414 INVALID_TYPE_PARAM_DEFAULT,
416 RENAMED_AND_REMOVED_LINTS,
419 PATTERNS_IN_FNS_WITHOUT_BODY,
420 LEGACY_DIRECTORY_OWNERSHIP,
421 LEGACY_CONSTRUCTOR_VISIBILITY,
422 MISSING_FRAGMENT_SPECIFIER,
423 PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
424 LATE_BOUND_LIFETIME_ARGUMENTS,
425 ORDER_DEPENDENT_TRAIT_OBJECTS,
429 UNCONDITIONAL_RECURSION,
430 SINGLE_USE_LIFETIMES,
433 TYVAR_BEHIND_RAW_POINTER,
434 ELIDED_LIFETIMES_IN_PATHS,
436 ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE,
437 UNSTABLE_NAME_COLLISIONS,
438 IRREFUTABLE_LET_PATTERNS,
439 DUPLICATE_MACRO_EXPORTS,
440 INTRA_DOC_LINK_RESOLUTION_FAILURE,
441 MISSING_DOC_CODE_EXAMPLES,
443 WHERE_CLAUSES_OBJECT_SAFETY,
444 PROC_MACRO_DERIVE_RESOLUTION_FALLBACK,
445 MACRO_USE_EXTERN_CRATE,
446 MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS,
447 parser::QUESTION_MARK_MACRO_SEP,
448 parser::ILL_FORMED_ATTRIBUTE_INPUT,
449 DEPRECATED_IN_FUTURE,
450 AMBIGUOUS_ASSOCIATED_ITEMS,
452 MUTABLE_BORROW_RESERVATION_CONFLICT,
456 // this could be a closure, but then implementing derive traits
457 // becomes hacky (and it gets allocated)
458 #[derive(PartialEq, RustcEncodable, RustcDecodable, Debug)]
459 pub enum BuiltinLintDiagnostics {
461 BareTraitObject(Span, /* is_global */ bool),
462 AbsPathWithModule(Span),
463 DuplicatedMacroExports(ast::Ident, Span, Span),
464 ProcMacroDeriveResolutionFallback(Span),
465 MacroExpandedMacroExportsAccessedByAbsolutePaths(Span),
466 ElidedLifetimesInPaths(usize, Span, bool, Span, String),
467 UnknownCrateTypes(Span, String, String),
468 UnusedImports(String, Vec<(Span, String)>),
469 NestedImplTrait { outer_impl_trait_span: Span, inner_impl_trait_span: Span },
470 RedundantImport(Vec<(Span, bool)>, ast::Ident),
473 pub(crate) fn add_elided_lifetime_in_path_suggestion(
475 db: &mut DiagnosticBuilder<'_>,
478 incl_angl_brckt: bool,
479 insertion_span: Span,
482 let (replace_span, suggestion) = if incl_angl_brckt {
483 (insertion_span, anon_lts)
485 // When possible, prefer a suggestion that replaces the whole
486 // `Path<T>` expression with `Path<'_, T>`, rather than inserting `'_, `
487 // at a point (which makes for an ugly/confusing label)
488 if let Ok(snippet) = sess.source_map().span_to_snippet(path_span) {
489 // But our spans can get out of whack due to macros; if the place we think
490 // we want to insert `'_` isn't even within the path expression's span, we
491 // should bail out of making any suggestion rather than panicking on a
492 // subtract-with-overflow or string-slice-out-out-bounds (!)
493 // FIXME: can we do better?
494 if insertion_span.lo().0 < path_span.lo().0 {
497 let insertion_index = (insertion_span.lo().0 - path_span.lo().0) as usize;
498 if insertion_index > snippet.len() {
501 let (before, after) = snippet.split_at(insertion_index);
502 (path_span, format!("{}{}{}", before, anon_lts, after))
504 (insertion_span, anon_lts)
509 &format!("indicate the anonymous lifetime{}", if n >= 2 { "s" } else { "" }),
511 Applicability::MachineApplicable
515 impl BuiltinLintDiagnostics {
516 pub fn run(self, sess: &Session, db: &mut DiagnosticBuilder<'_>) {
518 BuiltinLintDiagnostics::Normal => (),
519 BuiltinLintDiagnostics::BareTraitObject(span, is_global) => {
520 let (sugg, app) = match sess.source_map().span_to_snippet(span) {
521 Ok(ref s) if is_global => (format!("dyn ({})", s),
522 Applicability::MachineApplicable),
523 Ok(s) => (format!("dyn {}", s), Applicability::MachineApplicable),
524 Err(_) => ("dyn <type>".to_string(), Applicability::HasPlaceholders)
526 db.span_suggestion(span, "use `dyn`", sugg, app);
528 BuiltinLintDiagnostics::AbsPathWithModule(span) => {
529 let (sugg, app) = match sess.source_map().span_to_snippet(span) {
531 // FIXME(Manishearth) ideally the emitting code
532 // can tell us whether or not this is global
533 let opt_colon = if s.trim_start().starts_with("::") {
539 (format!("crate{}{}", opt_colon, s), Applicability::MachineApplicable)
541 Err(_) => ("crate::<path>".to_string(), Applicability::HasPlaceholders)
543 db.span_suggestion(span, "use `crate`", sugg, app);
545 BuiltinLintDiagnostics::DuplicatedMacroExports(ident, earlier_span, later_span) => {
546 db.span_label(later_span, format!("`{}` already exported", ident));
547 db.span_note(earlier_span, "previous macro export is now shadowed");
549 BuiltinLintDiagnostics::ProcMacroDeriveResolutionFallback(span) => {
550 db.span_label(span, "names from parent modules are not \
551 accessible without an explicit import");
553 BuiltinLintDiagnostics::MacroExpandedMacroExportsAccessedByAbsolutePaths(span_def) => {
554 db.span_note(span_def, "the macro is defined here");
556 BuiltinLintDiagnostics::ElidedLifetimesInPaths(
557 n, path_span, incl_angl_brckt, insertion_span, anon_lts
559 add_elided_lifetime_in_path_suggestion(
569 BuiltinLintDiagnostics::UnknownCrateTypes(span, note, sugg) => {
570 db.span_suggestion(span, ¬e, sugg, Applicability::MaybeIncorrect);
572 BuiltinLintDiagnostics::UnusedImports(message, replaces) => {
573 if !replaces.is_empty() {
574 db.tool_only_multipart_suggestion(
577 Applicability::MachineApplicable,
581 BuiltinLintDiagnostics::NestedImplTrait {
582 outer_impl_trait_span, inner_impl_trait_span
584 db.span_label(outer_impl_trait_span, "outer `impl Trait`");
585 db.span_label(inner_impl_trait_span, "nested `impl Trait` here");
587 BuiltinLintDiagnostics::RedundantImport(spans, ident) => {
588 for (span, is_imported) in spans {
589 let introduced = if is_imported { "imported" } else { "defined" };
592 format!("the item `{}` is already {} here", ident, introduced)
600 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for HardwiredLints {}