[project @ 2000-11-21 14:31:58 by simonmar]
[ghc-hetmet.git] / ghc / compiler / compMan / CmLink.lhs
1 %
2 % (c) The University of Glasgow, 2000
3 %
4 \section[CmLink]{Linker for GHCI}
5
6 \begin{code}
7 module CmLink ( Linkable(..),  Unlinked(..),
8                 filterModuleLinkables, 
9                 findModuleLinkable_maybe,
10                 modname_of_linkable, is_package_linkable,
11                 LinkResult(..),
12                 link, 
13                 unload,
14                 PersistentLinkerState{-abstractly!-}, emptyPLS,
15 #ifdef GHCI
16                 linkExpr
17 #endif
18   ) where
19
20
21 import Interpreter
22 import DriverPipeline
23 import CmTypes
24 import CmStaticInfo     ( GhciMode(..) )
25 import Outputable       ( SDoc )
26 import Digraph          ( SCC(..), flattenSCC )
27 import DriverUtil
28 import Module           ( ModuleName )
29 import RdrName
30 import FiniteMap
31 import Outputable
32 import ErrUtils         ( showPass )
33 import CmdLineOpts      ( DynFlags(..) )
34 import Panic            ( panic )
35
36 import Exception
37 import Monad
38 import IO
39
40 #include "HsVersions.h"
41 \end{code}
42
43 \begin{code}
44 data PersistentLinkerState 
45    = PersistentLinkerState {
46
47 #ifdef GHCI
48         -- Current global mapping from RdrNames to closure addresses
49         closure_env :: ClosureEnv,
50
51         -- the current global mapping from RdrNames of DataCons to 
52         -- info table addresses.
53         -- When a new Unlinked is linked into the running image, or an existing
54         -- module in the image is replaced, the itbl_env must be updated
55         -- appropriately.
56         itbl_env    :: ItblEnv
57
58         -- notionally here, but really lives in the C part of the linker:
59         --            object_symtab :: FiniteMap String Addr
60 #else
61         dummy :: ()     --  sigh, can't have an empty record
62 #endif
63
64      }
65
66 data LinkResult 
67    = LinkOK   PersistentLinkerState
68    | LinkErrs PersistentLinkerState [SDoc]
69
70 findModuleLinkable_maybe :: [Linkable] -> ModuleName -> Maybe Linkable
71 findModuleLinkable_maybe lis mod 
72    = case [LM time nm us | LM time nm us <- lis, nm == mod] of
73         []   -> Nothing
74         [li] -> Just li
75         many -> pprPanic "findModuleLinkable" (ppr mod)
76
77
78 emptyPLS :: IO PersistentLinkerState
79 #ifdef GHCI
80 emptyPLS = return (PersistentLinkerState { closure_env = emptyFM, 
81                                            itbl_env    = emptyFM })
82 #else
83 emptyPLS = return (PersistentLinkerState {})
84 #endif
85 \end{code}
86
87 \begin{code}
88 link :: GhciMode                -- interactive or batch
89      -> DynFlags                -- dynamic flags
90      -> Bool                    -- attempt linking in batch mode?
91      -> [Linkable]              -- only contains LMs, not LPs
92      -> PersistentLinkerState 
93      -> IO LinkResult
94
95 -- For the moment, in the batch linker, we don't bother to tell doLink
96 -- which packages to link -- it just tries all that are available.
97 -- batch_attempt_linking should only be *looked at* in batch mode.  It
98 -- should only be True if the upsweep was successful and someone
99 -- exports main, i.e., we have good reason to believe that linking
100 -- will succeed.
101
102 -- There will be (ToDo: are) two lists passed to link.  These
103 -- correspond to
104 --
105 --      1. The list of all linkables in the current home package.  This is
106 --         used by the batch linker to link the program, and by the interactive
107 --         linker to decide which modules from the previous link it can 
108 --         throw away.
109 --      2. The list of modules on which we just called "compile".  This list
110 --         is used by the interactive linker to decide which modules need
111 --         to be actually linked this time around (or unlinked and re-linked 
112 --         if the module was recompiled).
113
114 link mode dflags batch_attempt_linking linkables pls1
115    = do let verb = verbosity dflags
116         when (verb >= 3) $ do
117              hPutStrLn stderr "CmLink.link: linkables are ..."
118              hPutStrLn stderr (showSDoc (vcat (map ppr linkables)))
119         res <- link' mode dflags batch_attempt_linking linkables pls1
120         when (verb >= 3) $ 
121              hPutStrLn stderr "CmLink.link: done"
122         return res
123
124 link' Batch dflags batch_attempt_linking linkables pls1
125    | batch_attempt_linking
126    = do let o_files = concatMap getOfiles linkables
127         -- don't showPass in Batch mode; doLink will do that for us.
128         doLink o_files
129         -- doLink only returns if it succeeds
130         return (LinkOK pls1)
131    | otherwise
132    = do let verb = verbosity dflags
133         when (verb >= 3) $ do
134             hPutStrLn stderr "CmLink.link(batch): upsweep (partially?) failed OR main not exported;"
135             hPutStrLn stderr "not linking."
136         return (LinkOK pls1)
137    where
138       getOfiles (LP _)    = panic "CmLink.link(getOfiles): shouldn't get package linkables"
139       getOfiles (LM _ _ us) = map nameOfObject (filter isObject us)
140
141 link' Interactive dflags batch_attempt_linking linkables pls1
142     = do showPass dflags "Linking"
143          pls2 <- unload pls1
144          linkObjs linkables pls2
145
146
147 ppLinkableSCC :: SCC Linkable -> SDoc
148 ppLinkableSCC = ppr . flattenSCC
149
150
151 modname_of_linkable (LM _ nm _) = nm
152 modname_of_linkable (LP _)      = panic "modname_of_linkable: package"
153
154 is_package_linkable (LP _)     = True
155 is_package_linkable (LM _ _ _) = False
156
157 filterModuleLinkables :: (ModuleName -> Bool) 
158                       -> [Linkable] 
159                       -> [Linkable]
160 filterModuleLinkables p [] = []
161 filterModuleLinkables p (li:lis)
162    = case li of
163         LP _         -> retain
164         LM _ modnm _ -> if p modnm then retain else dump
165      where
166         dump   = filterModuleLinkables p lis
167         retain = li : dump
168
169 -----------------------------------------------------------------------------
170 -- Linker for interactive mode
171
172 #ifndef GHCI
173 linkObjs      = panic "CmLink.linkObjs: no interpreter"
174 unload        = panic "CmLink.unload: no interpreter"
175 lookupClosure = panic "CmLink.lookupClosure: no interpreter"
176 #else
177 linkObjs [] pls = linkFinish pls [] []
178 linkObjs (l@(LM _ _ uls) : ls) pls
179    | all isObject uls = do
180         mapM_ loadObj [ file | DotO file <- uls ] 
181         linkObjs ls pls
182    | all isInterpretable uls  = linkInterpretedCode (l:ls) [] [] pls
183    | otherwise                = invalidLinkable
184 linkObjs _ pls = 
185    throwDyn (OtherError "CmLink.linkObjs: found package linkable")
186
187  
188 linkInterpretedCode [] mods ul_trees pls = linkFinish pls mods ul_trees
189 linkInterpretedCode (LM _ m uls : ls) mods ul_trees pls
190    | all isInterpretable uls = 
191         linkInterpretedCode ls (m:mods) (uls++ul_trees) pls
192         
193    | any isObject uls
194         = throwDyn (OtherError "can't link object code that depends on interpreted code")
195    | otherwise = invalidLinkable
196 linkInterpretedCode _ _ _ pls = 
197    throwDyn (OtherError "CmLink.linkInterpretedCode: found package linkable")
198
199 invalidLinkable = throwDyn (OtherError "linkable doesn't contain entirely objects interpreted code")
200
201
202 -- link all the interpreted code in one go.  We first remove from the
203 -- various environments any previous versions of these modules.
204 linkFinish pls mods ul_trees = do
205    resolveObjs
206    let itbl_env'    = filterRdrNameEnv mods (itbl_env pls)
207        closure_env' = filterRdrNameEnv mods (closure_env pls)
208        stuff        = [ (trees,itbls) | Trees trees itbls <- ul_trees ]
209
210    (ibinds, new_itbl_env, new_closure_env) <-
211         linkIModules itbl_env' closure_env' stuff
212
213    let new_pls = PersistentLinkerState {
214                                   closure_env = new_closure_env,
215                                   itbl_env    = new_itbl_env
216                         }
217    return (LinkOK new_pls)
218
219 -- purge the current "linked image"
220 unload :: PersistentLinkerState -> IO PersistentLinkerState
221 unload pls = return pls{ closure_env = emptyFM, itbl_env = emptyFM }
222
223 linkExpr :: PersistentLinkerState -> UnlinkedIExpr -> IO HValue
224 linkExpr PersistentLinkerState{ itbl_env = ie, closure_env = ce } expr
225   = iExprToHValue ie ce expr
226 #endif
227 \end{code}