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