Reputation: 634
I'm starting with ANTLR, but I get some errors and I really 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?
Upvotes: 1
Views: 201
Reputation: 170148
There are a few things wrong with your grammar:
Token
s, so returns [String s]
is ignored after TKDC
;backtrack=true
in your options
section does not apply to lexer rules, that is why you get mismatched character '9' expecting 'C'
(no backtracking there!);expr
rule: (LETTER SPACE DIGIT | TKDC) {$s = $DIGIT.text + $TKDC.text;}
doesn't make much sense (to me). You either want to match LETTER SPACE DIGIT
or TKDC
, yet you're trying to grab the text
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?
Upvotes: 1