<<

CSS 448/548 Lab

Write a yacc to convert infix expressions to postfix and to evaluate them. Use the (, , ) grammar. Expressions with negative factors (which must be in parentheses), the unary minus, must be added to the grammar. Your code is to the expression in postfix notation and produce the answer to the expression. Use standard postfix notation (E.g., "2+3" infix is "2 3 +" postfix). Show a unary minus as a 'm' (E.g., 2+(‐3) infix is "2 3 m +" postfix).

SAMPLE INPUT: 2+3 3 - (4*5) + 6 34+678-(((2+3)-4)*8/2-1)*97 34+(78-(((234+5)-8)*9/2-9)*7+((3+5)-(2-1)*3))*0 2 + (-5) - (-4) 2+ (-(1+3))

SAMPLE OUTPUT: 2 3 + = 5 3 4 5 * - 6 + = -11 34 678 + 2 3 + 4 - 8 * 2 / 1 - 97 * - = 421 34 78 234 5 + 8 - 9 * 2 / 9 - 7 * - 3 5 + 2 1 - 3 * - + 0 * + = 34 2 5 m + 4 m - = 1 2 1 3 + m + = -2

Notes ‐‐ Use the , , grammar, allowing negative factors in parentheses (unary minus). The grammar (without the unary minus), starting with one expression is as follows: + | - | * | / | | ( ) → DIGIT | DIGIT

‐‐ Parts of what you do are similar to the samples. This lab is closest to y3 with the token DIGIT. You won't have other yacc declarations as in y2 (%left) because associativity and precedence are handled in the grammar itself.

‐‐ Log onto a machine and, if desired, create a directory to put your yacc stuff into: yacc Change to the directory: yacc (Note that 'cd' by itself always takes you to your home directory.) Copy the “hw” yacc file, main.cpp, the simple makefile that has main, and file “hwdata” which holds data from the web.

The file "hw" is a copy of my "y3". There is a simple makefile for your use. It assumes that your yacc file is called "hw" and makes an executable file called "hw.out" . To try it out, enter: To check out the C code produced, file y.tab.c, enter: y.tab.c (When using the 'more' command, the 'space' displays the next screen, 'enter' for one line scroll, 'q' to quit.) To execute and enter expressions, enter: hw.out

To do the lab, edit using pico: pico hw (Note that in pico, control‐c tells the line number.) Each you make changes in "hw", Use 'make' to obtain an updated executable.

‐‐ You can run the executables interactively or using a data file. The file, data1, contains several expressions. For example, you can enter: y3.out < data1 and it will work as if you entered these expressions. You can do the same thing for the yacc program that you write. A file sample.data contains the data in the above sample input, so you can enter: hw.out < sample.data

‐‐ When you are completely done, script your yacc file and output by doing the following: script hw hw make Mail the typescript file to the css448 account: cat hw.data [email protected] hw.out < hw.data control-d