myparselib - A Library for Parsing Simple Arithmetic Expressions

1. Functionality

myparselib is a very simple library provided to read in simple arithmetic expressions in CSc 352 programming assignments. It defines a tree data structure that can be used for representing expressions, together with functions to construct and view such trees.

The tree data type is defined (in the file myparse.h) as follows:

typedef struct tn {
  int ntype;
  int nval;
  struct tn *child1;
  struct tn *child2;
} tree_node;
The fields of this structure have the following meaning:

These fields are used as follows (in the table below, A and B denote arbitrary expressions):

Expression ntype nval child1 child2
an integer constant N TN_NUMBER N undefined undefined
-A TN_UMINUS undefined pointer to the root
node of the tree for A
undefined
A + B TN_PLUS undefined pointer to the root
node of the tree for A
pointer to the root
node of the tree for B
A - B TN_MINUS undefined pointer to the root
node of the tree for A
pointer to the root
node of the tree for B
A * B TN_MULT undefined pointer to the root
node of the tree for A
pointer to the root
node of the tree for B
A / B TN_DIV undefined pointer to the root
node of the tree for A
pointer to the root
node of the tree for B

In addition, the library provides the following functions:

tree_node * readExpr( void )
This function reads in an expression on a single line of text from stdin and returns a pointer to the expression tree for it. The structure of the tree is as described above (see also the example below). When end-of-file is encountered, it returns NULL. If an error is encountered, it gives an error message and exits with status -1.

void print_tree(tree_node *tptr)
This function prints out the expression tree given to it as an argument. The expression is printed out in ``prefix'' form, i.e., where the operator is printed first followed by a list of the operands (similar to Lisp and Scheme). Its primary use is for debugging.

2. Using the Library

In order to use this library, your program should include the file myparse.h using

#include <myparse.h>
To do this, you will have to tell the compiler (1) where to find this include file; (2) the name of this library; and (3) where to find the library. This issue is discussed here. In particular:
Library name: myparse
Include file directories: /home/cs352/FALL02/hw6_stuff
Library code directories: /home/cs352/FALL02/hw6_stuff/lib

3. An Example

Suppose that the following expression is read in from stdin:

(1 + 2) * - ( (6) - 4/2)
Then, a call to readExpr() returns the following tree: