Syntax

Syntax is the structure of program phrases in a language. A grammar describes the syntax of a language.

Untitled

Above you can see the different steps in Syntax and Semantics. Syntax is how you write the program, and semantics is the meaning of what you write.

Just like there are many different types of programming languages, there are also many different types of grammars and grammar languages used to define grammars. But the principles used are often similar (just like is the case for different programming languages). In this course we will focus on BNF and SDF.

Backus–Naur form (BNF) is a notation technique for context-free grammars used to describe the syntax of programming languages, communication protocols, and other formal languages.

BNF is a popular grammar notation, mainly because it is simple and easy to understand. It is a relatively primitive way of defining grammars and does not offer any mechanisms for dealing with ambiguity (e.g. by specifying precedence and associativity).

BNF uses a set of symbols and rules to define the structure of a language, allowing developers to create unambiguous descriptions of syntax:

Untitled

which reads as “define ($::=$) $\text{E}$ to be either $n$ (a literal) or ($|$) the surface syntax consisting of an $\text{E}$, a plus sign ($+$), and another $\text{E}$, or ($|$) the surface syntax consisting of an $\text{E}$, a multiply sign ($*$), and another $\text{E}$”

BNF is defined by a set of so-called derivation rules. These rules define symbols which can be derived from a choice of sequences of literals and other symbols. We distinguish 2 types of symbols: terminals and non-terminals symbols. Terminal symbols are symbols that do not depend on the other symbols (they terminate the derivation). Non-terminal symbols are symbols that depend on other symbols.

Non-terminals are placeholders, like $\text{E}$ above: they stand for many more possibilities. They are given this name because the grammar doesn’t “terminate” here: the name is a place-holder that can (and must) be further expanded.

Terminals, in contrast, are concrete syntax, like $n$, $+$, $*$ above. They are so-called because they stand for themselves and can’t be expanded further. They are sometimes also called literals, because they must be written literally as shown. For this reason, any decorative symbols do not surround them. Everything is written literally unless it’s a non-terminal, in which case it’s replaced by something according to the definition of the non-terminal.

Untitled

An example of such a BNF grammar is provided below:

<digit> ::= "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"
<number> ::= <digit> <number> | <digit>

Here we defined two symbols: