]> ruin.nu Git - proglang.git/blob - Compile.hs
c3e93f94850a720839196f010a8b6fe6294b60ce
[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 EDefault = error "EDefault called from an illegal place"
13 compileExp (BiOpExp e o e') = "("++compileExp e++")"++op o++"("++compileExp e'++")"
14 compileExp (ENeg e) = "-("++compileExp e++")"
15 compileExp (ENot e) ="!("++compileExp e++")" 
16 compileExp (EPost (Ident i) Plus) = i++"++"
17 compileExp (EPost (Ident i) Minus) = i++"--"
18 compileExp EReadI = "read()"
19 compileExp EReadB = "read()"
20
21 op :: Op -> String
22 op Eq = "=="
23 op NEq = "!="
24 op Plus = "+"
25 op Minus = "-"
26 op Times = "*" 
27 op Div = "/" 
28 op Lt = "<"
29 op ELt = "<="
30 op Gt = ">"
31 op EGt = ">="
32
33 compileStm :: Stm -> String
34 compileStm (SNoop) = ";\n"
35 compileStm (SExp e) = compileExp e++";\n"
36 compileStm (SIf b s s') = "if("++compileExp b++")"++compileStm s++" \nelse "++compileStm s'
37 compileStm (SPrint e) = "printf(\"%d\\n\","++compileExp e++");\n"
38 compileStm (SBlock ss) = "{\n"++concat (map (("\t"++).compileStm) ss)++"\n}\n"
39 compileStm (SWhile e s) = "while("++compileExp e++")"++compileStm s
40 compileStm (SDecl t (Ident i) EDefault) = "int "++i++"=0;\n"
41 compileStm (SDecl t (Ident i) e) = "int "++i++"="++compileExp e++";\n"