module Language.Copilot.AdHocC (
varDecl, arrDecl, varInit, arrayInit, funcDecl
, includeBracket, includeQuote, printf, printfNewline
) where
import Data.List (intersperse)
import Language.Atom (Type(..))
import Language.Atom.Code (cType)
varDecl :: Type -> [String] -> String
varDecl t vars =
cType t ++ " " ++ unwords (intersperse "," vars) ++ ";"
arrDecl :: Type -> [(String, Int)] -> String
arrDecl t arrs =
cType t ++ " " ++ unwords (intersperse "," mkArrs) ++ ";"
where mkArrs = map (\(a,size) -> a ++ "[" ++ show size ++ "]") arrs
varInit :: Show a => Type -> String -> a -> String
varInit t var val = cType t ++ " " ++ var ++ " = " ++ show val ++ ";"
arrayInit :: Show a => Type -> String -> [a] -> String
arrayInit t var vals =
cType t ++ " " ++ var ++ "[" ++ show (length vals)
++ "] = " ++ bracesListShow ++ ";"
where
bracesListShow :: String
bracesListShow =
"{" ++ (foldl (++) "" $ intersperse "," $ map show vals) ++ "}"
funcDecl :: Maybe Type -> String -> [Type] -> String
funcDecl t fn argTs = makeRet t ++ " " ++ fn ++ "(" ++ makeArgTs ++ ");"
where makeRet Nothing = "void"
makeRet (Just t') = cType t'
makeArgTs | null argTs = "void"
| otherwise = unwords (intersperse "," $ map cType argTs)
includeBracket :: String -> String
includeBracket lib = "#include <" ++ lib ++ ">"
includeQuote :: String -> String
includeQuote lib = "#include \"" ++ lib ++ "\""
printfPre :: String -> String
printfPre = ("printf(\"" ++)
printfPost :: [String] -> String
printfPost vars =
let sep = if null vars then " " else ", "
in "\"" ++ sep ++ unwords (intersperse "," vars) ++ ");"
newline :: String
newline = "\\n"
printf, printfNewline :: String -> [String] -> String
printfNewline text vars = (printfPre text) ++ newline ++ (printfPost vars)
printf text vars = (printfPre text) ++ (printfPost vars)