CIE AS & A Level Computer Science, section 16.2 (Translation software)
Describing syntax
The syntax of a language is described precisely so that compilers can check it. Two ways are syntax diagrams and Backus-Naur Form (BNF).
Syntax diagrams
A syntax diagram is a set of boxes and arrows to show what can come next. Rounded boxes hold literal symbols, rectangles hold other items, and arrows can loop back to show repetition.
Backus-Naur Form
BNF is written as rules:
<non-terminal> ::= definition
<name>is a non-terminal: something defined by another rule.- Plain symbols are terminals: they appear in the language itself.
|means or.::=means is defined as.
Example: a digit and an integer
<digit> ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
<integer> ::= <digit> | <digit><integer>
The second rule is recursive: an integer is either one digit, or a digit followed by an integer. So 407 is valid: <digit> 4 then <integer> 07, and so on.
Example: a simple assignment
<letter> ::= a | b | c
<identifier> ::= <letter> | <letter><identifier>
<assignment> ::= <identifier> = <integer>
abc = 42 is valid. 42 = abc is not.
Why use them
They are exact and unambiguous, so a language can be defined and a compiler's syntax checker built from them.
Common mistake: forgetting that repetition in BNF is written with recursion (a rule that uses itself). Also, always include a non-recursive option (such as <digit>), or the rule can never end.
Exam tip: when asked to write a rule, put the terminal choices with | and make repeated items recursive. Check your rule by deriving a valid example step by step.
Check yourself
What does ::= mean in BNF?
"Is defined as".
Why is the rule ::= | recursive?
The definition of integer uses integer again, allowing any number of digits.
Is "12" a valid under that rule?
Yes, a digit followed by an integer which is a single digit.