Skip to content

Commit 4465e2f

Browse files
committed
Auto merge of #4355 - lzutao:macro_expn_try_err, r=flip1995
Fix macro expansion in try_err lint Fixes #4309 changelog: none
2 parents 7bd7d40 + 90a7b60 commit 4465e2f

File tree

4 files changed

+53
-4
lines changed

4 files changed

+53
-4
lines changed

clippy_lints/src/try_err.rs

+8-3
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use crate::utils::{match_qpath, paths, snippet, span_lint_and_sugg};
1+
use crate::utils::{in_macro_or_desugar, match_qpath, paths, snippet, snippet_with_macro_callsite, span_lint_and_sugg};
22
use if_chain::if_chain;
33
use rustc::hir::*;
44
use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
@@ -67,10 +67,15 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TryErr {
6767

6868
then {
6969
let err_type = cx.tables.expr_ty(err_arg);
70+
let origin_snippet = if in_macro_or_desugar(err_arg.span) {
71+
snippet_with_macro_callsite(cx, err_arg.span, "_")
72+
} else {
73+
snippet(cx, err_arg.span, "_")
74+
};
7075
let suggestion = if err_type == return_type {
71-
format!("return Err({})", snippet(cx, err_arg.span, "_"))
76+
format!("return Err({})", origin_snippet)
7277
} else {
73-
format!("return Err({}.into())", snippet(cx, err_arg.span, "_"))
78+
format!("return Err({}.into())", origin_snippet)
7479
};
7580

7681
span_lint_and_sugg(

tests/ui/try_err.fixed

+19
Original file line numberDiff line numberDiff line change
@@ -78,3 +78,22 @@ fn main() {
7878
closure_matches_test().unwrap();
7979
closure_into_test().unwrap();
8080
}
81+
82+
macro_rules! bar {
83+
() => {
84+
String::from("aasdfasdfasdfa")
85+
};
86+
}
87+
88+
macro_rules! foo {
89+
() => {
90+
bar!()
91+
};
92+
}
93+
94+
pub fn macro_inside(fail: bool) -> Result<i32, String> {
95+
if fail {
96+
return Err(foo!());
97+
}
98+
Ok(0)
99+
}

tests/ui/try_err.rs

+19
Original file line numberDiff line numberDiff line change
@@ -78,3 +78,22 @@ fn main() {
7878
closure_matches_test().unwrap();
7979
closure_into_test().unwrap();
8080
}
81+
82+
macro_rules! bar {
83+
() => {
84+
String::from("aasdfasdfasdfa")
85+
};
86+
}
87+
88+
macro_rules! foo {
89+
() => {
90+
bar!()
91+
};
92+
}
93+
94+
pub fn macro_inside(fail: bool) -> Result<i32, String> {
95+
if fail {
96+
Err(foo!())?;
97+
}
98+
Ok(0)
99+
}

tests/ui/try_err.stderr

+7-1
Original file line numberDiff line numberDiff line change
@@ -28,5 +28,11 @@ error: returning an `Err(_)` with the `?` operator
2828
LL | Err(err)?;
2929
| ^^^^^^^^^ help: try this: `return Err(err.into())`
3030

31-
error: aborting due to 4 previous errors
31+
error: returning an `Err(_)` with the `?` operator
32+
--> $DIR/try_err.rs:96:9
33+
|
34+
LL | Err(foo!())?;
35+
| ^^^^^^^^^^^^ help: try this: `return Err(foo!())`
36+
37+
error: aborting due to 5 previous errors
3238

0 commit comments

Comments
 (0)