Additional rewrite rule for AST in ANTLR

I have a problem building AST in ANTLR (I am using ANTLR 3.2, ANTLRWorks 1.4).

This is my grammar:

classDeclaration
    :
    (
        'class' n=IDENTIFIER ('extends' e=IDENTIFIER)?
        '{'
        …
        '}'
    )
        -> ^(CLASSDECLARATION ^(NAME $n) ^(EXTENDS $e)
;

The problem arises with the optional part of the class - ('extends' e=IDENTIFIER)?.

So the grammar works with this class declaration:

class Test1 extends AbstractTest1 {
…
}

And it fails if I exclude the part extendsas follows:

class Test2 {
…
}

ANTLR just stops before this snippet and gives this exception in the console: javax.swing.text.BadLocationException: Position not represented by view

How can I point to ANTLR to treat the rewrite rule ^(EXTENDS $e)as optional?

+3
source share
1 answer

The problem is solved. Nothing complicated, just had to use the generic RegExp syntax:

^(EXTENDS $e)?
+2
source

Source: https://habr.com/ru/post/1777309/


All Articles