Chapter 7Formal Languagesnotes.en.pdf:138-139

BNF Notation

Alternatives |, repetition *, optional ?

Def 7.2.8BNF
Concept

BNF (Backus-Naur Form, Definition 7.2.8, notes p. 138) is the practical
shorthand everyone actually uses to write context-free grammars. It was invented
to specify the syntax of ALGOL 60 and is now universal: every programming
language reference uses BNF.

BNF adds five convenience constructors to plain production rules:

1. Alternatives s1s2sns_1 \mid s_2 \mid \dots \mid s_n — choose one of the
sis_i. This is shorthand for nn rules sharing a head.
2. Repetition ss^* — zero or more ss's. s+s^+ means one or more.
3. Optional [s][s] — zero or one ss.
4. Grouping (s1;s2;;sn)(s_1 ; s_2 ; \dots ; s_n) — usually for repetition.
5. Character sets [st][s - t] — all characters cc with scts \le c \le t.
6. Complements [^  s1,,sn][\hat{} \; s_1, \dots, s_n] — all characters except those.

All of these can be eliminated by introducing auxiliary nonterminals and
extra rules. So BNF is purely a notational convenience — it adds zero expressive
power. For example, XZ(s)WX \to Z (s^*) W expands to:
- XZYWX \to Z Y W
- YϵY \to \epsilon
- YYsY \to Y s

And XZ(s+)WX \to Z (s^+) W expands to:
- XZYWX \to Z Y W
- YsY \to s
- YYsY \to Y s

BNF is the lingua franca of compiler writers and language designers.

Worked example
Step 0 of 2
Practice — score 100% to advance
Multiple choice
Q1
In BNF, s+s^+ means…
Q2
In BNF, [s][s] means…
Q3
s1s2s3s_1 \mid s_2 \mid s_3 is shorthand for…
Q4
Can BNF constructors be eliminated?
Q5
Where is BNF most commonly used?
Match definitions
Match each concept on the left to its definition on the right.
Order the steps
Arrange these proof steps in the correct order using the arrows.
1
Add YϵY \to \epsilon (or YsY \to s) for the base case
2
Add YsYY \to s Y (or YYsY \to Y s) for the recursive case
3
Introduce a fresh nonterminal YY to replace the constructor
4
Identify the BNF constructor: ss^* vs s+s^+ vs [s][s]
Loading…