Interpreter

Interpreter

Intent

Given a language, defines a representation for it's grammar along with an interpreter that uses the representation to interpret sentences in the language.

Applicability

Use the interpreter pattern when there is a language to interpret, you can represent statements in the language as abstract syntax trees. The interpreter pattern works best when:

  • The grammar is simple. For complex grammars, the class hierarchy for the grammar becomes large and unmanageable.
  • efficiency is not a critical concern. The most efficient interpreters are usually not implemented by interpreting parse trees directly but by first translating them into another form.

Structure

Orange

Participants

  • AbstractExpression: declares an abstract Interpret operation that is common to all nodes in the abstract syntax tree.
  • TerminalExpression: implements an Interpret operation associated with terminal symbols in the grammar.
  • NonTerminalExpression: implements an Interpret operation for non-terminal symbols.
  • Context: contains information that's global to the interpreter.
  • Client: builds an abstract syntax tree representing a particular sentence in the language that the grammar defines.

Collaborations

  • The client builds the sentence as an abstract syntax tree of Nonterminalexpression and TerminalExpression instances. Then the client initializes the context and invokes the Interpret operation.
  • Each NonterminalExpression node defines Interpret in terms of Interpret on each subexpression. The Interpret operation of each TerminalExpression defines the base case in the recursion.
  • The Interpret operations at each node use the context to store and access the state of the interpreter.

Consequences

  • It's easy to change and extend the grammar. Because the pattern uses classes to represent grammar rules, you can use inheritance to change or extend the grammar.
  • Implementing the grammar is easy.
  • Complex grammars are hard to maintain.
  • Adding new ways to interpret expressions.

Sample Code

Interpreter

Related Patterns

  • Composite: The abstract syntax tree is an instance of the Composite pattern.
  • Flyweight shows how to share terminal symbols within the abstract syntax tree.
  • Iterator: The interpreter can use an Iterator to traverse the structure.
  • Visitor can be used to maintain the behaviour in each node in the abstract syntax tree in one class.