[core.reflect] Detect Padding in structs or classes
Stefan Koch
uplink.coder at googlemail.com
Fri Oct 1 18:30:35 UTC 2021
On Friday, 1 October 2021 at 17:35:24 UTC, Stefan Koch wrote:
> There has been a PR to introduce `-vpadding` into dmd which
> warns on padding in structs.
> This can actually be trivially done by core reflect.
>
Ah dang.
This code will be bogus for classes as we need it iterate the
base classes for this
Which we can do but not when visiting the superclass of both
Struct and Class Declarations.
We need to specialize for classes.
And add the following code to the visitor
```D
override void visit(ClassDeclaration cd)
{
ulong lastOffset;
ulong lastSize;
ulong wastedBytes;
// for classes we need to keep a stack of bases
// let's go!
ClassDeclaration[] baseStack = [cd];
for(auto base = cd.base; base; base = base.base)
{
baseStack ~= base;
}
foreach_reverse(base;baseStack)
{
foreach(f;base.fields)
{
wastedBytes += ((f.offset - lastOffset) -
lastSize);
lastOffset = f.offset;
lastSize = f.type.size;
}
}
if (wastedBytes)
pads ~= PadDetctedTuple(cd.name, wastedBytes);
}
```
And once we did that
```D
static immutable stdio_n = nodeFromName("std_stdio",
ReflectFlags.Members | ReflectFlags.MemberRecursion, sc);
pragma(msg, detectPadding(stdio_n));
```
will result in
`[PadDetctedTuple("_IO_FILE", 8LU), PadDetctedTuple("_IO_FILE",
8LU), PadDetctedTuple("StdioException", 16LU)]`
So yes the StdioExecption is somewhat fatty. But not 76 bytes of
waste ;)
More information about the Digitalmars-d
mailing list