[antlr-interest] Lexer rule with alternatives (Newbie question)

John B. Brodie jbb at acm.org
Sat Nov 22 09:16:48 PST 2008


> My question is below:
> I have a grammar:
>
> expr    :
>         (operand) (OPER operand)*
>         ;
> operand :
>         ID|INT
>         ;
> OPER    :
>         ('+'|'-'|'*'|'/')
>         ;
> INT     :       
>         ('0'..'9')+
>         ;
> ID      :
>         ('a'..'z'|'A'..'Z'|'_')('a'..'z'|'A'..'Z'|'_'|'0'..'9')*
>         ;
>
> And for the input "t+1", I have the error:
> line 1:4 mismatched input '+'
>
works for me. no errors reported. using the attached test rig under ANTLR 
v3.1, August 12, 2008.

> But when I switch "OPER" to "oper", All work as it should. I don't
> understand Why it's so.
>
> Thank you
Hope this helps.
-- 
John B. Brodie

//---------------------begin attachment-------------------------
grammar Test;

options {
	output = AST;
	ASTLabelType = CommonTree;
}

@members {
    private static final String [] x = new String[]{
        "1+1", "t+1"
    };

    public static void main(String [] args) {
        for( int i = 0; i < x.length; ++i ) {
            try {
                System.out.println("about to parse:`"+x[i]+"`");
                TestLexer lexer = new TestLexer(new ANTLRStringStream(x[i]));
                CommonTokenStream tokens = new CommonTokenStream(lexer);

                TestParser parser = new TestParser(tokens);
                TestParser.expr_return p_result = parser.expr();

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

expr    :
        (operand) (OPER operand)*
        ;
operand :
        ID|INT
        ;
OPER    :
        ('+'|'-'|'*'|'/')
        ;
INT     :       
        ('0'..'9')+
        ;
ID      :
        ('a'..'z'|'A'..'Z'|'_')('a'..'z'|'A'..'Z'|'_'|'0'..'9')*
        ;
//---------------------end of attachment------------------------


-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.antlr.org/pipermail/antlr-interest/attachments/20081122/694a8c9c/attachment.html 


More information about the antlr-interest mailing list