There are three foundation classes in the implementation of the interpreter, Program, Statement, and Expression. The following shows how the three are related:
Program
ThisProgramclass glues together the parsing and execution components of the parser. This class defines two principal methods,loadandrun. Theloadmethod reads statements from an input stream and parses them into a collection of statements, therunmethod iterates over the collection and executes each of the statements. TheProgramclass also provides a collection of variables for the program to use as well as a stack for storing data.
Statement
TheStatementclass contains a single parsed statement. This class is actually subclassed into a specific type of statement (PRINT, GOTO, IF, and so on) but all statements contain the methodexecutewhich is called to execute the statement in the context of aProgramclass instance.
Expression
TheExpressionclass contains the parse tree of an expression. During execution, thevaluemethod is used to evaluate the expression and return its value. LikeStatement, theExpressionclass is primarily designed to be subclassed by specific types of expressions.
All of these classes work together to form the basis of an interpreter. The Program class simultaneously encapsulates the parsing operation and execution operation, whereas the Statement and Expression classes encapsulate the actual computational concepts of the language we've implemented. For these three articles on building
interpreters, the example language has been BASIC.
Statement and Expression. First let's take a look at Expression.The instances of Expression are created by the method expression in the class ParseExpression. The ParseExpression class implements the expression parser in this interpreter. This class is a peer of the ParseStatement class, which uses the statement method to parse BASIC statements. Instances of Expression have an internal type that identifies what operator the instance represents, and two methods, value and stringValue, that return the computed value of the expression. Additionally, when an Expression instance is created, it is nominally
given two parameters representing the left and right side of the expression's operation. Shown in source form, the first part
of the Expression is as follows:
JAVABy Anonymous on October 19, 2009, 3:49 amwHAT IS iNTERPREATER IN JAVA.
Reply | Read entire comment
View all comments