开发者

extending the c programming language with gcc

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?


You could write a preprocessor that parses your language and compiles it to C, which is then passed on to gcc. This is how early implementations of C++ worked. However, you may prefer to hack on LLVM's clang, which is designed to support several C-family languages and, as part of LLVM, is also designed to be more modular and easier to extend.


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.


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.


You could hack something on top of http://cil.sourceforge.net/

Clang is another option, but it's not the most useful code rewriting tool, and modifying its parser frontend is not that easy.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