MoeBoeMe
MoeBoeMe

Reputation: 133

javaCC parser generator can't handle EOF

This is the code I've been using which I copied from here (from page 13 on; I could succesfully execute and parse an addition example from an input.txt file which contained numbers and + signs sintactically correct i.e. 4 + 2 returns six, but 4 ++ 2 gives an error)

options {
    STATIC = false ;
}

PARSER_BEGIN ( Calculator )
    import java.io.PrintStream ;

class Calculator
{
    public static void main ( String [] args)
    throws ParseException, TokenMgrError, NumberFormatException
    {
        Calculator parser = new Calculator( System.in ) ;
        parser.Start(System.out) ;
    }
    double previousValue = 0.0 ;
}
PARSER_END ( Calculator )

SKIP : { " " }
TOKEN : { < EOL : "\n" | "\r" | "\r\n" > }
TOKEN : { < PLUS : "+" > }
TOKEN : { < NUMBER : <DIGITS> | <DIGITS> "." <DIGITS> | <DIGITS> "." | "." <DIGITS> > }
TOKEN : { <#DIGITS : (["0"-"9"])+ > }

void Start(PrintStream printStream) throws NumberFormatException :
{}
{
    (
        previousValue = Expression()
        <EOL>
        {printStream.println(previousValue) ; }
    )*
    <EOF>
}

double Expression () throws NumberFormatException :
{
    double i ;
    double value ;  
}
{
    value = Primary ()
    (
        <PLUS>
        i = Primary()
        { value += i ; }
    )*
    { return value ; }
}

double Primary () throws NumberFormatException :
{
    Token t ;
}
{
    t = <NUMBER>
    { return Double.parseDouble( t.image ) ; }
}

´

C:\Users\Jay\workspace\javaCC>javacc calculator0.jj

Generates all the required java files correctly, all those I compile with no errors nor warnings with

javac *.java

But then, When I try to run

java Calculator < input.txt

where input.txt contains

4 + 2 + 2

for some reason in this new version I get

Exception in thread "main" ParseException: Encountered "<EOF>" at line 1, column 11.
Was expecting one of:
    <EOL> ...
    "+" ...

        at Calculator.generateParseException(Calculator.java:218)
        at Calculator.jj_consume_token(Calculator.java:156)
        at Calculator.Start(Calculator.java:27)
        at Calculator.main(Calculator.java:10)

How can I fix this?

Upvotes: 1

Views: 2492

Answers (1)

MoeBoeMe
MoeBoeMe

Reputation: 133

I found a solution. It was a little bug on that PDF and I was able to solve it. Only three characters needed to be added to fix that bug.

The answer is to change:

void Start(PrintStream printStream) throws NumberFormatException :
{}
{
    (
        previousValue = Expression()
        <EOL>
        {printStream.println(previousValue) ; }
    )*
    <EOF>
}

for

void Start(PrintStream printStream) throws NumberFormatException :
{}
{
    (
        previousValue = Expression()
        (<EOL>)*
        {printStream.println(previousValue) ; }
    )*
    <EOF>
}

And it works like a charm.

Upvotes: 2

Related Questions