In CUP: How to make something optional to parse?

 ̄綄美尐妖づ 提交于 2019-12-10 15:27:18

问题


     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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!