The common element in "while statements" and "do statements" is the continuation condition, which is an expression inside parentheses, always indicated with the keyword while
. If you wanted to, you could capture this commonality with something like:
<while-clause> ::= "while" "(" <expression> ")"
<while-statement> ::= <while-clause> <embedded-statement>
<do-statement> ::= "do" <embedded-statement> <while-clause> ";"
I'm not sure whether that adds any readability to the grammar. The actual C# grammar doesn't bother; it just uses
<while-statement> ::= "while" "(" <expression> ")" <embedded-statement>
<do-statement> ::= "do" <embedded-statement> "while" "(" <expression> ")" ";"
Thanks to @JörgWMittag for the above link, in which you have to search for while_statement
because the productions aren't tagged. Also see the specification text.
Either way, the productions simply reflect the evident syntax. At a high level, you can get surprisingly far into the writing of a grammar by just explaining the construct in your own language. ("A while statement starts with the keyword while
, followed by the continuation expression surrounded by parentheses, and then the statement to be iterated.")
The only subtlety here is the use of <embedded-statement>
instead of, say, <statement>
. That's because C#, like C and other C-derivatives, doesn't permit embedded statements to be declarations or to have labels. (If you want to do that, you'd need to embed a "block" (that is, a list of statements inside {
…}
).
while
statement or the grammar? $\endgroup$