Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Haskell parser with GHC API
-- ghc Main.hs -package ghc
module Main where
import DynFlags
import FastString
import HsSyn
import Lexer
import Outputable
import Parser
import RdrName
import SrcLoc
import StaticFlags
import StringBuffer
import System.Environment
main :: IO ()
main = do
[file] <- getArgs
mp <- parseHaskell file
case mp of
Nothing -> putStrLn "Parse failed"
Just mdl -> print $ map (showSDoc . ppr) $ hsmodDecls mdl
parseHaskell :: FilePath -> IO (Maybe (HsModule RdrName))
parseHaskell file = do
initStaticOpts
sbuf <- hGetStringBuffer file
let srcloc = mkSrcLoc (mkFastString file) 1 1
return $ case unP parseModule (mkPState defaultDynFlags sbuf srcloc) of
POk _ (L _ mdl) -> Just mdl
PFailed _ _ -> Nothing
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment