开发者

Equal (not a token) in an ANTLR grammar. What does this mean?

What does the construct basename = in the following rule?

tabname:
   (ID'.')? basename = ID
;

开发者_如何学JAVAThere is this single occurrence of basename in the grammar.

Thanks


Using equals in that syntax creates a variable called basename that can then be referenced in actions:

tabname:
    (ID '.')? basename=ID {
        if ($basename.equals("CAT"))
            System.out.println("CAT found");
    };


It is used to name variables.

This can be very useful if you want to run some code during the parser.

Consider the java calculator example:

expr returns [float r]
{
float a,b;
r=0;
}
:   #(PLUS a=expr b=expr)   {r = a+b;}
|   #(STAR a=expr b=expr)   {r = a*b;}
|   i:INT           {r = (float)Integer.parseInt(i.getText());}
;

Here we say when we match a tree that has a PLUS or STAR token followed by 2 expressions, we'll match the expressions and name them a and b respectively.

After we'll use those variables we matched in a java statement. This statement is contained inside the { and } brackets. Here we use the java statements to actually do the calculation.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