Skip to content

Instantly share code, notes, and snippets.

@kazu-yamamoto
Created March 16, 2012 07:16
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kazu-yamamoto/2048983 to your computer and use it in GitHub Desktop.
Save kazu-yamamoto/2048983 to your computer and use it in GitHub Desktop.
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