Skip to content

Commit 9d12b04

Browse files
authored
Merge pull request #2806 from mockersf/loop-mut-cond
better parsing of condition in while loop for mutability
2 parents f30db14 + 5379fc1 commit 9d12b04

File tree

2 files changed

+35
-4
lines changed

2 files changed

+35
-4
lines changed

clippy_lints/src/loops.rs

+7-4
Original file line numberDiff line numberDiff line change
@@ -2154,9 +2154,10 @@ fn check_infinite_loop<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, cond: &'tcx Expr, b
21542154
let mut mut_var_visitor = VarCollectorVisitor {
21552155
cx,
21562156
ids: HashMap::new(),
2157+
def_ids: HashMap::new(),
21572158
skip: false,
21582159
};
2159-
walk_expr(&mut mut_var_visitor, expr);
2160+
mut_var_visitor.visit_expr(cond);
21602161
if mut_var_visitor.skip {
21612162
return;
21622163
}
@@ -2172,7 +2173,7 @@ fn check_infinite_loop<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, cond: &'tcx Expr, b
21722173
if delegate.skip {
21732174
return;
21742175
}
2175-
if !delegate.used_mutably.iter().any(|(_, v)| *v) {
2176+
if !(delegate.used_mutably.iter().any(|(_, v)| *v) || mut_var_visitor.def_ids.iter().any(|(_, v)| *v)) {
21762177
span_lint(
21772178
cx,
21782179
WHILE_IMMUTABLE_CONDITION,
@@ -2189,6 +2190,7 @@ fn check_infinite_loop<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, cond: &'tcx Expr, b
21892190
struct VarCollectorVisitor<'a, 'tcx: 'a> {
21902191
cx: &'a LateContext<'a, 'tcx>,
21912192
ids: HashMap<NodeId, bool>,
2193+
def_ids: HashMap<def_id::DefId, bool>,
21922194
skip: bool,
21932195
}
21942196

@@ -2203,6 +2205,9 @@ impl<'a, 'tcx> VarCollectorVisitor<'a, 'tcx> {
22032205
Def::Local(node_id) | Def::Upvar(node_id, ..) => {
22042206
self.ids.insert(node_id, false);
22052207
},
2208+
Def::Static(def_id, mutable) => {
2209+
self.def_ids.insert(def_id, mutable);
2210+
},
22062211
_ => {},
22072212
}
22082213
}
@@ -2221,8 +2226,6 @@ impl<'a, 'tcx> Visitor<'tcx> for VarCollectorVisitor<'a, 'tcx> {
22212226
}
22222227
}
22232228

2224-
fn visit_block(&mut self, _b: &'tcx Block) {}
2225-
22262229
fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
22272230
NestedVisitorMap::None
22282231
}
+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
#![allow(dead_code)]
2+
3+
/// Issue: https://github.com/rust-lang-nursery/rust-clippy/issues/2596
4+
pub fn loop_on_block_condition(u: &mut isize) {
5+
while { *u < 0 } {
6+
*u += 1;
7+
}
8+
}
9+
10+
/// https://github.com/rust-lang-nursery/rust-clippy/issues/2584
11+
fn loop_with_unsafe_condition(ptr: *const u8) {
12+
let mut len = 0;
13+
while unsafe { *ptr.offset(len) } != 0 {
14+
len += 1;
15+
}
16+
}
17+
18+
/// https://github.com/rust-lang-nursery/rust-clippy/issues/2710
19+
static mut RUNNING: bool = true;
20+
fn loop_on_static_condition() {
21+
unsafe {
22+
while RUNNING {
23+
RUNNING = false;
24+
}
25+
}
26+
}
27+
28+
fn main() {}

0 commit comments

Comments
 (0)