mansi kbchawla mansi kbchawla - 2 months ago 14
Java Question

Why am I getting syntax checking failed everytime I parse an assignment statement using javacc tool?

I have made a

AssignStatement
class and I am trying to pass the string using javacc

The assignment statement is of the form :
a=b+c*d


Here is the source code

PARSER_BEGIN(AssignStatement)

public class AssignStatement
{

public static void main(String s[])
{
try
{
AssignStatement as=new AssignStatement(System.in);
as.StartSymbol();
System.out.println("Syntax checking successfully");
}

catch(Throwable e)
{
System.out.println("Syntex checking failed"+e.getMessage());
}
}
}

PARSER_END(AssignStatement)

SKIP: {"" | "\t" | "\n" | "\r" }
TOKEN:{ "(" | ")" | "+" | "*" | ":="| <NUM: (["0"-"9"])+> | <ID:(["0"-"9"])+>
}

void StartSymbol(): {}
{
(AStmt())*<EOF>
}

void AStmt(): {}
{
LOOKAHEAD(2) <ID> "=" AStmt()
| Term() ("+" Term())*
}

void Term(): {}
{
Factor() ("*" Factor())*
}

void Factor(): {}
{
<NUM>
| <ID>
| "(" AStmt() ")"
}


The output I got after I did
java AssignStatement


"a=10+20*30" or a=10+20*30



Syntax checking failed error: Bailing out of infinite loop caused by repeated empty string matches at line 1, column 1.


From my point of you there can be 2 possibilities


  1. I am taking input from user wrong [in that case please suggest and also how to take input from a file

  2. My grammar is wrong. Please suggest



Please guide if anyone can?

Answer

The problem is on the line

SKIP: {"" | "\t" | "\n" | "\r" }

This says that you want to skip any 0 length strings. The problem is that having found such a token, the lexer removes 0 characters from the input, and then, of course, it finds the same 0 length token and so on ad infinitum.

Perhaps you meant

SKIP: {" " | "\t" | "\n" | "\r" }

Now, on input "a=10+20*30", no regular expression will match and you will get a TokenManagerError.

Matching the empty string has its (rare) uses. This is not one of them.

A second problem is with the rule

TOKEN:{ ... <NUM: (["0"-"9"])+> | <ID:(["0"-"9"])+> }

Since the definition of ID is the same as the definition of NUM, it will never succeed. Perhaps you want something like

TOKEN:{ ... <NUM: (["0"-"9"])+> | <ID:(["a"-"z"])+> }

If you do that you won't get the TokenManagerError on the input "a=10+20*30".