rust-clippy/clippy_lints/src/utils/internal_lints.rs

254 lines
7.8 KiB
Rust
Raw Normal View History

use rustc::lint::*;
2018-07-19 07:53:23 +00:00
use rustc::{declare_lint, lint_array};
use rustc::hir::*;
2018-07-16 13:07:39 +00:00
use rustc::hir;
2017-09-05 09:33:04 +00:00
use rustc::hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
use rustc_data_structures::fx::FxHashMap;
use crate::utils::{match_qpath, paths, span_lint, span_lint_and_sugg};
use syntax::symbol::LocalInternedString;
use syntax::ast::{Crate as AstCrate, Ident, ItemKind, Name};
use syntax::codemap::Span;
2017-09-05 09:33:04 +00:00
use std::collections::{HashMap, HashSet};
/// **What it does:** Checks for various things we like to keep tidy in clippy.
///
/// **Why is this bad?** We like to pretend we're an example of tidy code.
///
/// **Known problems:** None.
///
/// **Example:** Wrong ordering of the util::paths constants.
2018-03-28 13:24:26 +00:00
declare_clippy_lint! {
pub CLIPPY_LINTS_INTERNAL,
2018-03-28 13:24:26 +00:00
internal,
"various things that will negatively affect your clippy experience"
}
/// **What it does:** Ensures every lint is associated to a `LintPass`.
///
/// **Why is this bad?** The compiler only knows lints via a `LintPass`. Without
/// putting a lint to a `LintPass::get_lints()`'s return, the compiler will not
/// know the name of the lint.
///
/// **Known problems:** Only checks for lints associated using the `lint_array!`
/// macro.
///
/// **Example:**
/// ```rust
/// declare_lint! { pub LINT_1, ... }
/// declare_lint! { pub LINT_2, ... }
/// declare_lint! { pub FORGOTTEN_LINT, ... }
/// // ...
/// pub struct Pass;
/// impl LintPass for Pass {
/// fn get_lints(&self) -> LintArray {
/// lint_array![LINT_1, LINT_2]
/// // missing FORGOTTEN_LINT
/// }
/// }
/// ```
2018-03-28 13:24:26 +00:00
declare_clippy_lint! {
pub LINT_WITHOUT_LINT_PASS,
2018-03-28 13:24:26 +00:00
internal,
"declaring a lint without associating it in a LintPass"
}
/// **What it does:** Checks for the presence of the default hash types "HashMap" or "HashSet"
/// and recommends the FxHash* variants.
///
/// **Why is this bad?** The FxHash variants have better performance
/// and we don't need any collision prevention in clippy.
declare_clippy_lint! {
pub DEFAULT_HASH_TYPES,
internal,
"forbid HashMap and HashSet and suggest the FxHash* variants"
}
#[derive(Copy, Clone)]
pub struct Clippy;
impl LintPass for Clippy {
fn get_lints(&self) -> LintArray {
lint_array!(CLIPPY_LINTS_INTERNAL)
}
}
impl EarlyLintPass for Clippy {
2018-07-23 11:01:12 +00:00
fn check_crate(&mut self, cx: &EarlyContext<'_>, krate: &AstCrate) {
2017-09-05 09:33:04 +00:00
if let Some(utils) = krate
.module
.items
.iter()
.find(|item| item.ident.name == "utils")
2017-08-09 07:30:56 +00:00
{
if let ItemKind::Mod(ref utils_mod) = utils.node {
2017-09-05 09:33:04 +00:00
if let Some(paths) = utils_mod
.items
.iter()
.find(|item| item.ident.name == "paths")
2017-08-09 07:30:56 +00:00
{
if let ItemKind::Mod(ref paths_mod) = paths.node {
let mut last_name: Option<LocalInternedString> = None;
for item in &paths_mod.items {
2018-06-28 13:46:58 +00:00
let name = item.ident.as_str();
if let Some(ref last_name) = last_name {
if **last_name > *name {
2017-08-09 07:30:56 +00:00
span_lint(
cx,
CLIPPY_LINTS_INTERNAL,
item.span,
"this constant should be before the previous constant due to lexical \
2017-09-05 09:33:04 +00:00
ordering",
2017-08-09 07:30:56 +00:00
);
}
}
last_name = Some(name);
}
}
}
}
}
}
}
#[derive(Clone, Debug, Default)]
pub struct LintWithoutLintPass {
declared_lints: HashMap<Name, Span>,
registered_lints: HashSet<Name>,
}
impl LintPass for LintWithoutLintPass {
fn get_lints(&self) -> LintArray {
lint_array!(LINT_WITHOUT_LINT_PASS)
}
}
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LintWithoutLintPass {
fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
2018-07-16 13:07:39 +00:00
if let hir::ItemKind::Static(ref ty, MutImmutable, body_id) = item.node {
if is_lint_ref_type(ty) {
self.declared_lints.insert(item.name, item.span);
} else if is_lint_array_type(ty) && item.name == "ARRAY" {
if let VisibilityKind::Inherited = item.vis.node {
let mut collector = LintCollector {
output: &mut self.registered_lints,
cx,
};
collector.visit_expr(&cx.tcx.hir.body(body_id).value);
}
}
}
}
fn check_crate_post(&mut self, cx: &LateContext<'a, 'tcx>, _: &'tcx Crate) {
for (lint_name, &lint_span) in &self.declared_lints {
// When using the `declare_lint!` macro, the original `lint_span`'s
// file points to "<rustc macros>".
// `compiletest-rs` thinks that's an error in a different file and
// just ignores it. This causes the test in compile-fail/lint_pass
// not able to capture the error.
// Therefore, we need to climb the macro expansion tree and find the
// actual span that invoked `declare_lint!`:
2017-08-09 07:30:56 +00:00
let lint_span = lint_span
.ctxt()
2017-08-09 07:30:56 +00:00
.outer()
.expn_info()
.map(|ei| ei.call_site)
.expect("unable to get call_site");
if !self.registered_lints.contains(lint_name) {
2017-08-09 07:30:56 +00:00
span_lint(
cx,
LINT_WITHOUT_LINT_PASS,
lint_span,
&format!("the lint `{}` is not added to any `LintPass`", lint_name),
);
}
}
}
}
fn is_lint_ref_type(ty: &Ty) -> bool {
2018-07-12 08:03:06 +00:00
if let TyKind::Rptr(
2017-10-31 17:03:54 +00:00
_,
2017-09-05 09:33:04 +00:00
MutTy {
ty: ref inner,
mutbl: MutImmutable,
},
) = ty.node
2017-08-09 07:30:56 +00:00
{
2018-07-12 08:03:06 +00:00
if let TyKind::Path(ref path) = inner.node {
return match_qpath(path, &paths::LINT);
}
}
false
}
fn is_lint_array_type(ty: &Ty) -> bool {
2018-07-12 08:03:06 +00:00
if let TyKind::Path(ref path) = ty.node {
match_qpath(path, &paths::LINT_ARRAY)
} else {
false
}
}
struct LintCollector<'a, 'tcx: 'a> {
output: &'a mut HashSet<Name>,
cx: &'a LateContext<'a, 'tcx>,
}
impl<'a, 'tcx: 'a> Visitor<'tcx> for LintCollector<'a, 'tcx> {
fn visit_expr(&mut self, expr: &'tcx Expr) {
walk_expr(self, expr);
}
2018-08-08 06:00:23 +00:00
fn visit_path(&mut self, path: &'tcx Path, _: HirId) {
if path.segments.len() == 1 {
2018-06-28 13:46:58 +00:00
self.output.insert(path.segments[0].ident.name);
}
}
fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
2017-02-02 16:53:28 +00:00
NestedVisitorMap::All(&self.cx.tcx.hir)
}
}
pub struct DefaultHashTypes {
map: FxHashMap<String, String>,
}
impl DefaultHashTypes {
pub fn new() -> Self {
let mut map = FxHashMap::default();
map.insert("HashMap".to_owned(), "FxHashMap".to_owned());
map.insert("HashSet".to_owned(), "FxHashSet".to_owned());
Self { map }
}
}
impl LintPass for DefaultHashTypes {
fn get_lints(&self) -> LintArray {
lint_array!(DEFAULT_HASH_TYPES)
}
}
impl EarlyLintPass for DefaultHashTypes {
fn check_ident(&mut self, cx: &EarlyContext<'_>, ident: Ident) {
let ident_string = ident.to_string();
if let Some(replace) = self.map.get(&ident_string) {
let msg = format!("Prefer {} over {}, it has better performance and we don't need any collision prevention in clippy", replace, ident_string);
span_lint_and_sugg(cx, DEFAULT_HASH_TYPES, ident.span, &msg, "use", replace.to_owned());
}
}
}