Backus-Naur Form (BNF) is a formal notation for describing the syntax of programming languages. It is a type of context-free grammar (CFG) and uses rules called productions.
| Symbol | Meaning | Example |
|---|---|---|
<name> | Non-terminal (to be replaced) | <digit> |
::= | "Is defined as" | <digit> ::= 0 | 1 | 2 | ... |
| | Alternation (OR) | 0 | 1 | 2 |
| Terminal | Literal symbol (not in angle brackets) | 0, 1, +, = |
<integer> ::= <sign><digits> | <digits> <sign> ::= + | - <digits> ::= <digit> | <digit><digits> <digit> ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
Start with the top-level non-terminal and apply rules until only terminals remain. This is called a derivation.
// Derive "-37":
<integer> → <sign><digits>
→ - <digits>
→ - <digit><digits>
→ - 3 <digits>
→ - 3 <digit>
→ - 3 7
EBNF extends BNF with additional notation to make grammars more concise:
| EBNF notation | Meaning |
|---|---|
[...] | Optional (zero or one) |
{...} | Repetition (zero or more) |
(...) | Grouping |
// EBNF for integer (equivalent to above):
<integer> ::= [+ | -] <digit> {<digit>}
BNF naturally handles recursion — a rule that refers to itself. This is used to express repetition:
// Recursive definition of a list of digits: <digits> ::= <digit> | <digit><digits> // This generates: 0, 1, 00, 01, 10, 123, 4567, ... // Recursive definition for balanced brackets: <expr> ::= (<expr>) | ε
A syntax diagram (also called a railroad diagram) is a visual alternative to BNF. It shows valid syntax as paths through a diagram.
| Shape | Represents |
|---|---|
| Rectangle | Non-terminal (rule) |
| Oval/rounded box | Terminal (literal) |
| Arrow | Path/direction of reading |
| Split/loop | Alternation or repetition |
BNF describes context-free languages — more powerful than regular languages. CFLs can express nested/recursive structures (like balanced brackets, arithmetic expressions) that regular expressions cannot.
| Formalism | Language class | Example |
|---|---|---|
| Regular expressions / FSMs | Regular languages | Identifiers, keywords |
| BNF / CFG | Context-free languages | Arithmetic expressions, balanced brackets |
| Turing machines | Recursively enumerable | All computable problems |
8 questions · instantly marked · AQA 7517 standard
| Term | Definition |
|---|
10 questions · 10 minutes