-- | Atom compilation.
module Language.Atom.Compile
  ( compile
  ) where

import Control.Monad.State hiding (join)
import Data.Maybe
import System.Exit
import System.IO

import Language.Atom.Code
import Language.Atom.Scheduling
import Language.Atom.Elaboration
import Language.Atom.Language hiding (Atom)

-- | Compiles an atom description to C.
compile :: Name -> Config -> Atom () -> IO ()
compile name config atom = do
  r <- elaborate name atom
  case r of
    Nothing -> putStrLn "ERROR: Design rule checks failed." >> exitWith (ExitFailure 1)
    Just (rules, init) -> do
      r <- schedule name rules
      case r of
        Nothing -> putStrLn "ERROR: Rule scheduling failed." >> exitWith (ExitFailure 1)
        Just schedule -> do
          putStrLn "Starting code generation..."
          hFlush stdout
          writeC name config schedule init