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::expr_visitor_no_bodies;
7 use rustc_hir::intravisit::{FnKind, Visitor};
8 use rustc_lint::{LateContext, LateLintPass};
9 use rustc_session::{declare_lint_pass, declare_tool_lint};
10 use rustc_span::{sym, Span};
12 declare_clippy_lint! {
14 /// Checks for usage of `panic!`, `unimplemented!`, `todo!`, `unreachable!` or assertions in a function of type result.
16 /// ### Why is this bad?
17 /// For some codebases, it is desirable for functions of type result to return an error instead of crashing. Hence panicking macros should be avoided.
19 /// ### Known problems
20 /// Functions called from a function returning a `Result` may invoke a panicking macro. This is not checked.
24 /// fn result_with_panic() -> Result<bool, String>
31 /// fn result_without_panic() -> Result<bool, String> {
32 /// Err(String::from("error"))
35 #[clippy::version = "1.48.0"]
36 pub PANIC_IN_RESULT_FN,
38 "functions of type `Result<..>` that contain `panic!()`, `todo!()`, `unreachable()`, `unimplemented()` or assertion"
41 declare_lint_pass!(PanicInResultFn => [PANIC_IN_RESULT_FN]);
43 impl<'tcx> LateLintPass<'tcx> for PanicInResultFn {
46 cx: &LateContext<'tcx>,
47 fn_kind: FnKind<'tcx>,
48 _: &'tcx hir::FnDecl<'tcx>,
49 body: &'tcx hir::Body<'tcx>,
53 if !matches!(fn_kind, FnKind::Closure) && is_type_diagnostic_item(cx, return_ty(cx, hir_id), sym::Result) {
54 lint_impl_body(cx, span, body);
59 fn lint_impl_body<'tcx>(cx: &LateContext<'tcx>, impl_span: Span, body: &'tcx hir::Body<'tcx>) {
60 let mut panics = Vec::new();
61 expr_visitor_no_bodies(|expr| {
62 let Some(macro_call) = root_macro_call_first_node(cx, expr) else { return true };
64 &*cx.tcx.item_name(macro_call.def_id).as_str(),
65 "unimplemented" | "unreachable" | "panic" | "todo" | "assert" | "assert_eq" | "assert_ne"
67 panics.push(macro_call.span);
72 .visit_expr(&body.value);
73 if !panics.is_empty() {
78 "used `unimplemented!()`, `unreachable!()`, `todo!()`, `panic!()` or assertion in a function that returns `Result`",
81 "`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",
83 diag.span_note(panics, "return Err() instead of panicking");