Skip to content

Commit 6205bcf

Browse files
committed
Add match-based manual try to clippy::question_mark
1 parent 12ca363 commit 6205bcf

4 files changed

Lines changed: 327 additions & 13 deletions

File tree

‎clippy_lints/src/question_mark.rs‎

Lines changed: 165 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,18 +8,18 @@ use clippy_utils::source::snippet_with_applicability;
88
use clippy_utils::ty::{implements_trait, is_type_diagnostic_item};
99
use clippy_utils::{
1010
eq_expr_value, higher, is_else_clause, is_in_const_context, is_lint_allowed, is_path_lang_item, is_res_lang_ctor,
11-
pat_and_expr_can_be_question_mark, path_to_local, path_to_local_id, peel_blocks, peel_blocks_with_stmt,
12-
span_contains_comment,
11+
pat_and_expr_can_be_question_mark,path_res,path_to_local, path_to_local_id, peel_blocks, peel_blocks_with_stmt,
12+
span_contains_cfg,span_contains_comment,
1313
};
1414
use rustc_errors::Applicability;
1515
use rustc_hir::LangItem::{self,OptionNone,OptionSome,ResultErr,ResultOk};
1616
use rustc_hir::def::Res;
1717
use rustc_hir::{
18-
BindingMode,Block,Body,ByRef,Expr,ExprKind,LetStmt,Mutability,Node,PatKind,PathSegment,QPath,Stmt,
19-
StmtKind,
18+
Arm,BindingMode,Block,Body,ByRef,Expr,ExprKind,FnRetTy,HirId,LetStmt,MatchSource,Mutability,Node,Pat,
19+
PatKind,PathSegment,QPath,Stmt,StmtKind,TyKind,
2020
};
2121
use rustc_lint::{LateContext,LateLintPass};
22-
use rustc_middle::ty::Ty;
22+
use rustc_middle::ty::{self,Ty};
2323
use rustc_session::impl_lint_pass;
2424
use rustc_span::sym;
2525
use rustc_span::symbol::Symbol;
@@ -58,6 +58,9 @@ pub struct QuestionMark {
5858
/// if it is greater than zero.
5959
/// As for why we need this in the first place: <https://github.com/rust-lang/rust-clippy/issues/8628>
6060
try_block_depth_stack:Vec<u32>,
61+
/// Keeps track of the number of inferred return type closures we are inside, to avoid problems
62+
/// with the `Err(x.into())` expansion being ambiguious.
63+
inferred_ret_closure_stack:u16,
6164
}
6265

6366
impl_lint_pass!(QuestionMark => [QUESTION_MARK,MANUAL_LET_ELSE]);
@@ -68,6 +71,7 @@ impl QuestionMark {
6871
msrv: conf.msrv.clone(),
6972
matches_behaviour: conf.matches_for_let_else,
7073
try_block_depth_stack:Vec::new(),
74+
inferred_ret_closure_stack:0,
7175
}
7276
}
7377
}
@@ -271,6 +275,135 @@ fn check_is_none_or_err_and_early_return<'tcx>(cx: &LateContext<'tcx>, expr: &Ex
271275
}
272276
}
273277

