tags:

views:

73

answers:

2

All of the examples which I see read in a file the lex & parse it.

I need to have a function which takes a string (char *, I'm generating C code) as parameter, and acts upon that.

How can I do that best? I thought of writing the string to a stream, then feeding that to the lexer, but it doesn't feel right. Is there any better way?

Thanks in advance

A: 

I think you should feed it to a stream. You could feed it to stdin if you'd like. That way, your code shouldn't differ too much from reading strings from a file.

just_wes
I suspect that feeding to stdin might be dangerous, as we can't predict who else might be feeding it at the same time.As I said above, I'd much rather pass a char *, but can't see an easy alternative to stream - alas
Mawg
+2  A: 

You would need to use the antlr3NewAsciiStringInPlaceStream method.

You didn't say what version of Antlr you were using so I'll assume Antlr v3.

The inputs to this method are the string to parse, it's length and then you can probably use NULL for the last input.

This produces an input stream similar to the antlr3AsciiFileStreamNew that you would use to parse a file.

I see that you mentioned writing the input to a stream. If you can use C++ then that's the best method you'll probably come by.

This is the barebones code I normally use:

std::istringstream  issInput(std::cin); // make this an ifstream if you want to parse a file
Lexer     oLexer(issInput);
Parser    oParser(oLexer);

oFactory("CommonASTWithHiddenTokens",&antlr::CommonASTWithHiddenTokens::factory);
 antlr::ASTFactory oFactory;
oParser.initializeASTFactory(oFactory);
oParser.setASTFactory(&oFactory);

oParser.main();
antlr::RefAST ast = oParser.getAST();
if (ast)
{
    TreeWalker oTreeWalker;
    oTreeWalker.main(ast, rPCode);
}
chollida
yes, V3. Unfortunately, I have to cater for the lowest common denominator, so it must be C, rather than C++.I'd rather just pass a char * if I can, but suspect that it must be stream, alas. It just seems messy ...thanks for the example
Mawg
IF C is what you're stuck with the the solution is to use the `antlr3NewAsciiStringInPlaceStream` that I showed in my solution. Just create one and pass it to your lexer and your Done. It couldn't be simpler:)
chollida