SlideShare a Scribd company logo
1 of 31
Interpreter
By: Mahmoodreza Jahanseir
Amirkabir University of Technology Computer Engineering
Amirkabir University of Technology Computer Engineering Department Fall 2010
Intent
Given a language, define a representation for its grammar along
with an interpreter that uses the representation to interpret
sentences in the language.
2
Amirkabir University of Technology Computer Engineering Department Fall 2010
Motivation
The Interpreter pattern describes:
 how to define a grammar for simple languages,
 represent sentences in the language,
 and interpret these sentences.
3
Amirkabir University of Technology Computer Engineering Department Fall 2010
4
Basically the Interpreter pattern has limited area where it can be
applied. We can discuss the Interpreter pattern only in terms of
formal grammars but in this area there are better solutions that
is why it is not frequently used.
The Interpreter pattern uses a class to represent each grammar
rule.
Amirkabir University of Technology Computer Engineering Department Fall 2010
Applicability
Use the Interpreter pattern when there is a language to interpret,
and you can represent statements in the language as abstract
syntax trees.
The Interpreter pattern works best when
1) the grammar is simple.
2) For complex grammars, the class hierarchy for the grammar becomes large
and unmanageable.
3) They can interpret expressions without building abstract syntax trees,
which can save space and possibly time.
5
Amirkabir University of Technology Computer Engineering Department Fall 2010
Applicability (cont…)
– efficiency is not a critical concern.
2) The most efficient interpreters are usually not implemented by
interpreting parse trees directly but by first translating them into another
form.
6
Amirkabir University of Technology Computer Engineering Department Fall 2010
Structure
7
Amirkabir University of Technology Computer Engineering Department Fall 2010
8
Amirkabir University of Technology Computer Engineering Department Fall 2010
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.
 an instance is required for every terminal symbol in a sentence.
 NonterminalExpression
 one such class is required for every rule R ::= R1 R2 ... Rn in the grammar.
 maintains instance variables of type AbstractExpression for each of the
symbols R1 through Rn.
9
Amirkabir University of Technology Computer Engineering Department Fall 2010
Participants (cont…)
 implements an Interpret operation for nonterminal symbols in the
grammar. Interpret typically calls itself recursively on the variables
representing R1 through Rn.
Context
 contains information that's global to the interpreter.
Client
 builds (or is given) an abstract syntax tree representing a particular
sentence in the language that the grammar defines.
 invokes the Interpret operation.
10
Amirkabir University of Technology Computer Engineering Department Fall 2010
Collaborations
 The client builds (or is given) 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.
11
Amirkabir University of Technology Computer Engineering Department Fall 2010
Consequences
 Benefits:
 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, too. Classes defining nodes in the abstract
syntax tree have similar implementations.
 Adding new ways to interpret expressions. The Interpreter pattern makes it easier
to evaluate an expression in a new way.
 For example, you can support pretty printing or type-checking an expression by defining a
new operation on the expression classes.
 If you keep creating new ways of interpreting an expression, then consider using the Visitor
pattern to avoid changing the grammar classes.
12
Amirkabir University of Technology Computer Engineering Department Fall 2010
Consequences (cont…)
Liability:
 Complex grammars are hard to maintain. The Interpreter pattern
defines at least one class for every rule in the grammar. Hence
grammars containing many rules can be hard to manage and
maintain. when the grammar is very complex, other techniques such
as parser or compiler generators are more appropriate.
13
Amirkabir University of Technology Computer Engineering Department Fall 2010
Implementation
1) Creating the abstract syntax tree.
 The Interpreter pattern doesn't explain how to create an abstract syntax tree.
 The abstract syntax tree can be created by a table-driven parser, by a hand-
crafted parser, or directly by the client.
2) Defining the Interpret operation.
 If it's common to create a new interpreter, then it's better to use the Visitor
pattern to put Interpret in a separate "visitor" object.
3) Sharing terminal symbols with the Flyweight pattern.
 Grammars whose sentences contain many occurrences of a terminal symbol
might benefit from sharing a single copy of that symbol.
14
Amirkabir University of Technology Computer Engineering Department Fall 2010
Example
 First example is a system for manipulating and evaluating Boolean
expressions implemented in C++. The grammar is defined as follows:
 We define two operations on Boolean expressions:
