Search code examples
javabnfjavaccformal-languages

Requiring or not a parameter


I'm using JavaCC on Java 8.

I have the following BNF form :

Program -> ( Definition )* EOF
Definition -> ( FUNCTION_DEF ) ( FUNCTION_NAME ) ( PARAMATER_NAME ) ( OPEN_B ) ( FUNCTION_BODY ) ( CLOSE_B ) 

With the following lexical analyser

TOKEN : { < EOL : "\n" | "\r" | "\r\n" > }
TOKEN : { < FUNCTION_DEF : "DEF" > }
TOKEN : { < FUNCTION_NAME : ( ["A"-"Z"] )+ > }
TOKEN : { < PARAMATER_NAME : ( ["a"-"z"] )+ > }
TOKEN : { < OPEN_B : "{" > }
TOKEN : { < CLOSE_B : "}" > }
TOKEN : { < SPACE : " " > }

As an input, I have the following :

DEF ABC x { x+1 }
DEF MAIN { ABC(1) }

My parser throws a parsing error because it requires a parameter name, obviously. How could I manage to require a parameter name ONLY if the function name is not MAIN?

Thanks


Solution

  • You may consider defining a separate expression for the MAIN function and then adding it to the definition of a program as an optional part:

    Program -> ( MainDefinition )? ( Definition )* EOF
    Definition -> ( FUNCTION_DEF ) ( FUNCTION_NAME ) ( PARAMATER_NAME ) ( OPEN_B ) ( FUNCTION_BODY ) ( CLOSE_B )
    MainDefinition -> ( FUNCTION_DEF ) "MAIN" ( OPEN_B ) ( FUNCTION_BODY ) ( CLOSE_B )
    

    Edit

    To allow MAIN to be either at the beginning, at the end or in the middle of other functions' definition, you can just change the Program expression like this

    Program -> ( Definition )* ( MainDefinition )? ( Definition )* EOF