magnudae
magnudae

Reputation: 1272

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?

Upvotes: 6

Views: 1885

Answers (1)

DanTheMan
DanTheMan

Reputation: 291

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.

Upvotes: 6

Related Questions