From: Michael Andreen Date: Tue, 14 Mar 2006 20:23:09 +0000 (+0000) Subject: compiler seems to be working X-Git-Url: https://ruin.nu/git/?p=proglang.git;a=commitdiff_plain;h=cdcd3b92ee3145e646634d428b02118238d47f33;hp=04f0a9566794cf761b7bcf83190051a400ec3653 compiler seems to be working --- diff --git a/CompInt.hs b/CompInt.hs index d5aa2ca..1934447 100644 --- a/CompInt.hs +++ b/CompInt.hs @@ -48,6 +48,10 @@ main = do args <- getArgs case args of [] -> hGetContents stdin >>= run interpret pProgram - "-c":f:[] -> runFile (\fun st -> writeFile (f++".c") $ compile fun st) pProgram f + "-c":f:[] -> let file = (f++".c") in do + putStrLn $ "Compiling "++f++" to the C99-compatible file:"++file + runFile (\fun st -> writeFile file $ compile fun st) pProgram f f:[] -> runFile interpret pProgram f - _ -> print "Too many arguments" + _ -> do + putStrLn "Usage: ./CompInt [-c] " + putStrLn "-c : compile to C99-compatible file" diff --git a/Compile.hs b/Compile.hs index eb70d0c..f2de7ec 100644 --- a/Compile.hs +++ b/Compile.hs @@ -3,12 +3,14 @@ module Compile (compile,compileExp, compileStm) where import Abssyntax import Prelude hiding (lookup) -cHeader = "#include \nint read(){\nint n;\nscanf(\"%d\",&n);\nreturn n;\n}\nint main(void){\n" +cHeader = "#include \nint read(){\nint n;\nscanf(\"%d\",&n);\nreturn n;\n}\n" -cFooter = "return 0;}" +cMiddle = "\nint main(void){\n" + +cFooter = "return 0;}\n" compile :: [Func] -> [Stm] -> String -compile f s = cHeader++concat (map compileStm s)++cFooter +compile f s = cHeader++concat (map compileFuncDecl f)++concat (map compileFunc f)++cMiddle++concat (map compileStm s)++cFooter compileExp :: Exp -> String compileExp (EBool True) = "1"; @@ -23,6 +25,7 @@ compileExp (EPost (Ident i) Plus) = i++"++" compileExp (EPost (Ident i) Minus) = i++"--" compileExp EReadI = "read()" compileExp EReadB = "read()" +compileExp (EFunc (Ident i) as) = i++"("++(foldl1 (\a b -> a++","++b) (map compileExp as))++")" op :: Op -> String op Eq = "==" @@ -48,3 +51,10 @@ compileStm (SDeclD t i) = compileStm (SDecl t i $ case t of TBool -> EBool False ) compileStm (SDecl t (Ident i) e) = "int "++i++"="++compileExp e++";\n" +compileStm (SReturn e) = "return "++compileExp e++";" + +compileFunc :: Func -> String +compileFunc (Func _ (Ident i) d ss) = "\nint "++i++"("++(foldl1 (\a b -> a++","++b) (map (\(Decl _ (Ident i)) -> "int "++i) d))++"){\n"++concat (map compileStm ss)++"\n}\n" + +compileFuncDecl :: Func -> String +compileFuncDecl (Func _ (Ident i) d ss) = "\nint "++i++"("++(foldl1 (\a b -> a++","++b) (map (\(Decl _ (Ident i)) -> "int "++i) d))++");\n"