zig icon indicating copy to clipboard operation
zig copied to clipboard

translate-c: variable declaration in switch block produces invalid zig code

Open Pyrolistical opened this issue 2 years ago • 5 comments

Zig Version

0.11.0-dev.1857+010596c93

Steps to Reproduce and Observed Behavior

Given repo.c:

static int foo (int x) {
  switch (x) {
    int y;
    case 0:
      y = 3;
      x = y;
      break;
  }
  return x;
}

Run:

zig translate-c repo.c > repo.zig
zig build-lib repo.zig 

Errors with:

repo.zig:60:17: error: use of undeclared identifier 'y'
                y = 3;

repo.zig at line 60:

pub fn foo(arg_x: c_int) callconv(.C) c_int {
    var x = arg_x;
    while (true) {
        switch (x) {
            @as(c_int, 0) => {
                y = 3;
                x = y;
                break;
            },
            else => {},
        }
        break;
    }
    return x;
}

Expected Behavior

Expect repo lib to be built without error.

Pyrolistical avatar Mar 05 '23 18:03 Pyrolistical

The workaround is to move int y; out of the switch block in repo.c, but that can change behaviour.

Pyrolistical avatar Mar 05 '23 18:03 Pyrolistical

And the C code is valid.

Screenshot 2023-03-05 102742

I originally encountered this in sqlite. You can see a more real-world example by downloading https://www.sqlite.org/2023/sqlite-amalgamation-3410000.zip.

Search for YYMINORTYPE yylhsminor; in sqlite.c.

Pyrolistical avatar Mar 05 '23 18:03 Pyrolistical

@vrischmann How does zig-sqlite avoid this issue?

Pyrolistical avatar Mar 05 '23 18:03 Pyrolistical

How does zig-sqlite avoid this issue?

Unsure about zig-sqlite, but it might be worth noting that translate-c is an unnecessary step if you're just trying to compile some C code (e.g. zig build-lib repo.c will work).

squeek502 avatar Mar 06 '23 05:03 squeek502

Yeah, I can confirm that cimport of sqlite.h and a regular build of the amalgamation works fine, but translate c breaks because of the switch issue reported here. The break applies to all uses of the Lemon parser generator that's part of the SQLite code base. Sometimes a translate c step is useful, for example if you want to call a C function at comptime, so it'd be nice for this to be fixed.

rsepassi avatar Mar 16 '23 05:03 rsepassi