What's the current state of the art for module compilation?
Mengu
mengukagan at gmail.com
Sat Nov 28 01:37:35 UTC 2026
On Friday, 27 November 2026 at 19:55:21 UTC, Walter Bright wrote:
> On 11/24/2026 3:20 AM, David Given wrote:
>> - I was told that using generated .di files with certain
>> constructs (templates, auto return, something annotation-based
>> which I forget) doesn't work and produces .di files which will
>> in turn cause miscompilation and runtime crashes. Can anyone
>> confirm or deny that?
>
> I'd need to see an example of such a failure. Some experiments
> I tried don't result in erroneous generation.
>
> But definitely errors will happen if a .d file is changed, and
> the .di file is not updated accordingly.
Let me give this a try. Disclaimer: The following is not AI slop.
They have been discovered with a new tool called
[Ephyra](https://github.com/datadog-labs/ephyra).
### DMD `.di` header generation bugs
All 9 bugs below affect D interface files generated with `dmd -H`
at commit `458663f51b` (`DMD AArch64 D Compiler
v2.113.0-beta.1-1338-g458663f51b`). Every test case compiles and
runs with direct `.d` compilation. Each failure occurs only when
you compile `app.d` against `di/lib.di` generated by `dmd -H` and
link `app.o` with `lib.o`.
To reproduce any runtime or link failure below, run these
commands in a directory containing `lib.d` and `app.d`:
```bash
dmd -of=direct lib.d app.d
./direct
mkdir -p di
dmd -H -Hf=di/lib.di -c -of=lib.o lib.d
dmd -I=di -c -of=app.o app.d
dmd -of=via_di lib.o app.o
./via_di
```
To reproduce any `.di` compile failure below, run these commands:
```bash
mkdir -p di
dmd -H -Hf=di/lib.di -o- lib.d
dmd -I=di -o- app.d
```
### Runtime crashes
#### 1. Nested visibility drops the inner visibility
When a visibility block or colon attribute wraps a single
declaration with a different visibility, `dmd -H` drops the inner
visibility keyword. In a class, turning a `public` method into a
`private` method removes it from the vtable and shifts every
later virtual slot by one. The program compiles and links, then
crashes with `SIGSEGV`. Reversing the order (`public { private
int first() {} }`) turns a `private` method into a virtual
`public` method, which dispatches the wrong method at runtime or
exposes private module symbols.
`lib.d`:
```d
module lib;
class Base
{
int val = 10;
private
{
public int first() { return val + 111; }
}
int second(int* q) { return *q + val + 222; }
int third() { return val + 333; }
}
int callViaBase(Base b, int* q)
{
return b.first() + b.second(q) + b.third();
}
```
`app.d`:
```d
module app;
import lib;
import core.stdc.stdio : printf;
class Sub : Base
{
override int second(int* q) { return *q + 777; }
override int third() { return 888; }
}
void main()
{
int x = 42;
Base b = new Sub();
printf("R=%d,%d,%d\n", callViaBase(b, &x), b.second(&x),
b.third());
}
```
Generated `di/lib.di`:
```d
class Base
{
int val = 10;
private int first();
int second(int* q);
int third();
}
```
`./direct` prints `R=130078,819,888`. `./via_di` terminates with
`SIGSEGV`.
**Root cause.** In `compiler/src/dmd/hdrgen.d:1184-1194`,
`visitVisibilityDeclaration` prints the outer visibility first.
When `ad.decl.length == 1` and `(*ad.decl)[0]` is another
`VisibilityDeclaration`, line 1191 calls `visitAttribDeclaration`
on the inner node and skips printing the inner visibility.
**Fix.** When `ad.decl` is non-null, `ad.decl.length == 1`, and
`(*ad.decl)[0].isVisibilityDeclaration` is non-null, do not emit
the outer visibility. Call `toCBuffer((*ad.decl)[0], *buf, *hgs)`
instead, because the inner visibility overrides the outer
visibility in D. Check that `ad.decl` is non-null before you read
`ad.decl.length`.
#### 2. Attributes on `invariant` attach to the next declaration
In `.di` mode, `dmd -H` omits `invariant` declarations but still
emits any attribute placed on them. The dangling attribute
attaches to the next sibling declaration.
This produces four failure modes:
- `align(1) invariant { ... }` before a pointer field shifts that
field to offset 1 in `app.o` while `lib.o` uses offset 8, so
dereferencing the pointer causes `SIGSEGV`.
- `private invariant { ... }` before a virtual class method marks
that method `private` in `lib.di`, which shifts the vtable and
causes `SIGSEGV`.
- `extern(C++) invariant { ... }` before a D method changes its
linkage in `lib.di`, which fails at link time with an undefined
C++ symbol.
- `@Tag(1) invariant { ... }` before a field or function attaches
`@Tag(1)` to the next member.
`lib.d`:
```d
module lib;
struct S
{
ubyte tag = 1;
align(1) invariant { assert(tag == 1); }
int* ptr;
}
S makeS(int* p)
{
S s;
s.ptr = p;
return s;
}
```
`app.d`:
```d
module app;
import lib;
import core.stdc.stdio : printf;
void main()
{
int target = 42;
S s = makeS(&target);
printf("R=%d\n", *s.ptr);
}
```
Generated `di/lib.di`:
```d
struct S
{
ubyte tag = 1;
align (1) int* ptr;
}
```
`./direct` prints `R=42`. `./via_di` terminates with `SIGSEGV`.
**Root cause.** `visitInvariantDeclaration` in
`compiler/src/dmd/hdrgen.d:1989-1992` returns without output when
`hgs.hdrgen` is true. `visitAttribDeclaration` in
`compiler/src/dmd/hdrgen.d:1117` emits `{}` for a single
`UnitTestDeclaration`, and it does not check for
`InvariantDeclaration` or for nested attribute wrappers around
omitted declarations.
**Fix.** Add a helper in `compiler/src/dmd/hdrgen.d` that returns
true when a `Dsymbol` emits nothing in `.di` mode:
`UnitTestDeclaration`, `InvariantDeclaration`, and any
`AttribDeclaration` whose `decl` array contains only omitted
symbols. In `visitAttribDeclaration`, emit `{}` or omit the
wrapper when every child is omitted.
#### 3. Stripped `const` initializers and function bodies diverge
under `__traits(compiles, ...)`
`dmd -H` strips initializers from module-level `const` and
`immutable` variables, and it strips bodies from non-`auto`
functions. Direct compile-time uses such as `const size_t N = 4;
int[N] a;` fail to compile against `lib.di`. When a `static if`
guards a field, virtual method, or `extern(C) auto` return branch
with `__traits(compiles, ...)`, `lib.o` evaluates the condition
to `true` and `app.o` evaluates it to `false`. Both object files
compile and link with no diagnostic, then crash or read the wrong
register at runtime.
`lib.d`:
```d
module lib;
const int FLAG = 1;
int helper() { return 1; }
enum HAS_A = __traits(compiles, { enum _x = FLAG; });
enum HAS_B = __traits(compiles, { enum _x = helper(); });
struct S
{
static if (HAS_A && HAS_B)
{
long pad = 0;
}
int* ptr;
}
S makeS(int* p)
{
S s;
s.ptr = p;
return s;
}
```
`app.d`:
```d
module app;
import lib;
import core.stdc.stdio : printf;
void main()
{
int v = 42;
auto s = makeS(&v);
printf("R=%d,%zu\n", *s.ptr, S.sizeof);
}
```
Generated `di/lib.di`:
```d
extern const int FLAG;
int helper();
enum HAS_A = __traits(compiles, ()
{
enum _x = FLAG;
}
);
enum HAS_B = __traits(compiles, ()
{
enum _x = helper();
}
);
```
`./direct` prints `R=42,16`. `./via_di` terminates with
`SIGSEGV`, because `lib.o` writes `ptr` at offset 8 and `app.o`
reads `ptr` at offset 0.
The same bug affects `extern(C) auto` return types:
```d
module lib;
int helper() { return 1; }
extern(C) auto getVal()
{
static if (__traits(compiles, { enum _x = helper(); }))
return 42.5;
else
return 42L;
}
```
`lib.o` returns a `double` in floating-point register `d0`.
`app.o` infers `long` and reads integer register `x0`, which
prints `1.000000` instead of `42.500000`.
**Root cause.** `visitVarDecl` in
`compiler/src/dmd/hdrgen.d:2152-2202` sets `isextern = true` and
drops `v._init` for all module-level variables except
`STC.manifest`, including `const` and `immutable` compile-time
constants. Also, `genhdrfile` runs before semantic analysis in
`compiler/src/dmd/main.d:591-615`, and `bodyToBuffer` in
`compiler/src/dmd/hdrgen.d:1446` strips normal function bodies
without knowing whether a `static if` or `enum` evaluates them at
compile time.
**Fix.** For `const` and `immutable` module variables with an
initializer, preserve the initializer in `visitVarDecl` instead
of rewriting them to `extern const T x;`. For CTFE-dependent
`static if` and `__traits(compiles, ...)` expressions, resolve
module-level conditional compilation before header emission so
`lib.di` matches the AST compiled into `lib.o`.
### Silent miscompilations
#### 4. UDAs on `enum` members are dropped
`dmd -H` drops all user-defined attributes attached to `enum`
members. Reflection code that reads `__traits(getAttributes,
E.a)` sees zero attributes when compiling against `lib.di`.
`lib.d`:
```d
module lib;
struct Tag { int v; }
enum Flag;
enum E
{
@(Tag(1), Flag) a = 10,
@Tag(2) b = 20,
}
```
`app.d`:
```d
module app;
import lib;
import core.stdc.stdio : printf;
void main()
{
printf("UDAs=%zu\n", __traits(getAttributes, E.a).length);
}
```
Generated `di/lib.di`:
```d
enum E
{
a = 10,
b = 20,
}
```
`./direct` prints `UDAs=2`. `./via_di` prints `UDAs=0`.
**Root cause.** The parser stores enum member UDAs in
`em.userAttribDecl` at `compiler/src/dmd/parse.d:3505`.
`visitEnumMember` in `compiler/src/dmd/hdrgen.d:1047-1058`
ignores `em.userAttribDecl`.
**Fix.** Print `em.userAttribDecl` at the start of
`visitEnumMember` using the UDA-flattening helper described in
Bug 6.
#### 5. `static this()` and `static ~this()` inside template
functions are stripped
When a struct nested inside a template function defines `static
this()` or `static ~this()`, `dmd -H` emits them without bodies.
The consumer compiles and links against `lib.di`, and the static
constructor and destructor never run.
`lib.d`:
```d
module lib;
__gshared int dtorRan = 0;
int tf(T)(T x)
{
struct Local
{
static int val = 1;
static this() { val = 99; }
static ~this() { dtorRan = 42; }
}
return cast(int)x + Local.val;
}
```
`app.d`:
```d
module app;
import lib;
import core.stdc.stdio : printf;
shared static ~this() { printf("DTOR=%d\n", dtorRan); }
void main() { printf("R=%d\n", tf(5)); }
```
Generated `di/lib.di`:
```d
int tf(T)(T x)
{
struct Local
{
static int val = 1;
static this();
static ~this();
}
return cast(int)x + Local.val;
}
```
`./direct` prints `R=104` and `DTOR=42`. `./via_di` prints `R=6`
and `DTOR=0`.
**Root cause.** `bodyToBuffer` in
`compiler/src/dmd/hdrgen.d:1466-1472` increments
`hgs.insideFuncBody` and resets `hgs.tpltMember` to `0`.
`visitStaticCtorDeclaration` at `compiler/src/dmd/hdrgen.d:1964`
and `visitStaticDtorDeclaration` at
`compiler/src/dmd/hdrgen.d:1980` check only `if (hgs.hdrgen &&
!hgs.tpltMember)`.
**Fix.** Change both checks to `if (hgs.hdrgen && !hgs.tpltMember
&& !hgs.insideFuncBody && !hgs.doFuncBodies)`, or delegate
directly to `bodyToBuffer(d)`.
### Compile errors in generated `.di` files
#### 6. Stacked UDAs emit undefined `AliasSeq!(...)`
Any declaration with two or more stacked `@` attributes produces
`AliasSeq!(...)` in `lib.di`. `AliasSeq` is a Phobos template,
not a built-in symbol, so importing `lib.di` fails to compile.
This affects functions, templates, structs, classes, fields,
constructors, destructors, aliases, and attribute blocks.
`lib.d`:
```d
module lib;
struct Tag { int v; }
enum Flag;
@Tag(7) @Flag int fn(int x) { return x + 1; }
```
`app.d`:
```d
module app;
import lib;
void main() { int r = fn(1); }
```
Generated `di/lib.di`:
```d
@(AliasSeq!(Tag(7)), AliasSeq!(Flag))int fn(int x);
```
`dmd -I=di -o- app.d` fails with `Error: template instance
AliasSeq!(Tag(7)) template AliasSeq is not defined`.
**Root cause.** `UserAttributeDeclaration.concat` in
`compiler/src/dmd/attrib.d:722-739` combines stacked UDA lists by
wrapping each list in a `TupleExp`.
`visitUserAttributeDeclaration` in
`compiler/src/dmd/hdrgen.d:1363-1369` passes `d.atts` to
`argsToBuffer`, and `visitTuple` at
`compiler/src/dmd/hdrgen.d:2644-2660` prints every `TupleExp` as
`AliasSeq!(...)`.
**Fix.** Add a helper in `compiler/src/dmd/hdrgen.d` that prints
UDA argument lists by recursively flattening any `TupleExp` with
`e0 is null` into comma-separated expressions inside `@(...)`.
Call this helper from `visitUserAttributeDeclaration`,
`moduleToBuffer2`, `parameterToBuffer`, and `visitEnumMember`.
Emit a space after `@(...)` when `d.decl.length == 1`.
#### 7. Multi-UDA parameters starting with a call expression emit
invalid syntax
When a function parameter has multiple UDAs inside `@(...)` and
the first UDA is a call expression, `dmd -H` drops the enclosing
parentheses. The generated `.di` file fails to parse.
`lib.d`:
```d
module lib;
struct Tag { int v; }
enum Flag;
auto fn(@(Tag(12), Flag) int x) { return x + 1; }
```
`app.d`:
```d
module app;
import lib;
void main() { int r = fn(1); }
```
Generated `di/lib.di`:
```d
auto fn(@Tag(12), (Flag) int x)
{
return x + 1;
}
```
`dmd -I=di -o- app.d` fails with `Error: basic type expected, not
','`.
**Root cause.** `parameterToBuffer` in
`compiler/src/dmd/hdrgen.d:3781-3794` computes `isAnonymous` from
`atts[0]` alone:
```d
bool isAnonymous = p.userAttribDecl.atts.length > 0 &&
!(*p.userAttribDecl.atts)[0].isCallExp();
```
When `atts.length > 1` and `atts[0]` is a `CallExp`,
`isAnonymous` is `false`, so `parameterToBuffer` omits the outer
parentheses.
**Fix.** Always wrap parameter UDAs in `@(...)`, or require
parentheses whenever `atts.length != 1 ||
!(*atts)[0].isCallExp()`. Use the `TupleExp`-flattening helper
from Bug 6 so stacked parameter UDAs (`@Tag(12) @Flag int x`)
also print without `AliasSeq!`.
#### 8. Prefix `scope` or `return` on eponymous function
templates emits duplicate attributes
An eponymous member function template with prefix `scope` or
`return` prints the attribute both before and after the parameter
list. Compiling against `lib.di` fails with `Error: redundant
attribute 'scope'`.
`lib.d`:
```d
module lib;
struct Holder
{
int x = 10;
scope auto fn(T)(T k) { return x + cast(int)k; }
}
```
`app.d`:
```d
module app;
import lib;
void main()
{
Holder h;
int r = h.fn(3);
}
```
Generated `di/lib.di`:
```d
struct Holder
{
int x = 10;
auto scope fn(T)(T k) scope
{
return x + cast(int)k;
}
}
```
`dmd -I=di -o- app.d` fails with `Error: redundant attribute
'scope'`.
**Root cause.** `visitFuncDeclaration` in
`compiler/src/dmd/hdrgen.d:1864` masks `STC.scope_ | STC.return_
| STC.returnScope | STC.returnRef` before printing
`f.storage_class`, because `visitFuncIdentWithPrefix` prints them
after the parameter list. `visitEponymousMember` at
`compiler/src/dmd/hdrgen.d:1516` omits that mask.
**Fix.** Apply the same storage-class mask in
`visitEponymousMember` at line 1516:
```d
if (stcToBuffer(*buf, fd.storage_class & ~(STC.scope_ |
STC.return_ | STC.returnScope | STC.returnRef)))
buf.put(' ');
```
#### 9. `immutable(char)[]` is rewritten to `string` when
`string` is shadowed
`dmd -H` rewrites `immutable(char)[]`, `immutable(wchar)[]`, and
`immutable(dchar)[]` to `string`, `wstring`, and `dstring`
without checking whether those aliases are shadowed in the module.
`lib.d`:
```d
module lib;
alias string = int;
size_t slen(immutable(char)[] s) { return s.length; }
```
`app.d`:
```d
module app;
import lib;
void main()
{
immutable(char)[] s = "hi";
auto n = slen(s);
}
```
Generated `di/lib.di`:
```d
alias string = int;
size_t slen(string s);
```
`dmd -I=di -o- app.d` fails because `slen` now expects an `int`
parameter.
**Root cause.** `visitDArray` in
`compiler/src/dmd/hdrgen.d:4467-4484` substitutes `"string"`,
`"wstring"`, and `"dstring"` whenever `hgs.declstring` is false.
**Fix.** In `visitDArray`, skip the `string`, `wstring`, and
`dstring` shorthand when `hgs.hdrgen` is true so `.di` files
always emit `immutable(char)[]`, `immutable(wchar)[]`, and
`immutable(dchar)[]`.
### Summary
| # | Construct | Observed failure with `.di` | Source location |
|---|---|---|---|
| 1 | Nested visibility (`private { public ... }`) | Runtime
`SIGSEGV` or wrong virtual dispatch |
`compiler/src/dmd/hdrgen.d:1184-1194` |
| 2 | Attributed `invariant` | Runtime `SIGSEGV`, link error, or
attribute leak | `compiler/src/dmd/hdrgen.d:1117,1989-1992` |
| 3 | Stripped `const` init or fn body with `__traits(compiles)`
| Runtime `SIGSEGV`, ABI mismatch, or CTFE error |
`compiler/src/dmd/hdrgen.d:1446,2152-2202` |
| 4 | UDAs on `enum` members | Silent miscompilation (UDAs
dropped) | `compiler/src/dmd/hdrgen.d:1047-1058` |
| 5 | `static this()` or `static ~this()` in template fn | Silent
miscompilation (ctor and dtor skipped) |
`compiler/src/dmd/hdrgen.d:1469-1472,1964,1980` |
| 6 | Stacked UDAs (`@A @B`) | Compile error (`AliasSeq`
undefined) | `compiler/src/dmd/attrib.d:722-739`,
`compiler/src/dmd/hdrgen.d:1363-1369` |
| 7 | Multi-UDA parameter with call expression first | Parse
error (`basic type expected, not ','`) |
`compiler/src/dmd/hdrgen.d:3781-3794` |
| 8 | Prefix `scope` or `return` on eponymous fn template |
Compile error (`redundant attribute 'scope'`) |
`compiler/src/dmd/hdrgen.d:1516` |
| 9 | `immutable(char)[]` with shadowed `string` | Compile error
(parameter rewritten to `int`) |
`compiler/src/dmd/hdrgen.d:4467-4484` |
More information about the Digitalmars-d
mailing list