Add ImportC compiler to dmd

Walter Bright newshound2 at digitalmars.com
Mon May 10 01:45:22 UTC 2021


[A meta comment in reply to Adam]

The end goal is to be able to import a C file and it will "just work". The 
following problems need to be solved to make this happen:

a. collecting user-supplied #defines

b. running the C preprocessor

c. collecting the final set of macro definitions at the end of the preprocessor run

d. converting the collection (C) to D equivalents, for example:

     #define ABC 3  => enum ABC = 3;

     #define f(g) ((g)+1)  =>  auto f(T)(T g) { return g + 1; }

Going further than that is likely to be intractable, Atila has spent a lot of 
time on this, he likely pushed it further.

e. Running the C compiler

==================

ImportC only addresses (e).

Does this make it useless? Frankly, I have no idea. I don't know any way of 
finding out other than making it work and seeing what happens. But there are 
some things that are knowable:

1. C changes only glacially. It's not like the 
https://www.winchestermysteryhouse.com/ constantly adding new rooms and 
different architectural styles.

2. C is a simple language. It only took a 5 days to get this far with it. DMD's 
lexer, semantics, optimizer and code gen can all be leveraged. I know how to 
write a C compiler.

3. Writing a C preprocessor is a nightmare. Fortunately, I already did that 
https://github.com/facebookarchive/warp and we can use it if we choose.

4. A builtin C compiler will be very fast, and quite small.

5. We will have complete control over it. We can adjust it so it works best for 
us. We don't need to fork or get anyone's buy-in. We control the user experience.

6. The D code will be able to inline C code, and even CTFE it.

7. We can easily do inline assembler for it. (It's already there!)

8. There are a lot of wacky C extensions out there. We only need to implement 
currently used ones (not the 16 bit stuff), and only the stuff that appears in C 
headers.

9. Without a C compiler, we're stuck with, wedded to, and beholden to libclang. 
I wouldn't be surprised that the eventual cost of adapting ourselves to libclang 
will exceed the cost of doing our own C compiler.

10. By nailing (e), then (a..d) starts looking possible.

11. C++ can compile C code, which is a ginormous advantage for C++. Can we 
afford not to do that?

12. Being built-in, in the box, batteries included, rather than an add-on, has 
enormous positive implications for D. It's hard to understate it. Think how 
great it was for Ddoc and unittest being built-in.


More information about the Digitalmars-d mailing list