Skip to content

Commit dead45f

Browse files
committed
Auto merge of #5957 - xvschneider:AddUnwrapInsideResultLint, r=yaahc
Adding new lint to prevent usage of 'unwrap' inside functions that re… ### Change Adding a new lint that will emit a warning when using "unwrap" or "expect" inside a function that returns result. ### Motivation These functions promote recoverable errors to non-recoverable errors which may be undesirable in code bases which wish to avoid panics. ### Test plan Running: `TESTNAME=unwrap_in_result cargo uitest `--- changelog: none
2 parents e45c59e + 91024f1 commit dead45f

File tree

6 files changed

+237
-0
lines changed

6 files changed

+237
-0
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -1778,6 +1778,7 @@ Released 2018-09-13
17781778
[`unused_label`]: https://rust-lang.github.io/rust-clippy/master/index.html#unused_label
17791779
[`unused_self`]: https://rust-lang.github.io/rust-clippy/master/index.html#unused_self
17801780
[`unused_unit`]: https://rust-lang.github.io/rust-clippy/master/index.html#unused_unit
1781+
[`unwrap_in_result`]: https://rust-lang.github.io/rust-clippy/master/index.html#unwrap_in_result
17811782
[`unwrap_used`]: https://rust-lang.github.io/rust-clippy/master/index.html#unwrap_used
17821783
[`use_debug`]: https://rust-lang.github.io/rust-clippy/master/index.html#use_debug
17831784
[`use_self`]: https://rust-lang.github.io/rust-clippy/master/index.html#use_self

clippy_lints/src/lib.rs

+4
Original file line numberDiff line numberDiff line change
@@ -314,6 +314,7 @@ mod unused_io_amount;
314314
mod unused_self;
315315
mod unused_unit;
316316
mod unwrap;
317+
mod unwrap_in_result;
317318
mod use_self;
318319
mod useless_conversion;
319320
mod vec;
@@ -850,6 +851,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
850851
&unused_unit::UNUSED_UNIT,
851852
&unwrap::PANICKING_UNWRAP,
852853
&unwrap::UNNECESSARY_UNWRAP,
854+
&unwrap_in_result::UNWRAP_IN_RESULT,
853855
&use_self::USE_SELF,
854856
&useless_conversion::USELESS_CONVERSION,
855857
&utils::internal_lints::CLIPPY_LINTS_INTERNAL,
@@ -1094,6 +1096,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
10941096
store.register_late_pass(|| box pattern_type_mismatch::PatternTypeMismatch);
10951097
store.register_late_pass(|| box stable_sort_primitive::StableSortPrimitive);
10961098
store.register_late_pass(|| box repeat_once::RepeatOnce);
1099+
store.register_late_pass(|| box unwrap_in_result::UnwrapInResult);
10971100
store.register_late_pass(|| box self_assignment::SelfAssignment);
10981101
store.register_late_pass(|| box float_equality_without_abs::FloatEqualityWithoutAbs);
10991102

@@ -1133,6 +1136,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
11331136
LintId::of(&shadow::SHADOW_REUSE),
11341137
LintId::of(&shadow::SHADOW_SAME),
11351138
LintId::of(&strings::STRING_ADD),
1139+
LintId::of(&unwrap_in_result::UNWRAP_IN_RESULT),
11361140
LintId::of(&verbose_file_reads::VERBOSE_FILE_READS),
11371141
LintId::of(&write::PRINT_STDOUT),
11381142
LintId::of(&write::USE_DEBUG),

clippy_lints/src/unwrap_in_result.rs

