Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

antlr - loop through nodes

Tags:

antlr

antlr4

I have the following grammar (simplified):

filter   : eq | and;

eq       : 'eq' '(' property ',' value ')';

and      : 'and' '(' filter ',' filter (',' filter)* ')';

...

I am parsing simple prefix constructions like:

and(eq(name,john),eq(location,usa))

What is the best way to loop through the filter nodes of a and node? The generated class AndContext has a function filter(int index), but nothing more. I want to do something like:

AndContext c = ...;

for (int i = 0; i < c.numberOfFilters(); ++i) {
    FilterContext f = c.filter(i);
}

There is the function getChildCount(), but it returns the count of all nodes (including the terminal nodes representing (, ), etc.), and not just the interesting filter nodes.

like image 719
Steve Kelio Avatar asked Aug 16 '26 11:08

Steve Kelio


1 Answers

Let's say your grammar looks like this:

grammar F;

eq       : 'eq' '(' property ',' value ')';
and      : 'and' '(' filter ',' filter (',' filter)* ')';
filter   : eq | and;
property : 'name' | 'location';
value    : 'john' | 'usa';

then you could extend the generated FBaseListener and override its enterAnd to get to the FilterContexts:

public class Main {

    public static void main(String[] args) throws Exception {
        FLexer lexer = new FLexer(new ANTLRInputStream("and(eq(name,john),eq(location,usa))"));
        FParser parser = new FParser(new CommonTokenStream(lexer));
        ParseTreeWalker.DEFAULT.walk(new AndListener(), parser.and());
    }
}

class AndListener extends FBaseListener {

    @Override
    public void enterAnd(@NotNull FParser.AndContext ctx) {
        for (FParser.FilterContext filterContext : ctx.filter()) {
            System.out.println("filterContext=" + filterContext.getText());
        }
    }
}

which will print:

filterContext=eq(name,john)
filterContext=eq(location,usa)
like image 191
Bart Kiers Avatar answered Aug 20 '26 18:08

Bart Kiers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!