The Interpreter Pattern Defining the Interpreter l Intent

  • Slides: 10
Download presentation
The Interpreter Pattern

The Interpreter Pattern

Defining the Interpreter l Intent l Given a language, define a representation for its

Defining the Interpreter l Intent l Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.

Pieces of the Interpreter l Abstract Expression l Terminal Expressions l Non. Terminal Expression

Pieces of the Interpreter l Abstract Expression l Terminal Expressions l Non. Terminal Expression l Context l Hold global information for the interpreter l Client Builds the Abstract Syntax Tree l Invokes Interpret on the tree l

Flow of the Interpreter l Build the Abstract Syntax Tree l Interpret the tree

Flow of the Interpreter l Build the Abstract Syntax Tree l Interpret the tree in the given Context Each non-terminal node will interpret its children and return a result from that. l Terminal nodes return actual values for nonterminal nodes to use. l The context serves as a global data for interpreting the entire tree l

Example Language: Arithmetic l Grammar l Equation : : = Variable | Integer |

Example Language: Arithmetic l Grammar l Equation : : = Variable | Integer | Plus | Minus | Times | Divide | Mod | Negate | ‘(‘ Eq ‘) l Terminal equations l l l Variable: : = ‘a’ | ‘b’ | ‘c’ …. |”ab” | … Integer: : = 1 | 2 | 3 | 4 | 5 | 6 | … Non-Terminal equations l Plus: : = Eq ‘+’ Eq Minus: : = Eq ‘-’ Eq Times: : = Eq ’*’ Eq Divide: : = Eq ‘-’ Eq Mod: : = Eq ‘%’ Eq …Negate: : ‘-’ Eq

Abstract Syntax Tree Example l 5 *2+B

Abstract Syntax Tree Example l 5 *2+B

Consequences l Easily extensible grammar l Implementing grammar is easy l Complex grammar is

Consequences l Easily extensible grammar l Implementing grammar is easy l Complex grammar is difficult to manage l Can easily add new ways to interpret expressions through the Visitor.

Related Patterns l Composite l l Interator l l Can be useful for traveling

Related Patterns l Composite l l Interator l l Can be useful for traveling the AST Visitor l l The Composite pattern is essential for representing the AST Essential for implementing multiple ways of interpreting the AST Flyweight l Especially useful when terminal symbols are used repetitively

Common uses l Widely used in compilers that are implemented with an OO language

Common uses l Widely used in compilers that are implemented with an OO language l Any case where you use the Composite Pattern to represent a language