]> ruin.nu Git - proglang.git/blob - Compile.hs
replace E with in
[proglang.git] / Compile.hs
1 module Compile (compileExp, compileStm) where
2
3 import Abssyntax
4 import Prelude hiding (lookup)
5
6 compileExp :: Exp -> String
7 compileExp (EBool True) = "1";
8 compileExp (EBool False) = "0";
9 compileExp (EInt n) = show n
10 compileExp (EVar (Ident i)) = i
11 compileExp (EAss (Ident i) e) = i++"="++compileExp e
12 compileExp (BiOpExp e o e') = "("++compileExp e++")"++op o++"("++compileExp e'++")"
13 compileExp (ENeg e) = "-("++compileExp e++")"
14 compileExp (ENot e) ="!("++compileExp e++")" 
15 compileExp (EPost (Ident i) Plus) = i++"++"
16 compileExp (EPost (Ident i) Minus) = i++"--"
17 compileExp EReadI = "read()"
18 compileExp EReadB = "read()"
19
20 op :: Op -> String
21 op Eq = "=="
22 op NEq = "!="
23 op Plus = "+"
24 op Minus = "-"
25 op Times = "*" 
26 op Div = "/" 
27 op Lt = "<"
28 op ELt = "<="
29 op Gt = ">"
30 op EGt = ">="
31
32 compileStm :: Stm -> String
33 compileStm (SNoop) = ";\n"
34 compileStm (SExp e) = compileExp e++";\n"
35 compileStm (SIf b s s') = "if("++compileExp b++")"++compileStm s++" \nelse "++compileStm s'
36 compileStm (SPrint e) = "printf(\"%d\\n\","++compileExp e++");\n"
37 compileStm (SBlock ss) = "{\n"++concat (map (("\t"++).compileStm) ss)++"\n}\n"
38 compileStm (SWhile e s) = "while("++compileExp e++")"++compileStm s
39 compileStm (SDeclD t i) = compileStm (SDecl t i $ case t of
40         TInt -> EInt 0
41         TBool -> EBool False
42         )
43 compileStm (SDecl t (Ident i) e) = "int "++i++"="++compileExp e++";\n"