问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/15064980/in-cup-how-to-make-something-optional-to-parse