@@ -596,13 +596,22 @@ bool Converter::ConvertVarDeclSkipInit(clang::VarDecl *decl) {
596596}
597597
598598void Converter::ConvertVarDeclInitializer (clang::VarDecl *decl) {
599+ bool registers_destructor = NeedsStaticDestructor (decl);
600+ if (registers_destructor) {
601+ StrCat (" { let __static = " );
602+ }
599603 if (decl->hasInit ()) {
600604 ScopedValue constant (constant_evaluated_,
601605 HasConstantEvaluatedInit (ctx_, decl));
602606 ConvertVarInit (decl->getType (), decl->getInit ());
603607 } else if (!clang::isa<clang::ParmVarDecl>(decl)) {
604608 StrCat (ConvertVarDefaultInit (decl));
605609 }
610+ if (registers_destructor) {
611+ StrCat (std::format (
612+ " ; libcc2rs::register_static_destructor(|| {}); __static }}" ,
613+ StaticDestructorCall (decl)));
614+ }
606615}
607616
608617void Converter::EmitHoistedInArmAssignment (clang::VarDecl *decl) {
@@ -701,7 +710,14 @@ bool Converter::NeedsScopedDestructor(const clang::VarDecl *decl) const {
701710 if (in_function_formals_ || !decl->isLocalVarDecl () || IsGlobalVar (decl)) {
702711 return false ;
703712 }
704- auto type = decl->getType ();
713+ return VarTypeNeedsDestructor (decl->getType ());
714+ }
715+
716+ bool Converter::NeedsStaticDestructor (const clang::VarDecl *decl) const {
717+ return IsGlobalVar (decl) && VarTypeNeedsDestructor (decl->getType ());
718+ }
719+
720+ bool Converter::VarTypeNeedsDestructor (clang::QualType type) const {
705721 if (auto lambda = AsLambdaClass (type);
706722 lambda && LambdaNeedsDestruction (lambda)) {
707723 return true ;
@@ -710,6 +726,13 @@ bool Converter::NeedsScopedDestructor(const clang::VarDecl *decl) const {
710726 TypeNeedsDestruction (type);
711727}
712728
729+ std::string Converter::StaticDestructorCall (const clang::VarDecl *decl) {
730+ auto destroy = AsLambdaClass (decl->getType ()) ? " destroy" : kDestructorName ;
731+ return std::format (
732+ " (*std::cell::LazyCell::force_mut(&mut *&raw mut {})).{}()" ,
733+ GetNamedDeclAsString (decl), destroy);
734+ }
735+
713736void Converter::EmitScopedDestructor (const clang::VarDecl *decl) {
714737 if (!NeedsScopedDestructor (decl)) {
715738 return ;
@@ -4829,13 +4852,13 @@ pub fn main() {{
48294852 argv.push(::std::ptr::null_mut());
48304853 unsafe {{
48314854 __cpp2rust_init_globals();
4832- ::std::process::exit (main_0((argv.len() - 1) as i32, argv.as_mut_ptr()) as i32)
4855+ libcc2rs::cpp2rust_exit (main_0((argv.len() - 1) as i32, argv.as_mut_ptr()) as i32)
48334856 }}
48344857}})" ,
48354858 main_function_name));
48364859 } else {
48374860 StrCat (std::format (" pub fn main() {{ unsafe {{ __cpp2rust_init_globals(); "
4838- " std::process::exit ({}() as i32); }} }}" ,
4861+ " libcc2rs::cpp2rust_exit ({}() as i32); }} }}" ,
48394862 main_function_name));
48404863 }
48414864}
0 commit comments