Due Wednesday, September 17, 2008
A Calculator Program in Lex
The purpose of this assignment is to familiarize you with using lex on our systems and provide and example of a lexical scanner you can play with. This program in lex has been modified from original assignment by Jose Amaral.
The file scan.l contains the description of tokens to generate a scanner using lex. To generate the scanner use the following command:
lex scan.lYou will notice that lex created the file lex.yy.c in your current directory. Now you must compile this file into an executable program. Do so with the following:
gcc -o scanner lex.yy.cNow you can run the executable scanner and play with it by typing in text and checking if it is recognized as a token. You may want to consult the file scan.l as you play with the scanner to understand how the tokens are specified. Make sure and try operators, words, parenthesis, etc. The scanner will output the type of symbol that it recognized for the input that you typed. What are the functions of period, space, and comma in this scanner? Can you list all the characters that are interpreted as special symbols by the scanner? You can use CTRL-D to terminate the scanner.
For this exercise the files zcalc.l and zcalc.y will be used. The file zcalc.l is a lex file written to match all the patterns that are required to generate the tokens to implement a simple calculator. The file zcalc.y describes the rules of the grammar that implements the calculator. First you should experiment playing with the calculator. Make sure to run the make clean to remove older versions of the files and then type make:
On the Suns, you will need to exit the makefile to use "gcc" instead of "cc". Both are C compilers, cc is available on the Macs, but not the Suns.You now have an infix calculator. If you type ``3 + 2'' the calculator answers with ``= 5''; if you type ``x = 4'' followed by ``3 * x'' the calculator responds with ``= 12''. You invoke the calculator by running the program zcalc. Here is a demonstration:
zcalcNow you should play with the calculator and check what works and what does not. You should be able to do addition, subtraction, and multiplication, as well as variable names and functions such as log, exp, and sqrt. We suggest that you look at the files zcalc.l and zcalc.y as you play. This way you will understand how the calculator was specified.
3 + 2
x = 4
3 * x