rust/clippy_utils/src/ptr.rs

58 lines
1.8 KiB
Rust
Raw Normal View History

use crate::source::snippet;
use crate::visitors::expr_visitor_no_bodies;
use crate::{path_to_local_id, strip_pat_refs};
use rustc_hir::intravisit::Visitor;
use rustc_hir::{Body, BodyId, ExprKind, HirId, PatKind};
2020-01-12 00:08:41 -06:00
use rustc_lint::LateContext;
use rustc_span::Span;
2018-11-27 14:14:15 -06:00
use std::borrow::Cow;
2017-10-08 03:51:44 -05:00
pub fn get_spans(
cx: &LateContext<'_>,
2017-10-08 03:51:44 -05:00
opt_body_id: Option<BodyId>,
idx: usize,
2019-05-17 16:53:54 -05:00
replacements: &[(&'static str, &'static str)],
2017-10-08 03:51:44 -05:00
) -> Option<Vec<(Span, Cow<'static, str>)>> {
if let Some(body) = opt_body_id.map(|id| cx.tcx.hir().body(id)) {
if let PatKind::Binding(_, binding_id, _, _) = strip_pat_refs(body.params[idx].pat).kind {
extract_clone_suggestions(cx, binding_id, replacements, body)
} else {
Some(vec![])
}
2017-10-08 03:51:44 -05:00
} else {
Some(vec![])
}
}
fn extract_clone_suggestions<'tcx>(
cx: &LateContext<'tcx>,
id: HirId,
2019-05-17 16:53:54 -05:00
replace: &[(&'static str, &'static str)],
2019-12-22 08:42:41 -06:00
body: &'tcx Body<'_>,
2017-10-08 03:51:44 -05:00
) -> Option<Vec<(Span, Cow<'static, str>)>> {
let mut abort = false;
let mut spans = Vec::new();
expr_visitor_no_bodies(|expr| {
if abort {
return false;
2017-10-08 03:51:44 -05:00
}
if let ExprKind::MethodCall(seg, [recv], _) = expr.kind {
if path_to_local_id(recv, id) {
2019-05-17 16:53:54 -05:00
if seg.ident.name.as_str() == "capacity" {
abort = true;
return false;
2017-10-08 03:51:44 -05:00
}
for &(fn_name, suffix) in replace {
2019-05-17 16:53:54 -05:00
if seg.ident.name.as_str() == fn_name {
spans.push((expr.span, snippet(cx, recv.span, "_") + suffix));
return false;
2017-10-08 03:51:44 -05:00
}
}
}
}
!abort
})
.visit_body(body);
if abort { None } else { Some(spans) }
2017-10-08 03:51:44 -05:00
}