278+
#[derive(Clone,Copy,Debug)]
279+
enumTryMode{
280+
Result,
281+
Option,
282+
}
283+
284+
fnfind_try_mode<'tcx>(cx:&LateContext<'tcx>,scrutinee:&Expr<'tcx>) -> Option<TryMode>{
285+
let scrutinee_ty = cx.typeck_results().expr_ty_adjusted(scrutinee);
286+
let ty::Adt(scrutinee_adt_def, _) = scrutinee_ty.kind()else{
287+
returnNone;
288+
};
289+
290+
match cx.tcx.get_diagnostic_name(scrutinee_adt_def.did())? {
291+
sym::Result => Some(TryMode::Result),
292+
sym::Option => Some(TryMode::Option),
293+
_ => None,
294+
}
295+
}
296+
297+
// Check that `pat` is `{ctor_lang_item}(val)`, returning `val`.
298+
fnextract_ctor_call<'a,'tcx>(
299+
cx:&LateContext<'tcx>,
300+
expected_ctor:LangItem,
301+
pat:&'aPat<'tcx>,
302+
) -> Option<&'aPat<'tcx>>{
303+
ifletPatKind::TupleStruct(variant_path,[val_binding], _) = &pat.kind
304+
&& is_res_lang_ctor(cx, cx.qpath_res(variant_path, pat.hir_id), expected_ctor)
305+
{
306+
Some(val_binding)
307+
}else{
308+
None
309+
}
310+
}
311+
312+
// Extracts the local ID of a plain `val` pattern.
313+
fnextract_binding_pat(pat:&Pat<'_>) -> Option<HirId>{
314+
ifletPatKind::Binding(BindingMode::NONE, binding, _,None) = pat.kind{
315+
Some(binding)
316+
}else{
317+
None
318+
}
319+
}
320+
321+
fncheck_arm_is_some_or_ok<'tcx>(cx:&LateContext<'tcx>,mode:TryMode,arm:&Arm<'tcx>) -> bool{
322+
let happy_ctor = match mode {
323+
TryMode::Result => ResultOk,
324+
TryMode::Option => OptionSome,
325+
};
326+
327+
// Check for `Ok(val)` or `Some(val)`
328+
if arm.guard.is_none()
329+
&& letSome(val_binding) = extract_ctor_call(cx, happy_ctor, arm.pat)
330+
// Extract out `val`
331+
&& letSome(binding) = extract_binding_pat(val_binding)
332+
// Check body is just `=> val`
333+
&& path_to_local_id(peel_blocks(arm.body), binding)
334+
{
335+
true
336+
}else{
337+
false
338+
}
339+
}
340+
341+
fncheck_arm_is_none_or_err<'tcx>(cx:&LateContext<'tcx>,mode:TryMode,arm:&Arm<'tcx>) -> bool{
342+
if arm.guard.is_some(){
343+
returnfalse;
344+
}
345+
346+
let arm_body = peel_blocks(arm.body);
347+
match mode {
348+
TryMode::Result => {
349+
// Check that pat is Err(val)
350+
ifletSome(ok_pat) = extract_ctor_call(cx,ResultErr, arm.pat)
351+
&& letSome(ok_val) = extract_binding_pat(ok_pat)
352+
// check `=> return Err(...)`
353+
&& letExprKind::Ret(Some(wrapped_ret_expr)) = arm_body.kind
354+
&& letExprKind::Call(ok_ctor,[ret_expr]) = wrapped_ret_expr.kind
355+
&& is_res_lang_ctor(cx,path_res(cx, ok_ctor),ResultErr)
356+
// check `...` is `val` from binding
357+
&& path_to_local_id(ret_expr, ok_val)
358+
{
359+
true
360+
}else{
361+
false
362+
}
363+
},
364+
TryMode::Option => {
365+
// Check the pat is `None`
366+
ifis_res_lang_ctor(cx,path_res(cx, arm.pat),OptionNone)
367+
// Check `=> return None`
368+
&& letExprKind::Ret(Some(ret_expr)) = arm_body.kind
369+
&& is_res_lang_ctor(cx,path_res(cx, ret_expr),OptionNone)
370+
&& !ret_expr.span.from_expansion()
371+
{
372+
true
373+
}else{
374+
false
375+
}
376+
},
377+
}
378+
}
379+
380+
fncheck_arms_are_try<'tcx>(cx:&LateContext<'tcx>,mode:TryMode,arm1:&Arm<'tcx>,arm2:&Arm<'tcx>) -> bool{
381+
(check_arm_is_some_or_ok(cx, mode, arm1) && check_arm_is_none_or_err(cx, mode, arm2))
382+
|| (check_arm_is_some_or_ok(cx, mode, arm2) && check_arm_is_none_or_err(cx, mode, arm1))
383+
}
384+
385+
fncheck_if_try_match<'tcx>(cx:&LateContext<'tcx>,expr:&Expr<'tcx>){
386+
ifletExprKind::Match(scrutinee,[arm1, arm2],MatchSource::Normal | MatchSource::Postfix) = expr.kind
387+
&& !expr.span.from_expansion()
388+
&& letSome(mode) = find_try_mode(cx, scrutinee)
389+
&& !span_contains_cfg(cx, expr.span)
390+
&& check_arms_are_try(cx, mode, arm1, arm2)
391+
{
392+
letmut applicability = Applicability::MachineApplicable;
393+
let snippet = snippet_with_applicability(cx, scrutinee.span.source_callsite(),"..",&mut applicability);
394+
395+
span_lint_and_sugg(
396+
cx,
397+
QUESTION_MARK,
398+
expr.span,
399+
"this `match` expression can be replaced with `?`",
400+
"try instead",
401+
snippet.into_owned() + "?",
402+
applicability,
403+
);
404+
}
405+
}
406+
274407
fncheck_if_let_some_or_err_and_early_return<'tcx>(cx:&LateContext<'tcx>,expr:&Expr<'tcx>){
275408
ifletSome(higher::IfLet{
276409
let_pat,
@@ -339,6 +472,17 @@ fn is_try_block(cx: &LateContext<'_>, bl: &Block<'_>) -> bool {
339472
}
340473
}
341474

475+
fnis_inferred_ret_closure(expr:&Expr<'_>) -> bool{
476+
letExprKind::Closure(closure) = expr.kindelse{
477+
returnfalse;
478+
};
479+
480+
match closure.fn_decl.output{
481+
FnRetTy::Return(ret_ty) => matches!(ret_ty.kind,TyKind::Infer),
482+
FnRetTy::DefaultReturn(_) => true,
483+
}
484+
}
485+
342486
impl<'tcx>LateLintPass<'tcx>forQuestionMark{
343487
fncheck_stmt(&mutself,cx:&LateContext<'tcx>,stmt:&'tcxStmt<'_>){
344488
if !is_lint_allowed(cx,QUESTION_MARK_USED, stmt.hir_id){
@@ -350,11 +494,27 @@ impl<'tcx> LateLintPass<'tcx> for QuestionMark {
350494
}
351495
self.check_manual_let_else(cx, stmt);
352496
}
497+
353498
fncheck_expr(&mutself,cx:&LateContext<'tcx>,expr:&'tcxExpr<'_>){
499+
ifis_inferred_ret_closure(expr){
500+
self.inferred_ret_closure_stack += 1;
501+
return;
502+
}
503+
354504
if !self.inside_try_block() && !is_in_const_context(cx) && is_lint_allowed(cx,QUESTION_MARK_USED, expr.hir_id)
355505
{
356506
check_is_none_or_err_and_early_return(cx, expr);
357507
check_if_let_some_or_err_and_early_return(cx, expr);
508+
509+
ifself.inferred_ret_closure_stack == 0{
510+
check_if_try_match(cx, expr);
511+
}
512+
}
513+
}
514+
515+
fncheck_expr_post(&mutself, _:&LateContext<'tcx>,expr:&'tcxExpr<'tcx>){
516+
ifis_inferred_ret_closure(expr){
517+
self.inferred_ret_closure_stack -= 1;
358518
}
359519
}
360520

‎tests/ui/question_mark.fixed‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,12 +96,42 @@ impl MoveStruct {
9696
}
9797

9898
fn func() -> Option<i32> {
99+
macro_rules! opt_none {
100+
() => {
101+
None
102+
};
103+
}
104+
99105
fn f() -> Option<String> {
100106
Some(String::new())
101107
}
102108

103109
f()?;
104110

111+
let _val = f()?;
112+
113+
let s: &str = match &Some(String::new()) {
114+
Some(v) => v,
115+
None => return None,
116+
};
117+
118+
f()?;
119+
120+
opt_none!()?;
121+
122+
match f() {
123+
Some(x) => x,
124+
None => return opt_none!(),
125+
};
126+
127+
match f() {
128+
Some(val) => {
129+
println!("{val}");
130+
val
131+
},
132+
None => return None,
133+
};
134+
105135
Some(0)
106136
}
107137

@@ -114,6 +144,10 @@ fn result_func(x: Result<i32, i32>) -> Result<i32, i32> {
114144

115145
x?;
116146

147+
let _val = func_returning_result()?;
148+
149+
func_returning_result()?;
150+
117151
// No warning
118152
let y = if let Ok(x) = x {
119153
x
@@ -157,6 +191,18 @@ fn result_func(x: Result<i32, i32>) -> Result<i32, i32> {
157191
Ok(y)
158192
}
159193

194+
fn infer_check() {
195+
let closure = |x: Result<u8, ()>| {
196+
// `?` would fail here, as it expands to `Err(val.into())` which is not constrained.
197+
let _val = match x {
198+
Ok(val) => val,
199+
Err(val) => return Err(val),
200+
};
201+
202+
Ok(())
203+
};
204+
}
205+
160206
// see issue #8019
161207
pub enum NotOption {
162208
None,

‎tests/ui/question_mark.rs‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,12 @@ impl MoveStruct {
124124
}
125125

126126
fnfunc() -> Option<i32>{
127+
macro_rules! opt_none {
128+
() => {
129+
None
130+
};
131+
}
132+
127133
fnf() -> Option<String>{
128134
Some(String::new())
129135
}
@@ -132,6 +138,39 @@ fn func() -> Option<i32> {
132138
returnNone;
133139
}
134140

141+
let _val = matchf(){
142+
Some(val) => val,
143+
None => returnNone,
144+
};
145+
146+
let s:&str = match&Some(String::new()){
147+
Some(v) => v,
148+
None => returnNone,
149+
};
150+
151+
matchf(){
152+
Some(val) => val,
153+
None => returnNone,
154+
};
155+
156+
matchopt_none!(){
157+
Some(x) => x,
158+
None => returnNone,
159+
};
160+
161+
matchf(){
162+
Some(x) => x,
163+
None => returnopt_none!(),
164+
};
165+
166+
matchf(){
167+
Some(val) => {
168+
println!("{val}");
169+
val
170+
},
171+
None => returnNone,
172+
};
173+
135174
Some(0)
136175
}
137176

@@ -146,6 +185,16 @@ fn result_func(x: Result<i32, i32>) -> Result<i32, i32> {
146185
return x;
147186
}
148187

188+
let _val = matchfunc_returning_result(){
189+
Ok(val) => val,
190+
Err(err) => returnErr(err),
191+
};
192+
193+
matchfunc_returning_result(){
194+
Ok(val) => val,
195+
Err(err) => returnErr(err),
196+
};
197+
149198
// No warning
150199
let y = ifletOk(x) = x {
151200
x
@@ -189,6 +238,18 @@ fn result_func(x: Result<i32, i32>) -> Result<i32, i32> {
189238
Ok(y)
190239
}
191240

241+
fninfer_check(){
242+
let closure = |x:Result<u8,()>| {
243+
// `?` would fail here, as it expands to `Err(val.into())` which is not constrained.
244+
let _val = match x {
245+
Ok(val) => val,
246+
Err(val) => returnErr(val),
247+
};
248+
249+
Ok(())
250+
};
251+
}
252+
192253
// see issue #8019
193254
pubenumNotOption{
194255
None,

0 commit comments

Comments
 (0)