Skip to content

Commit 30bef9e

Browse files
committed
Translate only the taken branch of constant if conditions
1 parent f467a98 commit 30bef9e

2 files changed

Lines changed: 19 additions & 6 deletions

File tree

‎cpp2rust/converter/converter.cpp‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1382,13 +1382,15 @@ bool Converter::VisitIfStmt(clang::IfStmt *stmt) {
13821382
stmt->setInit(init);
13831383
return false;
13841384
}
1385-
StrCat(keyword::kIf);
1386-
if (auto *cond = clang::dyn_cast<clang::ConstantExpr>(stmt->getCond());
1387-
cond && stmt->isConstexpr()) {
1388-
StrCat(cond->getResultAsAPSInt() != 0 ? keyword::kTrue : keyword::kFalse);
1389-
} else {
1390-
ConvertCondition(stmt->getCond());
1385+
if (bool taken = false;
1386+
!stmt->getConditionVariable() && !stmt->isConsteval() &&
1387+
!stmt->getCond()->isValueDependent() &&
1388+
stmt->getCond()->EvaluateAsBooleanCondition(taken, ctx_)) {
1389+
ConvertBody(taken ? stmt->getThen() : stmt->getElse());
1390+
return false;
13911391
}
1392+
StrCat(keyword::kIf);
1393+
ConvertCondition(stmt->getCond());
13921394
ConvertBody(stmt->getThen());
13931395
if (stmt->hasElseStorage()) {
13941396
StrCat(keyword::kElse);

‎tests/unit/if_constexpr.cpp‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,22 @@ int keep_both(int x) {
1818
}
1919
}
2020

21+
template <typename T> unsigned long long widen(T v) {
22+
if (sizeof(T) > 4) {
23+
T hi = v;
24+
hi <<= 32;
25+
return hi;
26+
}
27+
return v;
28+
}
29+
2130
int main() {
2231
int v = 7;
2332
assert(classify(&v) == 7);
2433
assert(classify(1L) == 2);
2534
assert(classify(1) == 1);
2635
assert(keep_both(1) == 2);
36+
assert(widen(1u) == 1);
37+
assert(widen(1ull) == 4294967296ull);
2738
return 0;
2839
}

0 commit comments

Comments
 (0)