Mixin C

Steven Schveighoffer schveiguy at gmail.com
Sat Mar 23 02:51:31 UTC 2024


On Friday, 8 March 2024 at 03:23:12 UTC, Paul Backus wrote:
> What if instead of importing C files like D modules, we could 
> write bits of C code directly in the middle of our D code, like 
> we do with inline ASM?
>
> It might look something like this:
>
> ```d
> void main()
> {
>     mixin(C) {
>         #include <stdio.h>
>         printf("Hello from C!\n");
>     }
> }
> ```
>
> Here's how it could work:
>
> 1. The compiler takes the content of the `mixin(C)` block and 
> passes it through the external C preprocessor.
> 2. The result of (1) is parsed as a C AST fragment using the 
> ImportC parser.
> 3. The result of (2) is spliced into the AST in place of the 
> `mixin(C)` block, and undergoes semantic analysis using ImportC 
> semantics.

So the entirety of `stdio.h` is included in the body of the D 
main function? Is that wise?

The other problem is if you want to use C expressions in D. For 
example, let's say you have the C definition:

```c
#define PI 3.14159
```

How can I use this in D land? I could assign it to a variable 
maybe?

```d
mixin(C) {
    #include "pidef.h"
    double PI_ = PI;
}
```

Note, I have to use a new name. And it has to be a variable, 
because that's all you can do in C. What if I wanted it to be an 
enum? Too bad, C doesn't support that.

What I'd like to see is:

a) the C preprocessor is run on *all the mixin(C) islands of the 
file* regardless of where they appear, whether they are in 
templates, etc. Basically, take all the mixin(C) things and 
concatenate them, run the result through the preprocessor, and 
put the results back where they were. THEN run the importC 
compiler on them. This allows a more cohesive C-like experience, 
without having to import/define things over and over.
b) Allow mixin(C) expressions, such as `enum PI = mixin(C) { PI 
}`. Maybe this was already the intention? But I didn't get that 
vibe from the proposal.

-Steve


More information about the dip.ideas mailing list