Syntax and Semantics of Programming Languages
BNF is a notation for writing the syntax rules of programming languages, developed by John Backus and Peter Naur in the late 1950s.
Predicting Which Sentences Are Legal
Every language, whether spoken or written for a computer, follows patterns. Some arrangements of words are acceptable and others are not. A programming language has its own version of this idea: certain arrangements of keywords, symbols, and names count as legal programs, and others are rejected before they can run. Before reading any rules, try a small prediction. Imagine a tiny language whose only legal sentences have the shape of a noun phrase followed by a verb phrase. Is 'cat sleeps' legal? Is 'the cat sleeps' legal? Keep your answers in mind, because the rest of this article shows how a precise description settles these questions without guessing.
What do you think happens?
Given a grammar whose sentences must be a noun phrase followed by a verb phrase, and where the noun phrase must begin with the word 'the', is 'cat sleeps' legal?
Reveal answer
No, because the noun phrase is missing the required word 'the'
The grammar fixes the arrangement of parts, so 'cat sleeps' does not match the required pattern. A legal sentence must be produced by the rules, and this one cannot be, because every noun phrase in this toy grammar starts with 'the'.
Syntax as a Set of Patterns
The set of patterns that decides legality is called the syntax of the language, sometimes also called its grammar. Once you accept that syntax is a set of patterns, a practical question follows: if you want to hand the rules of a language to a human reader, a tool, or a compiler, how do you write them down precisely? Prose descriptions tend to be vague, and vagueness is a serious problem when the reader is a program. One standard answer to this question is a notation called BNF.
What BNF Is and Where It Came From
BNF, which stands for Backus-Naur Form, is a notation for writing the syntax rules of programming languages. It was developed by the computer scientists John Backus and Peter Naur in the late 1950s.
The source also points to a parallel development. At about the same time, the linguist Noam Chomsky independently arrived at an equivalent system for describing the grammar of natural language. Two groups, working on very different kinds of language, reached systems that express the same underlying idea. This is worth remembering: BNF is not a rule invented only for computers, but a way of describing patterns in any language.
Syntactic Categories and Angle Brackets
Think about the English words noun, transitive verb, and prepositional phrase. Each names a kind of building block that can appear inside a sentence, not one particular word. The same is true for code: words such as statement, number, and while loop name kinds of pieces that can appear inside a Java program. Terms like these are called syntactic categories.
The angle brackets are what distinguish a category from ordinary text. The word while, written without brackets, is a literal piece of the language. The phrase <while-loop>, written with brackets, is a placeholder that stands for any whole while loop the rules allow. Anything in brackets is a category to be expanded further, and anything without brackets is a basic symbol that appears exactly as written.
Anatomy of a Single BNF Rule
A rule in BNF specifies the structure of an item in a given syntactic category. It does this in terms of other syntactic categories, basic symbols of the language, or both. A rule therefore has two jobs. It names the category being defined, and it describes what an item of that category looks like. The diagram below labels the parts of a small rule written for a toy grammar of English. This rule is a generated illustration of the form, not a rule taken from a real language. Note that one common notation uses the separator ::=, while other notations draw the separator differently.
Read the rule from left to right. On the left of the separator sits the category being defined. Everything to the right describes the arrangement of parts that a legal item of that category must have. Here, the category verb-phrase may be the basic symbol sleeps or the basic symbol runs. The vertical bar separates the alternatives, so either form is legal. The separator is the point where the definition begins.
Tracing a Derivation Step by Step
A single rule is only a partial picture. A grammar is a collection of rules, and each category on the right side of one rule is usually defined by another rule. To check whether a piece of text is legal, you repeatedly replace a category with the structure its rule gives, until nothing in brackets remains. The following toy grammar is generated for teaching purposes. It has four rules, one for each category, and the last two rules end in basic symbols rather than further categories.
- The first rule defines a sentence as a noun phrase followed by a verb phrase.
- The second rule defines a noun phrase as the word the followed by a noun.
- The third rule ends in basic symbols, so it stops expanding.
- The fourth rule also ends in basic symbols.
Deriving the sentence 'the cat sleeps'
Use the toy grammar to show that 'the cat sleeps' is a legal sentence by replacing one bracketed category at a time.
- 1Start at the top category
Begin with <sentence>, the category the grammar is built to describe.
- 2Expand the sentence
Replace <sentence> with its rule's right side: <noun-phrase> <verb-phrase>.
- 3Expand the noun phrase
Replace <noun-phrase> with the <noun-phrase> rule: the <noun>. Now the string is the <noun> <verb-phrase>.
- 4Expand the noun
Replace <noun> with cat, one of its two allowed forms. The string is the cat <verb-phrase>.
- 5Expand the verb phrase
Replace <verb-phrase> with sleeps, one of its allowed forms. Nothing in brackets remains.
The sentence 'the cat sleeps' is legal under the toy grammar, because a sequence of replacements produces it and no bracketed category is left over.
The tree is the same information as the list of replacements, arranged so that each rule application is visible. Each step changed only one bracketed category, while the other pieces waited their turn. A reader who understands this process can look at any legal sentence and ask which rule produced each part of it. That question is the heart of parsing, which is covered in later work on this topic.
Trying the Grammar on Your Own
Using the toy grammar above, decide whether 'the dog runs' is legal. Write out the sequence of replacements you would make, starting from <sentence>. If you cannot finish the derivation, say which category is left unexpanded.
Hints
- Start from <sentence> and replace it with <noun-phrase> <verb-phrase>.
- The noun phrase must begin with the word the, followed by one of the nouns.
- The verb phrase must be one of the two basic symbols sleeps or runs.
Explain why 'the cat the dog' cannot be derived from the toy grammar, even though every word in it appears in a rule somewhere.
Hints
- Look at which categories can follow <noun-phrase> in a derivation.
- Count the categories and basic symbols the rules allow in a sentence.
Mistakes Beginners Make with BNF
Common mistake Treating angle-bracketed and unbracketed words as the same kind of thing
What it looks likeReading while and <while-loop> as interchangeable spellings of one idea.
Why it failsThe source states that anything in brackets is a category to be expanded further, while a word without brackets is a basic symbol that appears exactly as written.
Do this insteadRead <while-loop> as a placeholder for a whole loop, and read while as the literal keyword that must appear.
Common mistake Expecting BNF to check that a variable was defined earlier
What it looks likeWriting a rule for a use of a name and assuming it also guarantees a matching definition appears before it.
Why it failsBNF describes shape only. The requirement that a variable be defined before it is used cannot be stated with a BNF rule.
Do this insteadAccept that the rule can check the shape of a use, and leave the ordering check to a later stage of checking.
Common mistake Reading a BNF rule as a description of what the code does
The Limits of What BNF Can Express
BNF is powerful, but the source is clear about its limits. BNF cannot express all possible syntax rules. A useful example is the requirement that a variable must be defined before it is used. A BNF rule can describe the shape of an assignment or the shape of a use of a name, but it cannot state that the use must come after a matching definition somewhere earlier in the program. Rules like that belong to a different stage of checking.
These limits are a reason to pair BNF with other descriptions, not a reason to dismiss it. BNF does express the basic structure of a language, and it plays a central role in the design of compilers.
Revisiting the Opening Prediction
Return to the opening question. With the toy grammar, 'cat sleeps' is not legal, because no sequence of replacements produces it: the noun phrase must begin with the word the. 'The cat sleeps' is legal, because the derivation traced earlier produces it. Notice that the rules settled both answers without anyone running the sentence, which is the practical value of writing syntax down precisely.
Key Takeaways
- Syntax is the set of patterns that decides which programs are legal, and BNF (Backus-Naur Form) is a notation for writing those patterns precisely, developed by John Backus and Peter Naur in the late 1950s.
- Syntactic categories are written in angle brackets, such as <while-loop>, and stand for any whole item of that kind, while words without brackets are basic symbols that appear exactly as written.
- A BNF rule names the category being defined on the left and describes its allowed forms on the right, and a grammar is built from many such rules that expand categories step by step.
- BNF describes structure only: it cannot express rules such as defined-before-use and says nothing about meaning, so it is paired with other descriptions and later checking stages.