Skip to content

Commit f24f7e7

Browse files
riverblandrewrk
authored andcommitted
translate-c: Fix macro define of float constant using scientific notation
Fixes compiler attempting to use null value when translating macro define of float constant using scientific notation with no decimal point
1 parent ffe2b20 commit f24f7e7

File tree

2 files changed

+16
-10
lines changed

2 files changed

+16
-10
lines changed

src/translate_c.zig

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5602,16 +5602,18 @@ fn parseCNumLit(c: *Context, m: *MacroCtx) ParseError!Node {
56025602
},
56035603
.FloatLiteral => |suffix| {
56045604
if (suffix != .none) lit_bytes = lit_bytes[0 .. lit_bytes.len - 1];
5605-
const dot_index = mem.indexOfScalar(u8, lit_bytes, '.').?;
5606-
if (dot_index == 0) {
5607-
lit_bytes = try std.fmt.allocPrint(c.arena, "0{s}", .{lit_bytes});
5608-
} else if (dot_index + 1 == lit_bytes.len or !std.ascii.isDigit(lit_bytes[dot_index + 1])) {
5609-
// If the literal lacks a digit after the `.`, we need to
5610-
// add one since `1.` or `1.e10` would be invalid syntax in Zig.
5611-
lit_bytes = try std.fmt.allocPrint(c.arena, "{s}0{s}", .{
5612-
lit_bytes[0 .. dot_index + 1],
5613-
lit_bytes[dot_index + 1 ..],
5614-
});
5605+
5606+
if (mem.indexOfScalar(u8, lit_bytes, '.')) |dot_index| {
5607+
if (dot_index == 0) {
5608+
lit_bytes = try std.fmt.allocPrint(c.arena, "0{s}", .{lit_bytes});
5609+
} else if (dot_index + 1 == lit_bytes.len or !std.ascii.isDigit(lit_bytes[dot_index + 1])) {
5610+
// If the literal lacks a digit after the `.`, we need to
5611+
// add one since `1.` or `1.e10` would be invalid syntax in Zig.
5612+
lit_bytes = try std.fmt.allocPrint(c.arena, "{s}0{s}", .{
5613+
lit_bytes[0 .. dot_index + 1],
5614+
lit_bytes[dot_index + 1 ..],
5615+
});
5616+
}
56155617
}
56165618

56175619
if (suffix == .none)

test/translate_c.zig

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1135,11 +1135,15 @@ pub fn addCases(cases: *tests.TranslateCContext) void {
11351135
\\#define bar 16.e-2l
11361136
\\#define FOO 0.12345
11371137
\\#define BAR .12345
1138+
\\#define baz 1e1
1139+
\\#define BAZ 42e-3f
11381140
, &[_][]const u8{
11391141
"pub const foo = @as(f32, 3.14);",
11401142
"pub const bar = @as(c_longdouble, 16.0e-2);",
11411143
"pub const FOO = 0.12345;",
11421144
"pub const BAR = 0.12345;",
1145+
"pub const baz = 1e1;",
1146+
"pub const BAZ = @as(f32, 42e-3);",
11431147
});
11441148

11451149
cases.add("comments",

0 commit comments

Comments
 (0)