{-# OPTIONS_GHC -package ghc -w #-}
module API where

import DynFlags
import GHC
import PprTyThing
import System.Process
import System.IO
import Outputable
import Data.Maybe

-- 0. '-package' is ignored in source pragmas, without even a warning
-- 1. comments, including pragmas, will be lost in output
-- 2. there'll be a syntax error here due to extra lists in output
instance Num () where fromInteger = undefined

mode = CompManager
compileToCoreFlag = False

-- shouldn't something like this be in System.Process?
writer >| cmd = runInteractiveCommand cmd >>= \(i,o,e,p)->writer i
cmd |> reader = runInteractiveCommand cmd >>= \(i,o,e,p)->reader o

-- shouldn't GHC export a hostSession, 
-- so that we could ask for things like topDir there?
ghcDir = "c:/fptools/ghc/compiler/stage2/ghc-inplace --print-libdir" 
          |> (fmap dropLineEnds . hGetContents)
  where dropLineEnds = filter (not . (`elem` "\r\n"))

main = defaultErrorHandler defaultDynFlags $ do
  s          <- newSession . Just =<< ghcDir
  flags      <- getSessionDynFlags s
  (flags, _) <- parseDynamicFlags flags ["-package ghc"]
  GHC.defaultCleanupHandler flags $ do
    setSessionDynFlags s flags{ hscTarget=HscInterpreted }
    addTarget s =<< guessTarget "API_Layout.hs" Nothing
    load s LoadAllTargets
    prelude <- findModule s (mkModuleName "Prelude") Nothing
    usermod <- findModule s (mkModuleName "API") Nothing 
    setContext s [usermod] [prelude]
    Just cm <- checkModule s (mkModuleName "API") compileToCoreFlag
    unqual  <- getPrintUnqual s
    printForUser stdout unqual $ ppr $ parsedSource cm

