Interpreter Pattern.

Slides:



Advertisements
Similar presentations
Semantics Static semantics Dynamic semantics attribute grammars
Advertisements

Translator Architecture Code Generator ParserTokenizer string of characters (source code) string of tokens abstract program string of integers (object.
Behavioral Pattern: Interpreter C h a p t e r 5 – P a g e 149 Some programs benefit from having a language to describe operations that they can perform.
(A Completely Colorless Powerpoint Presentation of) The Interpreter Pattern David Witonsky.
INTERPRETER Main Topics What is an Interpreter. Why should we learn about them.
C. Varela; Adapted w/permission from S. Haridi and P. Van Roy1 Declarative Computation Model Defining practical programming languages Carlos Varela RPI.
Algorithm Programming Behavioral Design Patterns Bar-Ilan University תשס " ו by Moshe Fresko.
Interpreter By: Mahmoodreza Jahanseir Amirkabir University of Technology Computer Engineering Department Fall 2010.
The Interpreter Pattern. Defining the Interpreter Intent Given a language, define a representation for its grammar along with an interpreter that uses.
Chapter 2 Syntax A language that is simple to parse for the compiler is also simple to parse for the human programmer. N. Wirth.
Syntax Directed Translation. Syntax directed translation Yacc can do a simple kind of syntax directed translation from an input sentence to C code We.
Chapter 1 Introduction Dr. Frank Lee. 1.1 Why Study Compiler? To write more efficient code in a high-level language To provide solid foundation in parsing.
Design Pattern Interpreter By Swathi Polusani. What is an Interpreter? The Interpreter pattern describes how to define a grammar for simple languages,
AN IMPLEMENTATION OF A REGULAR EXPRESSION PARSER
The Java Programming Language
CS 280 Data Structures Professor John Peterson. How Does Parsing Work? You need to know where to start (“statement”) This grammar is constructed so that.
COMP Parsing 2 of 4 Lecture 22. How do we write programs to do this? The process of getting from the input string to the parse tree consists of.
ISBN Chapter 3 Describing Semantics -Attribute Grammars -Dynamic Semantics.
Interpretation Environments and Evaluation. CS 354 Spring Translation Stages Lexical analysis (scanning) Parsing –Recognizing –Building parse tree.
02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.
Interpreter CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns Some material taken from:
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Design Patterns IX Interpreter, Mediator, Template Method recap.
COMP Parsing 3 of 4 Lectures 23. Using the Scanner Break input into tokens Use Scanner with delimiter: public void parse(String input ) { Scanner.
Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.
Towards the better software metrics tool motivation and the first experiences Gordana Rakić Zoran Budimac.
CPS 506 Comparative Programming Languages Syntax Specification.
Theory of Programming Languages Introduction. What is a Programming Language? John von Neumann (1940’s) –Stored program concept –CPU actions determined.
Muhammad Idrees, Lecturer University of Lahore 1 Top-Down Parsing Top down parsing can be viewed as an attempt to find a leftmost derivation for an input.
The Visitor Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
The Interpreter Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
Interpreter By: Mahmoodreza Jahanseir Amirkabir University of Technology Computer Engineering Department Fall 2010.
Maitrayee Mukerji. INPUT MEMORY PROCESS OUTPUT DATA INFO.
1 Problem Solving  The purpose of writing a program is to solve a problem  The general steps in problem solving are: Understand the problem Dissect the.
Comp 411 Principles of Programming Languages Lecture 3 Parsing
Chapter 3 – Describing Syntax
Modern Programming Tools And Techniques-I
The need for Programming Languages
Parsing 2 of 4: Scanner and Parsing
Design Patterns: Brief Examples
Unit II-Chapter No. : 5- design Patterns
Strategy Pattern Jim Fawcett CSE776 – Design Patterns Fall 2014.
COMP261 Lecture 18 Parsing 3 of 4.
CS510 Compiler Lecture 4.
Factory Patterns 1.
Chapter 3 – Describing Syntax
Context-free Languages
Flyweight Design Pattern
Presentation by Julie Betlach 7/02/2009
Syntax Analysis Sections :.
Lexical and Syntax Analysis
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Programming Language Syntax 2
Jim Fawcett CSE776 – Design Patterns Summer 2003
The Metacircular Evaluator
Lecture 8: Top-Down Parsing
Behavioral Patterns Part-I introduction UNIT-VI
R.Rajkumar Asst.Professor CSE
Behavioral Design Pattern
Syntax-Directed Translation
Compilers Principles, Techniques, & Tools Taught by Jing Zhang
Strategy Design Pattern
The Recursive Descent Algorithm
6.001 SICP Interpretation Parts of an interpreter
Decorator Pattern.
Lec00-outline May 18, 2019 Compiler Design CS416 Compiler Design.
Software Design Lecture : 39.
COMPILER CONSTRUCTION
COP 4620 / 5625 Programming Language Translation / Compiler Writing Fall 2003 Lecture 2, 09/04/2003 Prof. Roy Levow.
Faculty of Computer Science and Information System
Strategy Pattern Jim Fawcett CSE776 – Design Patterns Fall 2014.
Presentation transcript:

Interpreter Pattern

Interpreter pattern provides a way to evaluate language grammar or expression. This type of pattern comes under behavioral pattern. This pattern involves implementing an expression interface which tells to interpret a particular context. This pattern is used in SQL parsing, symbol processing engine etc.

Intent Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language. Motivation If a particular kind of problem occurs often enough, then it might be worth while to express instances of the problem as sentences in a simple language. Then you can build an interpreter that solves the problem by interpreting these sentences. For example, searching for strings that match a pattern is a common problem. Regular expressions are a standard language for specifying patterns of strings. Rather than building custom algorithms to match each pattern against strings, search algorithms could interpret a regular expression that specifies a set of strings to match.

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 the grammar is simple. For complex grammars, the class hierarchy for the grammar becomes large and unmanageable. Tools such as parser generators are a better alternative in such cases. They can interpret expressions without building abstract syntax trees, which can save space and possibly time. 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. For example, regular expressions are often transformed into state machines. But even then, the translator can be implemented by the Interpreter pattern, so the pattern is still applicable.

Participants · AbstractExpression (RegularExpression) o declares an abstract Interpret operation that is common to all nodes in the abstract syntax tree. · TerminalExpression (LiteralExpression) o implements an Interpret operation associated with terminal symbols in the grammar. · NonterminalExpression (AlternationExpression,RepetitionExpression, SequenceExpressions) o one such class is required for every rule R ::= R1 R2 ... Rn in the grammar. · Context o contains information that's global to the interpreter. · Client o builds (or is given) an abstract syntax tree representing a particular sentence in the language that the grammar defines o invokes the Interpret operation.

Collaborations The client builds (or is given) the sentence as an abstract syntax tree of Non terminal Expression and Terminal Expression instances. Then the client initializes the context and invokes the Interpret operation. Each Non terminal Expression node defines Interpret in terms of Interpret on each sub expression. The Interpret operation of each Terminal Expression 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 The Interpreter pattern has the following benefits and liabilities: It's easy to change and extend the grammar. Implementing the grammar is easy, too. Complex grammars are hard to maintain. Adding new ways to interpret expressions.

Implementation We are going to create an interface Expression and concrete classes implementing the Expression interface. A class Terminal Expression is defined which acts as a main interpreter of context in question. Other classes OrExpression, AndExpression are used to create combinational expressions. InterpreterPatternDemo, our demo class, will use Expression class to create rules and demonstrate parsing of expressions.

Step 1 Create an expression interface. Expression.java public interface Expression { public boolean interpret(String context); } Step 2 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; 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);

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);

Step 3 InterpreterPatternDemo uses Expression class to create rules and then parse them. InterpreterPatternDemo.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);

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 woman? " + isMarriedWoman.interpret("Married Julie")); }

Step 4 Verify the output. John is male? true Julie is a married woman? true