Now that we have said the deeply unfashionable thing that syntax is not isolated from semantics we can now see why we bother to use a grammar analyzer within a compiler.
Put simply a syntax tree or its equivalent can be used to generate the machine code or intermediate code that the expression corresponds to.
The syntax tree can be considered as a program that tells you how to evaluate the expression.
For example, a common method of generating code from a tree is to walk all its nodes using a “depth first” algorithm.
That is, visit the deepest nodes first and generate an instruction corresponding to the value or operator stored at each node. The details of how to do this vary but you can see the general idea in this diagram.
So now you know. We use grammar to parse expressions, to make syntax trees, to generate the code.
A Real Grammar Of Arithmetic
You might like to see what a real grammar for simple arithmetic expressions looks like:
Of course it leaves out proper variable names, operators other than +, -, * and / but it is a reasonable start.
Summary
Grammar is not just related to the different machines that characterize the languages they describe. Grammars are generally useful in computer science.
The most common method of describing a grammar is some variation on BNF or Backus-Naur Form. It is important to realize that there is no standard for this, but the variations are usually easy to understand.
Extended BNF allows it to describe language forms that are specified as regular expressions.
Often syntax diagrams are easier to understand than pure BNF.
A grammar is often said to be to do with the syntax of a language and nothing at all to do with semantics, the meaning. This isn’t completely true.
To be useful, a grammar has to reveal the meaning of a language and it has to be compatible with its meaning.
With a suitable grammar you can work backwards from the sequence of symbols to the rules that created them. This is called parsing.
There are many parsing algorithms and in general simple grammars have simple parsing methods.
If a grammar is compatible with the meaning of a language then parsing can be used to construct a syntax tree which shows how the components group together.
A syntax tree can have many uses, but the main one in computer science is to generate a sequence of machine instructions that correspond to the original sequence of symbols. This is how a compiler works.