Skip to content

Commit da6c836

Browse files
committed
Print float literals at full precision
1 parent f467a98 commit da6c836

2 files changed

Lines changed: 20 additions & 1 deletion

File tree

‎cpp2rust/converter/converter.cpp‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2329,7 +2329,19 @@ bool Converter::VisitIntegerLiteral(clang::IntegerLiteral *expr) {
23292329
}
23302330

23312331
bool Converter::VisitFloatingLiteral(clang::FloatingLiteral *expr) {
2332-
StrCat(GetNumAsString(expr->getValue()));
2332+
auto value = expr->getValue();
2333+
if (&value.getSemantics() != &llvm::APFloat::IEEEsingle()) {
2334+
bool loses_info = false;
2335+
value.convert(llvm::APFloat::IEEEdouble(),
2336+
llvm::APFloat::rmNearestTiesToEven, &loses_info);
2337+
}
2338+
llvm::SmallString<32> str;
2339+
if (value.isInfinity()) {
2340+
str = "f64::INFINITY";
2341+
} else {
2342+
value.toString(str, /*FormatPrecision=*/0, /*FormatMaxPadding=*/0);
2343+
}
2344+
StrCat(str);
23332345
computed_expr_type_ = ComputedExprType::FreshValue;
23342346
return false;
23352347
}

‎tests/unit/types.cpp‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// ADDITIONAL_COMPILE_FLAGS: -std=c++23
22

33
#include <cassert>
4+
#include <cfloat>
45
#include <cstddef>
56
#include <cstdint>
67
#include <inttypes.h>
@@ -25,6 +26,12 @@ int main() {
2526
std::nullptr_t xnp = nullptr;
2627
assert(xu8 + xu16 + xu32 + xu64 + xsz1 + xsz2 + xi1 + xi2 + xi3 + xi4 == 352);
2728
assert(xld * 2 == 3);
29+
double pi = 3.14159265358979;
30+
assert(pi < 3.141592654);
31+
double dmax = -DBL_MAX;
32+
assert(dmax < -1e308);
33+
long double ldmax = LDBL_MAX;
34+
assert(ldmax > DBL_MAX);
2835
assert(xwc + xc8 + xc16 + xc32 == 266);
2936
assert(xnp == nullptr);
3037
return 0;

0 commit comments

Comments
 (0)