Skip to content

c_import: records with no tag and no typedef name are named by their first user (#1396); pointer type args in sizeof; nested records; unspellable layouts opaque - #1419

Merged
ehartford merged 3 commits into
fix-1393-ref-default-joinfrom
fix-1396-anon-file-scope-struct
Sep 23, 2026
Merged

ehartford merged 3 commits into
fix-1393-ref-default-joinfrom
fix-1396-anon-file-scope-struct

Conversation

@ehartford

@ehartford ehartford commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #1396. Rebased onto main after #1386 and #1399 merged; the branch holds three commits.

Root cause (#1396)

src/CImport.w ci_translate_struct emitted with_cimport_decl_name(session, idx) as the type name. For a file-scope struct/union with no tag and no typedef name, that is libclang's cursor spelling, struct (unnamed at file:line:col), so the bindings failed to parse. Every use of such a record went through ClangBridge.w translate_type_recursive_mode's Record branch, which returns c_void for any anonymous record. So struct { int b; } g; also imported as extern var g: c_void, an array of the record collapsed to c_void, and a function returning one was dropped into the manifest.

Fix

The spec does not say how to name an unnamed record. §16.1 says c_import "makes all declarations available as With symbols", and §16.3b says an extern variable's type "must be concrete", which c_void is not. The issue itself says a record nothing can refer to "is not emitted". Following that:

  • ClangBridge.name_file_scope_anon_records names each file-scope record with no name after the first declaration, in translation-unit order, whose type reaches it:

    • g_anon for a variable, also through arrays and pointers
    • f_return_anon for a function's result, f_p_anon for parameter p, f_argN_anon for an unnamed parameter
    • T_anon for a typedef that reaches it through a pointer or array

    If another declaration already uses the name, it takes the first free _2, _3, and so on. The name depends only on declaration order and spellings, never on addresses or hashes, so it is fixpoint-deterministic. The cursor spelling cache and type translation both return this name.

  • If nothing uses the record (winnt.h's C_ASSERT(TYPE_ALIGNMENT(T)) builds one inside an array-size expression), neither C nor With can spell it, so it is not emitted (with_cimport_decl_is_unused_anon_record).

  • Lookups stay linear in the header, per c_import is linear in a header's declarations: emitted names are a hash set, decl locations an index #1386. A record finds its name through a hash on its Decl. A candidate name is checked against a hash set of the declarations' spellings, built once with c_import is linear in a header's declarations: emitted names are a hash set, decl locations an index #1386's emitted_name_slot. The member-record walk collects field cursors only, with no per-field strings. Nothing scans all declarations per name.

Shapes matrix (darwin; test/behavior/behav_c_import_anon_file_scope_record{,_uses}.w)

C imports as
typedef struct { int a; } X; type X (unchanged)
struct { int b; } g; type g_anon, extern var g: g_anon
static struct { int c; } g2; type g2_anon, extern var g2: g2_anon
extern struct { int d; long long e; } g3[4]; extern var g3: [4]g3_anon (was c_void)
struct { int f; } a, b; one type, a_anon, used by both
union { ... } gu; type gu_anon = union {...}
enum { EA, EB } ge; constants plus extern var ge: i32 (unchanged)
anonymous-in-anonymous: struct { struct { int x; } inner; union { ... }; int w; } gn; gn_anon_inner, gn_anon_anon_1, gn_anon
struct { int r; short s; } mk(void); fn mk() -> mk_return_anon (was omitted)
void take(struct { int q; } *p); fn take(p: *mut take_p_anon) (was *mut c_void)
typedef struct { int pa; } *PX; type PX_anon, type PX = *mut PX_anon
struct { int s; } *gp; extern var gp: *mut gp_anon
name taken (typedef int gz_anon;) gz_anon_2
static const struct { int lo, hi; } k = {3, 4}; let k: k_anon = k_anon { lo: 3, hi: 4 }
C_ASSERT(TYPE_ALIGNMENT(long long) == 8) not emitted

Blockers Windows hit next

  1. Parser (commit 1): sizeof[*mut c_void]() failed with "expected expression" at mut (§16.12 says sizeof takes any type). Inside name[...], a * followed by mut/const now parses as a type, like the existing fn/extern case. winnt.h's TOKEN_INTEGRITY_LEVEL_MAX_SIZE hit this.
  2. Member record with no name held through an array or pointer (commit 2). Example: struct { ... } ScopeRecord[1]; in SCOPE_TABLE_AMD64. It came out as a by-value c_void field. Now it is named Parent_field by CImport's member rule and emitted, and an array of a demoted record demotes the record that holds it. The flexible-array accessor rename used to replace every occurrence of the field's spelling, including inside the new type name. It now renames only the field.
  3. Tags declared inside a record (commit 2), such as wtypes.h's union __MIDL_IWinTypes_0009 {...} u;, and the constants of enum { A, B } k;. In C these are file scope, but they were never collected, so fields named unknown types. hoist_nested_tags now lists each one just before the record that holds it. With this, sqlite3.h's sqlite3_index_constraint, _orderby and _constraint_usage import with their fields instead of opaque.
  4. Demotion gaps (commit 3). These records either failed to compile or compiled with the wrong layout:
    • ci_collect_demoted_types skipped every tag that starts with _. Windows' _DCB bitfields came out as whole DWORD fields plus @[align(1)], and darwin's union wait as four 4-byte fields.
    • Member records were never checked for bitfields (§16.9).
    • #pragma pack(N) fields below their natural alignment were emitted @[align(N)]. §16.4 rule 2 forbids that: "Alignment must be at least the natural alignment of the type." These records now import opaque. This needs no ruling. D51's asymmetry rule (§1 of the ruling) says "A convention may be inferred silently when being wrong can only remove capability or reject a valid program." Opaque only removes capability, while an approximate layout could let safe code read or write at wrong offsets. The exact layout needs a packed(N) form the spec does not have yet; filed as c_import: exact packed(N) record layouts #1421.

Verification (iterate tier only; the seed battery has not run)

Base for every A/B below: main's stage1 at f008ef3. Candidate: this branch's stage1/stage2 at 4cb0617.

  • Migrate output: raw with migrate output for pcre2 (34 files) and zlib (19 files) is byte-identical to main's stage1.
  • c_import text (private HOME cache per run):
    • Identical for string.h, pthread.h, sys/socket.h, zlib.h, signal.h and time.h.
    • Changed only where the old output was wrong:
      • union wait is now opaque (stdlib.h).
      • The sqlite3_index_* records now have fields.
      • Underscore-tagged forward declarations gain a // ...: demoted to opaque comment (stdio.h, curses.h, sys/stat.h, dirent.h).
  • 63 c_import/c_facade behavior fixtures, each run with main's stage1 and this branch's stage1:
    • Same rc and output everywhere except the 3 new tests, which fail on main and pass here.
    • The 9 that fail on both are stage1 limits or expected-failure tests: 3 are expect-check-fail tests, 2 have no main, and 4 need stage2.
    • With stage2, those 4 pass: expr_scan_budget, owns_deprecated_warns, facade_libc_system_headers and overlay_memchr.
  • behav_c_import_scales_linearly, run alone: passes with stage1, and with stage2 in 4 s.
  • The 4 new fixtures pass with stage2.
  • Darwin release UATs (before the rebase, stage1, init + get + run): bzip2, sqlite3 and libcurl pass. zlib fails the same way on the old base (shadowing is not allowed for 'HAVE_UNISTD_H').
  • Windows 10 x64 (before the rebase, stage2, C:\Users\Eric\triage\fix1396):

Draft until the seed battery is green.

@ehartford

Copy link
Copy Markdown
Contributor Author

Batch battery X2 (seed-driven, NEW seed, with :drop-audit/:move-audit) on main 977e667 + #1404 → #1418 → #1419 → #1425 (head ee4e2e4, including the #1404/#1418 join-arm merge resolution): build ok, :fixpoint ok, :drop-audit ok, :move-audit ok, :test ok (no reds), :test-green ok, :last-green ok. #1424's four repros run clean on this build. Branches hold exactly the tested chain; merge in order #1404, #1418, #1419, #1425 — then batch Y (#1405 … #1360), then #1428.

@ehartford

Copy link
Copy Markdown
Contributor Author

Back to draft: this ships inside the combined battery with #1425/#1428 (rebased on main with batch Y). When that battery is green, the whole chain lands as ONE PR (#1425) and this PR closes into it.

@ehartford
ehartford force-pushed the fix-1396-anon-file-scope-struct branch from ec5a26a to 187a3ca Compare September 23, 2026 05:16
@ehartford
ehartford changed the base branch from main to fix-1393-ref-default-join September 23, 2026 05:16
@ehartford
ehartford added this pull request to stack #1437 September 23, 2026 05:17
@ehartford

Copy link
Copy Markdown
Contributor Author

Battery (seed-driven, new seed, with :drop-audit/:move-audit) on main 05b674e (incl. batch Y) + #1418 → #1419 → #1425 → #1428 (head eea9017): build ok, :fixpoint ok, :drop-audit ok, :move-audit ok, :test ok (no reds — including #1422's da_option_filter_observes_payload, so this clears main's #1424 red), :test-green ok, :last-green ok. Merges cleanly into main 1c76062. Now GitHub stack #1437 (gh stack link); merge the whole stack: gh stack merge 1428 --squash.

@ehartford
ehartford marked this pull request as ready for review September 23, 2026 05:17
Eric Hartford added 3 commits September 23, 2026 04:43
…e argument in expression position parses as a type (§16.12)

`*` followed by `mut` or `const` never dereferences anything, so inside
`name[...]` it begins a type, like the `fn`/`extern` function-pointer case
already beside it. c_import emits `sizeof[*mut c_void]()` for C's
`sizeof(PVOID)`; winnt.h's TOKEN_INTEGRITY_LEVEL_MAX_SIZE failed with
"expected expression" at `mut` once #1396's unnamed records parsed.

Test: behav_sizeof_pointer_type_arg.w.
…he first declaration that uses it; one nothing uses is not emitted (#1396)

Root cause: ci_translate_struct took with_cimport_decl_name, which for a
file-scope record with no tag and no typedef name is libclang's cursor
spelling `struct (unnamed at file:line:col)`, and emitted it as a type
name; the bindings failed to parse. Every use of such a record translated
as `c_void` (ClangBridge translate_type_recursive_mode's Record branch), so
`struct { int b; } g;` also imported as `extern var g: c_void`, an array of
it collapsed to `c_void`, and a function returning one was omitted.

ClangBridge now names each file-scope record with no name after the first
declaration, in translation-unit order, whose type reaches it: `g_anon`
(variable, also through arrays/pointers), `f_return_anon` / `f_p_anon`
(`f_argN_anon` unnamed), `T_anon` (typedef through a pointer/array); a name
another declaration already spells takes the first free `_2` suffix. The
cursor spelling cache and type translation both answer with it, so the
record, `extern var g: g_anon`, `[4]g3_anon` and `fn mk() -> mk_return_anon`
agree. Names depend only on declaration order and spellings: deterministic.
A record nothing uses — winnt.h's C_ASSERT(TYPE_ALIGNMENT(T)) builds one
inside an expression — has no spelling in C or With and is not emitted
(with_cimport_decl_is_unused_anon_record), as the issue prescribes.

Two neighbours winnt.h/wtypes.h reach next, same root (records libclang
lists only under another record):

- A member record with no name held through an array or pointer
  (`struct { ... } ScopeRecord[1];`, SCOPE_TABLE_AMD64) translated as
  `c_void`, i.e. an opaque by-value field. The bridge names it by CImport's
  member rule, `Parent_field`, CImport emits it, and an array of a demoted
  one demotes its holder. The flexible-array accessor rename replaced every
  occurrence of the field's spelling in the last field, including the new
  type name; it now renames the field only.
- A tag declared inside a record (`union __MIDL_IWinTypes_0009 {...} u;`,
  and `enum { A, B } k;` constants) is file scope in C but was never
  collected: the field named an unknown type. hoist_nested_tags lists each
  just before the top-level record holding it. sqlite3.h's
  sqlite3_index_constraint/_orderby/_constraint_usage import with fields
  now instead of opaque.

Lookups stay linear in the header (#1386): a record finds its name through
a hash on its Decl, and a candidate name is checked against a hash set of
the declarations' spellings built once (emitted_name_slot), never a scan.

Shapes (darwin, stage1): `struct {..} g;`, `static struct {..} g;`,
`extern struct {..} g[4];`, `struct {..} a, b;` (one type), union, anonymous
enum (constants), anonymous-in-anonymous members, function result and
prototype parameter, pointer typedef, pointer var, name collision, const
initializer, and the C_ASSERT expression record (not emitted).
Tests: behav_c_import_anon_file_scope_record.w (layouts, literals, const
initializer) and _uses.w (check-only: every declaration's type identity).
…s with bitfields, bitfields in member records, fields under their natural alignment (#1396)

Three holes in the demotion pre-scan, each an emitted record that either
failed to compile or compiled with the wrong layout:

- ci_collect_demoted_types skipped every tag with a leading underscore,
  though ci_translate_struct emits them: winbase.h's `_DCB` bitfields came
  out as whole DWORD fields with `@[align(1)]` ("alignment is less than
  natural"), and darwin's `union wait` as four 4-byte fields.
- ci_record_decl_directly_demoted_cursor (member records) never looked
  for bitfields (§16.9: a record with bitfields is opaque).
- A field below its natural alignment (`#pragma pack(2)`, wingdi.h's
  BITMAPFILEHEADER) was emitted `@[align(2)]`; §16.4 rule 2 forbids an
  alignment under the natural one, and `@[packed]` would drop the record's
  own alignment to 1. It imports opaque, usable by pointer, like a bitfield
  layout. An exact spelling needs a packed(N) layout the spec does not have.

Windows 10: the 146 "alignment is less than natural" errors in the
windows.h closure are gone. Darwin headers change only where they were
wrong: `union wait` is opaque; forward-declared `_` records gain the
"demoted to opaque" location comment.

Test: behav_c_import_nested_records.w (also covers the array/pointer member
records and nested tags of the previous commit).
@ehartford
ehartford force-pushed the fix-1396-anon-file-scope-struct branch from 187a3ca to c0fcc75 Compare September 23, 2026 09:57
@ehartford
ehartford removed this pull request from stack #1437 September 23, 2026 09:58
@ehartford
ehartford added this pull request to stack #1466 September 23, 2026 09:58
@ehartford

Copy link
Copy Markdown
Contributor Author

Stack #1466 battery (seed-driven, new seed, cold c_import cache, with :drop-audit/:move-audit) on main 1c76062 + #1418 → #1419 → #1425 → #1428 → #1449 → #1377 → #1459 → #1460 → #1461 → #1462 (head cf36211, including the #1449/#1462 Codegen resolution and the fixed #1460): build ok, :fixpoint ok, :drop-audit ok, :move-audit ok, :test ok (no reds), :test-green ok, :last-green ok. Each branch holds exactly its tested commits on the layer below. Merge the whole stack: gh stack merge 1462 --squash.

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

Labels

None yet

Projects

None yet

1 participant