1
votes

I am a beginner in ANTLR, and i want to make a program that detects variables. For that I wrote the following ANTLR code, but when I test it using grun, it gives me an error line 1:0 token recognition error at: 'p' on entering input p=10. I am unable to understand why does this not work.

grammar rules;
/*
*   Parser Rules
*/

addition : NUMBER PLUS NUMBER;
assign : VARIABLE ASSIGNMENT NUMBER;

/*
*   Lexer Rules
*/

VARIABLE : [a-zA-Z_]+;
NUMBER : [0-9]+ ;
WHITESPACE : [ \n\t\r]+ -> skip ;
NEWLINE: '\n';
PLUS : '+';
ASSIGNMENT : '=';

The rule for addition works fine, but the assign is not working. The command I am running on terminal is antlr4 rules.g4;grun rules assign -tokens and after that I input p=10 for testing, but still it does not work and shows me line 1:0 token recognition error at: 'p' error.

1
Do you get any messages/warnings from ANTLR? You might be missing a top-level rule expression := addition | assignjurez
@jurez I'm sorry. I was missing compiling the java files in the above commanduser185887

1 Answers

0
votes

The command I am running on terminal is antlr4 rules.g4;grun rules assign -tokens

antlr4 will generate Java source files from your grammar. grun will be accessing rulesParser.class and rulesLexer.class. What you're missing is the step in between where you use javac to compile the generated source files to class files.

Since you're not getting any errors about grun being unable to find the classes, you probably still have class files left over from the last time you ran javac. So grun is executing those old files, which apparently don't include anything that matches letters yet (or at least not the letter p). Compiling your source files with javac should fix this problem.