Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 11 additions & 24 deletions cpp2rust/converter/converter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -752,21 +752,19 @@ bool Converter::VarTypeNeedsDestructor(clang::QualType type) const {
}

std::string Converter::StaticDestructorCall(const clang::VarDecl *decl) {
auto destroy = AsLambdaClass(decl->getType()) ? "destroy" : kDestructorName;
return std::format(
"(*std::cell::LazyCell::force_mut(&mut *&raw mut {})).{}()",
GetNamedDeclAsString(decl), destroy);
return std::format("DestructibleUnsafe::destroy(&raw mut "
"*std::cell::LazyCell::force_mut(&mut *&raw mut {}))",
GetNamedDeclAsString(decl));
}

void Converter::EmitScopedDestructor(const clang::VarDecl *decl) {
if (!NeedsScopedDestructor(decl)) {
return;
}
auto destroy = AsLambdaClass(decl->getType()) ? "destroy" : kDestructorName;
StrCat(token::kSemiColon,
std::format("let _dtor_{0} = std::mem::DropGuard::new(&raw mut {0}, "
"|__p| unsafe {{ (*__p).{1}() }})",
GetNamedDeclAsString(decl), destroy));
"|__p| unsafe {{ DestructibleUnsafe::destroy(__p) }})",
GetNamedDeclAsString(decl)));
}

bool Converter::RecordDerivesDefault(const clang::RecordDecl *decl) {
Expand Down Expand Up @@ -1026,18 +1024,8 @@ std::string Converter::DestroyMembers(const clang::CXXRecordDecl *decl) {
std::string out;
for (auto *field : FieldsToDestroy(decl)) {
auto name = GetNamedDeclAsString(field);
auto type = field->getType();
if (type->isArrayType()) {
auto *elem = type->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
assert(elem);
out +=
std::format("for __e in self.{0}.iter_mut() {{ {1}::{2}(__e); }}\n",
name, GetRecordName(elem), kDestructorName);
} else {
out += std::format("{1}::{2}(&mut self.{0});\n", name,
GetRecordName(type->getAsCXXRecordDecl()),
kDestructorName);
}
out +=
std::format("DestructibleUnsafe::destroy(&raw mut self.{});\n", name);
}
return out;
}
Expand Down Expand Up @@ -4164,11 +4152,10 @@ bool Converter::VisitCXXDeleteExpr(clang::CXXDeleteExpr *expr) {
StrCat(
std::format("for __i in (0..libcc2rs::malloc_usable_size(__p as *mut "
"::libc::c_void) / ::std::mem::size_of::<{0}>()).rev() {{ "
"{0}::{1}(&mut *__p.add(__i)); }}",
record_name, kDestructorName));
"DestructibleUnsafe::destroy(__p.add(__i)); }}",
record_name));
} else {
StrCat(std::format("{}::{}(&mut *__p)", record_name, kDestructorName),
token::kSemiColon);
StrCat("DestructibleUnsafe::destroy(__p)", token::kSemiColon);
}
EmitDeallocation(expr, "__p");
return false;
Expand Down Expand Up @@ -4775,7 +4762,7 @@ Converter::GetStructAttributes(const clang::RecordDecl *decl) {

if (auto *cxx = clang::dyn_cast<clang::CXXRecordDecl>(decl);
cxx && RecordNeedsDestruction(cxx)) {
struct_attrs.emplace_back("DestructorUnsafe");
struct_attrs.emplace_back("DestructibleUnsafe");
}

if (RecordDerivesDefault(decl)) {
Expand Down
39 changes: 11 additions & 28 deletions cpp2rust/converter/models/converter_refcount.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -935,22 +935,17 @@ void ConverterRefCount::EmitScopedDestructor(const clang::VarDecl *decl) {
if (!NeedsScopedDestructor(decl)) {
return;
}
auto destroy = AsLambdaClass(decl->getType())
? std::string("with(|__f| __f.destroy())")
: std::format("{}()", kDestructorName);
StrCat(token::kSemiColon,
std::format("let _dtor_{0} = std::mem::DropGuard::new({0}.clone(), "
"|__p| __p.as_pointer().{1})",
GetNamedDeclAsString(decl), destroy));
"|__p| Destructible::destroy(__p.as_pointer()))",
GetNamedDeclAsString(decl)));
}

