Question

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

Was it helpful?

Solution

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);
}

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top