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
40 changes: 39 additions & 1 deletion cpp2rust/converter/converter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3798,8 +3798,39 @@ Converter::GetOverloadedFunctionName(const clang::FunctionDecl *decl) {
name += '_';
}

if (const auto *targs = decl->getTemplateSpecializationArgs()) {
std::vector<clang::TemplateArgument> args;
for (const auto &arg : targs->asArray()) {
if (arg.getKind() == clang::TemplateArgument::Pack) {
args.insert(args.end(), arg.pack_begin(), arg.pack_end());
} else {
args.push_back(arg);
}
}
for (const auto &arg : args) {
name += '_';
switch (arg.getKind()) {
case clang::TemplateArgument::Type:
name += Mapper::ToRustName(
arg.getAsType().getCanonicalType().getAsString());
break;
case clang::TemplateArgument::Integral:
name += Mapper::ToRustName(
std::string(GetNumAsString(arg.getAsIntegral())));
break;
default:
name += "targ";
break;
}
}
}

auto pred = [](char ch) { return ch != ' ' && ch != '_'; };
name.erase(std::find_if(name.rbegin(), name.rend(), pred).base(), name.end());

if (decl->isVariadic()) {
name += "_va";
}
if (const auto *method = clang::dyn_cast<clang::CXXMethodDecl>(decl)) {
if (method->isConst()) {
name += "_const";
Expand All @@ -3819,6 +3850,9 @@ Converter::GetOverloadedFunctionName(const clang::FunctionDecl *decl) {
}
}

ReplaceAll(name, "[", "arr");
ReplaceAll(name, "]", "arr");
ReplaceAll(name, ";", "_");
name.erase(std::remove_if(name.begin(), name.end(),
[](char c) {
return c == '<' || c == '>' || c == ' ' ||
Expand Down Expand Up @@ -4111,15 +4145,19 @@ void Converter::ConvertCXXMethodDecls(
const clang::CXXRecordDecl *decl, const std::string_view signature,
bool (*predicate)(clang::CXXMethodDecl *)) {
bool first = true;
for (auto *method : decl->methods()) {
auto convert_method = [&](clang::CXXMethodDecl *method) {
if (predicate(method)) {
if (first) {
StrCat(signature, token::kOpenCurlyBracket);
first = false;
}
VisitCXXMethodDecl(method);
}
};
for (auto *method : decl->methods()) {
convert_method(method);
}
ForEachTemplateInstantiatedMethod(decl, convert_method);
if (!first) {
StrCat(token::kCloseCurlyBracket);
}
Expand Down
28 changes: 28 additions & 0 deletions cpp2rust/converter/converter_lib.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@

#include "converter/converter_lib.h"

#include <clang/AST/DeclTemplate.h>
#include <clang/AST/ExprCXX.h>
#include <clang/AST/Mangle.h>
#include <clang/AST/ParentMapContext.h>
#include <clang/Basic/SourceManager.h>
#include <llvm/Support/Path.h>
#include <llvm/Support/raw_ostream.h>

#include <algorithm>
#include <array>
Expand Down Expand Up @@ -249,7 +251,28 @@ bool IsOverloadedFunction(const clang::FunctionDecl *decl) {
return !lookup_result.isSingleResult();
}

void ForEachTemplateInstantiatedMethod(
const clang::CXXRecordDecl *decl,
llvm::function_ref<void(clang::CXXMethodDecl *)> fn) {
for (auto d : decl->decls()) {
if (auto function_template_decl =
llvm::dyn_cast<clang::FunctionTemplateDecl>(d)) {
for (auto s : function_template_decl->specializations()) {
if (auto m = clang::dyn_cast<clang::CXXMethodDecl>(s);
m && !clang::isa<clang::CXXConstructorDecl>(m) &&
m->getDefinition()) {
fn(m);
}
}
}
}
}

bool IsOverloadedMethod(const clang::CXXMethodDecl *decl) {
if (decl->getTemplateSpecializationArgs() != nullptr &&
IsUserDefinedDecl(decl)) {
return true;
}
const auto method_name = decl->getNameAsString();
const auto *record = decl->getParent();
return std::count_if(record->method_begin(), record->method_end(),
Expand Down Expand Up @@ -502,6 +525,11 @@ static std::string GetParamSignature(const clang::Decl *decl) {
for (unsigned i = 0; i < fdecl->getNumParams(); ++i) {
args += fdecl->getParamDecl(i)->getType().getAsString();
}
if (const auto *targs = fdecl->getTemplateSpecializationArgs()) {
llvm::raw_string_ostream os(args);
clang::printTemplateArgumentList(
os, targs->asArray(), fdecl->getASTContext().getPrintingPolicy());
}
}
return args;
}
Expand Down
5 changes: 5 additions & 0 deletions cpp2rust/converter/converter_lib.h
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
#include <clang/AST/Expr.h>
#include <clang/AST/StmtCXX.h>
#include <clang/AST/Type.h>
#include <llvm/ADT/STLFunctionalExtras.h>

#include <optional>
#include <string>
Expand Down Expand Up @@ -61,6 +62,10 @@ bool IsMutatingCall(const clang::CallExpr *expr);

bool IsOverloadedFunction(const clang::FunctionDecl *decl);

void ForEachTemplateInstantiatedMethod(
const clang::CXXRecordDecl *decl,
llvm::function_ref<void(clang::CXXMethodDecl *)> fn);

bool IsOverloadedMethod(const clang::CXXMethodDecl *decl);

bool IsUserDefinedCopyConstructor(const clang::CXXConstructorDecl *ctor);
Expand Down
16 changes: 11 additions & 5 deletions cpp2rust/converter/mapper.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
#include <clang/Lex/Lexer.h>
#include <llvm/Support/ThreadPool.h>

#include <cctype>
#include <cstdlib>
#include <format>
#include <optional>
Expand Down Expand Up @@ -828,12 +829,17 @@ void AddRuleForUserDefinedType(clang::NamedDecl *decl) {
}

std::string ToRustName(std::string name) {
size_t pos = 0;
while ((pos = name.find_first_of("<>, ", pos)) != std::string::npos) {
name[pos] = '_';
++pos;
}
ReplaceAll(name, "::", "_");
ReplaceAll(name, "*", "ptr");
ReplaceAll(name, "&", "ref");
ReplaceAll(name, "[", "arr");
ReplaceAll(name, "]", "arr");
ReplaceAll(name, "-", "neg");
for (auto &c : name) {
if (!std::isalnum(c) && c != '_') {
c = '_';
}
}
return name;
}

Expand Down
12 changes: 10 additions & 2 deletions cpp2rust/converter/models/converter_refcount.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2734,12 +2734,16 @@ void ConverterRefCount::ConvertLateInstantiatedMethods(
!IsMethodOnPtr(method) &&
!decl_ids_.contains(GetMethodID(method));
});
for (auto *method : decl->methods()) {
auto convert_method = [&](clang::CXXMethodDecl *method) {
if (IsEmittableMethod(method) && method->hasBody() &&
IsMethodOnPtr(method) && !decl_ids_.contains(GetMethodID(method))) {
ConvertMethodOnPtr(method);
}
};
for (auto *method : decl->methods()) {
convert_method(method);
}
ForEachTemplateInstantiatedMethod(decl, convert_method);
}

void ConverterRefCount::ConvertCXXRecordMethods(clang::CXXRecordDecl *decl) {
Expand All @@ -2751,11 +2755,15 @@ void ConverterRefCount::ConvertCXXRecordMethods(clang::CXXRecordDecl *decl) {
!IsMethodOnPtr(method);
});

for (auto *method : decl->methods()) {
auto convert_method = [&](clang::CXXMethodDecl *method) {
if (IsMethodOnPtr(method) && method->getDefinition()) {
ConvertMethodOnPtr(method);
}
};
for (auto *method : decl->methods()) {
convert_method(method);
}
ForEachTemplateInstantiatedMethod(decl, convert_method);

if (!GetUserDefinedDestructor(decl) && HasFieldsNeedingDestruction(decl)) {
MethodsOnPtrFor(decl).trait_body +=
Expand Down
127 changes: 127 additions & 0 deletions tests/unit/out/refcount/overload_mangling.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
extern crate libcc2rs;
use libcc2rs::*;
use std::cell::RefCell;
use std::collections::BTreeMap;
use std::io::prelude::*;
use std::io::{Read, Seek, Write};
use std::os::fd::AsFd;
use std::rc::{Rc, Weak};
#[derive(Default)]
pub struct S {
pub base: Value<i32>,
}
impl Clone for S {
fn clone(&self) -> Self {
let __this: Value<S> = Rc::new(RefCell::new(Self {
base: Rc::new(RefCell::new((*self.base.borrow()))),
}));
let this: Ptr<S> = __this.as_pointer();
Rc::try_unwrap(__this).ok().unwrap().into_inner()
}
}
impl ByteRepr for S {
fn byte_size() -> usize {
4
}
fn to_bytes(&self, buf: &mut [u8]) {
(*self.base.borrow()).to_bytes(&mut buf[0..4]);
}
fn from_bytes(buf: &[u8]) -> Self {
Self {
base: Rc::new(RefCell::new(<i32>::from_bytes(&buf[0..4]))),
}
}
}
#[derive(Default)]
pub struct Box {
pub v: Value<i32>,
}
impl Clone for Box {
fn clone(&self) -> Self {
let __this: Value<Box> = Rc::new(RefCell::new(Self {
v: Rc::new(RefCell::new((*self.v.borrow()))),
}));
let this: Ptr<Box> = __this.as_pointer();
Rc::try_unwrap(__this).ok().unwrap().into_inner()
}
}
impl ByteRepr for Box {
fn byte_size() -> usize {
4
}
fn to_bytes(&self, buf: &mut [u8]) {
(*self.v.borrow()).to_bytes(&mut buf[0..4]);
}
fn from_bytes(buf: &[u8]) -> Self {
Self {
v: Rc::new(RefCell::new(<i32>::from_bytes(&buf[0..4]))),
}
}
}
pub fn main() {
std::process::exit(main_0());
}
fn main_0() -> i32 {
let s: Value<S> = Rc::new(RefCell::new(S {
base: Rc::new(RefCell::new(100)),
}));
assert!((({ SImpl::width_i32__char_const(&s.as_pointer(), 3,) }) == 103));
assert!((({ SImpl::width_i32__int_const(&s.as_pointer(), 3,) }) == 112));
assert!((({ SImpl::scale_i32__2_const(&s.as_pointer(), 5,) }) == 110));
assert!((({ SImpl::scale_i32__3_const(&s.as_pointer(), 5,) }) == 115));
assert!((({ SImpl::count_i32_const(&s.as_pointer(), 1,) }) == 101));
assert!((({ SImpl::count_i32__int_long_const(&s.as_pointer(), 1,) }) == 103));
assert!((({ SImpl::plain_i32_const(&s.as_pointer(), 1,) }) == 101));
assert!((({ SImpl::plain_i64_const(&s.as_pointer(), 1_i64,) }) == 102));
let b: Value<Box> = Rc::new(RefCell::new(Box {
v: Rc::new(RefCell::new(4)),
}));
assert!(((*(*b.borrow()).v.borrow()) == 4));
return 0;
}
pub trait SImpl {
fn plain_i32_const(&self, x: i32) -> i32;
fn plain_i64_const(&self, x: i64) -> i32;
fn width_i32__char_const(&self, x: i32) -> i32;
fn width_i32__int_const(&self, x: i32) -> i32;
fn scale_i32__2_const(&self, x: i32) -> i32;
fn scale_i32__3_const(&self, x: i32) -> i32;
fn count_i32_const(&self, x: i32) -> i32;
fn count_i32__int_long_const(&self, x: i32) -> i32;
}
impl SImpl for Ptr<S> {
fn plain_i32_const(&self, x: i32) -> i32 {
let x: Value<i32> = Rc::new(RefCell::new(x));
return ((*(*(*self).upgrade().deref()).base.borrow()) + (*x.borrow()));
}
fn plain_i64_const(&self, x: i64) -> i32 {
let x: Value<i64> = Rc::new(RefCell::new(x));
return (((*(*(*self).upgrade().deref()).base.borrow()) + ((*x.borrow()) as i32)) + 1);
}
fn width_i32__char_const(&self, x: i32) -> i32 {
let x: Value<i32> = Rc::new(RefCell::new(x));
return ((*(*(*self).upgrade().deref()).base.borrow())
+ ((*x.borrow()) * (::std::mem::size_of::<u8>() as i32)));
}
fn width_i32__int_const(&self, x: i32) -> i32 {
let x: Value<i32> = Rc::new(RefCell::new(x));
return ((*(*(*self).upgrade().deref()).base.borrow())
+ ((*x.borrow()) * (::std::mem::size_of::<i32>() as i32)));
}
fn scale_i32__2_const(&self, x: i32) -> i32 {
let x: Value<i32> = Rc::new(RefCell::new(x));
return ((*(*(*self).upgrade().deref()).base.borrow()) + ((*x.borrow()) * 2));
}
fn scale_i32__3_const(&self, x: i32) -> i32 {
let x: Value<i32> = Rc::new(RefCell::new(x));
return ((*(*(*self).upgrade().deref()).base.borrow()) + ((*x.borrow()) * 3));
}
fn count_i32_const(&self, x: i32) -> i32 {
let x: Value<i32> = Rc::new(RefCell::new(x));
return (((*(*(*self).upgrade().deref()).base.borrow()) + (*x.borrow())) + (0 as i32));
}
fn count_i32__int_long_const(&self, x: i32) -> i32 {
let x: Value<i32> = Rc::new(RefCell::new(x));
return (((*(*(*self).upgrade().deref()).base.borrow()) + (*x.borrow())) + (2 as i32));
}
}
Loading
Loading