简体   繁体   中英

Matching input alternatives in antlr 4

I am writing a simple parser to translate the query to SQL. I've completed the parser and got the parse tree, but now I need to translate those grammar to SQL using ANTLR 4.

If part of my grammar looks like

boolOp : OR|XOR|AND;

How will I print it if any matches exists?

Actually, I am trying to print AND if my query exists AND operator or if my query exists OR , then I have to print OR operator according to the grammar boolOp rule shown above.

PART OF MY CODE

public void exitBoolOp( Parser.BoolOpContext ctx)
{
    if (ctx.AND() == AND)
    {
        System.out.print(" AND "+"\t");
    }
    else if (ctx.OR() == OR)
    {
        System.out.print(" OR "+"\t");
    }
    else
    {
        System.out.print(" XOR "+"\t");
    }
}

The obvious problem I noticed in the code is the generated AND() , OR() , and XOR() methods return a TerminalNode , but the AND , OR , and XOR constants are declared as int . What you actually want to use is the expression:

if (ctx.AND() != null) {
    ...

Beyond this, you'll need to include more specific examples of your desired input and output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM