Hi All,
I am learning to use ANTLR and in trying out some stuff cannot work out
how to
parse for strings. My test grammar is as follows:
On trying an example, I am getting the error:
java -classpath /usr/java/lib/antlr.jar:. ExprParser '"joe";'
Exception in thread "main" line 1:2: expecting '"', found 'j'
at ExprLexer.nextToken(ExprLexer.java:80)
at antlr.TokenBuffer.fill(TokenBuffer.java:69)
at antlr.TokenBuffer.LA(TokenBuffer.java:80)
at antlr.LLkParser.LA(LLkParser.java:52)
at ExprParser.stmt(ExprParser.java:61)
at ExprParser.main(ExprParser.java:27)
Please help.
KM
------------------------------------------------------------------------------
{
im****t java.io.StringReader;
}
class ExprParser extends Parser;
options {
// buildAST = true;
}
{
public static void main(String[] args) throws Exception
{
for (int i = 0 ; i < args.length ; i++ ) {
ExprLexer lexer = new ExprLexer(new StringReader(args[i]));
ExprParser parser = new ExprParser(lexer);
parser.stmt();
}
}
}
stmt
:
( expr SEMI! )*
;
expr
:
atom ( PLUS atom )*
;
atom
:
STRING
;
class ExprLexer extends Lexer;
options {
// k = 2;
// charVocabulary = '\u0000' .. '\u00ff';
}
STRING
:
'"'! ( ESCAPE | ~('"'|'\\') )* '"'!
;
protected ESCAPE
:
'\\'
(
'n' { $setText("\n"); }
'r' { $setText("\r"); }
't' { $setText("\t"); }
'"' { $setText("\""); }
)
;
WS: ( ' ' | '\r' '\n' | '\n' | '\t' ) { $setType( Token.SKIP ); };
------------------------------------------------------------------------------