Skip to content

Commit bda8fa9

Browse files
committed
Code optimizations
1 parent abea5bf commit bda8fa9

3 files changed

Lines changed: 87 additions & 87 deletions

File tree

cpp2rust/converter/converter.cpp

Lines changed: 74 additions & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -194,24 +194,22 @@ std::string Converter::ConvertFreshRValue(clang::Expr *expr) {
194194
std::pair<std::string, std::string>
195195
Converter::MaterializeTemp(const std::string &binding_name,
196196
clang::QualType param_type, clang::Expr *expr) {
197-
auto value = ConvertRValue(expr);
198-
std::string binding = std::format("let mut {} = {} ;", binding_name, value);
199-
std::string ref = std::format("& mut {}", binding_name);
200-
return {binding, ref};
197+
return {std::format("let mut {} = {} ;", binding_name, ConvertRValue(expr)),
198+
std::format("& mut {}", binding_name)};
201199
}
202200

203201
bool Converter::VisitConstantArrayType(clang::ConstantArrayType *type) {
204-
StrCat("[");
202+
StrCat('[');
205203
Convert(type->getElementType());
206204
auto size = GetNumAsString(type->getSize());
207205
StrCat(std::format("; {}]", size.c_str()));
208206
return false;
209207
}
210208

211209
bool Converter::VisitIncompleteArrayType(clang::IncompleteArrayType *type) {
212-
StrCat("[");
210+
StrCat('[');
213211
Convert(type->getElementType());
214-
StrCat("]");
212+
StrCat(']');
215213
return false;
216214
}
217215

@@ -228,9 +226,10 @@ Converter::ConvertFunctionPointerType(const clang::FunctionProtoType *proto,
228226
std::string result =
229227
(kind == FnProtoType::LambdaCallOperator ? "impl Fn(" : "fn(");
230228
for (auto p_ty : proto->param_types()) {
231-
result += ToString(p_ty) + ",";
229+
result += ToString(p_ty);
230+
result += ',';
232231
}
233-
result += ")";
232+
result += ')';
234233
if (!proto->getReturnType()->isVoidType()) {
235234
result += std::format(" -> {}", ToString(proto->getReturnType()));
236235
}
@@ -420,7 +419,7 @@ bool Converter::ConvertVarDeclSkipInit(clang::VarDecl *decl) {
420419
}
421420
Convert(qual_type);
422421
if (is_parm_with_default_value) {
423-
StrCat(">");
422+
StrCat('>');
424423
}
425424
return true;
426425
}
@@ -635,7 +634,7 @@ void Converter::EmitRustStructOrUnion(clang::RecordDecl *decl) {
635634
}
636635
StrCat("#[derive(");
637636
for (auto *attr : GetStructAttributes(decl)) {
638-
StrCat(attr, ",");
637+
StrCat(attr, ',');
639638
}
640639
StrCat(")]");
641640

@@ -658,7 +657,7 @@ void Converter::EmitRustStructOrUnion(clang::RecordDecl *decl) {
658657

659658
ConvertCXXMethodDecls(
660659
cxx, std::format("{} {}", keyword::kImpl, struct_name),
661-
[](const auto *method) {
660+
[](auto *method) {
662661
return !method->isImplicit() &&
663662
!(method->getDefinition() &&
664663
method->getDefinition()->isDefaulted()) &&
@@ -674,7 +673,7 @@ void Converter::EmitRustStructOrUnion(clang::RecordDecl *decl) {
674673
std::format("{} impl {} for {}", keyword_unsafe_,
675674
GetUnsafeTypeAsString(cxx->bases_begin()->getType()),
676675
struct_name),
677-
[](const auto *method) {
676+
[](auto *method) {
678677
return !method->isImplicit() && method->isVirtual();
679678
});
680679
}
@@ -1250,7 +1249,7 @@ bool Converter::GetFmtArg(clang::Expr *arg, std::string &fmt,
12501249

12511250
bool Converter::GetRawArg(clang::Expr *arg, std::string &raw_args) {
12521251
if (arg->getType()->isCharType()) {
1253-
raw_args += "(&[" + ToString(arg) + "]";
1252+
raw_args += "(&[" + ToString(arg) + ']';
12541253
} else if (Mapper::Map(arg->getType()) == "Vec<u8>") {
12551254
PushExprKind push(*this, ExprKind::RValue);
12561255
std::string str = ToString(arg);
@@ -1316,7 +1315,7 @@ void Converter::ConvertCallToOstream(clang::CallExpr *expr) {
13161315

13171316
auto write_fmt_args = [&]() {
13181317
if (!fmt_args.empty() || !fmt.empty()) {
1319-
StrCat("write!(", stream_str, ",",
1318+
StrCat("write!(", stream_str, ',',
13201319
std::format(R"("{}",)", std::move(fmt)), std::move(fmt_args),
13211320
");");
13221321
fmt_args.clear();
@@ -1352,7 +1351,7 @@ void Converter::ConvertPrintf(clang::CallExpr *expr) {
13521351
}
13531352
StrCat(token::kComma);
13541353
}
1355-
StrCat(")");
1354+
StrCat(')');
13561355
}
13571356

13581357
std::optional<std::string> Converter::TryPluginConvert(clang::CallExpr *call) {
@@ -1374,7 +1373,7 @@ void Converter::ConvertVAArgCall(clang::CallExpr *expr) {
13741373
return;
13751374
}
13761375
if (IsBuiltinVaCopy(expr)) {
1377-
StrCat(ToString(expr->getArg(0)->IgnoreImpCasts()), "=",
1376+
StrCat(ToString(expr->getArg(0)->IgnoreImpCasts()), '=',
13781377
ToString(expr->getArg(1)->IgnoreImpCasts()), ".clone()");
13791378
return;
13801379
}
@@ -1395,15 +1394,16 @@ bool Converter::VisitCallExpr(clang::CallExpr *expr) {
13951394
auto **args = expr->getArgs();
13961395
auto num_args = expr->getNumArgs();
13971396
auto ctx = CollectPrvalueToLRefArgs(expr);
1398-
auto str = [&] {
1397+
std::string str;
1398+
{
13991399
PushExprKind push(*this, ExprKind::RValue);
1400-
return GetMappedAsString(expr, args, num_args, &ctx);
1401-
}();
1400+
str = GetMappedAsString(expr, args, num_args, &ctx);
1401+
};
14021402

14031403
if ((IsReferenceType(expr) ||
14041404
GetReturnTypeOfFunction(expr)->isReferenceType()) &&
14051405
!isAddrOf() && !isVoid()) {
1406-
str = "( * " + str + " )";
1406+
str = "( * " + std::move(str) + " )";
14071407
}
14081408

14091409
if (!ctx.temporary_bindings.empty()) {
@@ -1562,7 +1562,7 @@ void Converter::ConvertGenericCallExpr(clang::CallExpr *expr) {
15621562
StrCat(std::format("_{}", param_name));
15631563
}
15641564
if (is_parm_with_default_value) {
1565-
StrCat(")");
1565+
StrCat(')');
15661566
}
15671567
StrCat(token::kComma);
15681568
}
@@ -1575,7 +1575,7 @@ void Converter::ConvertGenericCallExpr(clang::CallExpr *expr) {
15751575
Convert(arg);
15761576
StrCat(".into()", token::kComma);
15771577
}
1578-
StrCat("]");
1578+
StrCat(']');
15791579
}
15801580
}
15811581
}
@@ -1596,8 +1596,7 @@ Converter::ConvertCallExpr(clang::CallExpr *expr) {
15961596
auto **args = expr->getArgs();
15971597
auto num_args = expr->getNumArgs();
15981598
auto ctx = CollectPrvalueToLRefArgs(expr);
1599-
auto mapped = GetMappedAsString(expr, args, num_args, &ctx);
1600-
StrCat(mapped);
1599+
StrCat(GetMappedAsString(expr, args, num_args, &ctx));
16011600
return ctx;
16021601
} else if (auto *opcall = clang::dyn_cast<clang::CXXOperatorCallExpr>(expr)) {
16031602
ConvertCXXOperatorCallExpr(opcall);
@@ -1884,11 +1883,11 @@ bool Converter::VisitExplicitCastExpr(clang::ExplicitCastExpr *expr) {
18841883
sub_expr->getType()->isFunctionPointerType()) {
18851884
StrCat("std::mem::transmute::<");
18861885
Convert(sub_expr->getType());
1887-
StrCat(",");
1886+
StrCat(',');
18881887
Convert(type);
18891888
StrCat(">(");
18901889
Convert(sub_expr);
1891-
StrCat(")");
1890+
StrCat(')');
18921891
return false;
18931892
}
18941893
{
@@ -2086,8 +2085,8 @@ bool Converter::ConvertIncAndDec(clang::UnaryOperator *expr) {
20862085
}
20872086

20882087
bool Converter::VisitUnaryOperator(clang::UnaryOperator *expr) {
2089-
if (Mapper::Contains(expr)) {
2090-
StrCat(GetMappedAsString(expr));
2088+
if (auto str = GetMappedAsString(expr); !str.empty()) {
2089+
StrCat(str);
20912090
return false;
20922091
}
20932092

@@ -2178,8 +2177,8 @@ bool Converter::VisitConditionalOperator(clang::ConditionalOperator *expr) {
21782177
std::string Converter::ConvertDeclRefExpr(clang::DeclRefExpr *expr) {
21792178
if (isAddrOf()) {
21802179
clang::Expr *addrof_op = ToAddrOf(ctx_, expr);
2181-
if (Mapper::Contains(addrof_op)) {
2182-
return GetMappedAsString(addrof_op);
2180+
if (auto str = GetMappedAsString(addrof_op); !str.empty()) {
2181+
return str;
21832182
}
21842183
}
21852184

@@ -2384,8 +2383,7 @@ bool Converter::VisitMemberExpr(clang::MemberExpr *expr) {
23842383
}
23852384

23862385
void Converter::ConvertMemberExpr(clang::MemberExpr *expr) {
2387-
if (Mapper::Contains(expr)) {
2388-
auto mapped = GetMappedAsString(expr);
2386+
if (auto mapped = GetMappedAsString(expr); !mapped.empty()) {
23892387
if (Mapper::ReturnsPointer(expr)) {
23902388
StrCat(token::kStar, mapped);
23912389
} else {
@@ -2607,7 +2605,7 @@ void Converter::ConvertCXXConstructExprArgs(clang::CXXConstructExpr *expr) {
26072605
if (has_default) {
26082606
StrCat("Some(");
26092607
ConvertVarInit(param_type, arg);
2610-
StrCat(")");
2608+
StrCat(')');
26112609
} else {
26122610
ConvertVarInit(param_type, arg);
26132611
}
@@ -2620,10 +2618,9 @@ void Converter::ConvertCXXConstructExprArgs(clang::CXXConstructExpr *expr) {
26202618
}
26212619

26222620
bool Converter::VisitCXXConstructExpr(clang::CXXConstructExpr *expr) {
2623-
if (Mapper::Contains(expr)) {
2624-
auto **args = expr->getArgs();
2625-
auto num_args = expr->getNumArgs();
2626-
StrCat(GetMappedAsString(expr, args, num_args));
2621+
if (auto str = GetMappedAsString(expr, expr->getArgs(), expr->getNumArgs());
2622+
!str.empty()) {
2623+
StrCat(str);
26272624
return false;
26282625
}
26292626

@@ -2956,8 +2953,8 @@ Converter::GetOverloadedFunctionName(const clang::FunctionDecl *decl) {
29562953
}
29572954

29582955
for (auto *parameter : decl->parameters()) {
2959-
auto type_as_string = GetUnsafeTypeAsString(parameter->getType());
2960-
name += type_as_string + "_";
2956+
name += GetUnsafeTypeAsString(parameter->getType());
2957+
name += '_';
29612958
}
29622959

29632960
auto pred = [](char ch) { return ch != ' ' && ch != '_'; };
@@ -2967,10 +2964,12 @@ Converter::GetOverloadedFunctionName(const clang::FunctionDecl *decl) {
29672964
name += "_const";
29682965
}
29692966

2970-
std::vector<char> tokens = {'<', '>', ' ', ':'};
2971-
for (auto token : tokens) {
2972-
name.erase(std::remove(name.begin(), name.end(), token), name.end());
2973-
}
2967+
name.erase(std::remove_if(name.begin(), name.end(),
2968+
[](char c) {
2969+
return c == '<' || c == '>' || c == ' ' ||
2970+
c == ':';
2971+
}),
2972+
name.end());
29742973
std::replace(name.begin(), name.end(), '*', 'p');
29752974

29762975
return name;
@@ -3077,7 +3076,7 @@ void Converter::ConvertUnsignedArithOperand(clang::Expr *expr,
30773076
}
30783077

30793078
void Converter::ConvertEqualsNullPtr(clang::Expr *expr) {
3080-
StrCat("(");
3079+
StrCat('(');
30813080
Convert(expr);
30823081
if (IsUniquePtr(expr->getType()) ||
30833082
expr->getType()->isFunctionPointerType()) {
@@ -3200,27 +3199,28 @@ void Converter::ConvertAbstractClass(clang::CXXRecordDecl *decl) {
32003199
auto access_specifier_as_string = AccessSpecifierAsString(decl->getAccess());
32013200
auto signature = std::format("{} {} trait {}", access_specifier_as_string,
32023201
keyword_unsafe_, trait_name);
3203-
auto predicate = [](const auto *method) {
3202+
auto predicate = [](auto *method) {
32043203
return !method->isImplicit() &&
32053204
!clang::isa<clang::CXXDestructorDecl>(method);
32063205
};
32073206
ConvertCXXMethodDecls(decl, signature, predicate);
32083207
}
32093208

3210-
template <typename Predicate>
3211-
void Converter::ConvertCXXMethodDecls(const clang::CXXRecordDecl *decl,
3212-
const std::string_view signature,
3213-
Predicate predicate) {
3214-
std::vector<clang::CXXMethodDecl *> methods;
3215-
std::copy_if(decl->method_begin(), decl->method_end(),
3216-
std::back_inserter(methods), predicate);
3217-
if (methods.empty()) {
3218-
return;
3209+
void Converter::ConvertCXXMethodDecls(
3210+
const clang::CXXRecordDecl *decl, const std::string_view signature,
3211+
bool (*predicate)(clang::CXXMethodDecl *)) {
3212+
bool first = true;
3213+
for (auto *method : decl->methods()) {
3214+
if (predicate(method)) {
3215+
if (first) {
3216+
StrCat(signature, token::kOpenCurlyBracket);
3217+
first = false;
3218+
}
3219+
VisitCXXMethodDecl(method);
3220+
}
32193221
}
3220-
StrCat(signature);
3221-
PushBrace brace(*this);
3222-
for (auto *method : methods) {
3223-
VisitCXXMethodDecl(method);
3222+
if (!first) {
3223+
StrCat(token::kCloseCurlyBracket);
32243224
}
32253225
}
32263226

@@ -3245,7 +3245,7 @@ void Converter::ConvertOrdAndPartialOrdTraitsBase(
32453245
StrCat(keyword::kImpl, "PartialEq for", record_name, "{");
32463246
StrCat("fn eq(&self, other: &Self) -> bool {");
32473247
StrCat(std::format("{} {{", keyword_unsafe_));
3248-
StrCat("!(", first_branch, ") && !(", second_branch, ")");
3248+
StrCat("!(", first_branch, ") && !(", second_branch, ')');
32493249
StrCat("}}}");
32503250

32513251
StrCat(keyword::kImpl, "Eq for", record_name, "{}");
@@ -3444,7 +3444,7 @@ void Converter::ConvertCast(clang::QualType qual_type) {
34443444

34453445
Converter::TempMaterializationCtx
34463446
Converter::CollectPrvalueToLRefArgs(clang::CallExpr *expr) {
3447-
TempMaterializationCtx ctx;
3447+
TempMaterializationCtx ctx(expr->getNumArgs());
34483448
if (auto *fn = expr->getCalleeDecl() ? expr->getCalleeDecl()->getAsFunction()
34493449
: nullptr) {
34503450
for (unsigned i = 0; i < expr->getNumArgs() && i < fn->getNumParams();
@@ -3459,26 +3459,26 @@ Converter::CollectPrvalueToLRefArgs(clang::CallExpr *expr) {
34593459
return ctx;
34603460
}
34613461

3462-
std::string Converter::TempMaterializationCtx::GetOrMaterialize(
3462+
const std::string &Converter::TempMaterializationCtx::GetOrMaterialize(
34633463
unsigned argument_num,
34643464
std::function<std::pair<std::string, std::string>(const std::string &,
34653465
clang::QualType)>
34663466
materialize_fn) {
3467-
if (auto it = materialized_refs_.find(argument_num);
3468-
it != materialized_refs_.end()) {
3469-
return it->second;
3467+
auto &str = materialized_refs_.at(argument_num);
3468+
if (!str.empty()) {
3469+
return str;
34703470
}
34713471

3472-
if (auto it = materialized_args.find(argument_num);
3473-
it != materialized_args.end()) {
3472+
if (auto m = materialized_args.at(argument_num)) {
34743473
auto [binding, ref] =
3475-
materialize_fn(std::format("__tmp_{}", argument_num), it->second);
3476-
temporary_bindings += binding;
3477-
materialized_refs_[argument_num] = ref;
3478-
return ref;
3474+
materialize_fn(std::format("__tmp_{}", argument_num), *m);
3475+
temporary_bindings += std::move(binding);
3476+
str = std::move(ref);
3477+
return str;
34793478
}
34803479

3481-
return "";
3480+
static const std::string empty_str;
3481+
return empty_str;
34823482
}
34833483

34843484
void Converter::PlaceholderCtx::dump() const {
@@ -3552,7 +3552,8 @@ std::string Converter::GetMappedAsString(clang::Expr *expr, clang::Expr **args,
35523552
unsigned num_args,
35533553
TempMaterializationCtx *ctx) {
35543554
auto *tgt_ir = Mapper::GetExprTgt(GetCalleeOrExpr(expr));
3555-
assert(tgt_ir && "GetExprTgt failed to find a translation rule");
3555+
if (!tgt_ir)
3556+
return {};
35563557

35573558
auto result = ConvertIRFragment(tgt_ir->body, expr, args, num_args, ctx);
35583559
if (tgt_ir->multi_statement) {

0 commit comments

Comments
 (0)