开发者

Simple ANTLR error

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 Tokens, 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!);
  • 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 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?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