11use clippy_utils:: diagnostics:: span_lint_and_sugg;
22use clippy_utils:: msrvs:: Msrv ;
3- use clippy_utils:: source:: snippet_with_context;
3+ use clippy_utils:: source:: { snippet_with_applicability, snippet_with_context} ;
4+ use clippy_utils:: sugg:: has_enclosing_paren;
45use clippy_utils:: { is_lint_allowed, msrvs, std_or_core} ;
56use rustc_errors:: Applicability ;
67use rustc_hir:: { BorrowKind , Expr , ExprKind , Mutability , Ty , TyKind } ;
78use rustc_lint:: LateContext ;
89use rustc_middle:: ty:: adjustment:: Adjust ;
10+ use rustc_span:: BytePos ;
911
1012use super :: BORROW_AS_PTR ;
1113
@@ -32,12 +34,21 @@ pub(super) fn check<'tcx>(
3234 return false ;
3335 }
3436
35- let suggestion = if msrv. meets ( msrvs:: RAW_REF_OP ) {
37+ let ( suggestion, span ) = if msrv. meets ( msrvs:: RAW_REF_OP ) {
3638 let operator_kind = match mutability {
3739 Mutability :: Not => "const" ,
3840 Mutability :: Mut => "mut" ,
3941 } ;
40- format ! ( "&raw {operator_kind} {snip}" )
42+ // Make sure that the span to be replaced doesn't include parentheses, that could break the
43+ // suggestion.
44+ let span = if has_enclosing_paren ( snippet_with_applicability ( cx, expr. span , "" , & mut app) ) {
45+ expr. span
46+ . with_lo ( expr. span . lo ( ) + BytePos ( 1 ) )
47+ . with_hi ( expr. span . hi ( ) - BytePos ( 1 ) )
48+ } else {
49+ expr. span
50+ } ;
51+ ( format ! ( "&raw {operator_kind} {snip}" ) , span)
4152 } else {
4253 let Some ( std_or_core) = std_or_core ( cx) else {
4354 return false ;
@@ -46,18 +57,10 @@ pub(super) fn check<'tcx>(
4657 Mutability :: Not => "addr_of" ,
4758 Mutability :: Mut => "addr_of_mut" ,
4859 } ;
49- format ! ( "{std_or_core}::ptr::{macro_name}!({snip})" )
60+ ( format ! ( "{std_or_core}::ptr::{macro_name}!({snip})" ) , expr . span )
5061 } ;
5162
52- span_lint_and_sugg (
53- cx,
54- BORROW_AS_PTR ,
55- expr. span ,
56- "borrow as raw pointer" ,
57- "try" ,
58- suggestion,
59- Applicability :: MachineApplicable ,
60- ) ;
63+ span_lint_and_sugg ( cx, BORROW_AS_PTR , span, "borrow as raw pointer" , "try" , suggestion, app) ;
6164 return true ;
6265 }
6366 false
0 commit comments