Skip to content

Commit

Permalink
stop warning never-returning calls
Browse files Browse the repository at this point in the history
and add more test cases
  • Loading branch information
J-ZhengLi committed Nov 21, 2023
1 parent 2d9fc6d commit 3e9a6d1
Show file tree
Hide file tree
Showing 4 changed files with 306 additions and 68 deletions.
113 changes: 80 additions & 33 deletions clippy_lints/src/loops/infinite_loops.rs
Original file line number Diff line number Diff line change
@@ -1,52 +1,64 @@
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::is_lint_allowed;
use clippy_utils::{fn_def_id, is_lint_allowed};
use hir::intravisit::{walk_expr, Visitor};
use hir::{Block, Destination, Expr, ExprKind, FnRetTy, Ty, TyKind};
use hir::{Expr, ExprKind, FnRetTy, FnSig, Node};
use rustc_ast::Label;
use rustc_errors::Applicability;
use rustc_hir as hir;
use rustc_lint::LateContext;

use super::INFINITE_LOOPS;

pub(super) fn check(
cx: &LateContext<'_>,
pub(super) fn check<'tcx>(
cx: &LateContext<'tcx>,
expr: &Expr<'_>,
loop_block: &Block<'_>,
loop_block: &'tcx hir::Block<'_>,
label: Option<Label>,
parent_fn_ret_ty: FnRetTy<'_>,
) {
if is_lint_allowed(cx, INFINITE_LOOPS, expr.hir_id)
|| matches!(
parent_fn_ret_ty,
FnRetTy::Return(Ty {
kind: TyKind::Never,
..
})
)
{
if is_lint_allowed(cx, INFINITE_LOOPS, expr.hir_id) {
return;
}

// Skip check if this loop is not in a function/method/closure. (In some weird case)
let Some(parent_fn_ret) = get_parent_fn_ret_ty(cx, expr) else {
return;
};
// Or, its parent function is already returning `Never`
if matches!(
parent_fn_ret,
FnRetTy::Return(hir::Ty {
kind: hir::TyKind::Never,
..
})
) {
return;
}

// First, find any `break` or `return` without entering any inner loop,
// then, find `return` or labeled `break` which breaks this loop with entering inner loop,
// otherwise this loop is a infinite loop.
let mut direct_br_or_ret_finder = BreakOrRetFinder::default();
direct_br_or_ret_finder.visit_block(loop_block);
let mut direct_visitor = LoopVisitor {
cx,
label,
is_finite: false,
enter_nested_loop: false,
};
direct_visitor.visit_block(loop_block);

let is_finite_loop = direct_br_or_ret_finder.found || {
let mut inner_br_or_ret_finder = BreakOrRetFinder {
let is_finite_loop = direct_visitor.is_finite || {
let mut inner_loop_visitor = LoopVisitor {
cx,
label,
is_finite: false,
enter_nested_loop: true,
..Default::default()
};
inner_br_or_ret_finder.visit_block(loop_block);
inner_br_or_ret_finder.found
inner_loop_visitor.visit_block(loop_block);
inner_loop_visitor.is_finite
};

if !is_finite_loop {
span_lint_and_then(cx, INFINITE_LOOPS, expr.span, "infinite loop detected", |diag| {
if let FnRetTy::DefaultReturn(ret_span) = parent_fn_ret_ty {
if let FnRetTy::DefaultReturn(ret_span) = parent_fn_ret {
diag.span_suggestion(
ret_span,
"if this is intentional, consider specifing `!` as function return",
Expand All @@ -56,37 +68,72 @@ pub(super) fn check(
} else {
diag.span_help(
expr.span,
"if this is not intended, add a `break` or `return` condition in this loop",
"if this is not intended, try adding a `break` or `return` condition in this loop",
);
}
});
}
}

#[derive(Default)]
struct BreakOrRetFinder {
fn get_parent_fn_ret_ty<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>) -> Option<FnRetTy<'tcx>> {
for (_, parent_node) in cx.tcx.hir().parent_iter(expr.hir_id) {
match parent_node {
Node::Item(hir::Item {
kind: hir::ItemKind::Fn(FnSig { decl, .. }, _, _),
..
})
| Node::TraitItem(hir::TraitItem {
kind: hir::TraitItemKind::Fn(FnSig { decl, .. }, _),
..
})
| Node::ImplItem(hir::ImplItem {
kind: hir::ImplItemKind::Fn(FnSig { decl, .. }, _),
..
})
| Node::Expr(Expr {
kind: ExprKind::Closure(hir::Closure { fn_decl: decl, .. }),
..
}) => return Some(decl.output),
_ => (),
}
}
None
}

struct LoopVisitor<'hir, 'tcx> {
cx: &'hir LateContext<'tcx>,
label: Option<Label>,
found: bool,
is_finite: bool,
enter_nested_loop: bool,
}

impl<'hir> Visitor<'hir> for BreakOrRetFinder {
impl<'hir> Visitor<'hir> for LoopVisitor<'hir, '_> {
fn visit_expr(&mut self, ex: &'hir Expr<'_>) {
match &ex.kind {
ExprKind::Break(Destination { label, .. }, ..) => {
ExprKind::Break(hir::Destination { label, .. }, ..) => {
// When entering nested loop, only by breaking this loop's label
// would be considered as exiting this loop.
if self.enter_nested_loop {
if label.is_some() && *label == self.label {
self.found = true;
self.is_finite = true;
}
} else {
self.found = true;
self.is_finite = true;
}
},
ExprKind::Ret(..) => self.found = true,
ExprKind::Ret(..) => self.is_finite = true,
ExprKind::Loop(..) if !self.enter_nested_loop => (),
_ => walk_expr(self, ex),
_ => {
// Calls to a function that never return
if let Some(did) = fn_def_id(self.cx, ex) {
let fn_ret_ty = self.cx.tcx.fn_sig(did).skip_binder().output().skip_binder();
if fn_ret_ty.is_never() {
self.is_finite = true;
return;
}
}
walk_expr(self, ex);
},
}
}
}
34 changes: 8 additions & 26 deletions clippy_lints/src/loops/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ mod while_let_on_iterator;

use clippy_config::msrvs::Msrv;
use clippy_utils::higher;
use rustc_hir::{self as hir, Expr, ExprKind, LoopSource, Pat};
use rustc_hir::{Expr, ExprKind, LoopSource, Pat};
use rustc_lint::{LateContext, LateLintPass};
use rustc_session::{declare_tool_lint, impl_lint_pass};
use rustc_span::source_map::Span;
Expand Down Expand Up @@ -678,22 +678,20 @@ declare_clippy_lint! {
"possibly unintended infinite loops"
}

pub struct Loops<'tcx> {
pub struct Loops {
msrv: Msrv,
enforce_iter_loop_reborrow: bool,
parent_fn_ret_ty: Option<hir::FnRetTy<'tcx>>,
}
impl<'tcx> Loops<'tcx> {
impl Loops {
pub fn new(msrv: Msrv, enforce_iter_loop_reborrow: bool) -> Self {
Self {
msrv,
enforce_iter_loop_reborrow,
parent_fn_ret_ty: None,
}
}
}

impl_lint_pass!(Loops<'_> => [
impl_lint_pass!(Loops => [
MANUAL_MEMCPY,
MANUAL_FLATTEN,
NEEDLESS_RANGE_LOOP,
Expand All @@ -717,7 +715,7 @@ impl_lint_pass!(Loops<'_> => [
INFINITE_LOOPS,
]);

impl<'tcx> LateLintPass<'tcx> for Loops<'tcx> {
impl<'tcx> LateLintPass<'tcx> for Loops {
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
let for_loop = higher::ForLoop::hir(expr);
if let Some(higher::ForLoop {
Expand Down Expand Up @@ -757,9 +755,7 @@ impl<'tcx> LateLintPass<'tcx> for Loops<'tcx> {
// also check for empty `loop {}` statements, skipping those in #[panic_handler]
empty_loop::check(cx, expr, block);
while_let_loop::check(cx, expr, block);
if let Some(parent_fn_ret_ty) = self.parent_fn_ret_ty {
infinite_loops::check(cx, expr, block, label, parent_fn_ret_ty);
}
infinite_loops::check(cx, expr, block, label);
}

while_let_on_iterator::check(cx, expr);
Expand All @@ -771,25 +767,11 @@ impl<'tcx> LateLintPass<'tcx> for Loops<'tcx> {
}
}

fn check_fn(
&mut self,
_: &LateContext<'tcx>,
kind: hir::intravisit::FnKind<'tcx>,
decl: &'tcx hir::FnDecl<'tcx>,
_: &'tcx hir::Body<'tcx>,
_: Span,
_: rustc_span::def_id::LocalDefId,
) {
if let hir::intravisit::FnKind::ItemFn(..) = kind {
self.parent_fn_ret_ty = Some(decl.output);
}
}

extract_msrv_attr!(LateContext);
}

impl<'tcx> Loops<'tcx> {
fn check_for_loop(
impl Loops {
fn check_for_loop<'tcx>(
&self,
cx: &LateContext<'tcx>,
pat: &'tcx Pat<'_>,
Expand Down
101 changes: 101 additions & 0 deletions tests/ui/infinite_loops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,31 @@ fn no_break() {
}
}

fn all_inf() {
loop {
//~^ ERROR: infinite loop detected
loop {
//~^ ERROR: infinite loop detected
loop {
//~^ ERROR: infinite loop detected
do_something();
}
}
do_something();
}
}

fn no_break_return_some_ty() -> Option<u8> {
loop {
do_something();
return None;
}
loop {
//~^ ERROR: infinite loop detected
do_something();
}
}

fn no_break_never_ret() -> ! {
loop {
do_something();
Expand Down Expand Up @@ -256,4 +281,80 @@ fn ret_in_macro(opt: Option<u8>) {
}
}

fn panic_like_macros_1() {
loop {
do_something();
panic!();
}
}

fn panic_like_macros_2() {
let mut x = 0;

loop {
do_something();
if true {
todo!();
}
}
loop {
do_something();
x += 1;
assert_eq!(x, 0);
}
loop {
do_something();
assert!(x % 2 == 0);
}
loop {
do_something();
match Some(1) {
Some(n) => println!("{n}"),
None => unreachable!("It won't happen"),
}
}
}

fn exit_directly(cond: bool) {
loop {
if cond {
std::process::exit(0);
}
}
}

trait MyTrait {
fn problematic_trait_method() {
loop {
//~^ ERROR: infinite loop detected
do_something();
}
}
fn could_be_problematic();
}

impl MyTrait for String {
fn could_be_problematic() {
loop {
//~^ ERROR: infinite loop detected
do_something();
}
}
}

fn inf_loop_in_closure() {
let _loop_forever = || {
loop {
//~^ ERROR: infinite loop detected
do_something();
}
};

let _somehow_ok = || -> ! {
loop {
do_something();
}
};
}

fn main() {}
Loading

0 comments on commit 3e9a6d1

Please sign in to comment.