Interpreter Pattern
This lesson delves into the interpreter pattern, which allows us to simplify representation and implementation of a new programming language albeit with limited syntax.
What is it ?
The interpreter literally means a translator, someone who can convert from one form of speech to a another. The interpreter pattern converts a language's sentences into its grammar and interprets them.
Understanding the interpreter pattern requires background knowledge in automata and theory of computation. We'll briefly go over some of the concepts required to understand the pattern.
Grammar
Every human language has an associated grammar that defines what constructs are legal or illegal. Similarly, computer languages are defined by grammar too. Given a snippet of code, the language defined by the grammar would determine if the code is syntactically correct or not. There are four types of grammar known as the Chomsky's hierarchy.
- Regular
- Context Free
- Context Sensitive
- Recursively Enumerable
Context Free Grammar
We'll be interested in context free grammar for the purposes of this lesson. Most programming languages use context free grammars to specify the syntax of a language. A syntactically correct program however may or may not compile.
A CFG consists of four components:
start symbol
a set of terminal symbols
a set of non-terminal symbols
a set of productions (rules)
Let's immediately see an example to understand what is meant by each of the above terms. Consider the below productions or rules for an arithematic expression
- <expression> --> number
- <expression> --> <expression> + <expression>
- <expression> --> <expression> - <expression>
- <expression> --> <expression> * <expression>
- <expression> --> <expression> / <expression>
The above rules say that the left hand side expression, which is a ...