+140
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
use crate::utils::{is_type_diagnostic_item, method_chain_args, return_ty, span_lint_and_then, walk_ptrs_ty};
2+
use if_chain::if_chain;
3+
use rustc_hir as hir;
4+
use rustc_lint::{LateContext, LateLintPass};
5+
use rustc_middle::hir::map::Map;
6+
use rustc_middle::ty;
7+
use rustc_session::{declare_lint_pass, declare_tool_lint};
8+
use rustc_span::Span;
9+
10+
declare_clippy_lint! {
11+
/// **What it does:** Checks for functions of type Result that contain `expect()` or `unwrap()`
12+
///
13+
/// **Why is this bad?** These functions promote recoverable errors to non-recoverable errors which may be undesirable in code bases which wish to avoid panics.
14+
///
15+
/// **Known problems:** This can cause false positives in functions that handle both recoverable and non recoverable errors.
16+
///
17+
/// **Example:**
18+
/// Before:
19+
/// ```rust
20+
/// fn divisible_by_3(i_str: String) -> Result<(), String> {
21+
/// let i = i_str
22+
/// .parse::<i32>()
23+
/// .expect("cannot divide the input by three");
24+
///
25+
/// if i % 3 != 0 {
26+
/// Err("Number is not divisible by 3")?
27+
/// }
28+
///
29+
/// Ok(())
30+
/// }
31+
/// ```
32+
///
33+
/// After:
34+
/// ```rust
35+
/// fn divisible_by_3(i_str: String) -> Result<(), String> {
36+
/// let i = i_str
37+
/// .parse::<i32>()
38+
/// .map_err(|e| format!("cannot divide the input by three: {}", e))?;
39+
///
40+
/// if i % 3 != 0 {
41+
/// Err("Number is not divisible by 3")?
42+
/// }
43+
///
44+
/// Ok(())
45+
/// }
46+
/// ```
47+
pub UNWRAP_IN_RESULT,
48+
restriction,
49+
"functions of type `Result<..>` or `Option`<...> that contain `expect()` or `unwrap()`"
50+
}
51+
52+
declare_lint_pass!(UnwrapInResult=> [UNWRAP_IN_RESULT]);
53+
54+
impl<'tcx> LateLintPass<'tcx> for UnwrapInResult {
55+
fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx hir::ImplItem<'_>) {
56+
if_chain! {
57+
// first check if it's a method or function
58+
if let hir::ImplItemKind::Fn(ref _signature, _) = impl_item.kind;
59+
// checking if its return type is `result` or `option`
60+
if is_type_diagnostic_item(cx, return_ty(cx, impl_item.hir_id), sym!(result_type))
61+
|| is_type_diagnostic_item(cx, return_ty(cx, impl_item.hir_id), sym!(option_type));
62+
then {
63+
lint_impl_body(cx, impl_item.span, impl_item);
64+
}
65+
}
66+
}
67+
}
68+
69+
use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
70+
use rustc_hir::{Expr, ImplItemKind};
71+
72+
struct FindExpectUnwrap<'a, 'tcx> {
73+
lcx: &'a LateContext<'tcx>,
74+
typeck_results: &'tcx ty::TypeckResults<'tcx>,
75+
result: Vec<Span>,
76+
}
77+
78+
impl<'a, 'tcx> Visitor<'tcx> for FindExpectUnwrap<'a, 'tcx> {
79+
type Map = Map<'tcx>;
80+
81+
fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
82+
// check for `expect`
83+
if let Some(arglists) = method_chain_args(expr, &["expect"]) {
84+
let reciever_ty = walk_ptrs_ty(self.typeck_results.expr_ty(&arglists[0][0]));
85+
if is_type_diagnostic_item(self.lcx, reciever_ty, sym!(option_type))
86+
|| is_type_diagnostic_item(self.lcx, reciever_ty, sym!(result_type))
87+
{
88+
self.result.push(expr.span);
89+
}
90+
}
91+
92+
// check for `unwrap`
93+
if let Some(arglists) = method_chain_args(expr, &["unwrap"]) {
94+
let reciever_ty = walk_ptrs_ty(self.typeck_results.expr_ty(&arglists[0][0]));
95+
if is_type_diagnostic_item(self.lcx, reciever_ty, sym!(option_type))
96+
|| is_type_diagnostic_item(self.lcx, reciever_ty, sym!(result_type))
97+
{
98+
self.result.push(expr.span);
99+
}
100+
}
101+
102+
// and check sub-expressions
103+
intravisit::walk_expr(self, expr);
104+
}
105+
106+
fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
107+
NestedVisitorMap::None
108+
}
109+
}
110+
111+
fn lint_impl_body<'tcx>(cx: &LateContext<'tcx>, impl_span: Span, impl_item: &'tcx hir::ImplItem<'_>) {
112+
if_chain! {
113+
114+
if let ImplItemKind::Fn(_, body_id) = impl_item.kind;
115+
then {
116+
let body = cx.tcx.hir().body(body_id);
117+
let impl_item_def_id = cx.tcx.hir().local_def_id(impl_item.hir_id);
118+
let mut fpu = FindExpectUnwrap {
119+
lcx: cx,
120+
typeck_results: cx.tcx.typeck(impl_item_def_id),
121+
result: Vec::new(),
122+
};
123+
fpu.visit_expr(&body.value);
124+
125+
// if we've found one, lint
126+
if !fpu.result.is_empty() {
127+
span_lint_and_then(
128+
cx,
129+
UNWRAP_IN_RESULT,
130+
impl_span,
131+
"used unwrap or expect in a function that returns result or option",
132+
move |diag| {
133+
diag.help(
134+
"unwrap and expect should not be used in a function that returns result or option" );
135+
diag.span_note(fpu.result, "potential non-recoverable error(s)");
136+
});
137+
}
138+
}
139+
}
140+
}

