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.

Slides:



Advertisements
Similar presentations
LECTURE 1 CMSC 201. Overview Goal: Problem solving and algorithm development. Learn to program in Python. Algorithm - a set of unambiguous and ordered.
Advertisements

True or false A variable of type char can hold the value 301. ( F )
(A Completely Colorless Powerpoint Presentation of) The Interpreter Pattern David Witonsky.
INTERPRETER Main Topics What is an Interpreter. Why should we learn about them.
Computer Science 1620 Loops.
1 CIS 205 Practice Test George Lamperti A word that has a predefined meaning in a C++ program and cannot be used as a variable name is known as.
Iteration This week we will learn how to use iteration in C++ Iteration is the repetition of a statement or block of statements in a program. C++ has three.
Switch structure Switch structure selects one from several alternatives depending on the value of the controlling expression. The controlling expression.
CS31: Introduction to Computer Science I Discussion 1A 4/2/2010 Sungwon Yang
CS 280 Data Structures Professor John Peterson. Lexer Project Questions? Must be in by Friday – solutions will be posted after class The next project.
Interpreter By: Mahmoodreza Jahanseir Amirkabir University of Technology Computer Engineering Department Fall 2010.
Basic Elements of C++ Chapter 2.
PRINCIPLES OF PROGRAMMING Revision. A Computer  A useful tool for solving a great variety of problems.  To make a computer do anything (i.e. solve.
CS 325: Software Engineering March 5, 2015 Modeling and Design of Rule-Based Systems Rule-Based Systems Interpreter Pattern Code Reviews.
Programming Languages
1 Syntax and Semantics The Purpose of Syntax Problem of Describing Syntax Formal Methods of Describing Syntax Derivations and Parse Trees Sebesta Chapter.
UNIT 3 TEMPLATE AND EXCEPTION HANDLING. Introduction  Program errors are also referred to as program bugs.  A C program may have one or more of four.
CONTROL FLOW IN C++ Satish Mishra PGT CS KV Trimulgherry.
Syntax Directed Translation. Syntax directed translation Yacc can do a simple kind of syntax directed translation from an input sentence to C code We.
High-Level Programming Languages: C++
CH Programming An introduction to programming concepts.
Design Pattern Interpreter By Swathi Polusani. What is an Interpreter? The Interpreter pattern describes how to define a grammar for simple languages,
CS 355 – PROGRAMMING LANGUAGES Dr. X. Topics Introduction The General Problem of Describing Syntax Formal Methods of Describing Syntax.
More on Input Output Input Stream : A sequence of characters from an input device (like the keyboard) to the computer (the program running). Output Stream.
CS Describing Syntax CS 3360 Spring 2012 Sec Adapted from Addison Wesley’s lecture notes (Copyright © 2004 Pearson Addison Wesley)
ISBN Chapter 3 Describing Semantics -Attribute Grammars -Dynamic Semantics.
TextBook Concepts of Programming Languages, Robert W. Sebesta, (10th edition), Addison-Wesley Publishing Company CSCI18 - Concepts of Programming languages.
C++ Programming: Basic Elements of C++.
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Design Patterns IX Interpreter, Mediator, Template Method recap.
Computing IV Singleton Pattern Xinwen Fu.
6/3/2016 CSI Chapter 02 1 Introduction of Flow of Control There are times when you need to vary the way your program executes based on given input.
COMPUTER PROGRAMMING. Iteration structures (loops) There may be a situation when you need to execute a block of code several number of times. In general,
Parse & Syntax Trees Syntax & Semantic Errors Mini-Lecture.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Introduction to Java Java Translation Program Structure
3.2 Semantics. 2 Semantics Attribute Grammars The Meanings of Programs: Semantics Sebesta Chapter 3.
Chapter 2: Introduction to C++. Language Elements Keywords Programmer-defined symbols (identifiers) Operators Punctuation Syntax Lines and Statements.
C++ Basics. Compilation What does compilation do? g++ hello.cpp g++ -o hello.cpp hello.
The Interpreter Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
Calvin College Controlling Behavior The if, switch and for Statements.
Compilers Computer Symbol Table Output Scanner (lexical analysis)
Interpreter By: Mahmoodreza Jahanseir Amirkabir University of Technology Computer Engineering Department Fall 2010.
1 CSC 1111 Introduction to Computing using C++ C++ Basics (Part 1)
Exception Handling How to handle the runtime errors.
CSE202: Lecture 5The Ohio State University1 Selection Structures.
Operational Semantics Mooly Sagiv Reference: Semantics with Applications Chapter 2 H. Nielson and F. Nielson
Chapter 3 – Describing Syntax CSCE 343. Syntax vs. Semantics Syntax: The form or structure of the expressions, statements, and program units. Semantics:
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 23, 2005 Lecture Number: 11.
Looping I (while statement). CSCE 1062 Outline  Looping/repetition construct  while statement (section 5.1)
The Ohio State University
Review 1.
ifstreams and ofstreams
Chapter Topics The Basics of a C++ Program Data Types
REPETITION CONTROL STRUCTURE
Computing Fundamentals
Basic Elements of C++.
Chapter 2 Assignment and Interactive Input
What does it mean? Notes from Robert Sebesta Programming Languages
Syntax versus Semantics
Basic Elements of C++ Chapter 2.
Basic Notions Review what is a variable? value? address? memory location? what is an identifier? variable name? keyword? what is legal identifier? what.
Conditional Statements
Representation, Syntax, Paradigms, Types
Interpreter Pattern.
Selection Statements.
Life is Full of Alternatives
Repetition Statements (Loops) - 2
ifstreams and ofstreams
Chapter 1 c++ structure C++ Input / Output
CS 325: Software Engineering
Presentation transcript:

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. The Interpreter Pattern generally describes defining a grammar for that language and using that grammar to interpret statements in that language.

The Interpreter Pattern C h a p t e r 5 – P a g e 150 The AbstractExpression defines an interface for executing an operation. The TerminalExpression implements an Interpret operation associated with terminal symbols in the grammar. One CompoundExpression class is required for every rule in the grammar, each one implementing an Interpret operation for nonterminal symbols in the grammar. The Context contains information that is global to the interpreter. The Client invokes the interpret operation and builds (or is given) an abstract syntax tree, assembled from CompoundExpressions and TerminalExpressions) representing a particular sentence in the language that the grammar defines.

