Question

I have defined a set of grammar rules. Consider this as a sample rules.

public bodylist
    : bodyset*
    ;

public bodyset
    : ruleSet
    | media
    | page
    ;  

If I have to parse using this rules, I have to do this as below.

        Stream inputStream = Console.OpenStandardInput();
        ANTLRInputStream input = new ANTLRInputStream(inputStream);
        CLexer lexer = new CLexer(input);
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        CParser parser = new CParser(tokens);

        parser.bodylist();

I am confused with the way of accessing the bodyset matching set of segments in the stream. It seems I have to do another parse as below

        parser.bodyset();

There can be morethan one bodyset grammar matching set of segments in the stream.

Lets say in the input stream we have more than one places where this rule is matched. What I want is to get information on the set of these bodyset information (in each, what is the start of the grammar rule and the end).

I was unable to find a way to access the information of the set of matches of bodyset grammar rule in the stream. I am confused with the API.

Was it helpful?

Solution

ANTLR 3 does not automatically create parse trees with listeners and visitors like ANTLR 4 does. You'll need to do one of the following:

  1. Upgrade to ANTLR 4, where the bodylist method will return a BodylistContext object, which provides a bodyset() method that returns a collection of BodysetContext objects (one for each bodyset that was parsed).
  2. Stay with ANTLR 3, but use the output=AST feature and tree grammars to process the input.
  3. Stay with ANTLR 3, and add action code to your grammar to manually construct a parse tree.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top