Search code examples
parsingcompiler-constructionjflex

In CUP: How to make something optional to parse?


     PROC_DECL -> "proc" [ "ret" TYPE ] NAME
                  "(" [ PARAM_DECL { "," PARAM_DECL } ] ")"
                  "{" { DECL } { STMT } "}"

This is the grammar for a Procedure declaration.

How do you say that the "ret" TYPE is optional without making multiple cases?


Solution

  • Use another production, say ret_stmt, which can be either empty or contain a single return statement so in your .cup file you will have this productions:

    ret_stmt ::= // empty 
                        {: /*your action for empty return statement*/ :}
                     // Single return statement          
                     | "ret":r TYPE:t
                        {: /*your action for single return statement*/ :}
    
    PROC_DECL ::= "proc":p ret_stmt:r NAME:n
                      "(" param_list:pl ")"
                      "{" { DECL } { STMT } "}"
                       {: /*your action for procedure declaration statement*/ :}
    

    You can use a similar approach with parameters declaration, adding the production param_list.