开发者

ANTLRWorks :Can't get operators to work

I've been trying to learn ANTLR for some time and finally got my hand开发者_运维问答s on The Definitive ANTLR reference. Well I tried the following in ANTLRWorks 1.4

grammar Test;

INT :   '0'..'9'+
    ;

WS  :   ( ' '
        | '\t'
        | '\r'
        | '\n'
        ) {$channel=HIDDEN;}
    ;

expression
    :   INT ('+'^ INT)*;

When I pass 2+4 and process expression, I don't get a tree with + as the root and 2 and 4 as the child nodes. Rather, I get expression as the root and 2, + and 4 as child nodes at the same level.

Can't figure out what I am doing wrong. Need help desparately.

BTW how can I get those graphic descriptions ?


Yes, you get the expression because it's an expression that your only rule expression is returning.

I have just added a virtual token PLUS to your example along with a rewrite expression that show the result your are expecting. But it seems that you have already found the solution :o)

grammar Test;

options {
    output=AST;
    ASTLabelType = CommonTree;
}
tokens {PLUS;}

@members {
   public static void main(String [] args) {
          try {
           TestLexer lexer =
               new TestLexer(new ANTLRStringStream("2+2"));
            CommonTokenStream tokens = new CommonTokenStream(lexer);
            TestParser parser = new TestParser(tokens);
            TestParser.expression_return p_result = parser.expression();

            CommonTree ast = p_result.tree;
            if( ast == null ) {
               System.out.println("resultant tree: is NULL");
            } else {
               System.out.println("resultant tree: " + ast.toStringTree());
            }
         } catch(Exception e) {
            e.printStackTrace();
         }
      }
}

expression
    :   INT ('+' INT)* -> ^(PLUS INT+);

INT :   '0'..'9'+
    ;

WS  :   ( ' '
        | '\t'
        | '\r'
        | '\n'
        ) {$channel=HIDDEN;}
    ;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