1 use clippy_utils::diagnostics::span_lint_and_then;
2 use clippy_utils::ty::is_type_diagnostic_item;
3 use clippy_utils::{find_macro_calls, is_expn_of, return_ty};
5 use rustc_hir::intravisit::FnKind;
6 use rustc_lint::{LateContext, LateLintPass};
7 use rustc_session::{declare_lint_pass, declare_tool_lint};
8 use rustc_span::{sym, Span};
10 declare_clippy_lint! {
12 /// Checks for usage of `panic!`, `unimplemented!`, `todo!`, `unreachable!` or assertions in a function of type result.
14 /// ### Why is this bad?
15 /// For some codebases, it is desirable for functions of type result to return an error instead of crashing. Hence panicking macros should be avoided.
17 /// ### Known problems
18 /// Functions called from a function returning a `Result` may invoke a panicking macro. This is not checked.
22 /// fn result_with_panic() -> Result<bool, String>
29 /// fn result_without_panic() -> Result<bool, String> {
30 /// Err(String::from("error"))
33 pub PANIC_IN_RESULT_FN,
35 "functions of type `Result<..>` that contain `panic!()`, `todo!()`, `unreachable()`, `unimplemented()` or assertion"
38 declare_lint_pass!(PanicInResultFn => [PANIC_IN_RESULT_FN]);
40 impl<'tcx> LateLintPass<'tcx> for PanicInResultFn {
43 cx: &LateContext<'tcx>,
44 fn_kind: FnKind<'tcx>,
45 _: &'tcx hir::FnDecl<'tcx>,
46 body: &'tcx hir::Body<'tcx>,
50 if !matches!(fn_kind, FnKind::Closure) && is_type_diagnostic_item(cx, return_ty(cx, hir_id), sym::result_type) {
51 lint_impl_body(cx, span, body);
56 fn lint_impl_body<'tcx>(cx: &LateContext<'tcx>, impl_span: Span, body: &'tcx hir::Body<'tcx>) {
57 let mut panics = find_macro_calls(
69 panics.retain(|span| is_expn_of(*span, "debug_assert").is_none());
70 if !panics.is_empty() {
75 "used `unimplemented!()`, `unreachable!()`, `todo!()`, `panic!()` or assertion in a function that returns `Result`",
78 "`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",
80 diag.span_note(panics, "return Err() instead of panicking");