UsingGhcAsLibrary: Main.hs

File Main.hs, 1.9 KB (added by simonpj, 8 years ago)
Line 
1module Main where
2
3import qualified GHC
4import DynFlags (defaultDynFlags)
5import Outputable (ppr, showSDoc)
6
7-- Set this to the root of your GHC installation
8-- (eg. /usr/local/lib/ghc-6.5)
9my_ghc_root = "/home/simonmar/nightly-HEAD/i386-unknown-linux"
10
11main =  GHC.defaultErrorHandler defaultDynFlags $ do
12        putStrLn "Starting"
13        GHC.init ["-B" ++ my_ghc_root]
14        putStrLn "Initialised"                         
15        let ghcMode = GHC.BatchCompile         
16        session <- GHC.newSession ghcMode
17        dflags0 <- GHC.getSessionDynFlags session
18        GHC.defaultCleanupHandler dflags0 $ do
19        dflags1 <- GHC.initPackages dflags0
20        GHC.setSessionDynFlags session dflags1
21        putStrLn "New session defined"
22        let preludeModule = GHC.mkModule "Prelude"     
23        GHC.setContext session [] [preludeModule]
24        putStrLn "Context set"
25        let stmt1 = "let n = 2 + 2"
26        runResult <- GHC.runStmt session stmt1
27
28        let result = case runResult of 
29                        GHC.RunOk []        -> "OK"
30                        GHC.RunOk (name: _) -> "OK: " ++ showSDoc (ppr name)
31                        _                   -> "Failed"
32
33        putStrLn ("Result is " ++ result)
34
35{- ---------------------------------------------------------------------------------------------
36
37Variables/types used:
38
39        init :: [String] -> IO [String]
40
41        data GhcMode = BatchCompile | Interactive | OneShot | ...
42
43        newSession :: GhcMode -> IO Session
44
45        mkModule :: OccName.UserString -> Module                        (type UserString = String)
46
47        setContext :: Session -> [Module] -> [Module] -> IO ()
48
49        runStmt :: Session -> String -> IO RunResult
50
51        data RunResult = RunOk [Name] | RunFailed | RunException Exception
52
53        ppr :: Outputtable a => a -> SDoc
54
55        showSDoc :: SDoc -> String
56
57
58-------------------------------------------------------------------------------------------------
59
60This program compiles successfully, but fails when it encounters the statement
61
62        GHC.init []
63
64with the error message:
65
66        Main: unknown exception
67
68-}