Class Parser

java.lang.Object
  extended by Parser

public class Parser
extends java.lang.Object

A parser for simple arithmetic expressions with the operators +, -, *, / and ( ) It was written as a demonstration of a recursive descent parser, therefore the emphasis is on simplicity.

Version:
16. Dec. 2007
Author:
P. Tellenbach

Field Summary
protected  int position
          Current position in the string
protected  java.lang.String str
          String to be parsed
 
Constructor Summary
Parser()
           
 
Method Summary
 Node parse(java.lang.String expr)
          Sets up the members, starts the parser and checks if the whole string was parsed correctly.
protected  Node parseExpression()
          Parses an "expression", which is a production with the operators + and -
protected  Node parseFactor()
          Parses a "factor", which is either an expression enclosed by "(" and ")" or a simple number.
protected  Node parseNumber()
          Returns an integer number from the string
protected  Node parseTerm()
          Parses a "term", which is a production with the operators "*" or "/"
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

str

protected java.lang.String str
String to be parsed


position

protected int position
Current position in the string

Constructor Detail

Parser

public Parser()
Method Detail

parseTerm

protected Node parseTerm()
                  throws ParseException
Parses a "term", which is a production with the operators "*" or "/"

Throws:
ParseException - thrown by parseFactor

parseFactor

protected Node parseFactor()
                    throws ParseException
Parses a "factor", which is either an expression enclosed by "(" and ")" or a simple number. Note the recursion via parseExpression.

Throws:
ParseException - if the expression is not terminated by ")"

parseExpression

protected Node parseExpression()
                        throws ParseException
Parses an "expression", which is a production with the operators + and -

Throws:
ParseException - thrown by parseTerm

parseNumber

protected Node parseNumber()
                    throws ParseException
Returns an integer number from the string

Throws:
ParseException - if the number is not valid

parse

public Node parse(java.lang.String expr)
           throws ParseException
Sets up the members, starts the parser and checks if the whole string was parsed correctly. Note that the string to be parsed may not contain whitespace.

Throws:
ParseException - if there are any unparsed characters