... | ... | @@ -15,8 +15,8 @@ This part of the commentary is not a tutorial on *using* the GHC API: for that, |
|
|
|
|
|
A typical interaction with the GHC API goes something like the following:
|
|
|
|
|
|
- You probably want to wrap the whole program in `defaultErrorHandler defaultDynFlags` to get error messages
|
|
|
- Create a new session: `newSession`
|
|
|
- You probably want to wrap the whole program in `defaultErrorHandler defaultFatalMessager defaultFlushOut` to get error messages
|
|
|
- Start a new GHC session: `runGhc`
|
|
|
- Set the flags: `getSessionDynFlags`, `setSessionDynFlags`.
|
|
|
- Add some *targets*: `setTargets`, `addTarget`, `guessTarget`
|
|
|
- Perform [Dependency Analysis](#dependency-analysis): `depanal`
|
... | ... | @@ -26,25 +26,32 @@ A typical interaction with the GHC API goes something like the following: |
|
|
Warning: Initializing GHC is tricky! Here is a template that seems to initialize GHC and a session. Derived from ghc's Main.main function.
|
|
|
|
|
|
```haskell
|
|
|
import DynFlags
|
|
|
{-# LANGUAGE CPP #-}
|
|
|
import GHC
|
|
|
|
|
|
mode = Interactive
|
|
|
|
|
|
main = defaultErrorHandler defaultDynFlags $ do
|
|
|
s <- newSession mode (Just "/usr/local/lib/ghc-6.5")
|
|
|
flags <- getSessionDynFlags s
|
|
|
(flags, _) <- parseDynamicFlags flags []
|
|
|
GHC.defaultCleanupHandler flags $ do
|
|
|
setSessionDynFlags s flags{ hscTarget=HscInterpreted }
|
|
|
-- your code here
|
|
|
import GHC.Paths ( libdir )
|
|
|
#if __GLASGOW_HASKELL__ >= 811
|
|
|
import GHC.Driver.Session ( defaultFatalMessager, defaultFlushOut )
|
|
|
#else
|
|
|
import DynFlags ( defaultFatalMessager, defaultFlushOut )
|
|
|
#endif
|
|
|
|
|
|
main =
|
|
|
defaultErrorHandler defaultFatalMessager defaultFlushOut $ do
|
|
|
runGhc (Just libdir) $ do
|
|
|
dflags <- getSessionDynFlags
|
|
|
setSessionDynFlags dflags { hscTarget = HscInterpreted
|
|
|
, ghcLink = LinkInMemory }
|
|
|
-- your code here, for example:
|
|
|
-- target <- guessTarget "test_main.hs" Nothing
|
|
|
-- setTargets [target]
|
|
|
-- load LoadAllTargets
|
|
|
```
|
|
|
|
|
|
|
|
|
You must pass the path to `package.conf` as an argument to `newSession`.
|
|
|
You must pass the path to `package.conf` as an argument to `runGhc`.
|
|
|
|
|
|
|
|
|
The `hscTarget` field of `DynFlags` tells the compiler what kind of output to generate from compilation. There is unfortunately some overlap between this and the `GhcMode` passed to `newSession`; we hope to clean this up in the future, but for now it's probably a good idea to make sure that these two settings are consisent. That is, if `mode==Interactive`, then `hscTarget==Interpreted`, if `mode==JustTypecheck` then `hscTarget==HscNothing`.
|
|
|
The `hscTarget` field of `DynFlags` tells the compiler what kind of output to generate from compilation. The `ghcLink` fiel of `DynFlags` tells the compiler what to do with the resulting object files.
|
|
|
|
|
|
## Targets
|
|
|
|
... | ... | |