Skip to content

Instantly share code, notes, and snippets.

@Minoru
Created November 3, 2010 20:32
Show Gist options
  • Save Minoru/661660 to your computer and use it in GitHub Desktop.
Save Minoru/661660 to your computer and use it in GitHub Desktop.
Shell to C translator (using new intermediate represantation)
import IR
type C = String
genC x = helper "" "" 0 x
where helper :: C -> C -> Int -> Statement -> C
helper defs code n (Sequence (x:[])) = helper (defs ++ genDefs n True x) (code ++ genCode n True x) (n + countDefs x) (Sequence [])
helper defs code n (Sequence (x:xs)) = helper (defs ++ genDefs n False x) (code ++ genCode n False x) (n + countDefs x) (Sequence xs)
helper defs code n (Sequence _ ) = "#include \"routines.h\"\nint main(){" ++ defs ++ code ++ "}"
helper defs code n (Command x xs) = "#include \"routines.h\"\nint main(){" ++ genDefs 0 True (Command x xs) ++ genCode 0 True (Command x xs) ++ "}"
countDefs :: Statement -> Int
countDefs (Command _ _) = 1
countDefs _ = 0
genDefs :: Int -> Bool -> Statement -> C
genDefs n return (Command (ConcatA x) _) = "const char* cmd" ++ show n ++ "[] = { " ++ fromConcatA x ++ "NULL };" ++ (if return then "int retval;" else "")
genDefs n return (Command x _) = "const char* cmd" ++ show n ++ "[] = { " ++ fromArray x ++ "NULL };" ++ (if return then "int retval;" else "")
genDefs n return x = "genDefs: n=" ++ show n ++ ", x=" ++ show x ++ ""
fromConcatA :: [Array] -> C
fromConcatA ((Field x):[]) = "\"" ++ parseExpression x ++ "\", "
fromConcatA ((Field x):xs) = "\"" ++ parseExpression x ++ "\", " ++ fromConcatA xs
fromConcatA _ = ""
fromArray :: Array -> C
fromArray (Field x) = "\"" ++ parseExpression x ++ "\", "
fromArray _ = ""
parseExpression :: Expression -> C
parseExpression (Const x) = x
parseExpression _ = ""
genCode :: Int -> Bool -> Statement -> C
genCode n return (Command (ConcatA x) _) = (if return then "retval=" else "") ++ "exec_command (cmd" ++ show n ++ ");" ++ (if return then "return retval;" else "")
genCode n return (Command x _) = (if return then "retval=" else "") ++ "exec_command (cmd" ++ show n ++ ");" ++ (if return then "return retval;" else "")
genCode n return x = "genCode: n=" ++ show n ++ ", x=" ++ show x ++ ""
main = putStr (genC ( Sequence [ Command (ConcatA [Field (Const "ping"),Field (Const "-c5"),Field (Const "google.com")]) [], Command (Field (Const "date")) [], Command (ConcatA [Field (Const "tuch"),Field (Const "example.file")]) [], Command (Field (Const "ncal")) [], Command (ConcatA [Field (Const "echo"),Field (Const "Hello, world!")]) [] ] ) )
--main = putStr (genC (Command (Field (Const "date")) []))
--main = putStr (genC (Sequence [(Command (ConcatA [Field (Const "ping"),Field (Const "google.com")]) [])]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment