module Copilot.Arduino.Main (arduino) where
import Language.Copilot (Spec, interpret, reify)
import Copilot.Compile.C99 (compile)
import Copilot.Arduino.Internals
import System.Directory
import System.Posix.Temp (mkdtemp)
import System.FilePath
import Control.Monad.Writer
import Data.List (isInfixOf)
import Options.Applicative
arduino :: Sketch () -> IO ()
arduino (Sketch s) = go =<< execParser opts
where
opts = info (parseCmdLine <**> helper)
( fullDesc
<> progDesc "Run this program with no options to generate an Arduino sketch."
)
go o = case interpretSteps o of
Just n -> interpret n spec
Nothing -> writeIno spec (mconcat fs)
(is, fs) = unzip (execWriter s)
spec = sequence_ is
data CmdLine = CmdLine
{ interpretSteps :: Maybe Integer
}
parseCmdLine :: Parser CmdLine
parseCmdLine = CmdLine
<$> optional (option auto
( long "interpret"
<> short 'i'
<> help "use copilot to interpret the program, displaying what it would do"
<> metavar "NUM"
))
writeIno :: Spec -> Framework -> IO ()
writeIno spec framework = do
toptmpdir <- getTemporaryDirectory
mytmpdir <- mkdtemp (toptmpdir </> "copilot")
reify spec >>= compile (mytmpdir </> "copilot")
c <- lines <$> readFile (mytmpdir </> "copilot.c")
let c' = filter (Prelude.not . isInfixOf "#include \"") c
d <- getCurrentDirectory
let dirbase = takeFileName d
writeFile (addExtension dirbase "ino") $
unlines $ sketchFramework framework c'
removeDirectoryRecursive mytmpdir