Skip to content

Commit 23debb3

Browse files
authored
Force rules that return C++ reference to return pointer/reference/Ptr in Rust (#647)
Defensive fix to avoid encountering #612 in the future
1 parent 11bd7e2 commit 23debb3

119 files changed

Lines changed: 1685 additions & 731 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎cpp2rust/converter/rules/registry.cpp‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,12 +160,35 @@ void checkGenerics(const std::string &dir, const std::string &name,
160160
}
161161
}
162162

163+
void checkReturn(const std::string &dir, const std::string &name, Model target,
164+
const clang::NamedDecl *decl,
165+
const TranslationRule::ExprRule &rule) {
166+
auto function = decl->getAsFunction();
167+
auto type =
168+
function ? function->getType()
169+
: llvm::cast<clang::VarDecl>(decl)->getType()->getPointeeType();
170+
auto function_type = type->getAs<clang::FunctionType>();
171+
assert(function_type &&
172+
"expression rule is neither a function nor a function pointer");
173+
if (function_type->getReturnType()->isReferenceType() &&
174+
!rule.return_type.is_pointer() && !rule.return_type.is_reference &&
175+
!rule.returns_place) {
176+
llvm::errs() << "rules/" << dir << ' ' << name
177+
<< ": C++ returns a reference but the "
178+
<< (target == Model::kRefCount ? "refcount" : "unsafe")
179+
<< " target returns by value\n";
180+
llvm::report_fatal_error("Expr rule returns a reference by value");
181+
}
182+
}
183+
163184
void addRule(clang::ASTContext &ctx, const std::string &dir,
164185
const std::string &name, const clang::NamedDecl *decl) {
165186
auto rule = findRule(Model::kUnsafe, dir, name);
187+
auto target = Model::kUnsafe;
166188
if (model_ == Model::kRefCount) {
167189
if (auto refcount_rule = findRule(model_, dir, name)) {
168190
rule = refcount_rule;
191+
target = model_;
169192
}
170193
}
171194
assert(rule && "rule has no target");
@@ -185,6 +208,7 @@ void addRule(clang::ASTContext &ctx, const std::string &dir,
185208
assert(llvm::isa<clang::VarDecl>(decl) &&
186209
"expression rule is neither a function nor a variable");
187210
}
211+
checkReturn(dir, name, target, decl, expr_rule);
188212
auto keys = RuleKeys::GetExprKeys(*sema_, decl);
189213
assert(!keys.empty() && "expression rule has no key");
190214
for (const auto &key : keys) {

‎cpp2rust/converter/translation_rule.cpp‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@ TypeInfo ParseTypeInfoJSON(const llvm::json::Object &obj) {
2828
info.is_refcount_pointer = *v;
2929
if (auto v = obj.getBoolean("is_unsafe_pointer"))
3030
info.is_unsafe_pointer = *v;
31+
if (auto v = obj.getBoolean("is_reference"))
32+
info.is_reference = *v;
3133
if (auto v = obj.getInteger("generic"))
3234
info.generic = *v;
3335
assert(!(info.is_refcount_pointer && info.is_unsafe_pointer));
@@ -438,6 +440,10 @@ ExprRule ParseExprRuleJSON(const llvm::json::Object &obj) {
438440
ir.is_extern = *v;
439441
}
440442

443+
if (auto v = obj.getBoolean("returns_place")) {
444+
ir.returns_place = *v;
445+
}
446+
441447
if (auto *generics = obj.getObject("generics")) {
442448
for (auto &[key, val] : *generics) {
443449
auto *arr = val.getAsArray();

‎cpp2rust/converter/translation_rule.h‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,7 @@ struct TypeInfo {
109109
std::string cpp_type;
110110
bool is_refcount_pointer = false;
111111
bool is_unsafe_pointer = false;
112+
bool is_reference = false;
112113
std::optional<Elems> elems;
113114
unsigned generic = 0;
114115

@@ -125,6 +126,7 @@ struct ExprRule {
125126
std::vector<BodyFragment> body;
126127
bool multi_statement = false;
127128
bool is_extern = false;
129+
bool returns_place = false;
128130

129131
void dump() const;
130132
bool usesInit() const;

‎rule-preprocessor/src/ir.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,8 @@ pub struct TypeInfo {
6868
pub is_refcount_pointer: bool,
6969
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
7070
pub is_unsafe_pointer: bool,
71+
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
72+
pub is_reference: bool,
7173
#[serde(default, skip_serializing_if = "Vec::is_empty")]
7274
pub derives: Vec<String>,
7375
#[serde(default, skip_serializing_if = "Option::is_none")]
@@ -105,6 +107,8 @@ pub struct FnIr {
105107
pub return_type: Option<TypeInfo>,
106108
#[serde(skip_serializing_if = "Option::is_none")]
107109
pub is_extern: Option<bool>,
110+
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
111+
pub returns_place: bool,
108112
}
109113

110114
impl FnIr {

‎rule-preprocessor/src/syntactic.rs‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -500,6 +500,7 @@ impl<'a> FnIrBuilder<'a> {
500500
ty: ty_str,
501501
is_refcount_pointer,
502502
is_unsafe_pointer,
503+
is_reference: matches!(&ty, ast::Type::RefType(_)),
503504
derives: Vec::new(),
504505
cpp_type: None,
505506
elems: None,
@@ -635,6 +636,40 @@ impl<'a> FnIrBuilder<'a> {
635636
.any(|a| a.kind() == SyntaxKind::EXTERN_BLOCK)
636637
}
637638

639+
fn returns_place(&self, params: &[ParamInfo]) -> bool {
640+
fn is_place(expr: ast::Expr, params: &[ParamInfo], projected: bool) -> bool {
641+
match expr {
642+
ast::Expr::FieldExpr(e) => {
643+
e.expr().is_some_and(|base| is_place(base, params, true))
644+
}
645+
ast::Expr::IndexExpr(e) => {
646+
e.base().is_some_and(|base| is_place(base, params, true))
647+
}
648+
ast::Expr::ParenExpr(e) => e
649+
.expr()
650+
.is_some_and(|inner| is_place(inner, params, projected)),
651+
ast::Expr::PrefixExpr(e) => {
652+
e.op_kind() == Some(ast::UnaryOp::Deref)
653+
&& e.expr()
654+
.is_some_and(|inner| is_place(inner, params, projected))
655+
}
656+
ast::Expr::PathExpr(e) => {
657+
projected
658+
&& e.path()
659+
.and_then(|path| path.as_single_name_ref())
660+
.is_some_and(|name| params.iter().any(|p| p.name == name.text()))
661+
}
662+
_ => false,
663+
}
664+
}
665+
self.fn_item
666+
.body()
667+
.and_then(|body| body.stmt_list())
668+
.filter(|stmt_list| stmt_list.statements().next().is_none())
669+
.and_then(|stmt_list| stmt_list.tail_expr())
670+
.is_some_and(|tail| is_place(tail, params, false))
671+
}
672+
638673
fn returns_mut_ref(&self) -> bool {
639674
self.fn_item
640675
.ret_type()
@@ -728,6 +763,7 @@ impl<'a> FnIrBuilder<'a> {
728763
ty: p.ty.clone(),
729764
is_refcount_pointer: p.is_refcount_pointer,
730765
is_unsafe_pointer: p.is_unsafe_pointer,
766+
is_reference: false,
731767
derives: Vec::new(),
732768
cpp_type: p.cpp_type.clone(),
733769
elems: None,
@@ -767,6 +803,7 @@ impl<'a> FnIrBuilder<'a> {
767803
multi_statement,
768804
body,
769805
is_extern: self.is_extern().then_some(true),
806+
returns_place: self.returns_place(&params),
770807
};
771808
ir.validate(&format!("{}:{}", path.display(), fn_name));
772809
ir
@@ -840,6 +877,7 @@ impl<'a> TypeIrBuilder<'a> {
840877
ty: ty.syntax().text().to_string(),
841878
is_refcount_pointer,
842879
is_unsafe_pointer,
880+
is_reference: false,
843881
derives: Vec::new(),
844882
cpp_type: None,
845883
elems: elems(&ty),

‎rules/array/tgt_refcount.rs‎

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -33,20 +33,28 @@ fn f4<T1: MoveCtor, const T2: usize>(a0: Ptr<T1>) -> Box<[T1]> {
3333
(0..T2).map(|__i| T1::move_ctor(a0.offset(__i))).collect()
3434
}
3535

36-
fn f5<T1: MoveAssign, const T2: usize>(a0: Ptr<T1>, a1: Ptr<T1>) {
36+
fn f5<T1: MoveAssign + ByteRepr, const T2: usize>(
37+
a0: Ptr<Box<[T1]>>,
38+
a1: Ptr<T1>,
39+
) -> Ptr<Box<[T1]>> {
3740
for __i in 0..T2 {
38-
T1::move_assign(&a0.offset(__i), a1.offset(__i));
41+
T1::move_assign(&a0.decay().offset(__i), a1.offset(__i));
3942
}
43+
a0
4044
}
4145

4246
fn f6<T1: Clone + ByteRepr, const T2: usize>(a0: Ptr<T1>) -> Box<[T1]> {
4347
(0..T2).map(|__i| a0.read_at(__i)).collect()
4448
}
4549

46-
fn f7<T1: CopyAssign, const T2: usize>(a0: Ptr<T1>, a1: Ptr<T1>) {
50+
fn f7<T1: CopyAssign + ByteRepr, const T2: usize>(
51+
a0: Ptr<Box<[T1]>>,
52+
a1: Ptr<T1>,
53+
) -> Ptr<Box<[T1]>> {
4754
for __i in 0..T2 {
48-
T1::copy_assign(&a0.offset(__i), a1.offset(__i));
55+
T1::copy_assign(&a0.decay().offset(__i), a1.offset(__i));
4956
}
57+
a0
5058
}
5159

5260
fn f8<T1, const T2: usize>(a0: [T1; T2]) -> Box<[T1]> {

‎rules/array/tgt_unsafe.rs‎

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -43,20 +43,28 @@ unsafe fn f4<T1: MoveCtorUnsafe, const T2: usize>(a0: &mut [T1; T2]) -> [T1; T2]
4343
std::array::from_fn(|__i| T1::move_ctor(&mut a0[__i]))
4444
}
4545

46-
unsafe fn f5<T1: MoveAssignUnsafe, const T2: usize>(a0: &mut [T1; T2], a1: &mut [T1; T2]) {
46+
unsafe fn f5<T1: MoveAssignUnsafe, const T2: usize>(
47+
a0: *mut [T1; T2],
48+
a1: &mut [T1; T2],
49+
) -> *mut [T1; T2] {
4750
for __i in 0..T2 {
48-
T1::move_assign(&mut a0[__i], &mut a1[__i]);
51+
T1::move_assign(&mut (*a0)[__i], &mut a1[__i]);
4952
}
53+
a0
5054
}
5155

5256
unsafe fn f6<T1: Clone, const T2: usize>(a0: [T1; T2]) -> [T1; T2] {
5357
a0.clone()
5458
}
5559

56-
unsafe fn f7<T1: CopyAssignUnsafe, const T2: usize>(a0: &mut [T1; T2], a1: &[T1; T2]) {
60+
unsafe fn f7<T1: CopyAssignUnsafe, const T2: usize>(
61+
a0: *mut [T1; T2],
62+
a1: &[T1; T2],
63+
) -> *mut [T1; T2] {
5764
for __i in 0..T2 {
58-
T1::copy_assign(&mut a0[__i], &a1[__i]);
65+
T1::copy_assign(&mut (*a0)[__i], &a1[__i]);
5966
}
67+
a0
6068
}
6169

6270
unsafe fn f8<T1, const T2: usize>(a0: [T1; T2]) -> [T1; T2] {

‎rules/deque/tgt_refcount.rs‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,10 +21,12 @@ fn f2<T1>(a0: Ptr<T1>) -> Ptr<T1> {
2121
a0
2222
}
2323

24-
fn f10<T1: Clone + ByteRepr>(a0: Ptr<Vec<T1>>, a1: Vec<T1>) {
25-
a0.write(a1)
24+
fn f10<T1: Clone + ByteRepr>(a0: Ptr<Vec<T1>>, a1: Vec<T1>) -> Ptr<Vec<T1>> {
25+
a0.write(a1);
26+
a0
2627
}
2728

28-
fn f11<T1: ByteRepr + Clone>(a0: Ptr<Vec<T1>>, a1: &mut Vec<T1>) {
29-
a0.write(std::mem::take(&mut *a1))
29+
fn f11<T1: ByteRepr + Clone>(a0: Ptr<Vec<T1>>, a1: &mut Vec<T1>) -> Ptr<Vec<T1>> {
30+
a0.write(std::mem::take(&mut *a1));
31+
a0
3032
}

‎rules/deque/tgt_unsafe.rs‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -57,12 +57,14 @@ unsafe fn f9<T1>(a0: &mut Vec<T1>) -> Vec<T1> {
5757
std::mem::take(&mut *a0)
5858
}
5959

60-
unsafe fn f10<T1: Clone>(a0: &mut Vec<T1>, a1: Vec<T1>) {
61-
*a0 = a1.clone()
60+
unsafe fn f10<T1: Clone>(a0: *mut Vec<T1>, a1: Vec<T1>) -> *mut Vec<T1> {
61+
*a0 = a1.clone();
62+
a0
6263
}
6364

64-
unsafe fn f11<T1>(a0: &mut Vec<T1>, a1: &mut Vec<T1>) {
65-
*a0 = std::mem::take(&mut *a1)
65+
unsafe fn f11<T1>(a0: *mut Vec<T1>, a1: &mut Vec<T1>) -> *mut Vec<T1> {
66+
*a0 = std::mem::take(&mut *a1);
67+
a0
6668
}
6769

6870
unsafe fn f12<T1>(a0: &mut Vec<T1>, init: T1) {

‎rules/iterator_category/tgt_refcount.rs‎

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -31,12 +31,14 @@ fn f2<T1: CppIterator<T2>, T2>(a0: T1) -> T1 {
3131
a0
3232
}
3333

34-
fn f3<T1: CppIterator<T2>, T2>(a0: &mut T1, a1: T1) {
35-
*a0 = a1.clone()
34+
fn f3<T1: CppIterator<T2> + ByteRepr, T2>(a0: Ptr<T1>, a1: T1) -> Ptr<T1> {
35+
a0.write(a1.clone());
36+
a0
3637
}
3738

38-
fn f4<T1: CppIterator<T2>, T2>(a0: &mut T1, a1: T1) {
39-
*a0 = a1
39+
fn f4<T1: CppIterator<T2> + ByteRepr, T2>(a0: Ptr<T1>, a1: T1) -> Ptr<T1> {
40+
a0.write(a1);
41+
a0
4042
}
4143

4244
fn f5<T1: CppIterator<T2>, T2>(a0: T1) -> Ptr<T2> {
@@ -131,16 +133,18 @@ fn f24<T1: From<T2>, T2>(a0: T2) -> T1 {
131133
<T1>::from(a0)
132134
}
133135

134-
fn f25<T1: CppIterator<T2>, T2>(a0: T1) -> T1 {
135-
let mut __it = a0;
136-
__it.iter_inc();
137-
__it
136+
fn f25<T1: CppIterator<T2> + ByteRepr, T2>(a0: Ptr<T1>) -> Ptr<T1> {
137+
a0.with_mut(|__v| {
138+
__v.iter_inc();
139+
});
140+
a0
138141
}
139142

140-
fn f26<T1: CppBidirectionalIterator<T2>, T2>(a0: T1) -> T1 {
141-
let mut __it = a0;
142-
__it.iter_dec();
143-
__it
143+
fn f26<T1: CppBidirectionalIterator<T2> + ByteRepr, T2>(a0: Ptr<T1>) -> Ptr<T1> {
144+
a0.with_mut(|__v| {
145+
__v.iter_dec();
146+
});
147+
a0
144148
}
145149

146150
fn f27<T1: CppInputIterator<T3> + PartialEq<T2>, T2: CppInputIterator<T3>, T3>(a0: T1, a1: T2) -> bool {

0 commit comments

Comments
 (0)