1. Evaluate, evaluates a Boolean expression in a context that assigns a true or false
value to each variable.
2. Replace, produces a new Boolean expression by replacing a variable with an
expression.
15
Amirkabir University of Technology Computer Engineering Department Fall 2010
16
Amirkabir University of Technology Computer Engineering Department Fall 2010
17
Create an expression interface:
- Expression.java
public interface Expression
{
public boolean interpret(String context);
}
Amirkabir University of Technology Computer Engineering Department Fall 2010
18
Create concrete classes implementing the above interface:
- TerminalExpression.java
public class TerminalExpression implements Expression
{
private String data;
public TerminalExpression(String data){
this.data = data; }
@Override public boolean interpret(String context)
{ if(context.contains(data)){ return true;
} return false;
} }
Amirkabir University of Technology Computer Engineering Department Fall 2010
19
- OrExpression.java
public class OrExpression implements Expression {
private Expression expr1 = null;
private Expression expr2 = null;
public OrExpression(Expression expr1, Expression expr2)
{
this.expr1 = expr1;
this.expr2 = expr2;
}
@Override
public boolean interpret(String context) {
return expr1.interpret(context) || expr2.interpret(context);
} }
Amirkabir University of Technology Computer Engineering Department Fall 2010
20
- AndExpression.java
public class AndExpression implements Expression
{
private Expression expr1 = null;
private Expression expr2 = null;
public AndExpression(Expression expr1, Expression expr2)
{
this.expr1 = expr1;
this.expr2 = expr2; }
@Override
public boolean interpret(String context) {
return expr1.interpret(context) && expr2.interpret(context);
} }
Amirkabir University of Technology Computer Engineering Department Fall 2010
21
nterpreterPatternDemo.java
public class InterpreterPatternDemo { //Rule: Robert and John are
male public static Expression getMaleExpression(){ Expression
robert = new TerminalExpression("Robert"); Expression john = new
TerminalExpression("John"); return new OrExpression(robert, john);
} //Rule: Julie is a married women public static Expression
getMarriedWomanExpression(){ Expression julie = new
TerminalExpression("Julie"); Expression married = new
TerminalExpression("Married"); return new AndExpression(julie,
married); }
Amirkabir University of Technology Computer Engineering Department Fall 2010
22
public static void main(String[] args)
{
Expression isMale = getMaleExpression();
Expression isMarriedWoman = getMarriedWomanExpression();
System.out.println("John is male? " +
isMale.interpret("John"));
System.out.println("Julie is a married women? " +
isMarriedWoman.interpret("Married Julie"));
} }
Amirkabir University of Technology Computer Engineering Department Fall 2010
Example (cont…)
Replace shows how the Interpreter pattern can be used for more
than just evaluating expressions. In this case, it manipulates the
expression itself.
23
Amirkabir University of Technology Computer Engineering Department Fall 2010
Example (cont…)
BooleanExp defines the interface for all classes that define a
Boolean expression:
public abstract class BooleanExp
{
public BooleanExp(){}
public abstract bool Evaluate(Context aContext);
public abstract BooleanExp Replace(string name, BooleanExp bExp);
public abstract BooleanExp Copy();
}
24
Amirkabir University of Technology Computer Engineering Department Fall 2010
Example (cont…)
 The class Context defines a mapping from variables to Boolean values.
public class Context
{
Hashtable values;
public Context()
{
values = new Hashtable();
}
public bool Lookup(VariableExp varExp)
{
return(bool)values[varExp.name];
}
public void Assign(VariableExp varExp, bool bval)
{
values.Add(varExp.name, bval);
}
}
25
Amirkabir University of Technology Computer Engineering Department Fall 2010
Example (cont…)
public class VariableExp : BooleanExp
{
public string name;
public VariableExp(string _name){name = _name;}
public override bool Evaluate(Context aContext)
{
return aContext.Lookup(this);
}
public override BooleanExp Replace(string _name, BooleanExp bExp)
{
if (_name.Equals(name))
return bExp.Copy();
else
return new VariableExp(name);
}
public override BooleanExp Copy()
{
return new VariableExp(name);
}
}
26
Amirkabir University of Technology Computer Engineering Department Fall 2010
Example (cont…)
public class AndExp : BooleanExp
{
public BooleanExp operand1;
public BooleanExp operand2;
public VariableExp(BooleanExp op1, BooleanExp op2)
{operand1 = op1; operand2 = op2;}
public override bool Evaluate(Context aContext)
{
return operand1.Evaluate(aContext) &&
operand2.Evaluate(aContext);
}
public override BooleanExp Replace(string _name, BooleanExp bExp)
{
return new AndExp(operand1.Replace(_name, bExp),
operand2.Replace(_name, bExp));
}
public override BooleanExp Copy()
{
return new AndExp(operand1.Copy(),operand2.Copy());
}
}
27
Amirkabir University of Technology Computer Engineering Department Fall 2010
Example (cont…)
 (true and x) or (y and (not x))
BooleanExp expression;
Context context;
VariableExp x = new VariableExp("X");
VariableExp y = new VariableExp("Y");
expression = new OrExp( new AndExp(new Constant(true), x), new AndExp(y, new
NotExp(x)) );
context.Assign(x, false);
context.Assign(y, true);
bool result = expression.Evaluate(context);
 we can replace the variable y with a new expression and then reevaluate it:
VariableExp z = new VariableExp("Z");
NotExp not_z = new NotExp(z);
BooleanExp replacement = expression.Replace("Y", not_z);
context.Assign(z, true);
result = replacement.Evaluate(context);
28
Amirkabir University of Technology Computer Engineering Department Fall 2010
Example (cont…)
 This example illustrates an important point about the Interpreter
pattern: many kinds of operations can "interpret" a sentence.
 Evaluate fits our idea of what an interpreter should do most closely—
that is, it interprets a program or expression and returns a simple
result.
 However, Replace can be viewed as an interpreter as well. It's an
interpreter whose context is the name of the variable being replaced
along with the expression that replaces it, and whose result is a new
expression.
 Even Copy can be thought of as an interpreter with an empty context.
29
Amirkabir University of Technology Computer Engineering Department Fall 2010
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 behavior in each node in the abstract
syntax tree in one class.
30
Amirkabir University of Technology Computer Engineering Department Fall 2010
Q&A

More Related Content

What's hot

referát.doc
referát.docreferát.doc
referát.docbutest
 
Cross lingual similarity discrimination with translation characteristics
Cross lingual similarity discrimination with translation characteristicsCross lingual similarity discrimination with translation characteristics
Cross lingual similarity discrimination with translation characteristicsijaia
 
Hw6 interpreter iterator GoF
Hw6 interpreter iterator GoFHw6 interpreter iterator GoF
Hw6 interpreter iterator GoFEdison Lascano
 
Programming In C++
Programming In C++ Programming In C++
Programming In C++ shammi mehra
 
[Paper Introduction] Translating into Morphologically Rich Languages with Syn...
[Paper Introduction] Translating into Morphologically Rich Languages with Syn...[Paper Introduction] Translating into Morphologically Rich Languages with Syn...
[Paper Introduction] Translating into Morphologically Rich Languages with Syn...NAIST Machine Translation Study Group
 
