Skip to content

sema/codegen: a bare scalar initializing a union-typed struct field is silently miscompiled (reads 0) #886

Closed

Description

@ehartford

Minimal repro (fails at -O0 — not an optimizer bug)

type Ufc = union { freq: u16 = 0, code: u16 = 0 }
type Cell { fc: Ufc }
impl Copy for Ufc
impl Copy for Cell
fn main:
    let c = Cell { fc: 12 }
    print(f"{c.fc.freq as i32}")     // prints 0, expected 12

Cell { fc: 12 } initializes the union-typed field fc with a bare scalar
12. The compiler ACCEPTS it (no diagnostic) but the value never reaches the
union member — c.fc.freq reads 0.

Two-field case shows the value lands in the wrong slot:

type Ufc = union { freq: u16 = 0, code: u16 = 0 }
type Udl = union { dad: u16 = 0, len: u16 = 0 }
type Cell { fc: Ufc, dl: Udl }
... let c = Cell { fc: 12, dl: 8 }
// fc.freq=12 fc.code=12 dl.dad=0 dl.len=0   — dl (the 2nd union field) got nothing

So the first bare-scalar union field takes the value; a later one is dropped
to 0. At -O1 the array form additionally computes wrong sums (the optimizer
compounds it), but the defect is present at -O0.

Impact — this is the root cause of #885

The re-migrated zlib's trees.w emits its static Huffman tables with bare-int
union-field init: ct_data_s { fc: 12, dl: 8 } (fc/dl are the classic zlib
{freq,code} / {dad,len} unions). Those tables come out wrong, so
compression produces corrupt output and inflate correctly returns
Z_DATA_ERROR. The pre-#749 migrator emitted the explicit form
ct_data_s { fc: ct_data_s_fc { freq: 12 }, dl: ct_data_s_dl { dad: 8 } },
which compiles correctly at -O1 (verified) — hence the old committed zlib works
and the re-migrated one does not.

The design question (needs a ruling)

Is StructWithUnionField { union_field: scalar } even valid With? A union is
ambiguous (which member?), so arguably it should require the explicit
Ufc { freq: 12 } form and the compiler should REJECT the bare scalar. Either
way the current behavior — accept and silently produce the wrong value — is a
bug. Two conforming resolutions:

The explicit-member form already works at every opt level, so the migrator
fix unblocks #885 regardless of which way the language question is ruled.

Activity

  1. ehartford commented on Aug 22, 2026

    @ehartford
    ContributorAuthor

    The migrator side is anonymous-union-specific

    The flattening only happens for a NAMED field of an anonymous union type
    (union {…} fc;), which is exactly zlib's ct_data. A named union type works:

    union U { unsigned short freq; unsigned short code; };
    struct S { union U fc; };
    const struct S t[2] = {{{12}},{{140}}};
    // migrates correctly to:  S { fc: U { freq: 12 } }
    
    struct ct_data_s { union { unsigned short freq; ... } fc; ... };
    const ct_data_s t[2] = {{{12},{8}}, ...};
    // migrates WRONG to:  ct_data_s { fc: 12, dl: 8 }   (union wrapper dropped)
    

    Both the single-struct and array forms flatten, so it is the struct-init
    lowering, not the array path.

    I tried the obvious migrator fix — switching
    with_cimport_struct_field_is_anonymous_record (ClangBridge.w:2680) from
    clang_Cursor_isAnonymous to clang_Cursor_isAnonymousRecordDecl (the latter
    keys on the anonymous tag, and clang_Cursor_isAnonymous is false for a
    named field of anon-union type in modern libclang). It did not change the
    output, so the flattening is deeper than that predicate — the value reaches the
    else/flatten branch (or a different init path) regardless. Reverted; not
    chasing the migrator's several init-lowering paths further.

    Recommendation: fix it compiler-side (the real defect)

    The migrator has multiple init-lowering paths and this would need to be right
    in all of them. The single true defect is that the compiler accepts
    Cell { fc: 12 } (a union-typed field given a bare scalar) and silently
    produces the wrong value
    . Fixing that one place resolves every migrator path
    at once:

    • If the language rules the bare form invalid → Sema rejects it (a loud error,
      not a silent 0), and the migrator's flattened output fails to compile,
      surfacing the migrator bug immediately instead of miscompiling zlib.
    • If the language rules it valid ("initialize the union's first member", the C
      positional-init semantics) → codegen writes the scalar to the member offset.

    That is the design question that needs a ruling (§ unions). Either resolution
    makes #885's zlib re-migration correct; the explicit-member form already works
    at every optimization level.

  2. ehartford commented on Aug 23, 2026

    @ehartford
    ContributorAuthor

    Migrator half fixed (6dd5414); the compiler defect stays open

    The migrator now emits the explicit fc: <synth> { a: 12 } for anon-union
    member init instead of the flattened fc: 12 (root cause: the arm initializer
    was a braced InitListExpr the arm-init lowering didn't descend into). zlib
    re-migrated and validated at -O1; #885 closed.

    Still open here: the compiler accepts a bare Cell { fc: 12 } for a
    union-typed field and silently stores the wrong value (the 7-line repro at the
    top). That is the language question — reject in Sema (unions require explicit
    member syntax, matching Rust/Zig) vs accept-and-codegen-first-member. The
    migrator no longer emits the bare form, so nothing in-tree hits it, but the
    silent miscompile should be closed by a ruling + Sema/codegen fix.

  3. ehartford commented on Aug 30, 2026

    @ehartford
    ContributorAuthor

    Fixed compiler-side in b3ecdf37 (battery green, reseeded), resolving the design question from the existing spec text rather than a new ruling:

    §16.4 already rules it — "Construction requires exactly one field initializer." A bare scalar for a union-typed field is not a union construction form; the compiler accepting it was non-compliance, not a semantics gap. Verified no drift: the union section is unchanged since filing (only spec change since is D31/§16.11), no competing struct-literal coercion text exists, and no decisions.md entry touches unions.

    • Sema now rejects it in the struct-literal field loop (the one path missing the check — bindings/calls/assignments already rejected int→union), with a fix-it naming the concrete form: a union-typed field requires an explicit member initializer; use `Ufc { freq: ... }` (§16.4). Covers both named and positional literal paths.
    • Tests: behav_union_field_bare_scalar (expect-check-fail), behav_union_field_explicit_ok (prints 12 8).
    • The migrator half was fixed earlier in 6dd54146 (zlib re-migrated, codegen/-O1: re-migrated zlib inflate path decompresses wrong at -O1 (Z_DATA_ERROR); -O0 fine #885 closed); nothing in-tree emitted the bare form since, confirmed by the green self-host battery.
    • The wider hole this exposed — struct-literal fields skip value-type checking entirely (str into an i32 field is accepted) — is filed separately as sema: struct-literal fields skip value-type checking entirely (str into i32 field accepted) #896 with the repro and the predicate to mirror.

    The silent-miscompile family from the zlib campaign is now closed loud.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions