From 05d9755766e45e454a16440bfc9f98abef992247 Mon Sep 17 00:00:00 2001 From: travisstaloch <1562827+travisstaloch@users.noreply.github.com> Date: Fri, 12 Apr 2024 03:10:42 -0700 Subject: [PATCH] translate-c: allow str literals in bool expressions this is a follow up to #19610 with fix suggested by Vexu in https://github.com/ziglang/zig/issues/14642#issuecomment-2048999384 --- src/translate_c.zig | 8 +++++++- test/cases/translate_c/strlit_as_bool.c | 8 ++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) create mode 100644 test/cases/translate_c/strlit_as_bool.c diff --git a/src/translate_c.zig b/src/translate_c.zig index 2e9213a8c7..bf6b8ec1d8 100644 --- a/src/translate_c.zig +++ b/src/translate_c.zig @@ -2086,6 +2086,11 @@ fn finishBoolExpr( } }, .Pointer => { + if (node.tag() == .string_literal) { + // @intFromPtr(node) != 0 + const int_from_ptr = try Tag.int_from_ptr.create(c.arena, node); + return Tag.not_equal.create(c.arena, .{ .lhs = int_from_ptr, .rhs = Tag.zero_literal.init() }); + } // node != null return Tag.not_equal.create(c.arena, .{ .lhs = node, .rhs = Tag.null_literal.init() }); }, @@ -5794,10 +5799,11 @@ fn macroIntToBool(c: *Context, node: Node) !Node { return node; } if (node.tag() == .string_literal) { + // @intFromPtr(node) != 0 const int_from_ptr = try Tag.int_from_ptr.create(c.arena, node); return Tag.not_equal.create(c.arena, .{ .lhs = int_from_ptr, .rhs = Tag.zero_literal.init() }); } - + // node != 0 return Tag.not_equal.create(c.arena, .{ .lhs = node, .rhs = Tag.zero_literal.init() }); } diff --git a/test/cases/translate_c/strlit_as_bool.c b/test/cases/translate_c/strlit_as_bool.c new file mode 100644 index 0000000000..4ba0cfe2a4 --- /dev/null +++ b/test/cases/translate_c/strlit_as_bool.c @@ -0,0 +1,8 @@ +void foo() { if(0 && "error message") {} } + +// translate-c +// c_frontend=clang +// +// pub export fn foo() void { +// if (false and (@intFromPtr("error message") != 0)) {} +// }