7. Trevor Cohn (usfd) Statistical Machine Translation
7. Trevor Cohn (usfd) Statistical Machine Translation7. Trevor Cohn (usfd) Statistical Machine Translation
7. Trevor Cohn (usfd) Statistical Machine TranslationRIILP
 
Mi0041 java and web design
Mi0041  java and web designMi0041  java and web design
Mi0041 java and web designStudy Stuff
 
Literals,variables,datatype in C#
Literals,variables,datatype in C#Literals,variables,datatype in C#
Literals,variables,datatype in C#Prasanna Kumar SM
 
CBAS: CONTEXT BASED ARABIC STEMMER
CBAS: CONTEXT BASED ARABIC STEMMERCBAS: CONTEXT BASED ARABIC STEMMER
CBAS: CONTEXT BASED ARABIC STEMMERijnlc
 
Top interview questions in c
Top interview questions in cTop interview questions in c
Top interview questions in cAvinash Seth
 
Usage of regular expressions in nlp
Usage of regular expressions in nlpUsage of regular expressions in nlp
Usage of regular expressions in nlpeSAT Journals
 
A Study Of Statistical Models For Query Translation :Finding A Good Unit Of T...
A Study Of Statistical Models For Query Translation :Finding A Good Unit Of T...A Study Of Statistical Models For Query Translation :Finding A Good Unit Of T...
A Study Of Statistical Models For Query Translation :Finding A Good Unit Of T...iyo
 
Quality estimation of machine translation outputs through stemming
Quality estimation of machine translation outputs through stemmingQuality estimation of machine translation outputs through stemming
Quality estimation of machine translation outputs through stemmingijcsa
 
BERT - Part 1 Learning Notes of Senthil Kumar
BERT - Part 1 Learning Notes of Senthil KumarBERT - Part 1 Learning Notes of Senthil Kumar
BERT - Part 1 Learning Notes of Senthil KumarSenthil Kumar M
 

What's hot (20)

Introduction to programing languages part 2
Introduction to programing languages   part 2Introduction to programing languages   part 2
Introduction to programing languages part 2
 
referát.doc
referát.docreferát.doc
referát.doc
 
Cross lingual similarity discrimination with translation characteristics
Cross lingual similarity discrimination with translation characteristicsCross lingual similarity discrimination with translation characteristics
Cross lingual similarity discrimination with translation characteristics
 
Hw6 interpreter iterator GoF
Hw6 interpreter iterator GoFHw6 interpreter iterator GoF
Hw6 interpreter iterator GoF
 
Programming In C++
Programming In C++ Programming In C++
Programming In C++
 
[Paper Introduction] Translating into Morphologically Rich Languages with Syn...
[Paper Introduction] Translating into Morphologically Rich Languages with Syn...[Paper Introduction] Translating into Morphologically Rich Languages with Syn...
[Paper Introduction] Translating into Morphologically Rich Languages with Syn...
 
7. Trevor Cohn (usfd) Statistical Machine Translation
7. Trevor Cohn (usfd) Statistical Machine Translation7. Trevor Cohn (usfd) Statistical Machine Translation
7. Trevor Cohn (usfd) Statistical Machine Translation
 
Mi0041 java and web design
Mi0041  java and web designMi0041  java and web design
Mi0041 java and web design
 
Literals,variables,datatype in C#
Literals,variables,datatype in C#Literals,variables,datatype in C#
Literals,variables,datatype in C#
 
CBAS: CONTEXT BASED ARABIC STEMMER
CBAS: CONTEXT BASED ARABIC STEMMERCBAS: CONTEXT BASED ARABIC STEMMER
CBAS: CONTEXT BASED ARABIC STEMMER
 
Ay34306312
Ay34306312Ay34306312
Ay34306312
 
Top interview questions in c
Top interview questions in cTop interview questions in c
Top interview questions in c
 
Usage of regular expressions in nlp
Usage of regular expressions in nlpUsage of regular expressions in nlp
Usage of regular expressions in nlp
 
Usage of regular expressions in nlp
Usage of regular expressions in nlpUsage of regular expressions in nlp
Usage of regular expressions in nlp
 
A Study Of Statistical Models For Query Translation :Finding A Good Unit Of T...
A Study Of Statistical Models For Query Translation :Finding A Good Unit Of T...A Study Of Statistical Models For Query Translation :Finding A Good Unit Of T...
A Study Of Statistical Models For Query Translation :Finding A Good Unit Of T...
 
Asp.net main
Asp.net mainAsp.net main
Asp.net main
 
Quality estimation of machine translation outputs through stemming
Quality estimation of machine translation outputs through stemmingQuality estimation of machine translation outputs through stemming
Quality estimation of machine translation outputs through stemming
 
BERT - Part 1 Learning Notes of Senthil Kumar
BERT - Part 1 Learning Notes of Senthil KumarBERT - Part 1 Learning Notes of Senthil Kumar
BERT - Part 1 Learning Notes of Senthil Kumar
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 

Similar to Interpreter Pattern Document

Interface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar SinghInterface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar Singhdheeraj_cse
 
PSEUDOCODE TO SOURCE PROGRAMMING LANGUAGE TRANSLATOR
PSEUDOCODE TO SOURCE PROGRAMMING LANGUAGE TRANSLATORPSEUDOCODE TO SOURCE PROGRAMMING LANGUAGE TRANSLATOR
PSEUDOCODE TO SOURCE PROGRAMMING LANGUAGE TRANSLATORijistjournal
 
Automated Refactoring of Legacy Java Software to Default Methods Talk at GMU
Automated Refactoring of Legacy Java Software to Default Methods Talk at GMUAutomated Refactoring of Legacy Java Software to Default Methods Talk at GMU
Automated Refactoring of Legacy Java Software to Default Methods Talk at GMURaffi Khatchadourian
 
