开发者

Optional rewrite rule for AST in ANTLR

开发者 https://www.devze.com 2023-01-27 20:51 出处:网络
I have a problem while building AST in ANTLR (I\'m using ANTLR 3.2, ANTLRWorks 1.4). This is my grammar:

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

This is my grammar:

classDeclaration
    :
    (
        'class' n=IDENTIFIER ('extends' e=IDENTIFIER)?
    开发者_StackOverflow社区    '{'
        …
        '}'
    )
        -> ^(CLASSDECLARATION ^(NAME $n) ^(EXTENDS $e)
;

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

So the grammar works good with this class declaration:

class Test1 extends AbstractTest1 {
…
}

And fails when I exclude extends part, as follows:

class Test2 {
…
}

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

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


Got the problem solved. Nothing tricky, just had to use common RegExp syntax:

^(EXTENDS $e)?
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号