translate-c: preserve zero fractional part in float literals

This commit is contained in:
Veikka Tuominen 2021-03-17 11:32:11 +02:00
parent 7c6eb41619
commit ac7217e1f5
3 changed files with 21 additions and 10 deletions

View File

@ -3248,11 +3248,11 @@ fn transFloatingLiteral(c: *Context, scope: *Scope, stmt: *const clang.FloatingL
var dbl = stmt.getValueAsApproximateDouble();
const is_negative = dbl < 0;
if (is_negative) dbl = -dbl;
const str = try std.fmt.allocPrint(c.arena, "{d}", .{dbl});
var node = if (dbl == std.math.floor(dbl))
try Tag.integer_literal.create(c.arena, str)
const str = if (dbl == std.math.floor(dbl))
try std.fmt.allocPrint(c.arena, "{d}.0", .{dbl})
else
try Tag.float_literal.create(c.arena, str);
try std.fmt.allocPrint(c.arena, "{d}", .{dbl});
var node = try Tag.float_literal.create(c.arena, str);
if (is_negative) node = try Tag.negate.create(c.arena, node);
return maybeSuppressResult(c, scope, used, node);
}

View File

@ -3,6 +3,17 @@ const tests = @import("tests.zig");
const nl = std.cstr.line_sep;
pub fn addCases(cases: *tests.RunTranslatedCContext) void {
cases.add("division of floating literals",
\\#define _NO_CRT_STDIO_INLINE 1
\\#include <stdio.h>
\\#define PI 3.14159265358979323846f
\\#define DEG2RAD (PI/180.0f)
\\int main(void) {
\\ printf("DEG2RAD is: %f\n", DEG2RAD);
\\ return 0;
\\}
, "DEG2RAD is: 0.017453" ++ nl);
cases.add("use global scope for record/enum/typedef type transalation if needed",
\\void bar(void);
\\void baz(void);

View File

@ -2428,7 +2428,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void {
\\ b: c_int,
\\};
\\pub extern var a: struct_Foo;
\\pub export var b: f32 = 2;
\\pub export var b: f32 = 2.0;
\\pub export fn foo() void {
\\ var c: [*c]struct_Foo = undefined;
\\ _ = a.b;
@ -2992,17 +2992,17 @@ pub fn addCases(cases: *tests.TranslateCContext) void {
\\pub extern fn fn_bool(x: bool) void;
\\pub extern fn fn_ptr(x: ?*c_void) void;
\\pub export fn call() void {
\\ fn_int(@floatToInt(c_int, 3));
\\ fn_int(@floatToInt(c_int, 3));
\\ fn_int(@floatToInt(c_int, 3));
\\ fn_int(@floatToInt(c_int, 3.0));
\\ fn_int(@floatToInt(c_int, 3.0));
\\ fn_int(@floatToInt(c_int, 3.0));
\\ fn_int(@as(c_int, 1094861636));
\\ fn_f32(@intToFloat(f32, @as(c_int, 3)));
\\ fn_f64(@intToFloat(f64, @as(c_int, 3)));
\\ fn_char(@bitCast(u8, @truncate(i8, @as(c_int, '3'))));
\\ fn_char(@bitCast(u8, @truncate(i8, @as(c_int, '\x01'))));
\\ fn_char(@bitCast(u8, @truncate(i8, @as(c_int, 0))));
\\ fn_f32(3);
\\ fn_f64(3);
\\ fn_f32(3.0);
\\ fn_f64(3.0);
\\ fn_bool(@as(c_int, 123) != 0);
\\ fn_bool(@as(c_int, 0) != 0);
\\ fn_bool(@ptrToInt(fn_int) != 0);