SLIDE 4 4
Lecture 2 Formal Grammars CS631 Fall 2000 19
Practice Exercise
Give a BNF grammar for each of the following languages:
- 1. The set of all strings consisting of 0 or more a’s with a
semicolon after each one.
- 2. The set of all strings consisting of 1 or more a’s separated
by semicolons (but not before the first or after the last).
- 3. The set of all strings consisting of 0 or more a’s separated
by semicolons (but not before the first or after the last).
Lecture 2 Formal Grammars CS631 Fall 2000 20
EBNF
✁ Additional syntax to simplify some
grammar chores:
– {x} to mean zero or more repetitions of x – [x] to mean x is optional (i.e. x | <empty>) – () for grouping – | to mean a choice among alternatives – quotes around terminals, if necessary, to
distinguish from all these meta-symbols
Lecture 2 Formal Grammars CS631 Fall 2000 21
Practice Exercise
Give an EBNF grammar for each of these languages. Use the EBNF extensions where possible to simplify the grammars.
- 1. All the languages from the previous set of exercises.
- 2. The language of legal Pascal compound statements: the
keyword begin, followed by 0 or more statements separated by semicolons, followed by end. (Don’t worry about productions for the <statement> nonterminal.)
- 3. The language of legal C iteration statements using while,
and do. (Don’t worry about productions for the <expression> and <statement> nonterminals.)
Lecture 2 Formal Grammars CS631 Fall 2000 22
Many Other Variations
✁ BNF and EBNF ideas are widely used. ✁ Exact notation differs, in spite of occasional
efforts to get uniformity.
– Niklaus Wirth. What Can We Do About the
Unnecessary Diversity of Notation for Syntatic
- Definitions. Communications of the ACM,
November, 1977.
✁ But as long as you understand the ideas,
differences in notation are easy to pick up.
Lecture 2 Formal Grammars CS631 Fall 2000 23
Example: Java Grammar Excerpt
WhileStatement:
while ( Expression ) Statement
WhileStatementNoShortIf:
while ( Expression ) StatementNoShortIf
DoStatement:
do Statement while ( Expression ) ;
ForStatement:
for ( ForInitopt ; Expressionopt ; ForUpdateopt ) Statement
Lecture 2 Formal Grammars CS631 Fall 2000 24
Example: Java Grammar continued
ForInit: StatementExpressionList LocalVariableDeclaration ForUpdate: StatementExpressionList StatementExpressionList: StatementExpression StatementExpressionList , StatementExpression