fix: match_as_ref wrongly unmangled macros

This commit is contained in:
Linshu Yang 2026-01-02 23:07:31 +00:00
parent 02e4f853ef
commit 0cfbe56d04
4 changed files with 49 additions and 3 deletions

View file

@ -46,6 +46,7 @@ pub(crate) fn check(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr:
let cast = if input_ty == output_ty { "" } else { ".map(|x| x as _)" };
let mut applicability = Applicability::MachineApplicable;
let ctxt = expr.span.ctxt();
span_lint_and_then(
cx,
MATCH_AS_REF,
@ -59,7 +60,7 @@ pub(crate) fn check(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr:
"use `Option::as_ref()`",
format!(
"{}.as_ref(){cast}",
Sugg::hir_with_applicability(cx, ex, "_", &mut applicability).maybe_paren(),
Sugg::hir_with_context(cx, ex, ctxt, "_", &mut applicability).maybe_paren(),
),
applicability,
);
@ -69,7 +70,7 @@ pub(crate) fn check(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr:
format!("use `Option::{method}()` directly"),
format!(
"{}.{method}(){cast}",
Sugg::hir_with_applicability(cx, ex, "_", &mut applicability).maybe_paren(),
Sugg::hir_with_context(cx, ex, ctxt, "_", &mut applicability).maybe_paren(),
),
applicability,
);

View file

@ -90,3 +90,13 @@ fn issue15932() {
let _: Option<&dyn std::fmt::Debug> = Some(0).as_ref().map(|x| x as _);
}
fn wrongly_unmangled_macros() {
macro_rules! test_expr {
($val:expr) => {
Some($val)
};
}
let _: Option<&u32> = test_expr!(42).as_ref();
}

View file

@ -114,3 +114,17 @@ fn issue15932() {
Some(ref mut v) => Some(v),
};
}
fn wrongly_unmangled_macros() {
macro_rules! test_expr {
($val:expr) => {
Some($val)
};
}
let _: Option<&u32> = match test_expr!(42) {
//~^ match_as_ref
None => None,
Some(ref v) => Some(v),
};
}

View file

@ -127,5 +127,26 @@ LL - };
LL + let _: Option<&dyn std::fmt::Debug> = Some(0).as_ref().map(|x| x as _);
|
error: aborting due to 6 previous errors
error: manual implementation of `Option::as_ref`
--> tests/ui/match_as_ref.rs:125:27
|
LL | let _: Option<&u32> = match test_expr!(42) {
| ___________________________^
LL | |
LL | | None => None,
LL | | Some(ref v) => Some(v),
LL | | };
| |_____^
|
help: use `Option::as_ref()` directly
|
LL - let _: Option<&u32> = match test_expr!(42) {
LL -
LL - None => None,
LL - Some(ref v) => Some(v),
LL - };
LL + let _: Option<&u32> = test_expr!(42).as_ref();
|
error: aborting due to 7 previous errors