Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 693
magnudae Avatar asked Feb 25 '13 10:02

magnudae


People also ask

What is cup parser?

CUP is a parser generator. It takes a CUP program - essentially an LALR(1) parsable grammar, and generates a Java program that will parse input that satisfies that grammar. CUP assumes that a lexical analyser is provided separately. Normally, the lexical analyser is generated using JFlex.

What is Cup in compiler design?

CUP is a system for generating LALR parsers from simple specifications. It serves the same role as the widely used program YACC [1] and in fact offers most of the features of YACC. However, CUP is written in Java, uses specifications including embedded Java code, and produces parsers which are implemented in Java.

What is cup Java?

CUP stands for Construction of Useful Parsers and is an LALR parser generator for Java.


1 Answers

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.

like image 190
DanTheMan Avatar answered Oct 29 '22 16:10

DanTheMan