SOFTWARE TOOL FOR TRANSLATING PSEUDOCODE TO A PROGRAMMING LANGUAGE
SOFTWARE TOOL FOR TRANSLATING PSEUDOCODE TO A PROGRAMMING LANGUAGESOFTWARE TOOL FOR TRANSLATING PSEUDOCODE TO A PROGRAMMING LANGUAGE
SOFTWARE TOOL FOR TRANSLATING PSEUDOCODE TO A PROGRAMMING LANGUAGEIJCI JOURNAL
 
SOFTWARE TOOL FOR TRANSLATING PSEUDOCODE TO A PROGRAMMING LANGUAGE
SOFTWARE TOOL FOR TRANSLATING PSEUDOCODE TO A PROGRAMMING LANGUAGESOFTWARE TOOL FOR TRANSLATING PSEUDOCODE TO A PROGRAMMING LANGUAGE
SOFTWARE TOOL FOR TRANSLATING PSEUDOCODE TO A PROGRAMMING LANGUAGEIJCI JOURNAL
 
Pemrograman komputer 4 (ekspresi)
Pemrograman komputer  4 (ekspresi)Pemrograman komputer  4 (ekspresi)
Pemrograman komputer 4 (ekspresi)jayamartha
 
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...Raffi Khatchadourian
 
Password protected diary
Password protected diaryPassword protected diary
Password protected diarySHARDA SHARAN
 
Natural Language Interface for Java Programming: Survey
Natural Language Interface for Java Programming: SurveyNatural Language Interface for Java Programming: Survey
Natural Language Interface for Java Programming: Surveyrahulmonikasharma
 
Android coding guide lines
Android coding guide linesAndroid coding guide lines
Android coding guide lineslokeshG38
 
The NuGram dynamic grammar language
The NuGram dynamic grammar languageThe NuGram dynamic grammar language
The NuGram dynamic grammar languageNu Echo Inc.
 
Generative programming (mostly parser generation)
Generative programming (mostly parser generation)Generative programming (mostly parser generation)
Generative programming (mostly parser generation)Ralf Laemmel
 
Introduction to systems programming
Introduction to systems programmingIntroduction to systems programming
Introduction to systems programmingMukesh Tekwani
 
The future of DSLs - functions and formal methods
The future of DSLs - functions and formal methodsThe future of DSLs - functions and formal methods
The future of DSLs - functions and formal methodsMarkus Voelter
 
Pattern-Level Programming with Asteroid
Pattern-Level Programming with AsteroidPattern-Level Programming with Asteroid
Pattern-Level Programming with Asteroidijpla
 
Declare Your Language: Syntax Definition
Declare Your Language: Syntax DefinitionDeclare Your Language: Syntax Definition
Declare Your Language: Syntax DefinitionEelco Visser
 

Similar to Interpreter Pattern Document (20)

Interface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar SinghInterface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar Singh
 
PSEUDOCODE TO SOURCE PROGRAMMING LANGUAGE TRANSLATOR
PSEUDOCODE TO SOURCE PROGRAMMING LANGUAGE TRANSLATORPSEUDOCODE TO SOURCE PROGRAMMING LANGUAGE TRANSLATOR
PSEUDOCODE TO SOURCE PROGRAMMING LANGUAGE TRANSLATOR
 
Automated Refactoring of Legacy Java Software to Default Methods Talk at GMU
Automated Refactoring of Legacy Java Software to Default Methods Talk at GMUAutomated Refactoring of Legacy Java Software to Default Methods Talk at GMU
Automated Refactoring of Legacy Java Software to Default Methods Talk at GMU
 
PDFTextProcessing
PDFTextProcessingPDFTextProcessing
PDFTextProcessing
 
SOFTWARE TOOL FOR TRANSLATING PSEUDOCODE TO A PROGRAMMING LANGUAGE
SOFTWARE TOOL FOR TRANSLATING PSEUDOCODE TO A PROGRAMMING LANGUAGESOFTWARE TOOL FOR TRANSLATING PSEUDOCODE TO A PROGRAMMING LANGUAGE
SOFTWARE TOOL FOR TRANSLATING PSEUDOCODE TO A PROGRAMMING LANGUAGE
 
SOFTWARE TOOL FOR TRANSLATING PSEUDOCODE TO A PROGRAMMING LANGUAGE
SOFTWARE TOOL FOR TRANSLATING PSEUDOCODE TO A PROGRAMMING LANGUAGESOFTWARE TOOL FOR TRANSLATING PSEUDOCODE TO A PROGRAMMING LANGUAGE
SOFTWARE TOOL FOR TRANSLATING PSEUDOCODE TO A PROGRAMMING LANGUAGE
 
Pemrograman komputer 4 (ekspresi)
Pemrograman komputer  4 (ekspresi)Pemrograman komputer  4 (ekspresi)
Pemrograman komputer 4 (ekspresi)
 
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
 
Password protected diary
Password protected diaryPassword protected diary
Password protected diary
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Arabic MT Project
Arabic MT ProjectArabic MT Project
Arabic MT Project
 
Natural Language Interface for Java Programming: Survey
Natural Language Interface for Java Programming: SurveyNatural Language Interface for Java Programming: Survey
Natural Language Interface for Java Programming: Survey
 
Android coding guide lines
Android coding guide linesAndroid coding guide lines
Android coding guide lines
 
The NuGram dynamic grammar language
The NuGram dynamic grammar languageThe NuGram dynamic grammar language
The NuGram dynamic grammar language
 
Generative programming (mostly parser generation)
Generative programming (mostly parser generation)Generative programming (mostly parser generation)
Generative programming (mostly parser generation)
 
