ANTLR 4 Parser Grammar

How can I improve my parser grammar so that instead of creating an AST containing a couple of rules decFunc

for my test code. It will create only one and sum

become the second root. I tried to solve this problem in a couple of different ways, but I always get a left recursive error. This is my test code:

f :: [Int] -> [Int] -> [Int]
f x y = zipWith (sum) x y
sum :: [Int] -> [Int]
sum a = foldr(+) a

      

This is my grammar: This is the image with two decFunc

in this link http://postimg.org/image/w5goph9b7/

prog        : stat+;

stat        : decFunc  | impFunc ;


decFunc     : ID '::' formalType ( ARROW formalType )* NL impFunc
            ;

anotherFunc : ID+;


formalType  : 'Int' | '[' formalType ']' ;


impFunc     : ID+ '=' hr NL

            ;


hr          : 'map' '(' ID* ')'  ID*
                | 'zipWith' '(' ('*' |'/' |'+' |'-') ')' ID+ | 'zipWith' '(' anotherFunc ')' ID+
                | 'foldr'   '(' ('*' |'/' |'+' |'-') ')' ID+
                | hr  op=('*'| '/' | '.&.' | 'xor' ) hr | DIGIT
                | 'shiftL' hr hr | 'shiftR' hr hr
                | hr  op=('+'| '-') hr | DIGIT
                | '(' hr ')'
                | ID '(' ID* ')'
                | ID
                ;

      

+3


source to share


1 answer


The test input contains two instances of content that will match the rule decFunc

. Generated parsing treeshows that: two subdisks, each deFunc

with a root.

Antlr v4 does not give a true AST, where f

and sum

are the roots of separate subtrees.

Is there anything I can do with grammar to do both the roots f

and sum

- Jonny Magnam

Not directly in the Antlr v4 grammar. You could:



  • switch to Antlr v3 or another analyzer tool and define the generated AST as you like.
  • go through the parsing Antlr v4 and create a separate AST for your desired form.
  • just use the parse tree directly with the knowledge that it is informatively equivalent to the classically defined AST, and the implementation provides a number of practical advantages.

In particular, the standard academic ANT is mutable, which means that every (or all but the first) visitor is an ordinary, not generated, and that any change in the basic grammar or intermediate structure of ANT will require revision and likely changes to each subsequent visitor and their implemented logic.

The Antlr v4 parse tree is essentially immutable, allowing the accumulation of decorations for tree nodes without losing relational integrity. All visitors use a common basic structure, which greatly reduces the fragility due to grammar changes and the effects of previous completed visitors. In practical terms, tree structures are easy to construct, quickly, and independently of each other, except when clearly desired. They can achieve greater separation of concerns in design and easier maintenance of code in practice.

Choose the right tool for all the work, no matter how you define it.

+3


source







All Articles