1 use clippy_utils::diagnostics::span_lint_and_then;
2 use clippy_utils::macros::root_macro_call_first_node;
3 use clippy_utils::return_ty;
4 use clippy_utils::ty::is_type_diagnostic_item;
5 use clippy_utils::visitors::{for_each_expr, Descend};
6 use core::ops::ControlFlow;
8 use rustc_hir::intravisit::FnKind;
9 use rustc_lint::{LateContext, LateLintPass};
10 use rustc_session::{declare_lint_pass, declare_tool_lint};
11 use rustc_span::{sym, Span};
13 declare_clippy_lint! {
15 /// Checks for usage of `panic!`, `unimplemented!`, `todo!`, `unreachable!` or assertions in a function of type result.
17 /// ### Why is this bad?
18 /// For some codebases, it is desirable for functions of type result to return an error instead of crashing. Hence panicking macros should be avoided.
20 /// ### Known problems
21 /// Functions called from a function returning a `Result` may invoke a panicking macro. This is not checked.
25 /// fn result_with_panic() -> Result<bool, String>
32 /// fn result_without_panic() -> Result<bool, String> {
33 /// Err(String::from("error"))
36 #[clippy::version = "1.48.0"]
37 pub PANIC_IN_RESULT_FN,
39 "functions of type `Result<..>` that contain `panic!()`, `todo!()`, `unreachable()`, `unimplemented()` or assertion"
42 declare_lint_pass!(PanicInResultFn => [PANIC_IN_RESULT_FN]);
44 impl<'tcx> LateLintPass<'tcx> for PanicInResultFn {
47 cx: &LateContext<'tcx>,
48 fn_kind: FnKind<'tcx>,
49 _: &'tcx hir::FnDecl<'tcx>,
50 body: &'tcx hir::Body<'tcx>,
54 if !matches!(fn_kind, FnKind::Closure) && is_type_diagnostic_item(cx, return_ty(cx, hir_id), sym::Result) {
55 lint_impl_body(cx, span, body);
60 fn lint_impl_body<'tcx>(cx: &LateContext<'tcx>, impl_span: Span, body: &'tcx hir::Body<'tcx>) {
61 let mut panics = Vec::new();
62 let _: Option<!> = for_each_expr(body.value, |e| {
63 let Some(macro_call) = root_macro_call_first_node(cx, e) else {
64 return ControlFlow::Continue(Descend::Yes);
67 cx.tcx.item_name(macro_call.def_id).as_str(),
68 "unimplemented" | "unreachable" | "panic" | "todo" | "assert" | "assert_eq" | "assert_ne"
70 panics.push(macro_call.span);
71 ControlFlow::Continue(Descend::No)
73 ControlFlow::Continue(Descend::Yes)
76 if !panics.is_empty() {
81 "used `unimplemented!()`, `unreachable!()`, `todo!()`, `panic!()` or assertion in a function that returns `Result`",
84 "`unimplemented!()`, `unreachable!()`, `todo!()`, `panic!()` or assertions should not be used in a function that returns `Result` as `Result` is expected to return an error instead of crashing",
86 diag.span_note(panics, "return Err() instead of panicking");