Need a tutorial for using GHC to parse and typecheck Haskell

前端 未结 4 1718
执念已碎
执念已碎 2020-12-30 23:04

I\'m working on a project for analyzing Haskell code. I decided to use GHC to parse the source and infer types rather than write my own code to do that. Right now, I\'m sl

4条回答
  •  说谎
    说谎 (楼主)
    2020-12-30 23:14

    Ah! found a much better entry point into the docs at: http://www.haskell.org/ghc/docs/latest/html/libraries/ghc-6.12.1/GHC.html

    I updated the wikipage with this example:

    Here we demonstrate calling parseModule, typecheckModule, desugarModule, getNamesInScope, and getModuleGraph. This works for haskell-platform, ghc-6.12.1.

    bugs: libdir is hardcoded. See ghc-paths above.

    --A.hs
    --invoke: ghci -package ghc A.hs
    import GHC
    import Outputable
    
    --import GHC.Paths ( libdir )
    import DynFlags ( defaultDynFlags )
    libdir = "/usr/local/lib/ghc-6.12.1"
    targetFile = "B.hs"
    
    main = do
       res <- example
       print $ showSDoc ( ppr res )
    
    example = 
        defaultErrorHandler defaultDynFlags $ do
          runGhc (Just libdir) $ do
            dflags <- getSessionDynFlags
            setSessionDynFlags dflags
            target <- guessTarget targetFile Nothing
            setTargets [target]
            load LoadAllTargets
            modSum <- getModSummary $ mkModuleName "B"
            p <- parseModule modSum
            t <- typecheckModule p
            d <- desugarModule t
            l <- loadModule d
            n <- getNamesInScope
            c <- return $ coreModule d
    
            g <- getModuleGraph
            mapM showModule g     
            return $ (parsedSource d,"/n-----/n",  typecheckedSource d)
    
    --B.hs
    module B where
    
    main = print "Hello, World!"
    

提交回复
热议问题