Commit 4b9fd57aa8

Evan Haas <evan@lagerdata.com>
2022-03-08 19:38:51
translate-c: use nested scope for comma operator in macros
Fixes #11040
1 parent d805add
src/translate_c.zig
@@ -5563,7 +5563,7 @@ fn parseCExpr(c: *Context, m: *MacroCtx, scope: *Scope) ParseError!Node {
         const ignore = try Tag.discard.create(c.arena, .{ .should_skip = false, .value = last });
         try block_scope.statements.append(ignore);
 
-        last = try parseCCondExpr(c, m, scope);
+        last = try parseCCondExpr(c, m, &block_scope.base);
         if (m.next().? != .Comma) {
             m.i -= 1;
             break;
test/behavior/translate_c_macros.h
@@ -37,3 +37,5 @@ union U {
 #define IGNORE_ME_10(x) (volatile const void)(x)
 
 #define UNION_CAST(X) (union U)(X)
+
+#define NESTED_COMMA_OPERATOR (1, (2, 3))
test/behavior/translate_c_macros.zig
@@ -56,3 +56,9 @@ test "casting to union with a macro" {
     casted = h.UNION_CAST(d);
     try expectEqual(d, casted.d);
 }
+
+test "nested comma operator" {
+    if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO
+
+    try expectEqual(@as(c_int, 3), h.NESTED_COMMA_OPERATOR);
+}
test/run_translated_c.zig
@@ -1851,4 +1851,14 @@ pub fn addCases(cases: *tests.RunTranslatedCContext) void {
         \\    return 0;
         \\}
     , "");
+
+    cases.add("Nested comma operator in macro. Issue #11040",
+        \\#include <stdlib.h>
+        \\#define FOO (1, (2,  3))
+        \\int main(void) {
+        \\    int x = FOO;
+        \\    if (x != 3) abort();
+        \\    return 0;
+        \\}
+    , "");
 }