6
     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?

magnudae
  • 1,272
  • 2
  • 13
  • 32

1 Answers1

6

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.

DanTheMan
  • 191
  • 4
  • 11
  • I have made a post regarding a problem I've encountered while trying your solution here: https://stackoverflow.com/questions/52862424/how-to-match-the-empty-case-in-cup-parser-grammar Would you know how to solve this? – adhdj Oct 18 '18 at 00:53