« Smack The Server | Main | Y! Q2/07 Hack Day »

Antlr3 + generated C + OSX

I've been a fan of Antlr for a while now. I've used it to generate intrinsic classes for ActionScript2 so that our team could build an incremental compiler. I just bought the Antlr3 book (in PDF format) and have been going through the examples as I reach them.

As I went through the book I decided that I wanted to combine learning Antlr with my recent LLVM fascination. LLVM is in C/C++ so I decided to use the 'C' output language option in Antlr. I haven't found any documentation on line on how to use the C API, but through some trials I've ported the first example in the book to C.

The first big trial that I faced was that XCode defaults to C++ mode, which is fine for compiling C code as long as you use the right decorations. Some of the Antlr3C support lib uses 'or' which the preprocessor converts to '||'. I spent a day and found that you can disable this by using the '-fno-operator-names' compiler flag.

Most of the code is very similar to the Java version. The second problem I ran into is when you try to connect the dots between creating the lexer and the parser. In Java you just create a CommonTokenStream and pass the lexer into its constructor. In the C version you have to drill down the nested structs to find the token stream. It's not hard to find, it just takes way to long to drill down through the files.

extern "C" {
#import <antlr3.h>
#import "ExprLexer.h"
#import "ExprParser.h"
}

int main (int argc, char * const argv[]) {
    if(argc != 2) {
        printf("Which file do you want to parse?");
        return 0;
    }
   
    pANTLR3_INPUT_STREAM pInputStream = antlr3AsciiFileStreamNew((pANTLR3_UINT8)argv[1]);
   
    pExprLexer exprLex = ExprLexerNew(pInputStream);
   
    pANTLR3_COMMON_TOKEN_STREAM pTokenStream = antlr3CommonTokenStreamSourceNew(0, exprLex->pLexer->tokSource);
   
    pExprParser exprPar  = ExprParserNew(pTokenStream);
   
    exprPar->prog(exprPar);
   
    return 0;
}

TrackBack

TrackBack URL for this entry:
http://benjaminhalsted.com/blog-mt/mt-tb.fcgi/10

Post a comment

(If you haven't left a comment here before, you may need to be approved by the site owner before your comment will appear. Until then, it won't appear on the entry. Thanks for waiting.)