简体   繁体   中英

How does Bison deal with some optional part in BNF grammars?

I'm a freshman in Bison and Compiler principles, now I'm trying to write an easy Verilog parser in Flex&Bison according to the IEEE Standard. Here is the question: when a grammar's body has optional parts, which are enclosed by square brackets, what should I do in Bison? The BNF grammar maybe like this:

input_declaration ::= input [ net_type ] [ signed ] [ range ]  list_of_port_identifiers 

1, Should I enumerate them one by one like the following?

input_declaration : INPUT list_of_port_identifiers
                             | INPUT net_type list_of_port_identifiers
                             | INPUT signed list_of_port_identifiers
                             | INPUT net_type signed list_of_port_identifiers
                             ....

This way can do solve the problem, but I feel it's so stupid.

2, Should I write a %empty directive in the optional parts' grammar like the following?

net_type:
         %empty
        | SUPPLY0 
        | SUPPLY1 
        | TRI     
        | TRIAND  
        | TRIOR   
        | WIRE    
        | WAND    
        | WOR     
        ;

But I think this will cause some conflicts. So what is the best idea for this?

The best solution is (2):

net_type: %empty | ...;
signed:   %empty | ...;
range:    %empty | ...;

You should not see any conflicts between them unless they share tokens.

If you attempted to write all combinations as (1) and it worked, I still believe that you probably left out one combination by mistake, as Bison would in any case detect the conflict as in (2) and warn you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM