I want to write my own programming language as an extension of the c programming language. The entire programming language that I am inventing are simply shorthands which translate to valid c code. For example:
namespace TcpConnection {
void* connect(char *addr)
}
would translate to:
void* TcpConnection_connect(char *addr)
All that is done is a simple name replacement. This is only one example of an extension which I want to provide. Another simple extension would be function overloading (this would concatenate to the end of the function name the types of its arguments.
In any case, the result is perfectly valid C code. Is there any way to do this without going into gcc code?
I did something similar to embed an assembly language for a custom bytecode format, using some C99 macro magic and Perl.
The macros
#define x3_pragma_(...) _Pragma(#__VA_ARGS__)
#define x3_asm(...) ((const struct x3instruction []){ \
x3_pragma_(X3 ASM __VA_ARGS__) \
})
transform
x3_asm(exit = find val(0))
into
((const struct x3instruction []){
#pragma X3 ASM exit = find val(0)
})
which gets piped through a Perl script to get
((const struct x3instruction []){
{ { { X3_OPFINDVAL, { .as_uint = (0) } }, { X3_OPEXIT, { 0 } } } },
})
A sample invocation of gcc and perl would look like this:
gcc -E foo.c | perl x3pp.pl | gcc -o foo.o -x c -
It's more complicated than stricly necessary, but I found it beneficial that the C preprocessor runs before my custom preprocessor, and I also liked that by using pragmas, the source stays legal C.
For prototyping, maybe just go with a preprocessor written in the language of your choice (C, Perl, Python...) and then build it into your Makefile rules. Just to get an easy, low-cost way to try it all out...
Use a different file extension, and turn .foo into .c.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With