I'm starting with ANTLR, but I get some errors and I rea开发者_JS百科lly don't understand why.
Here you have my really simple grammar
grammar Expr;
options {backtrack=true;}
@header {}
@members {}
expr returns [String s]
: (LETTER SPACE DIGIT | TKDC) {$s = $DIGIT.text + $TKDC.text;}
;
// TOKENS
SPACE : ' ' ;
LETTER : 'd' ;
DIGIT : '0'..'9' ;
TKDC returns [String s] : 'd' SPACE 'C' {$s = "d C";} ;
This is the JAVA source, where I only ask for the "expr" result:
import org.antlr.runtime.*;
class Testantlr {
public static void main(String[] args) throws Exception {
ExprLexer lex = new ExprLexer(new ANTLRFileStream(args[0]));
CommonTokenStream tokens = new CommonTokenStream(lex);
ExprParser parser = new ExprParser(tokens);
try {
System.out.println(parser.expr());
} catch (RecognitionException e) {
e.printStackTrace();
}
}
}
The problem comes when my input file has the following content d 9.
I get the following error:
x line 1:2 mismatched character '9' expecting 'C'
x line 1:3 no viable alternative at input '<EOF>'
Does anyone knwos the problem here?
There are a few things wrong with your grammar:
- lexer rules can only return
Token
s, soreturns [String s]
is ignored afterTKDC
; backtrack=true
in youroptions
section does not apply to lexer rules, that is why you getmismatched character '9' expecting 'C'
(no backtracking there!);- the contents of your
expr
rule:(LETTER SPACE DIGIT | TKDC) {$s = $DIGIT.text + $TKDC.text;}
doesn't make much sense (to me). You either want to matchLETTER SPACE DIGIT
orTKDC
, yet you're trying to grab thetext
of both choices:$DIGIT.text
and$TKDC.text
.
It looks to me TKDC
needs to be "promoted" to a parser rule instead.
I think you dumbed down your example a bit too much to illustrate the problem you were facing. Perhaps it's a better idea to explain your actual problem instead: what are you trying to parse exactly?
精彩评论