Introduction to systems programming
Introduction to systems programmingIntroduction to systems programming
Introduction to systems programming
 
The future of DSLs - functions and formal methods
The future of DSLs - functions and formal methodsThe future of DSLs - functions and formal methods
The future of DSLs - functions and formal methods
 
I1 geetha3 revathi
I1 geetha3 revathiI1 geetha3 revathi
I1 geetha3 revathi
 
Pattern-Level Programming with Asteroid
Pattern-Level Programming with AsteroidPattern-Level Programming with Asteroid
Pattern-Level Programming with Asteroid
 
Declare Your Language: Syntax Definition
Declare Your Language: Syntax DefinitionDeclare Your Language: Syntax Definition
Declare Your Language: Syntax Definition
 

Recently uploaded

Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...lizamodels9
 
Keppel Ltd. 1Q 2024 Business Update Presentation Slides
Keppel Ltd. 1Q 2024 Business Update  Presentation SlidesKeppel Ltd. 1Q 2024 Business Update  Presentation Slides
Keppel Ltd. 1Q 2024 Business Update Presentation SlidesKeppelCorporation
 
Lowrate Call Girls In Sector 18 Noida ❤️8860477959 Escorts 100% Genuine Servi...
Lowrate Call Girls In Sector 18 Noida ❤️8860477959 Escorts 100% Genuine Servi...Lowrate Call Girls In Sector 18 Noida ❤️8860477959 Escorts 100% Genuine Servi...
Lowrate Call Girls In Sector 18 Noida ❤️8860477959 Escorts 100% Genuine Servi...lizamodels9
 
Vip Dewas Call Girls #9907093804 Contact Number Escorts Service Dewas
Vip Dewas Call Girls #9907093804 Contact Number Escorts Service DewasVip Dewas Call Girls #9907093804 Contact Number Escorts Service Dewas
Vip Dewas Call Girls #9907093804 Contact Number Escorts Service Dewasmakika9823
 
Call Girls In Connaught Place Delhi ❤️88604**77959_Russian 100% Genuine Escor...
Call Girls In Connaught Place Delhi ❤️88604**77959_Russian 100% Genuine Escor...Call Girls In Connaught Place Delhi ❤️88604**77959_Russian 100% Genuine Escor...
Call Girls In Connaught Place Delhi ❤️88604**77959_Russian 100% Genuine Escor...lizamodels9
 
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...lizamodels9
 
M.C Lodges -- Guest House in Jhang.
M.C Lodges --  Guest House in Jhang.M.C Lodges --  Guest House in Jhang.
M.C Lodges -- Guest House in Jhang.Aaiza Hassan
 
Call Girls In Radisson Blu Hotel New Delhi Paschim Vihar ❤️8860477959 Escorts...
Call Girls In Radisson Blu Hotel New Delhi Paschim Vihar ❤️8860477959 Escorts...Call Girls In Radisson Blu Hotel New Delhi Paschim Vihar ❤️8860477959 Escorts...
Call Girls In Radisson Blu Hotel New Delhi Paschim Vihar ❤️8860477959 Escorts...lizamodels9
 
Banana Powder Manufacturing Plant Project Report 2024 Edition.pptx
Banana Powder Manufacturing Plant Project Report 2024 Edition.pptxBanana Powder Manufacturing Plant Project Report 2024 Edition.pptx
Banana Powder Manufacturing Plant Project Report 2024 Edition.pptxgeorgebrinton95
 
Case study on tata clothing brand zudio in detail
Case study on tata clothing brand zudio in detailCase study on tata clothing brand zudio in detail
Case study on tata clothing brand zudio in detailAriel592675
 
A.I. Bot Summit 3 Opening Keynote - Perry Belcher
A.I. Bot Summit 3 Opening Keynote - Perry BelcherA.I. Bot Summit 3 Opening Keynote - Perry Belcher
A.I. Bot Summit 3 Opening Keynote - Perry BelcherPerry Belcher
 
FULL ENJOY - 9953040155 Call Girls in Chhatarpur | Delhi
FULL ENJOY - 9953040155 Call Girls in Chhatarpur | DelhiFULL ENJOY - 9953040155 Call Girls in Chhatarpur | Delhi
FULL ENJOY - 9953040155 Call Girls in Chhatarpur | DelhiMalviyaNagarCallGirl
 
Marketing Management Business Plan_My Sweet Creations
Marketing Management Business Plan_My Sweet CreationsMarketing Management Business Plan_My Sweet Creations
Marketing Management Business Plan_My Sweet Creationsnakalysalcedo61
 
Lean: From Theory to Practice — One City’s (and Library’s) Lean Story… Abridged
Lean: From Theory to Practice — One City’s (and Library’s) Lean Story… AbridgedLean: From Theory to Practice — One City’s (and Library’s) Lean Story… Abridged
Lean: From Theory to Practice — One City’s (and Library’s) Lean Story… AbridgedKaiNexus
 
Non Text Magic Studio Magic Design for Presentations L&P.pptx
Non Text Magic Studio Magic Design for Presentations L&P.pptxNon Text Magic Studio Magic Design for Presentations L&P.pptx
Non Text Magic Studio Magic Design for Presentations L&P.pptxAbhayThakur200703
 
Call Girls In Kishangarh Delhi ❤️8860477959 Good Looking Escorts In 24/7 Delh...
Call Girls In Kishangarh Delhi ❤️8860477959 Good Looking Escorts In 24/7 Delh...Call Girls In Kishangarh Delhi ❤️8860477959 Good Looking Escorts In 24/7 Delh...
Call Girls In Kishangarh Delhi ❤️8860477959 Good Looking Escorts In 24/7 Delh...lizamodels9
 