src/lintlist/mod.rs

+7
Original file line numberDiff line numberDiff line change
@@ -2516,6 +2516,13 @@ pub static ref ALL_LINTS: Vec<Lint> = vec![
25162516
deprecation: None,
25172517
module: "unused_unit",
25182518
},
2519+
Lint {
2520+
name: "unwrap_in_result",
2521+
group: "restriction",
2522+
desc: "functions of type `Result<..>` or `Option`<...> that contain `expect()` or `unwrap()`",
2523+
deprecation: None,
2524+
module: "unwrap_in_result",
2525+
},
25192526
Lint {
25202527
name: "unwrap_used",
25212528
group: "restriction",

tests/ui/unwrap_in_result.rs

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
#![warn(clippy::unwrap_in_result)]
2+
3+
struct A;
4+
5+
impl A {
6+
// should not be detected
7+
fn good_divisible_by_3(i_str: String) -> Result<bool, String> {
8+
// checks whether a string represents a number divisible by 3
9+
let i_result = i_str.parse::<i32>();
10+
match i_result {
11+
Err(_e) => Err("Not a number".to_string()),
12+
Ok(i) => {
13+
if i % 3 == 0 {
14+
return Ok(true);
15+
}
16+
Err("Number is not divisible by 3".to_string())
17+
},
18+
}
19+
}
20+
21+
// should be detected
22+
fn bad_divisible_by_3(i_str: String) -> Result<bool, String> {
23+
// checks whether a string represents a number divisible by 3
24+
let i = i_str.parse::<i32>().unwrap();
25+
if i % 3 == 0 {
26+
Ok(true)
27+
} else {
28+
Err("Number is not divisible by 3".to_string())
29+
}
30+
}
31+
32+
fn example_option_expect(i_str: String) -> Option<bool> {
33+
let i = i_str.parse::<i32>().expect("not a number");
34+
if i % 3 == 0 {
35+
return Some(true);
36+
}
37+
None
38+
}
39+
}
40+
41+
fn main() {
42+
A::bad_divisible_by_3("3".to_string());
43+
A::good_divisible_by_3("3".to_string());
44+
}

tests/ui/unwrap_in_result.stderr

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
error: used unwrap or expect in a function that returns result or option
2+
--> $DIR/unwrap_in_result.rs:22:5
3+
|
4+
LL | / fn bad_divisible_by_3(i_str: String) -> Result<bool, String> {
5+
LL | | // checks whether a string represents a number divisible by 3
6+
LL | | let i = i_str.parse::<i32>().unwrap();
7+
LL | | if i % 3 == 0 {
8+
... |
9+
LL | | }
10+
LL | | }
11+
| |_____^
12+
|
13+
= note: `-D clippy::unwrap-in-result` implied by `-D warnings`
14+
= help: unwrap and expect should not be used in a function that returns result or option
15+
note: potential non-recoverable error(s)
16+
--> $DIR/unwrap_in_result.rs:24:17
17+
|
18+
LL | let i = i_str.parse::<i32>().unwrap();
19+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
20+
21+
error: used unwrap or expect in a function that returns result or option
22+
--> $DIR/unwrap_in_result.rs:32:5
23+
|
24+
LL | / fn example_option_expect(i_str: String) -> Option<bool> {
25+
LL | | let i = i_str.parse::<i32>().expect("not a number");
26+
LL | | if i % 3 == 0 {
27+
LL | | return Some(true);
28+
LL | | }
29+
LL | | None
30+
LL | | }
31+
| |_____^
32+
|
33+
= help: unwrap and expect should not be used in a function that returns result or option
34+
note: potential non-recoverable error(s)
35+
--> $DIR/unwrap_in_result.rs:33:17
36+
|
37+
LL | let i = i_str.parse::<i32>().expect("not a number");
38+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
39+
40+
error: aborting due to 2 previous errors
41+

0 commit comments

Comments
 (0)