ImportC + metaprogramming?

Steven Schveighoffer schveiguy at
Sun Jan 16 02:28:04 UTC 2022

I was just watching Brian's talk on OpenBSD porting to D, and in the 
comments on Youtube, someone asked about how ImportC might help with 
avoiding having to port headers.

His response contained this truth nugget: "IIRC, importC goes directly 
from C source to D AST, so importC would need to gain the ability to 
rewrite its AST back into D source code."

One of the biggest problems with ImportC as everyone knows is the 
preprocessor. One thing that absolutely sucks is if you have something like:

#define foo 42

This information is lost forever once you preprocess the file. But you 
can expose this by converting this to an enum! How to do it?

Well, this won't work:

enum foo = foo; // translates to `enum 42 = 42`

So you have to come up with a *different* name, and then expose that. 
This really sucks, and I believe projects like dstep translate the thing 
to A D enum, and avoid using the preprocessor at all. But in the world 
of C, there's not an easy way to do this without coming up with some 
horrific naming mangle.

I thought, maybe if you import the C file, then you can introspect 
something from D! But no, there is nothing left to introspect once the c 
preprocessor is done. For actual functions, etc. that would work great, 
but not #defines.

But Brian's statement got me thinking -- what if we allowed just a 
*little bit* of the D camel's nose into the tent? Like some escape that 
could allow the D compiler to actually inject some meta into the AST 
while preprocessing?

What if we had something like a .cm or something file, which is treated 
like C + metaprogramming (e.g. __traits)? Then we can use a specialized 
preprocessor to be part of the compilation step that allows assisting 
with the header "porting".

Is this crazy talk, or does it make any sense?


More information about the Digitalmars-d mailing list