Skip to content

Commit f2419b9

Browse files
committed
Refactoring to use `constant_context
Use `constant_context`, `.is_str()` and `builtin_index()` to simplify.
1 parent 780a4c8 commit f2419b9

File tree

1 file changed

+5
-49
lines changed

1 file changed

+5
-49
lines changed

clippy_lints/src/repeat_once.rs

+5-49
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,9 @@
1-
use crate::consts::{miri_to_const, Constant};
1+
use crate::consts::{constant_context, Constant};
22
use crate::utils::{in_macro, is_type_diagnostic_item, snippet, span_lint_and_sugg, walk_ptrs_ty};
33
use if_chain::if_chain;
4-
use rustc_ast::ast::LitKind;
54
use rustc_errors::Applicability;
6-
use rustc_hir::def::{DefKind, Res};
75
use rustc_hir::{Expr, ExprKind};
86
use rustc_lint::{LateContext, LateLintPass};
9-
use rustc_middle::ty::{self, Ty};
107
use rustc_session::{declare_lint_pass, declare_tool_lint};
118

129
declare_clippy_lint! {
@@ -44,10 +41,11 @@ impl<'tcx> LateLintPass<'tcx> for RepeatOnce {
4441
if_chain! {
4542
if let ExprKind::MethodCall(ref path, _, ref args, _) = expr.kind;
4643
if path.ident.name == sym!(repeat);
47-
if is_once(cx, &args[1]) && !in_macro(args[0].span);
44+
if let Some(Constant::Int(1)) = constant_context(cx, cx.tables()).expr(&args[1]);
45+
if !in_macro(args[0].span);
4846
then {
4947
let ty = walk_ptrs_ty(cx.tables().expr_ty(&args[0]));
50-
if is_str(ty){
48+
if ty.is_str() {
5149
span_lint_and_sugg(
5250
cx,
5351
REPEAT_ONCE,
@@ -57,7 +55,7 @@ impl<'tcx> LateLintPass<'tcx> for RepeatOnce {
5755
format!("{}.to_string()", snippet(cx, args[0].span, r#""...""#)),
5856
Applicability::MachineApplicable,
5957
);
60-
} else if is_slice(ty) {
58+
} else if let Some(_) = ty.builtin_index() {
6159
span_lint_and_sugg(
6260
cx,
6361
REPEAT_ONCE,
@@ -82,45 +80,3 @@ impl<'tcx> LateLintPass<'tcx> for RepeatOnce {
8280
}
8381
}
8482
}
85-
86-
fn is_once<'tcx>(cx: &LateContext<'_>, expr: &'tcx Expr<'_>) -> bool {
87-
match expr.kind {
88-
ExprKind::Lit(ref lit) => {
89-
if let LitKind::Int(ref lit_content, _) = lit.node {
90-
*lit_content == 1
91-
} else {
92-
false
93-
}
94-
},
95-
ExprKind::Path(rustc_hir::QPath::Resolved(None, path)) => {
96-
if let Res::Def(DefKind::Const, def_id) = path.res {
97-
let ty = cx.tcx.type_of(def_id);
98-
let con = cx
99-
.tcx
100-
.const_eval_poly(def_id)
101-
.ok()
102-
.map(|val| rustc_middle::ty::Const::from_value(cx.tcx, val, ty))
103-
.unwrap();
104-
let con = miri_to_const(con);
105-
con == Some(Constant::Int(1))
106-
} else {
107-
false
108-
}
109-
},
110-
_ => false,
111-
}
112-
}
113-
114-
fn is_str(ty: Ty<'_>) -> bool {
115-
match ty.kind {
116-
ty::Str => true,
117-
_ => false,
118-
}
119-
}
120-
121-
fn is_slice(ty: Ty<'_>) -> bool {
122-
match ty.kind {
123-
ty::Slice(..) | ty::Array(..) => true,
124-
_ => false,
125-
}
126-
}

0 commit comments

Comments
 (0)