1
1
use clippy_utils:: diagnostics:: span_lint_and_sugg;
2
2
use 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;
4
5
use clippy_utils:: { is_lint_allowed, msrvs, std_or_core} ;
5
6
use rustc_errors:: Applicability ;
6
7
use rustc_hir:: { BorrowKind , Expr , ExprKind , Mutability , Ty , TyKind } ;
7
8
use rustc_lint:: LateContext ;
8
9
use rustc_middle:: ty:: adjustment:: Adjust ;
10
+ use rustc_span:: BytePos ;
9
11
10
12
use super :: BORROW_AS_PTR ;
11
13
@@ -32,12 +34,21 @@ pub(super) fn check<'tcx>(
32
34
return false ;
33
35
}
34
36
35
- let suggestion = if msrv. meets ( msrvs:: RAW_REF_OP ) {
37
+ let ( suggestion, span ) = if msrv. meets ( msrvs:: RAW_REF_OP ) {
36
38
let operator_kind = match mutability {
37
39
Mutability :: Not => "const" ,
38
40
Mutability :: Mut => "mut" ,
39
41
} ;
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)
41
52
} else {
42
53
let Some ( std_or_core) = std_or_core ( cx) else {
43
54
return false ;
@@ -46,18 +57,10 @@ pub(super) fn check<'tcx>(
46
57
Mutability :: Not => "addr_of" ,
47
58
Mutability :: Mut => "addr_of_mut" ,
48
59
} ;
49
- format ! ( "{std_or_core}::ptr::{macro_name}!({snip})" )
60
+ ( format ! ( "{std_or_core}::ptr::{macro_name}!({snip})" ) , expr . span )
50
61
} ;
51
62
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) ;
61
64
return true ;
62
65
}
63
66
false
0 commit comments