RE Capital's Visionary Leadership under Newman Leech
RE Capital's Visionary Leadership under Newman LeechRE Capital's Visionary Leadership under Newman Leech
RE Capital's Visionary Leadership under Newman LeechNewman George Leech
 
Vip Female Escorts Noida 9711199171 Greater Noida Escorts Service
Vip Female Escorts Noida 9711199171 Greater Noida Escorts ServiceVip Female Escorts Noida 9711199171 Greater Noida Escorts Service
Vip Female Escorts Noida 9711199171 Greater Noida Escorts Serviceankitnayak356677
 

Recently uploaded (20)

Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
 
Keppel Ltd. 1Q 2024 Business Update Presentation Slides
Keppel Ltd. 1Q 2024 Business Update  Presentation SlidesKeppel Ltd. 1Q 2024 Business Update  Presentation Slides
Keppel Ltd. 1Q 2024 Business Update Presentation Slides
 
Lowrate Call Girls In Sector 18 Noida ❤️8860477959 Escorts 100% Genuine Servi...
Lowrate Call Girls In Sector 18 Noida ❤️8860477959 Escorts 100% Genuine Servi...Lowrate Call Girls In Sector 18 Noida ❤️8860477959 Escorts 100% Genuine Servi...
Lowrate Call Girls In Sector 18 Noida ❤️8860477959 Escorts 100% Genuine Servi...
 
Vip Dewas Call Girls #9907093804 Contact Number Escorts Service Dewas
Vip Dewas Call Girls #9907093804 Contact Number Escorts Service DewasVip Dewas Call Girls #9907093804 Contact Number Escorts Service Dewas
Vip Dewas Call Girls #9907093804 Contact Number Escorts Service Dewas
 
Call Girls In Connaught Place Delhi ❤️88604**77959_Russian 100% Genuine Escor...
Call Girls In Connaught Place Delhi ❤️88604**77959_Russian 100% Genuine Escor...Call Girls In Connaught Place Delhi ❤️88604**77959_Russian 100% Genuine Escor...
Call Girls In Connaught Place Delhi ❤️88604**77959_Russian 100% Genuine Escor...
 
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
 
M.C Lodges -- Guest House in Jhang.
M.C Lodges --  Guest House in Jhang.M.C Lodges --  Guest House in Jhang.
M.C Lodges -- Guest House in Jhang.
 
Call Girls In Radisson Blu Hotel New Delhi Paschim Vihar ❤️8860477959 Escorts...
Call Girls In Radisson Blu Hotel New Delhi Paschim Vihar ❤️8860477959 Escorts...Call Girls In Radisson Blu Hotel New Delhi Paschim Vihar ❤️8860477959 Escorts...
Call Girls In Radisson Blu Hotel New Delhi Paschim Vihar ❤️8860477959 Escorts...
 
Banana Powder Manufacturing Plant Project Report 2024 Edition.pptx
Banana Powder Manufacturing Plant Project Report 2024 Edition.pptxBanana Powder Manufacturing Plant Project Report 2024 Edition.pptx
Banana Powder Manufacturing Plant Project Report 2024 Edition.pptx
 
Case study on tata clothing brand zudio in detail
Case study on tata clothing brand zudio in detailCase study on tata clothing brand zudio in detail
Case study on tata clothing brand zudio in detail
 
A.I. Bot Summit 3 Opening Keynote - Perry Belcher
A.I. Bot Summit 3 Opening Keynote - Perry BelcherA.I. Bot Summit 3 Opening Keynote - Perry Belcher
A.I. Bot Summit 3 Opening Keynote - Perry Belcher
 
FULL ENJOY - 9953040155 Call Girls in Chhatarpur | Delhi
FULL ENJOY - 9953040155 Call Girls in Chhatarpur | DelhiFULL ENJOY - 9953040155 Call Girls in Chhatarpur | Delhi
FULL ENJOY - 9953040155 Call Girls in Chhatarpur | Delhi
 
KestrelPro Flyer Japan IT Week 2024 (English)
KestrelPro Flyer Japan IT Week 2024 (English)KestrelPro Flyer Japan IT Week 2024 (English)
KestrelPro Flyer Japan IT Week 2024 (English)
 
Marketing Management Business Plan_My Sweet Creations
Marketing Management Business Plan_My Sweet CreationsMarketing Management Business Plan_My Sweet Creations
Marketing Management Business Plan_My Sweet Creations
 
Lean: From Theory to Practice — One City’s (and Library’s) Lean Story… Abridged
Lean: From Theory to Practice — One City’s (and Library’s) Lean Story… AbridgedLean: From Theory to Practice — One City’s (and Library’s) Lean Story… Abridged
Lean: From Theory to Practice — One City’s (and Library’s) Lean Story… Abridged
 
Non Text Magic Studio Magic Design for Presentations L&P.pptx
Non Text Magic Studio Magic Design for Presentations L&P.pptxNon Text Magic Studio Magic Design for Presentations L&P.pptx
Non Text Magic Studio Magic Design for Presentations L&P.pptx
 
Call Girls In Kishangarh Delhi ❤️8860477959 Good Looking Escorts In 24/7 Delh...
Call Girls In Kishangarh Delhi ❤️8860477959 Good Looking Escorts In 24/7 Delh...Call Girls In Kishangarh Delhi ❤️8860477959 Good Looking Escorts In 24/7 Delh...
Call Girls In Kishangarh Delhi ❤️8860477959 Good Looking Escorts In 24/7 Delh...
 
RE Capital's Visionary Leadership under Newman Leech
RE Capital's Visionary Leadership under Newman LeechRE Capital's Visionary Leadership under Newman Leech
RE Capital's Visionary Leadership under Newman Leech
 
