[antlr-interest] semantic predicates
Dominik Dietrich
dominik.dietrich at dfki.de
Fri Feb 11 01:41:47 PST 2011
Hi,
I'm new to ANTLR and have a problem with the following toy grammar,
which uses semantic predicates to disambiguate operator precedences. The
idea is to support dynamic prolog style operator declarations, where
lower precedence binds tighter. On the input 3*3+3, the epsilon
production of the rule rterm is not choosen, but instead I get a
NoViableAltException, which I do not understand. I'm aware that I could
also express the precedences in the productions, but this is not what I
want because the overall goal later is to support dynamic operators. Can
you please help?
Thanks.
grammar PTermParser;
options {
output=AST;
}
@members {
public static void main(String[] args) throws Exception {
PTermParserLexer lex = new PTermParserLexer(new
ANTLRFileStream(args[0]));
CommonTokenStream tokens = new CommonTokenStream(lex);
PTermParserParser parser = new PTermParserParser(tokens);
try {
parser.term(1200);
} catch (RecognitionException e) {
e.printStackTrace();
}
}
}
WHITESPACE: (' ' | '\t')+ { $channel = HIDDEN; };
NEWLINE: ('\r'? '\n')+ { $channel = HIDDEN;} ;
IDENTIFIER : LETTER (LETTER | DIGIT | '_')*;
NUMBER : DIGIT+;
OPERATORSEQ : SPECIALCHAR+;
fragment LETTER
: 'a'..'z'
| 'A'..'Z'
;
fragment DIGIT : '0' .. '9';
fragment SPECIALCHAR : '+' | '-' | '*' | '/';
start
@init{
System.out.println("start");
}
: term[1200];
term[int prec]
@init{
System.out.println("term with "+$prec);
}
:
NUMBER rterm[$prec, 0]
| IDENTIFIER rterm[$prec, 0]
| '(' term[1200] ')' rterm[$prec, 0]
;
rterm[int pprec, int lprec]
@init{
System.out.println("rterm: pprec is "+pprec+" lprec is "+lprec);
}
: {(400 <= $pprec) && ($lprec < 400)}?=> ('+'^ term[400]
rterm[pprec,400]) { System.out.println("use + production");}
| {(300 <= $pprec) && ($lprec < 300)}?=> ('*'^ term[300]
rterm[pprec,300]) { System.out.println("use * production");}
|
;
More information about the antlr-interest
mailing list