Personal tools

GHC/As a library (up to 6.8)

From HaskellWiki

< GHC(Difference between revisions)
Jump to: navigation, search
Line 43: Line 43:
== Relevant information ==
== Relevant information ==
Init GHC
<pre>GHC.init :: String -> IO ()</pre>
This should be called once only. Initializes with TopDir path (the String passed in)
First create a session:  
First create a session:  
<pre>GHC.newSession :: DynFlags.GhcMode -> Session</pre>
<pre>GHC.newSession :: DynFlags.GhcMode -> Session</pre>

Revision as of 18:15, 15 September 2006


1 Using GHC as a library

In GHC 6.5 and subsequently you can import GHC as a Haskell library, which lets you write a Haskell program that has access to all of GHC.

This page is a place for everyone to add

  • Notes about how to get it working
  • Comments about the API
  • Suggestions for improvement

and so on.

1.1 Getting started

You'll need to get a version of GHC that supports the GHC API. Either download ghc from CVS or use darcs: darcs get --partial There are also nightly snapshot distributions available.

To use the GHC API you say simply

  import GHC

Doing this imports the module GHC from the package ghc, which comes with GHC 6.5 and subsequent. The module GHC exports the "GHC API", which is still in a state of flux. Currently it's not even Haddock-documented. You can see the source code (which is somewhat documented) here

Here's an example main program that does it Media:Main.hs. To compile Media:Main.hs, you have to turn on the flag "-package ghc", e.g.

  ghc -package ghc Main.hs

1.2 Using the GHC library from inside GHCi

This works, to some extent. However, beware about loading object code, because there is only a single linker symbol table in the runtime, so GHCi will be sharing the symbol table with the new GHC session.

Prelude> :m GHC
Prelude GHC> GHC.init (Just "/home/david/coding/haskell/ghc/usr/lib/ghc-6.5")
Prelude GHC> session <- newSession Interactive
Prelude GHC> setSessionDynFlags session =<< initPackages =<<
getSessionDynFlags session
Prelude GHC> setContext session [] [mkModule "Prelude"]
Prelude GHC> runStmt session "let add1 x = x + 1"
Prelude GHC> runStmt session "add1 2"
Prelude GHC> :q
Leaving GHCi.

1.3 Relevant information

Init GHC

GHC.init :: String -> IO ()

This should be called once only. Initializes with TopDir path (the String passed in)

First create a session:

GHC.newSession :: DynFlags.GhcMode -> Session

Load Module

HscTypes.TargetId = TargetModule ModuleName | TargetFile FilePath (Maybe Phase)

The Phase determines which phase to start from (preprocessing)

Enter Expressions/Run Statements

GHC.runStmt :: Session -> String -> IO RunResult
date GHC.RunResult
= RunOk [Name]
| RunFailed
| RunException

Error messages can be routed through a callback mechanism.

setSessionDynFlags ::