Enjoy ➥8448380779▻ Call Girls In Sector 18 Noida Escorts Delhi NCR
Enjoy ➥8448380779▻ Call Girls In Sector 18 Noida Escorts Delhi NCREnjoy ➥8448380779▻ Call Girls In Sector 18 Noida Escorts Delhi NCR
Enjoy ➥8448380779▻ Call Girls In Sector 18 Noida Escorts Delhi NCR
 
Vip Female Escorts Noida 9711199171 Greater Noida Escorts Service
Vip Female Escorts Noida 9711199171 Greater Noida Escorts ServiceVip Female Escorts Noida 9711199171 Greater Noida Escorts Service
Vip Female Escorts Noida 9711199171 Greater Noida Escorts Service
 

Interpreter Pattern Document

  • 1. Interpreter By: Mahmoodreza Jahanseir Amirkabir University of Technology Computer Engineering
  • 2. Amirkabir University of Technology Computer Engineering Department Fall 2010 Intent Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language. 2
  • 3. Amirkabir University of Technology Computer Engineering Department Fall 2010 Motivation The Interpreter pattern describes:  how to define a grammar for simple languages,  represent sentences in the language,  and interpret these sentences. 3
  • 4. Amirkabir University of Technology Computer Engineering Department Fall 2010 4 Basically the Interpreter pattern has limited area where it can be applied. We can discuss the Interpreter pattern only in terms of formal grammars but in this area there are better solutions that is why it is not frequently used. The Interpreter pattern uses a class to represent each grammar rule.
  • 5. Amirkabir University of Technology Computer Engineering Department Fall 2010 Applicability Use the Interpreter pattern when there is a language to interpret, and you can represent statements in the language as abstract syntax trees. The Interpreter pattern works best when 1) the grammar is simple. 2) For complex grammars, the class hierarchy for the grammar becomes large and unmanageable. 3) They can interpret expressions without building abstract syntax trees, which can save space and possibly time. 5
  • 6. Amirkabir University of Technology Computer Engineering Department Fall 2010 Applicability (cont…) – efficiency is not a critical concern. 2) The most efficient interpreters are usually not implemented by interpreting parse trees directly but by first translating them into another form. 6
  • 7. Amirkabir University of Technology Computer Engineering Department Fall 2010 Structure 7
  • 8. Amirkabir University of Technology Computer Engineering Department Fall 2010 8
  • 9. Amirkabir University of Technology Computer Engineering Department Fall 2010 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.  an instance is required for every terminal symbol in a sentence.  NonterminalExpression  one such class is required for every rule R ::= R1 R2 ... Rn in the grammar.  maintains instance variables of type AbstractExpression for each of the symbols R1 through Rn. 9
  • 10. Amirkabir University of Technology Computer Engineering Department Fall 2010 Participants (cont…)  implements an Interpret operation for nonterminal symbols in the grammar. Interpret typically calls itself recursively on the variables representing R1 through Rn. Context  contains information that's global to the interpreter. Client  builds (or is given) an abstract syntax tree representing a particular sentence in the language that the grammar defines.  invokes the Interpret operation. 10
  • 11. Amirkabir University of Technology Computer Engineering Department Fall 2010 Collaborations  The client builds (or is given) 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. 11
  • 12. Amirkabir University of Technology Computer Engineering Department Fall 2010 Consequences  Benefits:  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, too. Classes defining nodes in the abstract syntax tree have similar implementations.  Adding new ways to interpret expressions. The Interpreter pattern makes it easier to evaluate an expression in a new way.  For example, you can support pretty printing or type-checking an expression by defining a new operation on the expression classes.  If you keep creating new ways of interpreting an expression, then consider using the Visitor pattern to avoid changing the grammar classes. 12
  • 13. Amirkabir University of Technology Computer Engineering Department Fall 2010 Consequences (cont…) Liability:  Complex grammars are hard to maintain. The Interpreter pattern defines at least one class for every rule in the grammar. Hence grammars containing many rules can be hard to manage and maintain. when the grammar is very complex, other techniques such as parser or compiler generators are more appropriate. 13
  • 14. Amirkabir University of Technology Computer Engineering Department Fall 2010 Implementation 1) Creating the abstract syntax tree.  The Interpreter pattern doesn't explain how to create an abstract syntax tree.  The abstract syntax tree can be created by a table-driven parser, by a hand- crafted parser, or directly by the client. 2) Defining the Interpret operation.  If it's common to create a new interpreter, then it's better to use the Visitor pattern to put Interpret in a separate "visitor" object. 3) Sharing terminal symbols with the Flyweight pattern.  Grammars whose sentences contain many occurrences of a terminal symbol might benefit from sharing a single copy of that symbol. 14
  • 15. Amirkabir University of Technology Computer Engineering Department Fall 2010 Example  First example is a system for manipulating and evaluating Boolean expressions implemented in C++. The grammar is defined as follows:  We define two operations on Boolean expressions: 1. Evaluate, evaluates a Boolean expression in a context that assigns a true or false value to each variable. 2. Replace, produces a new Boolean expression by replacing a variable with an expression. 15
  • 16. Amirkabir University of Technology Computer Engineering Department Fall 2010 16
  • 17. Amirkabir University of Technology Computer Engineering Department Fall 2010 17 Create an expression interface: - Expression.java public interface Expression { public boolean interpret(String context); }
  • 18. Amirkabir University of Technology Computer Engineering Department Fall 2010 18 Create concrete classes implementing the above interface: - TerminalExpression.java public class TerminalExpression implements Expression { private String data; public TerminalExpression(String data){ this.data = data; } @Override public boolean interpret(String context) { if(context.contains(data)){ return true; } return false; } }
  • 19. Amirkabir University of Technology Computer Engineering Department Fall 2010 19 - OrExpression.java public class OrExpression implements Expression { private Expression expr1 = null; private Expression expr2 = null; public OrExpression(Expression expr1, Expression expr2) { this.expr1 = expr1; this.expr2 = expr2; } @Override public boolean interpret(String context) { return expr1.interpret(context) || expr2.interpret(context); } }
  • 20. Amirkabir University of Technology Computer Engineering Department Fall 2010 20 - AndExpression.java public class AndExpression implements Expression { private Expression expr1 = null; private Expression expr2 = null; public AndExpression(Expression expr1, Expression expr2) { this.expr1 = expr1; this.expr2 = expr2; } @Override public boolean interpret(String context) { return expr1.interpret(context) && expr2.interpret(context); } }
  • 21. Amirkabir University of Technology Computer Engineering Department Fall 2010 21 nterpreterPatternDemo.java public class InterpreterPatternDemo { //Rule: Robert and John are male public static Expression getMaleExpression(){ Expression robert = new TerminalExpression("Robert"); Expression john = new TerminalExpression("John"); return new OrExpression(robert, john); } //Rule: Julie is a married women public static Expression getMarriedWomanExpression(){ Expression julie = new TerminalExpression("Julie"); Expression married = new TerminalExpression("Married"); return new AndExpression(julie, married); }
  • 22. Amirkabir University of Technology Computer Engineering Department Fall 2010 22 public static void main(String[] args) { Expression isMale = getMaleExpression(); Expression isMarriedWoman = getMarriedWomanExpression(); System.out.println("John is male? " + isMale.interpret("John")); System.out.println("Julie is a married women? " + isMarriedWoman.interpret("Married Julie")); } }
  • 23. Amirkabir University of Technology Computer Engineering Department Fall 2010 Example (cont…) Replace shows how the Interpreter pattern can be used for more than just evaluating expressions. In this case, it manipulates the expression itself. 23
  • 24. Amirkabir University of Technology Computer Engineering Department Fall 2010 Example (cont…) BooleanExp defines the interface for all classes that define a Boolean expression: public abstract class BooleanExp { public BooleanExp(){} public abstract bool Evaluate(Context aContext); public abstract BooleanExp Replace(string name, BooleanExp bExp); public abstract BooleanExp Copy(); } 24
  • 25. Amirkabir University of Technology Computer Engineering Department Fall 2010 Example (cont…)  The class Context defines a mapping from variables to Boolean values. public class Context { Hashtable values; public Context() { values = new Hashtable(); } public bool Lookup(VariableExp varExp) { return(bool)values[varExp.name]; } public void Assign(VariableExp varExp, bool bval) { values.Add(varExp.name, bval); } } 25
  • 26. Amirkabir University of Technology Computer Engineering Department Fall 2010 Example (cont…) public class VariableExp : BooleanExp { public string name; public VariableExp(string _name){name = _name;} public override bool Evaluate(Context aContext) { return aContext.Lookup(this); } public override BooleanExp Replace(string _name, BooleanExp bExp) { if (_name.Equals(name)) return bExp.Copy(); else return new VariableExp(name); } public override BooleanExp Copy() { return new VariableExp(name); } } 26
  • 27. Amirkabir University of Technology Computer Engineering Department Fall 2010 Example (cont…) public class AndExp : BooleanExp { public BooleanExp operand1; public BooleanExp operand2; public VariableExp(BooleanExp op1, BooleanExp op2) {operand1 = op1; operand2 = op2;} public override bool Evaluate(Context aContext) { return operand1.Evaluate(aContext) && operand2.Evaluate(aContext); } public override BooleanExp Replace(string _name, BooleanExp bExp) { return new AndExp(operand1.Replace(_name, bExp), operand2.Replace(_name, bExp)); } public override BooleanExp Copy() { return new AndExp(operand1.Copy(),operand2.Copy()); } } 27
  • 28. Amirkabir University of Technology Computer Engineering Department Fall 2010 Example (cont…)  (true and x) or (y and (not x)) BooleanExp expression; Context context; VariableExp x = new VariableExp("X"); VariableExp y = new VariableExp("Y"); expression = new OrExp( new AndExp(new Constant(true), x), new AndExp(y, new NotExp(x)) ); context.Assign(x, false); context.Assign(y, true); bool result = expression.Evaluate(context);  we can replace the variable y with a new expression and then reevaluate it: VariableExp z = new VariableExp("Z"); NotExp not_z = new NotExp(z); BooleanExp replacement = expression.Replace("Y", not_z); context.Assign(z, true); result = replacement.Evaluate(context); 28
  • 29. Amirkabir University of Technology Computer Engineering Department Fall 2010 Example (cont…)  This example illustrates an important point about the Interpreter pattern: many kinds of operations can "interpret" a sentence.  Evaluate fits our idea of what an interpreter should do most closely— that is, it interprets a program or expression and returns a simple result.  However, Replace can be viewed as an interpreter as well. It's an interpreter whose context is the name of the variable being replaced along with the expression that replaces it, and whose result is a new expression.  Even Copy can be thought of as an interpreter with an empty context. 29
  • 30. Amirkabir University of Technology Computer Engineering Department Fall 2010 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 behavior in each node in the abstract syntax tree in one class. 30
  • 31. Amirkabir University of Technology Computer Engineering Department Fall 2010 Q&A

Editor's Notes

  1. <number>
  2. <number>
  3. <number>
  4. <number>
  5. <number>
  6. <number>
  7. <number>
  8. <number>
  9. <number>
  10. <number>
  11. <number>
  12. <number>
  13. <number>
  14. <number>
  15. <number>
  16. <number>
  17. <number>
  18. <number>
  19. <number>
  20. <number>
  21. <number>
  22. <number>