C h a p t e r 5 – P a g e 151 Example: Boolean Expressions A BooleanExpression is either a terminal expression (a Constant) or a compound expression (an AND, OR, or NOT Expression). A BooleanExpression is interpreted (or “interpreted) in the context of its variable names and values. For instance, the BooleanExpression (X AND NOT Y) OR Z in the context of (X,Y,Z) = (true, false, false) evaluates to eval(X AND NOT Y) OR eval(Z), which is (eval(X) AND eval(NOT Y)) OR false, which evaluates to (true AND NOT eval(Y)), which is NOT(false), resulting in an evaluation of true.

C h a p t e r 5 – P a g e 152 Example: Roman Numerals Reading left to right, a Roman Numeral can be interpreted via four “sub-interpreters”. First, the thousands characters (the leading “M” characters) are read. This is followed by the hundreds characters (either a nine- sequence “CM”, a four-sequence “CD”, or an optional five-sequence “D” followed by zero to three one-sequences “C”). The tens and ones characters are handled similarly. Notice that all of the derived “expressions” are terminal.

C h a p t e r 5 – P a g e 153 Roman Numeral Code in C++ #include using namespace std; class Thousand; class Hundred; class Ten; class One; class RomanNumeralInterpreter { public: RomanNumeralInterpreter(); // Creator for client RomanNumeralInterpreter(int){} // Creator for subclasses, avoids infinite loop int interpret(string); // interpret() for client virtual void interpret(string &input, int &total) // interpret() for derived classes { int index = 0; if (input.substr(0, 2) == nine()) { total += 9 * multiplier(); index += 2; } else if (input.substr(0, 2) == four()) { total += 4 * multiplier(); index += 2; }

C h a p t e r 5 – P a g e 154 else { if (input[0] == five()[0]) { total += 5 * multiplier(); index = 1; } else index = 0; int count = 1; while ( (input[index] == one()[0]) && (count <= 3) ) { total += 1 * multiplier(); index++; count++; } // remove leading characters processed input = input.substr(index, input.length() - index); } protected: // cannot be pure virtual because client asks for instance virtual string one() { return ""; } virtual string four() { return ""; } virtual string five() { return ""; } virtual string nine() { return ""; } virtual int multiplier() { return 0; } private: RomanNumeralInterpreter *thousands; RomanNumeralInterpreter *hundreds; RomanNumeralInterpreter *tens; RomanNumeralInterpreter *ones; };

C h a p t e r 5 – P a g e 155 class Thousand: public RomanNumeralInterpreter { public: // provide 1-argument creator to avoid infinite loop in base class creator Thousand(int): RomanNumeralInterpreter(1) {} protected: string one() { return "M"; } string four() { return ""; } string five() { return ""; } string nine() { return ""; } int multiplier() { return 1000; } }; class Hundred: public RomanNumeralInterpreter { public: Hundred(int): RomanNumeralInterpreter(1) {} protected: string one() { return "C"; } string four() { return "CD"; } string five() { return "D"; } string nine() { return "CM"; } int multiplier() { return 100; } }; class Ten: public RomanNumeralInterpreter { public: Ten(int): RomanNumeralInterpreter(1) {} protected: string one() { return "X"; } string four() { return "XL"; } string five() { return "L"; } string nine() { return "XC"; } int multiplier() { return 10; } };

C h a p t e r 5 – P a g e 156 class One: public RomanNumeralInterpreter { public: One(int): RomanNumeralInterpreter(1) {} protected: string one() { return "I"; } string four() { return "IV"; } string five() { return "V"; } string nine() { return "IX"; } int multiplier() { return 1; } }; RomanNumeralInterpreter::RomanNumeralInterpreter() { // use 1-argument creator to avoid infinite loop thousands = new Thousand(1); hundreds = new Hundred(1); tens = new Ten(1); ones = new One(1); } int RomanNumeralInterpreter::interpret(string input) { int total; total = 0; thousands->interpret(input, total); hundreds->interpret(input, total); tens->interpret(input, total); ones->interpret(input, total); if (input != "") // Input was invalid return 0; return total; }

C h a p t e r 5 – P a g e 157 void main() { RomanNumeralInterpreter interpreter; string input; cout << "Enter Roman Numeral: "; cin >> input; while (input != "quit") { cout << " interpretation is " << interpreter.interpret(input) << endl; cout << "Enter Roman Numeral: "; cin >> input; }

Interpreter Pattern Advantages C h a p t e r 5 – P a g e 158 When a program presents a number of different, but somewhat similar, cases with which it must contend, it can be advantageous to use a simple language to describe these cases and then have the program interpret that language. Recognizing cases where the Interpreter Pattern can be helpful can be problematic, and programmers who lack training in formal languages or compilers often overlook this option. One fairly obvious place where languages are applicable is when the program must parse algebraic strings in order to carry out operations based on the computation of user- entered equations. A far more useful situation that uses the Interpreter Pattern is when the program produces varying kinds of output (e.g., generating reports based on a database without having to resort to elaborate SQL queries).