]> ruin.nu Git - proglang.git/blobdiff - Compile.hs
adding compiler
[proglang.git] / Compile.hs
diff --git a/Compile.hs b/Compile.hs
new file mode 100644 (file)
index 0000000..c3e93f9
--- /dev/null
@@ -0,0 +1,41 @@
+module Compile (compileExp, compileStm) where
+
+import Abssyntax
+import Prelude hiding (lookup)
+
+compileExp :: Exp -> String
+compileExp (EBool True) = "1";
+compileExp (EBool False) = "0";
+compileExp (EInt n) = show n
+compileExp (EVar (Ident i)) = i
+compileExp (EAss (Ident i) e) = i++"="++compileExp e
+compileExp EDefault = error "EDefault called from an illegal place"
+compileExp (BiOpExp e o e') = "("++compileExp e++")"++op o++"("++compileExp e'++")"
+compileExp (ENeg e) = "-("++compileExp e++")"
+compileExp (ENot e) ="!("++compileExp e++")" 
+compileExp (EPost (Ident i) Plus) = i++"++"
+compileExp (EPost (Ident i) Minus) = i++"--"
+compileExp EReadI = "read()"
+compileExp EReadB = "read()"
+
+op :: Op -> String
+op Eq = "=="
+op NEq = "!="
+op Plus = "+"
+op Minus = "-"
+op Times = "*" 
+op Div = "/" 
+op Lt = "<"
+op ELt = "<="
+op Gt = ">"
+op EGt = ">="
+
+compileStm :: Stm -> String
+compileStm (SNoop) = ";\n"
+compileStm (SExp e) = compileExp e++";\n"
+compileStm (SIf b s s') = "if("++compileExp b++")"++compileStm s++" \nelse "++compileStm s'
+compileStm (SPrint e) = "printf(\"%d\\n\","++compileExp e++");\n"
+compileStm (SBlock ss) = "{\n"++concat (map (("\t"++).compileStm) ss)++"\n}\n"
+compileStm (SWhile e s) = "while("++compileExp e++")"++compileStm s
+compileStm (SDecl t (Ident i) EDefault) = "int "++i++"=0;\n"
+compileStm (SDecl t (Ident i) e) = "int "++i++"="++compileExp e++";\n"