std::string
ConverterRefCount::StaticDestructorCall(const clang::VarDecl *decl) {
auto destroy = AsLambdaClass(decl->getType())
? std::string("with(|__f| __f.destroy())")
: std::format("{}()", kDestructorName);
return std::format("{}.with(Value::clone).as_pointer().{}",
GetNamedDeclAsString(decl), destroy);
return std::format(
"Destructible::destroy({}.with(Value::clone).as_pointer())",
GetNamedDeclAsString(decl));
}

bool ConverterRefCount::ConvertIncAndDec(clang::UnaryOperator *expr) {
Expand Down Expand Up @@ -2025,11 +2020,10 @@ bool ConverterRefCount::VisitCXXDeleteExpr(clang::CXXDeleteExpr *expr) {
StrCat(keyword::kLet, "__p", token::kAssign, ToString(expr->getArgument()),
token::kSemiColon);
if (expr->isArrayForm()) {
StrCat(std::format("for __i in (0..__p.len()).rev() {{ __p.offset(__i as "
"isize).{}(); }}",
kDestructorName));
StrCat("for __i in (0..__p.len()).rev() { "
"Destructible::destroy(__p.offset(__i as isize)); }");
} else {
StrCat(std::format("__p.{}();", kDestructorName));
StrCat("Destructible::destroy(__p.clone());");
}
StrCat("__p.delete();");
return false;
Expand Down Expand Up @@ -2309,7 +2303,7 @@ ConverterRefCount::GetStructAttributes(const clang::RecordDecl *decl) {

if (auto *cxx = clang::dyn_cast<clang::CXXRecordDecl>(decl);
cxx && RecordNeedsDestruction(cxx)) {
attrs.emplace_back("Destructor");
attrs.emplace_back("Destructible");
}

if (RecordDerivesDefault(decl)) {
Expand Down Expand Up @@ -3643,19 +3637,8 @@ std::string
ConverterRefCount::DestroyMembers(const clang::CXXRecordDecl *decl) {
std::string out;
for (auto *field : FieldsToDestroy(decl)) {
auto name = GetNamedDeclAsString(field);
if (field->getType()->isArrayType()) {
auto *elem =
field->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
assert(elem);
out += std::format(
"{{ let __p = array_field_ptr!(self, {0}); for __i in "
"0..__p.len() {{ {2}::{1}(&__p.offset(__i as isize)); }} }}\n",
name, kDestructorName, TraitName(elem));
} else {
out +=
std::format("field_ptr!(self, {0}).{1}();\n", name, kDestructorName);
}
out += std::format("Destructible::destroy(field_ptr!(self, {}));\n",
GetNamedDeclAsString(field));
}
return out;
}
Expand Down
4 changes: 2 additions & 2 deletions libcc2rs-macros/src/destructor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,15 @@ pub fn expand(input: TokenStream, is_unsafe: bool) -> TokenStream {
let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
if is_unsafe {
quote! {
impl #impl_generics ::libcc2rs::DestructorUnsafe for #name #ty_generics #where_clause {
impl #impl_generics ::libcc2rs::DestructibleUnsafe for #name #ty_generics #where_clause {
unsafe fn destroy(p: *mut Self) {
unsafe { (*p).destructor() }
}
}
}
} else {
quote! {
impl #impl_generics ::libcc2rs::Destructor for #name #ty_generics #where_clause {
impl #impl_generics ::libcc2rs::Destructible for #name #ty_generics #where_clause {
fn destroy(p: ::libcc2rs::Ptr<Self>) {
p.destructor()
}
Expand Down
14 changes: 7 additions & 7 deletions libcc2rs-macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -200,23 +200,23 @@ pub fn derive_move_assign_unsafe(input: TokenStream) -> TokenStream {
assign::expand(input, "move", true)
}

// #[derive(Destructor)]
// #[derive(Destructible)]
// pub struct S { ... }
// impl SImpl for Ptr<S> {
// fn destructor(&self) { ... }
// }
//
// Implements libcc2rs::Destructor for S with its destructor, such that
// lambda! destroys the captures of type S with it. DestructorUnsafe is the
// Implements libcc2rs::Destructible for S with its destructor, through which
// the translation destroys every object of type S. DestructibleUnsafe is the
// same for the unsafe model, whose destructor is a method of S.

#[proc_macro_derive(Destructor)]
pub fn derive_destructor(input: TokenStream) -> TokenStream {
#[proc_macro_derive(Destructible)]
pub fn derive_destructible(input: TokenStream) -> TokenStream {
destructor::expand(input, false)
}

#[proc_macro_derive(DestructorUnsafe)]
pub fn derive_destructor_unsafe(input: TokenStream) -> TokenStream {
#[proc_macro_derive(DestructibleUnsafe)]
pub fn derive_destructible_unsafe(input: TokenStream) -> TokenStream {
destructor::expand(input, true)
}

Expand Down
31 changes: 20 additions & 11 deletions libcc2rs/src/capture.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
// - a type that is not Clone is not copyable, and neither is the lambda,
// so its copy constructor is unreachable.
// Likewise, the destructor of the lambda (`destroy_capture()`) destroys the
// captures that have a C++ destructor (Destructor), in reverse order.
// captures that have a C++ destructor (Destructible), in reverse order.
// In the refcount model, a capture by value is a Value, which is copied
// into a new Value, and a capture by reference is a Ptr, which is copied.

Expand Down Expand Up @@ -135,32 +135,41 @@ impl<T: MoveCtorUnsafe, const N: usize> MoveCtorUnsafe for [T; N] {
}

// The C++ destructor of a type, in the refcount model, for the types that
// have one. Records implement it with #[derive(Destructor)].
pub trait Destructor: Sized {
// have one. Records implement it with #[derive(Destructible)].
pub trait Destructible: Sized {
fn destroy(p: Ptr<Self>);
}

// The C++ destructor of a type, in the unsafe model. Records implement it
// with #[derive(DestructorUnsafe)].
pub trait DestructorUnsafe: Sized {
// with #[derive(DestructibleUnsafe)].
pub trait DestructibleUnsafe: Sized {
/// # Safety
/// `p` must point to a live value.
unsafe fn destroy(p: *mut Self);
}

impl<T: FnSig> Destructor for FnPtr<T> {
impl<T: FnSig> Destructible for FnPtr<T> {
fn destroy(p: Ptr<Self>) {
p.with(|f| f.destroy())
}
}

impl<T: FnSig> DestructorUnsafe for FnPtr<T> {
impl<T: FnSig> DestructibleUnsafe for FnPtr<T> {
unsafe fn destroy(p: *mut Self) {
unsafe { (*p).destroy() }
}
}

impl<T: DestructorUnsafe, const N: usize> DestructorUnsafe for [T; N] {
impl<T: Destructible + ByteRepr> Destructible for Box<[T]> {
fn destroy(p: Ptr<Self>) {
let elems = p.decay();
for i in (0..elems.len()).rev() {
T::destroy(elems.offset(i));
}
}
}

impl<T: DestructibleUnsafe, const N: usize> DestructibleUnsafe for [T; N] {
unsafe fn destroy(p: *mut Self) {
let p = p as *mut T;
for i in (0..N).rev() {
Expand Down Expand Up @@ -264,7 +273,7 @@ pub trait DestroyElems {
fn destroy_capture(&self);
}

impl<T: Destructor> DestroyElems for &&Capture<'_, Value<Box<[T]>>> {
impl<T: Destructible> DestroyElems for &&Capture<'_, Value<Box<[T]>>> {
fn destroy_capture(&self) {
let p: Ptr<T> = self.0.decay();
for i in (0..self.0.borrow().len()).rev() {
Expand All @@ -277,7 +286,7 @@ pub trait DestroyWithDtor {
fn destroy_capture(&self);
}

impl<T: Destructor> DestroyWithDtor for &Capture<'_, Value<T>> {
impl<T: Destructible> DestroyWithDtor for &Capture<'_, Value<T>> {
fn destroy_capture(&self) {
T::destroy(AsPointer::<T>::as_pointer(self.0))
}
Expand Down Expand Up @@ -359,7 +368,7 @@ pub trait DestroyWithDtorUnsafe {
unsafe fn destroy_capture(&self);
}

impl<T: DestructorUnsafe> DestroyWithDtorUnsafe for &CaptureUnsafe<T> {
impl<T: DestructibleUnsafe> DestroyWithDtorUnsafe for &CaptureUnsafe<T> {
unsafe fn destroy_capture(&self) {
unsafe { T::destroy(self.0) }
}
Expand Down
8 changes: 4 additions & 4 deletions libcc2rs/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ pub use fn_ptr::{FnPtr, Generic};

mod capture;
pub use capture::{
CopyAssign, CopyAssignUnsafe, Destructor, DestructorUnsafe, MoveAssign, MoveAssignUnsafe,
CopyAssign, CopyAssignUnsafe, Destructible, DestructibleUnsafe, MoveAssign, MoveAssignUnsafe,
MoveCtor, MoveCtorUnsafe,
};

Expand Down Expand Up @@ -104,7 +104,7 @@ mod format;
pub use format::*;

pub use libcc2rs_macros::{
ByteRepr, CopyAssign, CopyAssignUnsafe, CppFrom, CppFromUnsafe, Destructor, DestructorUnsafe,
FnPtrArg, MoveAssign, MoveAssignUnsafe, MoveCtor, MoveCtorUnsafe, Record, VaArg, goto,
goto_block, lambda, lambda_unsafe, switch,
ByteRepr, CopyAssign, CopyAssignUnsafe, CppFrom, CppFromUnsafe, Destructible,
DestructibleUnsafe, FnPtrArg, MoveAssign, MoveAssignUnsafe, MoveCtor, MoveCtorUnsafe, Record,
VaArg, goto, goto_block, lambda, lambda_unsafe, switch,
};
12 changes: 6 additions & 6 deletions libcc2rs/src/swap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
// types without one; the other types are assigned as a whole, by moving
// the value with the move constructor (MoveCtor), or else by copying it
// (Clone);
// - the temporary is destroyed with the destructor, if any (Destructor).
// - the temporary is destroyed with the destructor, if any (Destructible).
// The values are accessed one at a time, so they may be in the same
// allocation, e.g., two fields of a struct.
//
Expand All @@ -32,7 +32,7 @@ use std::cell::RefCell;
use std::rc::Rc;

use crate::capture::{
CopyAssign, CopyAssignUnsafe, Destructor, DestructorUnsafe, MoveAssign, MoveAssignUnsafe,
CopyAssign, CopyAssignUnsafe, Destructible, DestructibleUnsafe, MoveAssign, MoveAssignUnsafe,
MoveCtor, MoveCtorUnsafe,
};
use crate::rc::{AsPointer, Ptr, Value};
Expand Down Expand Up @@ -138,14 +138,14 @@ trivial!(Trivial, Ptr<T>, HasNone,
HasMoveCtor: MoveCtor for &&&&&Trivial<'_, T>,
HasMoveAssign: MoveAssign for &&&&Trivial<'_, T>,
HasCopyAssign: CopyAssign for &&&Trivial<'_, T>,
HasDestructor: Destructor for &&Trivial<'_, T>
HasDestructor: Destructible for &&Trivial<'_, T>
);

trivial!(TrivialUnsafe, *mut T, HasNoneUnsafe,
HasMoveCtorUnsafe: MoveCtorUnsafe for &&&&&TrivialUnsafe<'_, T>,
HasMoveAssignUnsafe: MoveAssignUnsafe for &&&&TrivialUnsafe<'_, T>,
HasCopyAssignUnsafe: CopyAssignUnsafe for &&&TrivialUnsafe<'_, T>,
HasDestructorUnsafe: DestructorUnsafe for &&TrivialUnsafe<'_, T>
HasDestructorUnsafe: DestructibleUnsafe for &&TrivialUnsafe<'_, T>
);

#[cold]
Expand Down Expand Up @@ -282,7 +282,7 @@ pub trait DestroyNone {
fn destroy(self);
}

impl<T: Destructor> DestroyWithDtor for &&Destroy<'_, T> {
impl<T: Destructible> DestroyWithDtor for &&Destroy<'_, T> {
fn destroy(self) {
T::destroy(self.0.clone())
}
Expand Down Expand Up @@ -386,7 +386,7 @@ pub trait DestroyNoneUnsafe {
unsafe fn destroy(self);
}

impl<T: DestructorUnsafe> DestroyWithDtorUnsafe for &&DestroyUnsafe<T> {
impl<T: DestructibleUnsafe> DestroyWithDtorUnsafe for &&DestroyUnsafe<T> {
unsafe fn destroy(self) {
unsafe { T::destroy(self.0) }
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ thread_local!(
thread_local!(
pub static useCount_3: Value<i32> = Rc::new(RefCell::new(0));
);
#[derive(Record, ByteRepr, VaArg, FnPtrArg, CopyAssign, Destructor)]
#[derive(Record, ByteRepr, VaArg, FnPtrArg, CopyAssign, Destructible)]
#[byte_size(4)]
pub struct LifetimeTracked {
#[offset(0)]
Expand Down Expand Up @@ -67,7 +67,7 @@ impl Default for LifetimeTracked {
{ LifetimeTracked::new() }
}
}
#[derive(Clone, Record, ByteRepr, VaArg, FnPtrArg, Destructor, Default)]
#[derive(Clone, Record, ByteRepr, VaArg, FnPtrArg, Destructible, Default)]
#[byte_size(4)]
pub struct AssertsDtorCountAtExit {
#[offset(0)]
Expand All @@ -77,7 +77,7 @@ thread_local!(
pub static check_4: Value<AssertsDtorCountAtExit> = {
let __static = Rc::new(RefCell::new(AssertsDtorCountAtExit { expected: 2 }));
libcc2rs::register_static_destructor(|| {
check_4.with(Value::clone).as_pointer().destructor()
Destructible::destroy(check_4.with(Value::clone).as_pointer())
});
__static
};
Expand All @@ -86,7 +86,7 @@ thread_local!(
pub static shared_5: Value<LifetimeTracked> = {
let __static = Rc::new(RefCell::new(LifetimeTracked::new()));
libcc2rs::register_static_destructor(|| {
shared_5.with(Value::clone).as_pointer().destructor()
Destructible::destroy(shared_5.with(Value::clone).as_pointer())
});
__static
};
Expand All @@ -103,7 +103,7 @@ thread_local!(
static local_6: Value<LifetimeTracked> = {
let __static = Rc::new(RefCell::new(LifetimeTracked::new()));
libcc2rs::register_static_destructor(|| {
local_6.with(Value::clone).as_pointer().destructor()
Destructible::destroy(local_6.with(Value::clone).as_pointer())
});
__static
};
Expand Down
Loading
Loading