P ---> A { A } '$'
A ---> lcletter '=' E ';'
E ---> T {('+'|'-') T}
T ---> S {('*'|'/') S}
S ---> F '^' S | F
F ---> lcletter | '(' E ')' | digit
This is a grammar for a simple language consisting of a sequence
of assignment statements, terminated by semicolons. The whole
program is terminated by a sharp ($). Operands are single lowercase
letters or single digits. Operators are = + - * / ^Here is a sample program (sentence) in this language:
a = 4;
b = (3 + a)*6;
c = a^2 + b^2; $
Adapt the parser for arithmetic expressions handed out in class to
this slightly larger language, so that you can parse the
input above.
With these conventions, the sample program above becomes the following as a sequence of symbolic quadruples.
(#,4,~,A)
(=,A,~,a)
(#,3,~,B)
(+,B,a,C)
(#,6,~,D)
(*,C,D,E)
(=,E,~,b)
(#,2,~,F)
(^,a,F,G)
(#,2,~,H)
(^,b,H,I)
(+,G,I,J)
(=,J,~,c)
($,~,~,~)
Add extra code to your parser so that it will translate the
sequence of assignment statements into this simple form
of quadruples.Hints:
private static char startIt = 'A'; // class variable
private static char newTemp() {
return startIt++;
}
Testing:
You can try the sample input above, or even simpler input initially. I have a working C interpreter for this simple language: source in C, source in HTML. NOTE: this C source must be compiled with an extra -lm option ("math library") because of the pow function. (This interpreter assumes that the source looks like the above, with a non-blank char for and "unused" parameter in a quad.) My interpreter also prints out the number assigned whenever there is an assignment quad. For the first input, the interpreter produces:
m[97] = 4.000000 m[98] = 42.000000 m[99] = 1780.000000What to turn in:
Try out the following solution to the quadratic formula as input to your program:
a = 1; b = 3; c = 1;
d = b*b - 4*a*c;
e = d^(1/2);
r = (0 - b + e)/(2*a); $
After translating, my interpreter should produce the
following when your quads are fed into it:
m[97] = 1.000000 m[98] = 3.000000 m[99] = 1.000000 m[100] = 5.000000 m[101] = 2.236068 m[114] = -0.381966Then try the following, with a more complex expression Here the output should be the same as that above, except for lines 4 and 5 omitted:
a = 1; b = 3; c = 1;
r = (0 - b + (b*b - 4*a*c)^(1/2))/(2*a); $