1

I'm pretty new to CFG, and I've tried out some samples as well. As of now I'm trying this for-loop to write it in CFG using BNF:

Start{
    int z = 20;
    for(int b = 0; b < 5; b++)  
    {
        //some statement
    }
}

Attempted BNF:

<program> ::= Start <blockstatements>
<blockstatements> ::= <statement> | <statement>; | <statement_list> | <empty>
<statement> ::= <typespecification> <varDeclaration> <assignment-operator> <expression> 
<typespecification> ::= char | short | int | long | float | double | string
<varDeclaration> ::= a | b | c | d | e | f | g | h | i | j | k | l | m | n | o | p | q | r | s | t | u | v | x | y | z
<assignment-operator> ::= =
<expression> ::= <value> 
<value> ::= <digit> | <letter> | <number> | <word> 
<digit> ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
<letter> ::= "A" | "B" | "C" | "D" | "E" | "F" | "G" | "H" | "I" | "J" | "K" | "L" | "M" | "N" | "O" | "P" | "Q" | "R" | "S" | 
            "T" | "U" | "V" | "W" | "X" | "Y" | "Z" | "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" | "i" | "j" | "k" | "l" | 
            "m" | "n" | "o" | "p" | "q" | "r" | "s" | "t" | "u" | "v" | "w" | "x" | "y" | "z"
<number> ::= <digit> + <digit> | <digit> - <digit> | <digit> * <digit> | <digit> / <digit>

The above CFG isn't complete and I wanted to make sure that I'm doing it correctly. Am I heading towards the right path? Should it be written as above or have I missed anything?

Any help could be appreciated.

Kulasangar
  • 113
  • 1
  • 6

1 Answers1

3

I've usually seen it expressed as something like:

forExpression ::= for ( <declExpression> <expression>; <expression> ) <blockStatement>

blockStatement ::= <statement> |  { <statementlist> }

statement ::= <declExpression> | <forExpression> | <ifExpression> | ...

<declExpression> includes the semi colon

You want to be very careful of the details like where you define where things like the semi colon are required,

In your <number> you don't have any priorities set up, there is also no option for parenthesis, ...

Creating a good CFG is hard which is why so many languages start out as a dialect of C and just take that grammar and adapt it.

ratchet freak
  • 4,696
  • 1
  • 18
  • 15