The Interpreter pattern helps to convert information from one language into another.
The language can be anything such as words in a sentence, numerical formulas or even software code.
The process is to convert the source information, into an Abstract Syntax Tree (AST) of Terminal and Non-Terminal expressions that all implement an interpret() method.
A Non-Terminal expression is a combination of other Non-Terminal and/or Terminal expressions.
Terminal means terminated, i.e., there is no further processing involved.
An AST root starts with a Non-Terminal expression and then resolves down each branch until all expressions terminate.
An example expression is A + B.
The A and B are Terminal expressions and the + is Non-Terminal because it depends on the two other Terminal expressions.
The Image below, is an AST for the expression 5 + 4 - 3 + 7 - 2
The official Interpreter pattern described in the original GoF Design Patterns book does not state how to construct an Abstract Syntax Tree. How your tree is constructed will depend on the grammatical constructs of your sentence that you want to interpret.
Abstract Syntax Trees can be created manually or dynamically from a custom parser script. In the first example code below, I construct the AST manually.
Once the AST is created, you can then choose the root node and then run the Interpret operation on that, and it should interpret the whole tree recursively.
Terminology
Abstract Expression: Describe the method(s) that Terminal and Non-Terminal expressions should implement.
Non-Terminal Expression: A composite of Terminal and/or Non-Terminal expressions.
Terminal Expression: A leaf node Expression.
Context: Context is state that can be passed through interpret operations if necessary.
Client: Builds or is given an Abstract Syntax Tree to interpret.
Interpreter UML Diagram
Source Code
In this example, I interpret the string 5 + 4 - 3 + 7 - 2 and then calculate the result.
The grammar of the string follows a pattern of Number ⇾ Operator ⇾ Number ⇾ etc.
I convert the string into a list of tokens that I can refer to by index in the array.
I then construct the AST manually, by adding a
Non-Terminal Add row containing two Terminals for the 5 and 4,
Non-Terminal Subtract row containing the previous Non-Terminal row and the 3
Non-Terminal Add row containing the previous Non-Terminal row and the 7
Non-Terminal Subtract row containing the previous Non-Terminal row and the 2
The AST root becomes the final row that was added, and then I can run the interpret() method on that, which will interpret the full AST recursively because each AST row references the row above it.
// The Interpreter Pattern ConceptinterfaceIAbstractExpression{// All Terminal and Non-Terminal expressions will implement// an `interpret` methodinterpret():number}classNumeralimplementsIAbstractExpression{// Terminal Expressionvalue:numberconstructor(value:string){this.value=parseInt(value)}interpret():number{returnthis.value}}classAddimplementsIAbstractExpression{// Non-Terminal Expression.left:IAbstractExpressionright:IAbstractExpressionconstructor(left:IAbstractExpression,right:IAbstractExpression){this.left=leftthis.right=right}interpret(){returnthis.left.interpret()+this.right.interpret()}}classSubtractimplementsIAbstractExpression{// Non-Terminal Expression.left:IAbstractExpressionright:IAbstractExpressionconstructor(left:IAbstractExpression,right:IAbstractExpression){this.left=leftthis.right=right}interpret(){returnthis.left.interpret()-this.right.interpret()}}// The Client// The sentence complies with a simple grammar of// Number -> Operator -> Number -> etc,constSENTENCE='5 + 4 - 3 + 7 - 2'console.log(SENTENCE)// Split the sentence into individual expressions that will be added to// an Abstract Syntax Tree(AST) as Terminal and Non - Terminal expressionsconstTOKENS=SENTENCE.split(' ')console.log(JSON.stringify(TOKENS))// Manually Creating an Abstract Syntax Tree from the tokensconstAST:IAbstractExpression[]=[]// An array of AbstractExpressionsAST.push(newAdd(newNumeral(TOKENS[0]),newNumeral(TOKENS[2])))// 5 + 4AST.push(newSubtract(AST[0],newNumeral(TOKENS[4])))// ^ - 3AST.push(newAdd(AST[1],newNumeral(TOKENS[6])))// ^ + 7AST.push(newSubtract(AST[2],newNumeral(TOKENS[8])))// ^ - 2// Use the final AST row as the root node.constAST_ROOT=AST.pop()// Interpret recursively through the full AST starting from the root.console.log((AST_ROOTasIAbstractExpression).interpret())// Print out a representation of the AST_ROOTconsole.dir(AST_ROOT,{depth:null})
The example use case will expand on the concept example by dynamically creating the AST and converting Roman numerals to integers as well as calculating the final result.
The Image below, is an AST for the expression 5 + IV - 3 + VII - 2
Example UML Diagram
Source Code
./src/interpreter/client.ts
1 2 3 4 5 6 7 8 910111213141516171819202122
// The Interpreter Pattern Use Case ExampleimportIAbstractExpressionfrom'./iabstract-expression'importParserfrom'./sentence-parser'// The sentence complies with a simple grammar of// Number -> Operator -> Number -> etc,constSENTENCE='5 + IV - 3 + VII - 2'// const SENTENCE = "4 + II + XII + 1 + 2"// const SENTENCE = "5 + 4 - 3 + 7 - 2"// const SENTENCE = "V + IV - III + 7 - II"// const SENTENCE= "CIX + V"// const SENTENCE = "CIX + V - 3 + VII - 2"// const SENTENCE = "MMMCMXCIX - CXIX + MCXXII - MMMCDXII - XVIII - CCXXXV"console.log(SENTENCE)constAST_ROOT=Parser.parse(SENTENCE)// Interpret recursively through the full AST starting from the root.console.log((AST_ROOTasIAbstractExpression).interpret())// Print out a representation of the AST_ROOTconsole.dir(AST_ROOT,{depth:null})
./src/interpreter/iabstract-expression.ts
12345678
exportdefaultinterfaceIAbstractExpression{// All Terminal and Non-Terminal expressions will implement// an `interpret` methodvalue?:numberleft?:IAbstractExpressionright?:IAbstractExpressioninterpret():number}
// Roman Numeral Expression. This is a Non-Terminal ExpressionimportIAbstractExpressionfrom'./iabstract-expression'importNumeralfrom'./numeral'exportdefaultclassRomanNumeralimplementsIAbstractExpression{// Non Terminal expressionromanNumeral:stringcontext:[string,number]constructor(romanNumeral:string){this.romanNumeral=romanNumeralthis.context=[romanNumeral,0]}interpret():number{RomanNumeral1000.interpret(this.context)RomanNumeral100.interpret(this.context)RomanNumeral10.interpret(this.context)RomanNumeral1.interpret(this.context)returnnewNumeral(this.context[1]).interpret()}}classRomanNumeral1extendsRomanNumeral{// Roman Numerals 1 - 9staticone='I'staticfour='IV'staticfive='V'staticnine='IX'staticmultiplier=1staticinterpret(context:[string,number]){if(context[0].length===0){returnnewNumeral(context[1]).interpret()}if(context[0].substring(0,2)===this.nine){context[1]+=9*this.multipliercontext[0]=context[0].substring(2)}elseif(context[0].substring(0,1)===this.five){context[1]+=5*this.multipliercontext[0]=context[0].substring(1)}elseif(context[0].substring(0,2)===this.four){context[1]+=+(4*this.multiplier)context[0]=context[0].substring(2)}while(context[0].length>0&&context[0][0]===this.one){context[1]+=1*this.multipliercontext[0]=context[0].substring(1)}returnnewNumeral(context[1]).interpret()}}classRomanNumeral10extendsRomanNumeral1{// Roman Numerals 10 - 99staticone='X'staticfour='XL'staticfive='L'staticnine='XC'staticmultiplier=10}classRomanNumeral100extendsRomanNumeral1{// Roman Numerals 100 - 999staticone='C'staticfour='CD'staticfive='D'staticnine='CM'staticmultiplier=100}classRomanNumeral1000extendsRomanNumeral1{// Roman Numerals 1000 - 3999staticone='M'staticfour=''staticfive=''staticnine=''staticmultiplier=1000}
// A Custom Parser for creating an Abstract Syntax TreeimportIAbstractExpressionfrom'./iabstract-expression'importAddfrom'./add'importNumeralfrom'./numeral'importRomanNumeralfrom'./roman-numeral'importSubtractfrom'./subtract'exportdefaultclassParser{// Dynamically create the Abstract Syntax Treestaticparse(sentence:string):IAbstractExpression|undefined{// Create the AST from the sentenceconsttokens=sentence.split(' ')consttree:IAbstractExpression[]=[]// Abstract Syntax Treewhile(tokens.length>1){constleftExpression=Parser.decideLeftExpression(tree,tokens)// get the operator, make the token list shorterconstoperator=tokens.shift()constright=tokens[0]if(!Number(right)){tree.push(newRomanNumeral(right))if(operator==='-'){tree.push(newSubtract(leftExpression,tree[tree.length-1]))}if(operator==='+'){tree.push(newAdd(leftExpression,tree[tree.length-1]))}}else{constrightExpression=newNumeral(right)if(!tree.length){// Empty Data Structures return False by defaultif(operator==='-'){tree.push(newSubtract(leftExpression,rightExpression))}if(operator==='+'){tree.push(newAdd(leftExpression,rightExpression))}}else{if(operator==='-'){tree.push(newSubtract(tree[tree.length-1],rightExpression))}if(operator==='+'){tree.push(newAdd(tree[tree.length-1],rightExpression))}}}}returntree.pop()}staticdecideLeftExpression(tree:IAbstractExpression[],tokens:string[]):IAbstractExpression{// On the First iteration, the left expression can be either a// number or roman numeral.Every consecutive expression is// reference to an existing AST rowconstleft=tokens.shift()letleftExpression:IAbstractExpressionif(!tree.length){// only applicable if first roundif(!Number(left)){// if 1st token a roman numeraltree=[]tree.push(newRomanNumeral(leftasstring))leftExpression=tree[tree.length-1]asIAbstractExpression}else{leftExpression=newNumeral(leftasstring)}returnleftExpression}else{leftExpression=tree[tree.length-1]asIAbstractExpressionreturnleftExpression}}}
ASTs are hard to create and are an enormous subject in themselves. My recommended approach is to create them manually first using a sample sentence to help understand all the steps individually, and then progress the conversion to be fully dynamic one step at a time ensuring that the grammatical constructs still work as you continue to progress.
The Interpreter pattern uses a class to represent each grammatical rule.
ASTs consist of multiple Non-Terminal and Terminal Expressions, that all implement an interpret() method.
Note that in the sample code above, the interpret() methods in the Non-Terminal expressions, all call further interpret() recursively. Only the Terminal expressions interpret() method returns an explicit value. See the Number class in the above code.