Skip to content

Commit 413c515

Browse files
authored
Avoid static-mut shared refs in global fn ptr null checks
1 parent 05258a5 commit 413c515

2 files changed

Lines changed: 20 additions & 6 deletions

File tree

cpp2rust/converter/converter.cpp

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3535,13 +3535,27 @@ void Converter::ConvertUnsignedArithOperand(clang::Expr *expr,
35353535
}
35363536

35373537
void Converter::ConvertEqualsNullPtr(clang::Expr *expr) {
3538-
StrCat('(');
3538+
if (IsGlobalVar(expr) &&
3539+
(IsUniquePtr(expr->getType()) ||
3540+
expr->getType()->isFunctionPointerType())) {
3541+
StrCat(keyword_unsafe_);
3542+
PushBrace unsafe_brace(*this);
3543+
{
3544+
PushParen paren(*this);
3545+
StrCat("&raw", keyword::kConst);
3546+
Convert(expr);
3547+
}
3548+
StrCat(".as_ref().unwrap().is_none()");
3549+
return;
3550+
}
3551+
3552+
PushParen paren(*this);
35393553
Convert(expr);
35403554
if (IsUniquePtr(expr->getType()) ||
35413555
expr->getType()->isFunctionPointerType()) {
3542-
StrCat(").is_none()");
3556+
StrCat(".is_none()");
35433557
} else {
3544-
StrCat(").is_null()");
3558+
StrCat(".is_null()");
35453559
}
35463560
}
35473561

tests/unit/out/unsafe/fn_ptr_global.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ pub unsafe fn set_op_3(mut fn_: Option<unsafe fn(i32) -> i32>) {
1717
g_op_2 = fn_;
1818
}
1919
pub unsafe fn call_op_4(mut x: i32) -> i32 {
20-
if !(g_op_2).is_none() {
20+
if !(unsafe { (&raw const g_op_2).as_ref().unwrap().is_none() }) {
2121
return (unsafe {
2222
let _arg0: i32 = x;
2323
(g_op_2).unwrap()(_arg0)
@@ -41,7 +41,7 @@ unsafe fn main_0() -> i32 {
4141
let _fn: Option<unsafe fn(i32) -> i32> = Some(double_it_0);
4242
set_op_3(_fn)
4343
});
44-
assert!(!((g_op_2).is_none()));
44+
assert!(!(unsafe { (&raw const g_op_2).as_ref().unwrap().is_none() }));
4545
assert!(((g_op_2) == (Some(double_it_0))));
4646
assert!(
4747
((unsafe {
@@ -64,7 +64,7 @@ unsafe fn main_0() -> i32 {
6464
let _fn: Option<unsafe fn(i32) -> i32> = None;
6565
set_op_3(_fn)
6666
});
67-
assert!((g_op_2).is_none());
67+
assert!(unsafe { (&raw const g_op_2).as_ref().unwrap().is_none() });
6868
assert!(
6969
((unsafe {
7070
let _x: i32 = 5;

0 commit comments

Comments
 (0)