]> git.proxmox.com Git - rustc.git/blame - src/tools/clippy/clippy_lints/src/panic_in_result_fn.rs
New upstream version 1.53.0+dfsg1
[rustc.git] / src / tools / clippy / clippy_lints / src / panic_in_result_fn.rs
CommitLineData
cdc7bbd5
XL
1use clippy_utils::diagnostics::span_lint_and_then;
2use clippy_utils::ty::is_type_diagnostic_item;
3use clippy_utils::{find_macro_calls, is_expn_of, return_ty};
f20569fa
XL
4use rustc_hir as hir;
5use rustc_hir::intravisit::FnKind;
6use rustc_lint::{LateContext, LateLintPass};
7use rustc_session::{declare_lint_pass, declare_tool_lint};
8use rustc_span::{sym, Span};
9
10declare_clippy_lint! {
11 /// **What it does:** Checks for usage of `panic!`, `unimplemented!`, `todo!`, `unreachable!` or assertions in a function of type result.
12 ///
13 /// **Why is this bad?** For some codebases, it is desirable for functions of type result to return an error instead of crashing. Hence panicking macros should be avoided.
14 ///
15 /// **Known problems:** Functions called from a function returning a `Result` may invoke a panicking macro. This is not checked.
16 ///
17 /// **Example:**
18 ///
19 /// ```rust
20 /// fn result_with_panic() -> Result<bool, String>
21 /// {
22 /// panic!("error");
23 /// }
24 /// ```
25 /// Use instead:
26 /// ```rust
27 /// fn result_without_panic() -> Result<bool, String> {
28 /// Err(String::from("error"))
29 /// }
30 /// ```
31 pub PANIC_IN_RESULT_FN,
32 restriction,
33 "functions of type `Result<..>` that contain `panic!()`, `todo!()`, `unreachable()`, `unimplemented()` or assertion"
34}
35
36declare_lint_pass!(PanicInResultFn => [PANIC_IN_RESULT_FN]);
37
38impl<'tcx> LateLintPass<'tcx> for PanicInResultFn {
39 fn check_fn(
40 &mut self,
41 cx: &LateContext<'tcx>,
42 fn_kind: FnKind<'tcx>,
43 _: &'tcx hir::FnDecl<'tcx>,
44 body: &'tcx hir::Body<'tcx>,
45 span: Span,
46 hir_id: hir::HirId,
47 ) {
48 if !matches!(fn_kind, FnKind::Closure) && is_type_diagnostic_item(cx, return_ty(cx, hir_id), sym::result_type) {
49 lint_impl_body(cx, span, body);
50 }
51 }
52}
53
54fn lint_impl_body<'tcx>(cx: &LateContext<'tcx>, impl_span: Span, body: &'tcx hir::Body<'tcx>) {
cdc7bbd5 55 let mut panics = find_macro_calls(
f20569fa
XL
56 &[
57 "unimplemented",
58 "unreachable",
59 "panic",
60 "todo",
61 "assert",
62 "assert_eq",
63 "assert_ne",
f20569fa
XL
64 ],
65 body,
66 );
cdc7bbd5 67 panics.retain(|span| is_expn_of(*span, "debug_assert").is_none());
f20569fa
XL
68 if !panics.is_empty() {
69 span_lint_and_then(
70 cx,
71 PANIC_IN_RESULT_FN,
72 impl_span,
73 "used `unimplemented!()`, `unreachable!()`, `todo!()`, `panic!()` or assertion in a function that returns `Result`",
74 move |diag| {
75 diag.help(
76 "`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",
77 );
78 diag.span_note(panics, "return Err() instead of panicking");
79 },
80 );
81 }
82}