GRR example: translate a Pascal-ish language to C.
includes constant folding optimizer!!!
main: X:stats = program(X):c
X = "error!":stderr
stats: X:stat ";" Y:stats = [X|Y]
X:stat = X
stat: "begin" X:stats "end" = X
X:ident ":=" Y:exp = assign(X,Y)
"if" X:comp "then" Y:stat = if(X,Y)
"while" X:comp "do" Y:stat = while(X,Y)
comp: X:exp "=" X:exp = eq(X,Y)
exp: X:term "+" Y:exp = plus(X,Y)
X:term = X
term: X:factor "*" Y:term = times(X,Y)
X:factor = X
factor: "(" X:exp ")" = X
X:ident = id(X)
"[0-9]+"/X = int(X:val)
ident: "[a-c]"/X = X
c: program(X:c) = "int a,b,c;\nmain() {\n" X "}\n"
[X:c|Y:c] = X ";\n" Y
assign(X:c,Y:opt:c) = X "=" Y
if(X:c,Y:c) = "if (" X ") {\n" Y "}"
while(X:c,Y:c) = "while (" X ") {\n" Y "}"
eq(X:opt:c,Y:opt:c) = X "==" Y
plus(X:c,Y:c) = X "+" Y
times(X:c,Y:c) = X "*" Y
ident(X) = X
int(X) = X:str
opt: plus(X:opt/int(Y),Z:opt/int(W)) = int((Y,W):add)
times(X:opt/int(Y),Z:opt/int(W))= int((Y,W):mul)
would turn:
while a=1 do
begin
c:=a*3;
if c=16*(8+8) then b:=5+1
end
into: (note the optimisations :-)
int a,b,c;
main() {
while (a == 1) {
c=a*3;
if (c==256) {
b=6
};
};
}