From e7acbe263459ea5cadbab60bd0711c0cfb20f74d Mon Sep 17 00:00:00 2001 From: Mark Colley <39366189+M-Colley@users.noreply.github.com> Date: Fri, 27 Nov 2026 22:30:20 +0000 Subject: [PATCH] Support partial anonymous nested structs and unions Fixes #36. Signed-off-by: Mark Colley <39366189+M-Colley@users.noreply.github.com> --- src/cffi/cparser.py | 36 ++++++--- src/cffi/model.py | 1 + src/cffi/recompiler.py | 50 +++++++++++-- testing/cffi1/test_recompiler_codegen.py | 93 ++++++++++++++++++++++++ 4 files changed, 164 insertions(+), 16 deletions(-) create mode 100644 testing/cffi1/test_recompiler_codegen.py diff --git a/src/cffi/cparser.py b/src/cffi/cparser.py index f36e1ac6..378a17b6 100644 --- a/src/cffi/cparser.py +++ b/src/cffi/cparser.py @@ -598,7 +598,7 @@ def _get_type_pointer(self, type, quals, declname=None): return model.PointerType(type, quals) def _get_type_and_quals(self, typenode, name=None, partial_length_ok=False, - typedef_example=None): + typedef_example=None, nested_in=None): # first, dereference typedefs, if we have it already parsed, we're good if (isinstance(typenode, pycparser.c_ast.TypeDecl) and isinstance(typenode.type, pycparser.c_ast.IdentifierType) and @@ -624,9 +624,12 @@ def _get_type_and_quals(self, typenode, name=None, partial_length_ok=False, length = f'_cffi_array_len({typedef_example})' typedef_example = "*" + typedef_example # + if nested_in is not None: + nested_in = (nested_in[0], f'{nested_in[1]}[0]') tp, quals = self._get_type_and_quals(typenode.type, partial_length_ok=partial_length_ok, - typedef_example=typedef_example) + typedef_example=typedef_example, + nested_in=nested_in) return model.ArrayType(tp, length), quals # if isinstance(typenode, pycparser.c_ast.PtrDecl): @@ -674,12 +677,18 @@ def _get_type_and_quals(self, typenode, name=None, partial_length_ok=False, # if isinstance(type, pycparser.c_ast.Struct): # 'struct foobar' - tp = self._get_struct_union_enum_type('struct', type, name) + tp = self._get_struct_union_enum_type( + 'struct', type, name, + nested=(nested_in is not None), + nested_in=nested_in) return tp, quals # if isinstance(type, pycparser.c_ast.Union): # 'union foobar' - tp = self._get_struct_union_enum_type('union', type, name) + tp = self._get_struct_union_enum_type( + 'union', type, name, + nested=(nested_in is not None), + nested_in=nested_in) return tp, quals # if isinstance(type, pycparser.c_ast.Enum): @@ -694,10 +703,12 @@ def _get_type_and_quals(self, typenode, name=None, partial_length_ok=False, # nested anonymous structs or unions end up here if isinstance(typenode, pycparser.c_ast.Struct): return self._get_struct_union_enum_type('struct', typenode, name, - nested=True), 0 + nested=True, + nested_in=nested_in), 0 if isinstance(typenode, pycparser.c_ast.Union): return self._get_struct_union_enum_type('union', typenode, name, - nested=True), 0 + nested=True, + nested_in=nested_in), 0 # raise FFIError(":%d: bad or unsupported type declaration" % typenode.coord.line) @@ -745,7 +756,8 @@ def _as_func_arg(self, type, quals): else: return type - def _get_struct_union_enum_type(self, kind, type, name=None, nested=False): + def _get_struct_union_enum_type(self, kind, type, name=None, nested=False, + nested_in=None): # First, a level of caching on the exact 'type' node of the AST. # This is obscure, but needed because pycparser "unrolls" declarations # such as "typedef struct { } foo_t, *foo_p" and we end up with @@ -838,6 +850,8 @@ def _get_struct_union_enum_type(self, kind, type, name=None, nested=False): # if tp.fldnames is not None: raise CDefError(f"duplicate declaration of struct {name}") + if nested_in is not None and not tp.has_c_name() and tp.enclosing is None: + tp.enclosing = nested_in fldnames = [] fldtypes = [] fldbitsize = [] @@ -856,10 +870,14 @@ def _get_struct_union_enum_type(self, kind, type, name=None, nested=False): bitsize = self._parse_constant(decl.bitsize) self._partial_length = False type, fqual = self._get_type_and_quals(decl.type, - partial_length_ok=True) + partial_length_ok=True, + nested_in=(tp, decl.name or '')) if self._partial_length: self._make_partial(tp, nested) - if isinstance(type, model.StructType) and type.partial: + item = type + while isinstance(item, model.ArrayType): + item = item.item + if isinstance(item, model.StructOrUnion) and item.partial: self._make_partial(tp, nested) fldnames.append(decl.name or '') fldtypes.append(type) diff --git a/src/cffi/model.py b/src/cffi/model.py index d12424c7..d25a5bd9 100644 --- a/src/cffi/model.py +++ b/src/cffi/model.py @@ -345,6 +345,7 @@ class StructOrUnion(StructOrUnionOrEnum): completed = 0 partial = False packed = 0 + enclosing = None def __init__(self, name, fldnames, fldtypes, fldbitsize, fldquals=None): self.name = name diff --git a/src/cffi/recompiler.py b/src/cffi/recompiler.py index 1d2bcdd5..0a8eb35f 100644 --- a/src/cffi/recompiler.py +++ b/src/cffi/recompiler.py @@ -816,12 +816,33 @@ def _generate_cpy_function_ctx(self, tp, name): # ---------- # named structs or unions + def _struct_access_path(self, tp): + parts = [] + cur = tp + while not cur.has_c_name(): + enclosing = cur.enclosing + if enclosing is None: + return None, None + parent_tp, field_expr = enclosing + if field_expr: + parts.append(field_expr) + cur = parent_tp + parts.reverse() + return cur.get_c_name(''), '.'.join(parts) + def _field_type(self, tp_struct, field_name, tp_field): if isinstance(tp_field, model.ArrayType): actual_length = tp_field.length if actual_length == '...': - ptr_struct_name = tp_struct.get_c_name('*') - actual_length = f'_cffi_array_len((({ptr_struct_name})0)->{field_name})' + if tp_struct.has_c_name(): + ptr_struct_name = tp_struct.get_c_name('*') + actual_length = f'_cffi_array_len((({ptr_struct_name})0)->{field_name})' + else: + root_cname, access_path = self._struct_access_path(tp_struct) + if root_cname is None: + raise VerificationError( + f"cannot generate '{tp_struct._get_c_name()}' in field {field_name!r}: unknown type name") + actual_length = f'_cffi_array_len((({root_cname} *)0)->{access_path}.{field_name})' tp_item = self._field_type(tp_struct, f'{field_name}[0]', tp_field.item) tp_field = model.ArrayType(tp_item, actual_length) @@ -897,6 +918,13 @@ def _struct_ctx(self, tp, cname, approxname, named_ptr=None): flags.append("_CFFI_F_EXTERNAL") reason_for_not_expanding = "external" flags = '|'.join(flags) or '0' + root_cname = access_path = None + if cname is None and tp.partial: + root_cname, access_path = self._struct_access_path(tp) + if root_cname is None: + raise NotImplementedError(f"internal inconsistency: {tp!r} is " + "partial but was not seen at " + "this point") c_fields = [] if reason_for_not_expanding is None: enumfields = list(self._enum_fields(tp)) @@ -909,17 +937,22 @@ def _struct_ctx(self, tp, cname, approxname, named_ptr=None): if fbitsize >= 0: op = OP_BITFIELD size = '%d /* bits */' % fbitsize - elif cname is None or ( + elif (cname is None and root_cname is None) or ( isinstance(fldtype, model.ArrayType) and fldtype.length is None): size = '(size_t)-1' + elif root_cname is not None: + size = f'sizeof((({root_cname} *)0)->{access_path}.{fldname})' else: size = 'sizeof((({})0)->{})'.format( tp.get_c_name('*') if named_ptr is None else named_ptr.name, fldname) - if cname is None or fbitsize >= 0: + if (cname is None and root_cname is None) or fbitsize >= 0: offset = '(size_t)-1' + elif root_cname is not None: + offset = (f'offsetof({root_cname}, {access_path}.{fldname})' + f' - offsetof({root_cname}, {access_path})') elif named_ptr is not None: offset = f'(size_t)(((char *)&(({named_ptr.name})4096)->{fldname}) - (char *)4096)' else: @@ -930,12 +963,15 @@ def _struct_ctx(self, tp, cname, approxname, named_ptr=None): first_field_index = len(self._lsts["field"]) self._lsts["field"].extend(c_fields) # - if cname is None: # unknown name, for _add_missing_struct_unions + if cname is None and root_cname is None: # unknown name, for _add_missing_struct_unions size = '(size_t)-2' align = -2 comment = "unnamed" else: - if named_ptr is not None: + if root_cname is not None: + size = f'sizeof((({root_cname} *)0)->{access_path})' + align = '-1 /* unknown alignment */' + elif named_ptr is not None: size = f'sizeof(*({named_ptr.name})0)' align = '-1 /* unknown alignment */' else: @@ -968,7 +1004,7 @@ def _add_missing_struct_unions(self): lst.sort(key=lambda tp_order: tp_order[1]) for tp, order in lst: if tp not in self._seen_struct_unions: - if tp.partial: + if tp.partial and self._struct_access_path(tp)[0] is None: raise NotImplementedError(f"internal inconsistency: {tp!r} is " "partial but was not seen at " "this point") diff --git a/testing/cffi1/test_recompiler_codegen.py b/testing/cffi1/test_recompiler_codegen.py new file mode 100644 index 00000000..ed278424 --- /dev/null +++ b/testing/cffi1/test_recompiler_codegen.py @@ -0,0 +1,93 @@ +import io +import pytest + +from cffi import FFI, recompiler +from testing.cffi0.test_parsing import FakeBackend + + +def _emit_c_source(cdef_src, module_name="testmod", preamble=""): + ffi = FFI(backend=FakeBackend()) + ffi.cdef(cdef_src) + recomp = recompiler.Recompiler(ffi, module_name) + recomp.collect_type_table() + recomp.collect_step_tables() + buf = io.StringIO() + recomp.write_source_to_f(buf, preamble) + return buf.getvalue() + + +def test_nested_anonymous_partial_struct(): + c_src = _emit_c_source(""" + struct a { + struct { + ...; + } d; + ...; + }; + """) + assert "sizeof(((struct a *)0)->d)" in c_src + assert "(size_t)-2" not in c_src + + +def test_nested_anonymous_partial_struct_with_fields(): + c_src = _emit_c_source(""" + struct a { + int b; + struct { + int c; + int arr[...]; + ...; + } d; + }; + """) + assert "sizeof(((struct a *)0)->d)" in c_src + assert "offsetof(struct a, d.c) - offsetof(struct a, d)" in c_src + assert "sizeof(((struct a *)0)->d.c)" in c_src + assert "_cffi_array_len(((struct a *)0)->d.arr)" in c_src + assert "(size_t)-2" not in c_src + + +def test_deeply_nested_anonymous_partial_union_and_array(): + c_src = _emit_c_source(""" + typedef struct { + union { + struct { + int x; + ...; + } inner[2]; + ...; + } mid; + } outer_t; + """) + assert "sizeof(((outer_t *)0)->mid)" in c_src + assert "sizeof(((outer_t *)0)->mid.inner[0])" in c_src + assert "offsetof(outer_t, mid.inner[0].x) - offsetof(outer_t, mid.inner[0])" in c_src + + +def test_unnamed_struct_containing_named_partial_struct(): + c_src = _emit_c_source(""" + struct a { + struct { + struct { + int x; + ...; + } inner; + }; + ...; + }; + """) + assert "sizeof(((struct a *)0)->inner)" in c_src + assert "offsetof(struct a, inner.x) - offsetof(struct a, inner)" in c_src + assert "(size_t)-2" not in c_src + + +def test_pointer_to_anonymous_partial_struct_still_rejected(): + ffi = FFI(backend=FakeBackend()) + with pytest.raises(NotImplementedError): + ffi.cdef(""" + struct a { + struct { + ...; + } *d; + }; + """)