c9ba801c3d9c37c90373f6c6c18503c43586ea0a
[ghc-hetmet.git] / ghc / compiler / compMan / CompManager.lhs
1 %
2 % (c) The University of Glasgow, 2000
3 %
4 \section[CompManager]{The Compilation Manager}
5
6 \begin{code}
7 module CompManager ( cmInit, cmLoadModule, 
8                      cmGetExpr, cmRunExpr,
9                      CmState, emptyCmState  -- abstract
10                    )
11 where
12
13 #include "HsVersions.h"
14
15 import List             ( nub )
16 import Maybe            ( catMaybes, maybeToList, fromMaybe )
17 import Maybes           ( maybeToBool )
18 import Outputable
19 import UniqFM           ( emptyUFM, lookupUFM, addToUFM, delListFromUFM )
20 import Digraph          ( SCC(..), stronglyConnComp, flattenSCC, flattenSCCs )
21 import Panic            ( panic )
22
23 import CmLink           ( PersistentLinkerState, emptyPLS, Linkable(..), 
24                           link, LinkResult(..), 
25                           filterModuleLinkables, modname_of_linkable,
26                           is_package_linkable )
27 import Interpreter      ( HValue )
28 import CmSummarise      ( summarise, ModSummary(..), 
29                           name_of_summary, deps_of_summary,
30                           mimp_name, ms_get_imports, is_source_import )
31 import Module           ( ModuleName, moduleName, packageOfModule, 
32                           isModuleInThisPackage, PackageName, moduleEnvElts )
33 import CmStaticInfo     ( Package(..), PackageConfigInfo )
34 import DriverPipeline   ( compile, preprocess, doLink, CompResult(..) )
35 import HscTypes         ( HomeSymbolTable, HomeIfaceTable, 
36                           PersistentCompilerState, ModDetails(..) )
37 import Name             ( lookupNameEnv )
38 import PrelNames        ( mainName )
39 import HscMain          ( initPersistentCompilerState )
40 import Finder           ( findModule, emptyHomeDirCache )
41 import BasicTypes       ( GhciMode(..) )
42 import DriverUtil       ( BarfKind(..) )
43 import Exception        ( throwDyn )
44 \end{code}
45
46
47
48 \begin{code}
49 cmInit :: PackageConfigInfo -> IO CmState
50 cmInit raw_package_info
51    = emptyCmState raw_package_info
52
53 cmGetExpr :: CmState
54           -> ModuleName
55           -> String
56           -> IO (CmState, Either [SDoc] HValue)
57 cmGetExpr cmstate modhdl expr
58    = return (panic "cmGetExpr:unimp")
59
60 cmRunExpr :: HValue -> IO ()
61 cmRunExpr hval
62    = return (panic "cmRunExpr:unimp")
63
64
65 -- Persistent state just for CM, excluding link & compile subsystems
66 data PersistentCMState
67    = PersistentCMState {
68         hst :: HomeSymbolTable,    -- home symbol table
69         hit :: HomeIfaceTable,     -- home interface table
70         ui  :: UnlinkedImage,      -- the unlinked images
71         mg  :: ModuleGraph,        -- the module graph
72         pci :: PackageConfigInfo   -- NEVER CHANGES
73      }
74
75 emptyPCMS :: PackageConfigInfo -> PersistentCMState
76 emptyPCMS pci 
77   = PersistentCMState { hst = emptyHST, hit = emptyHIT,
78                         ui  = emptyUI,  mg  = emptyMG, pci = pci }
79
80 emptyHIT :: HomeIfaceTable
81 emptyHIT = emptyUFM
82 emptyHST :: HomeSymbolTable
83 emptyHST = emptyUFM
84
85
86
87 -- Persistent state for the entire system
88 data CmState
89    = CmState {
90         pcms   :: PersistentCMState,       -- CM's persistent state
91         pcs    :: PersistentCompilerState, -- compile's persistent state
92         pls    :: PersistentLinkerState    -- link's persistent state
93      }
94
95 emptyCmState :: PackageConfigInfo -> IO CmState
96 emptyCmState pci
97     = do let pcms = emptyPCMS pci
98          pcs     <- initPersistentCompilerState
99          pls     <- emptyPLS
100          return (CmState { pcms   = pcms,
101                            pcs    = pcs,
102                            pls    = pls })
103
104 -- CM internal types
105 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
106 emptyUI :: UnlinkedImage
107 emptyUI = []
108
109 type ModuleGraph = [SCC ModSummary]  -- the module graph, topologically sorted
110 emptyMG :: ModuleGraph
111 emptyMG = []
112
113 \end{code}
114
115 The real business of the compilation manager: given a system state and
116 a module name, try and bring the module up to date, probably changing
117 the system state at the same time.
118
119 \begin{code}
120 cmLoadModule :: CmState 
121              -> ModuleName
122              -> IO (CmState, Maybe ModuleName)
123
124 cmLoadModule cmstate1 modname
125    = do -- version 1's are the original, before downsweep
126         let pcms1   = pcms   cmstate1
127         let pls1    = pls    cmstate1
128         let pcs1    = pcs    cmstate1
129         let mg1     = mg     pcms1
130         let hst1    = hst    pcms1
131         let hit1    = hit    pcms1
132         let ui1     = ui     pcms1
133    
134         let pcii    = pci    pcms1      -- this never changes
135
136         -- do the downsweep to reestablish the module graph
137         -- then generate version 2's by removing from HIT,HST,UI any
138         -- modules in the old MG which are not in the new one.
139
140         -- Throw away the old home dir cache
141         emptyHomeDirCache
142
143         putStr "cmLoadModule: downsweep begins\n"
144         mg2unsorted <- downsweep modname
145
146         let modnames1   = map name_of_summary (flattenSCCs mg1)
147         let modnames2   = map name_of_summary mg2unsorted
148         let mods_to_zap = filter (`notElem` modnames2) modnames1
149
150         let (hst2, hit2, ui2)
151                = removeFromTopLevelEnvs mods_to_zap (hst1, hit1, ui1)
152
153         let mg2 = topological_sort mg2unsorted
154
155         putStrLn "after tsort:\n"
156         putStrLn (showSDoc (vcat (map ppr ({-flattenSCCs-} mg2))))
157
158         -- Now do the upsweep, calling compile for each module in
159         -- turn.  Final result is version 3 of everything.
160
161         let threaded2 = ModThreaded pcs1 hst2 hit2
162
163         (upsweepOK, threaded3, sccOKs, newLis)
164            <- upsweep_sccs threaded2 [] [] mg2
165
166         let ui3 = add_to_ui ui2 newLis
167         let (ModThreaded pcs3 hst3 hit3) = threaded3
168
169         -- Try and do linking in some form, depending on whether the
170         -- upsweep was completely or only partially successful.
171         let ghci_mode = Batch  -- ToDo: fix!
172
173         if upsweepOK
174
175          then 
176            do putStrLn "UPSWEEP COMPLETELY SUCCESSFUL"
177               let someone_exports_main = any exports_main (moduleEnvElts hst3)
178               let mods_to_relink = upwards_closure mg2 
179                                       (map modname_of_linkable newLis)
180               pkg_linkables <- find_pkg_linkables_for pcii
181                                                       mg2 mods_to_relink
182               putStrLn ("needed package modules =\n" 
183                         ++ showSDoc (vcat (map ppr pkg_linkables)))
184               let sccs_to_relink = group_uis ui3 mg2 mods_to_relink
185               let all_to_relink  = map AcyclicSCC pkg_linkables 
186                                    ++ sccs_to_relink
187               linkresult <- link doLink ghci_mode someone_exports_main
188                                  pcii all_to_relink pls1
189               case linkresult of
190                  LinkErrs _ _
191                     -> panic "cmLoadModule: link failed (1)"
192                  LinkOK pls3 
193                     -> do let pcms3 = PersistentCMState { hst=hst3, hit=hit3, 
194                                                           ui=ui3, mg=mg2, pci=pcii }
195                           let cmstate3 
196                                  = CmState { pcms=pcms3, pcs=pcs3, pls=pls3 }
197                           return (cmstate3, Just modname)
198
199          else 
200            do putStrLn "UPSWEEP PARTIALLY SUCCESSFUL"
201               let mods_to_relink = downwards_closure mg2 
202                                       (map name_of_summary (flattenSCCs sccOKs))
203               pkg_linkables <- find_pkg_linkables_for pcii
204                                                       mg2 mods_to_relink
205               let sccs_to_relink = group_uis ui3 mg2 mods_to_relink
206               let all_to_relink  = map AcyclicSCC pkg_linkables 
207                                    ++ sccs_to_relink
208               linkresult <- link doLink ghci_mode False pcii all_to_relink pls1
209               let (hst4, hit4, ui4) 
210                      = removeFromTopLevelEnvs mods_to_relink (hst3,hit3,ui3)
211               case linkresult of
212                  LinkErrs _ _
213                     -> panic "cmLoadModule: link failed (2)"
214                  LinkOK pls4
215                     -> do let pcms4 = PersistentCMState { hst=hst4, hit=hit4, 
216                                                           ui=ui4, mg=mg2, pci=pcii }
217                           let cmstate4 
218                                  = CmState { pcms=pcms4, pcs=pcs3, pls=pls4 }
219                           return (cmstate4, Just modname)
220
221 exports_main :: ModDetails -> Bool
222 exports_main md
223    = maybeToBool (lookupNameEnv (md_types md) mainName)
224
225 -- Given a (home) module graph and a bunch of names of (home) modules
226 -- within that graph, return the names of any packages needed by the
227 -- named modules.  Do this by looking at their imports.  Assumes, and
228 -- checks, that all of "mods" are mentioned in "mg".
229 -- 
230 -- Then, having found the packages directly needed by "mods",
231 -- (1) round up, by looking in "pci", all packages they directly or
232 -- indirectly depend on, and (2) put these packages in topological
233 -- order, since that's important for some linkers.  Since cycles in
234 -- the package dependency graph aren't allowed, we can just return
235 -- the list of (package) linkables, rather than a list of SCCs.
236 find_pkg_linkables_for :: PackageConfigInfo -> [SCC ModSummary] -> [ModuleName]
237                        -> IO [Linkable]
238 find_pkg_linkables_for pcii mg mods
239    = let mg_summaries = flattenSCCs mg
240          mg_names     = map name_of_summary mg_summaries
241      in
242      -- Assert that the modules for which we seek the required packages
243      -- are all in the module graph, i.e. are all home modules.
244      if   not (all (`elem` mg_names) mods)
245      then panic "find_pkg_linkables_for"
246      else 
247      do let all_imports
248                = concat 
249                     [deps_of_summary summ
250                     | summ <- mg_summaries, name_of_summary summ `elem` mods]
251         let imports_not_in_home  -- imports which must be from packages
252                = nub (filter (`notElem` mg_names) all_imports)
253
254         -- Figure out the packages directly imported by the home modules
255         maybe_locs_n_mods <- mapM findModule imports_not_in_home
256         let home_pkgs_needed
257                = nub (concatMap get_pkg maybe_locs_n_mods)
258                  where get_pkg Nothing = []
259                        get_pkg (Just (mod, loc))
260                           = case packageOfModule mod of 
261                                Just p -> [p]; _ -> []
262
263         -- Discover the package dependency graph, and use it to find the
264         -- transitive closure of all the needed packages
265         let pkg_depend_graph :: [(PackageName,[PackageName])]
266             pkg_depend_graph = map (\pkg -> (_PK_ (name pkg), map _PK_ (package_deps pkg))) pcii
267
268         let all_pkgs_needed = simple_transitive_closure 
269                                  pkg_depend_graph home_pkgs_needed
270
271         -- Make a graph, in the style which Digraph.stronglyConnComp expects,
272         -- containing entries only for the needed packages.
273         let needed_graph
274                = concat
275                    [if srcP `elem` all_pkgs_needed
276                      then [(srcP, srcP, dstsP)] 
277                      else []
278                     | (srcP, dstsP) <- pkg_depend_graph]
279             tsorted = flattenSCCs (stronglyConnComp needed_graph)
280         
281         return (map LP tsorted)
282
283
284 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
285 simple_transitive_closure graph set
286    = let set2      = nub (concatMap dsts set ++ set)
287          dsts node = fromMaybe [] (lookup node graph)
288      in
289          if   length set == length set2 
290          then set 
291          else simple_transitive_closure graph set2
292
293
294 -- For each module in mods_to_group, extract the relevant linkable
295 -- out of "ui", and arrange these linkables in SCCs as defined by modGraph.
296 -- All this is so that we can pass SCCified Linkable groups to the
297 -- linker.  A constraint that should be recorded somewhere is that
298 -- all sccs should either be all-interpreted or all-object, not a mixture.
299 group_uis :: UnlinkedImage -> [SCC ModSummary] -> [ModuleName] -> [SCC Linkable]
300 group_uis ui modGraph mods_to_group
301    = map extract (cleanup (fishOut modGraph mods_to_group))
302      where
303         fishOut :: [SCC ModSummary] -> [ModuleName] -> [(Bool,[ModuleName])]
304         fishOut [] unused
305            | null unused = []
306            | otherwise   = panic "group_uis: modnames not in modgraph"
307         fishOut ((AcyclicSCC ms):sccs) unused
308            = case split (== (name_of_summary ms)) unused of
309                 (eq, not_eq) -> (False, eq) : fishOut sccs not_eq
310         fishOut ((CyclicSCC mss):sccs) unused
311            = case split (`elem` (map name_of_summary mss)) unused of
312                 (eq, not_eq) -> (True, eq) : fishOut sccs not_eq
313
314         cleanup :: [(Bool,[ModuleName])] -> [SCC ModuleName]
315         cleanup [] = []
316         cleanup ((isRec,names):rest)
317            | null names = cleanup rest
318            | isRec      = CyclicSCC names : cleanup rest
319            | not isRec  = case names of [name] -> AcyclicSCC name : cleanup rest
320                                         other  -> panic "group_uis(cleanup)"
321
322         extract :: SCC ModuleName -> SCC Linkable
323         extract (AcyclicSCC nm) = AcyclicSCC (getLi nm)
324         extract (CyclicSCC nms) = CyclicSCC (map getLi nms)
325
326         getLi nm = case [li | li <- ui, not (is_package_linkable li),
327                                         nm == modname_of_linkable li] of
328                       [li]  -> li
329                       other -> panic "group_uis:getLi"
330
331         split f xs = (filter f xs, filter (not.f) xs)
332
333
334 -- Add the given (LM-form) Linkables to the UI, overwriting previous
335 -- versions if they exist.
336 add_to_ui :: UnlinkedImage -> [Linkable] -> UnlinkedImage
337 add_to_ui ui lis
338    = foldr add1 ui lis
339      where
340         add1 :: Linkable -> UnlinkedImage -> UnlinkedImage
341         add1 li ui
342            = li : filter (\li2 -> not (for_same_module li li2)) ui
343
344         for_same_module :: Linkable -> Linkable -> Bool
345         for_same_module li1 li2 
346            = not (is_package_linkable li1)
347              && not (is_package_linkable li2)
348              && modname_of_linkable li1 == modname_of_linkable li2
349                                   
350
351 -- Compute upwards and downwards closures in the (home-) module graph.
352 downwards_closure,
353  upwards_closure :: [SCC ModSummary] -> [ModuleName] -> [ModuleName]
354
355 upwards_closure   = up_down_closure True
356 downwards_closure = up_down_closure False
357
358 up_down_closure :: Bool -> [SCC ModSummary] -> [ModuleName] -> [ModuleName]
359 up_down_closure up modGraph roots
360    = let mgFlat = flattenSCCs modGraph
361          nodes  = map name_of_summary mgFlat
362
363          fwdEdges, backEdges  :: [(ModuleName, [ModuleName])] 
364                    -- have an entry for each mod in mgFlat, and do not
365                    -- mention edges leading out of the home package
366          fwdEdges 
367             = map mkEdge mgFlat
368          backEdges -- Only calculated if needed, which is just as well!
369             = [(n, [m | (m, m_imports) <- fwdEdges, n `elem` m_imports])
370                | (n, n_imports) <- fwdEdges]
371
372          mkEdge summ
373             = (name_of_summary summ, 
374                -- ignore imports not from the home package
375                filter (`elem` nodes) (deps_of_summary summ))
376      in
377          simple_transitive_closure
378             (if up then backEdges else fwdEdges) (nub roots)
379
380
381
382 data ModThreaded  -- stuff threaded through individual module compilations
383    = ModThreaded PersistentCompilerState HomeSymbolTable HomeIfaceTable
384
385 -- Compile multiple SCCs, stopping as soon as an error appears
386 upsweep_sccs :: ModThreaded           -- PCS & HST & HIT
387              -> [SCC ModSummary]      -- accum: SCCs which succeeded
388              -> [Linkable]            -- accum: new Linkables
389              -> [SCC ModSummary]      -- SCCs to do (the worklist)
390                                       -- ...... RETURNING ......
391              -> IO (Bool{-success?-},
392                     ModThreaded,
393                     [SCC ModSummary], -- SCCs which succeeded
394                     [Linkable])       -- new linkables
395
396 upsweep_sccs threaded sccOKs newLis []
397    = -- No more SCCs to do.
398      return (True, threaded, sccOKs, newLis)
399
400 upsweep_sccs threaded sccOKs newLis (scc:sccs)
401    = -- Start work on a new SCC.
402      do (sccOK, threaded2, lisSCC) 
403            <- upsweep_scc threaded (flattenSCC scc)
404         if    sccOK
405          then -- all the modules in the scc were ok
406               -- move on to the next SCC
407               upsweep_sccs threaded2 
408                            (scc:sccOKs) (lisSCC++newLis) sccs
409          else -- we got a compilation error; give up now
410               return
411                  (False, threaded2, sccOKs, lisSCC++newLis)
412
413
414 -- Compile multiple modules (one SCC), stopping as soon as an error appears
415 upsweep_scc :: ModThreaded
416              -> [ModSummary]
417              -> IO (Bool{-success?-}, ModThreaded, [Linkable])
418 upsweep_scc threaded []
419    = return (True, threaded, [])
420 upsweep_scc threaded (mod:mods)
421    = do (moduleOK, threaded1, maybe_linkable) 
422            <- upsweep_mod threaded mod
423         if moduleOK
424          then -- No errors; get contribs from the rest
425               do (restOK, threaded2, linkables)
426                     <- upsweep_scc threaded1 mods
427                  return
428                     (restOK, threaded2, maybeToList maybe_linkable ++ linkables)
429          else -- Errors; give up _now_
430               return (False, threaded1, [])
431
432 -- Compile a single module.
433 upsweep_mod :: ModThreaded
434             -> ModSummary
435             -> IO (Bool{-success?-}, ModThreaded, Maybe Linkable)
436
437 upsweep_mod threaded1 summary1
438    = do let mod_name = name_of_summary summary1
439         let (ModThreaded pcs1 hst1 hit1) = threaded1
440         let old_iface = lookupUFM hit1 (name_of_summary summary1)
441         compresult <- compile summary1 old_iface hst1 hit1 pcs1
442
443         case compresult of
444
445            -- Compilation "succeeded", but didn't return a new iface or
446            -- linkable, meaning that compilation wasn't needed, and the
447            -- new details were manufactured from the old iface.
448            CompOK details Nothing pcs2
449               -> let hst2      = addToUFM hst1 mod_name details
450                      hit2      = hit1
451                      threaded2 = ModThreaded pcs2 hst2 hit2
452                  in  return (True, threaded2, Nothing)
453
454            -- Compilation really did happen, and succeeded.  A new
455            -- details, iface and linkable are returned.
456            CompOK details (Just (new_iface, new_linkable)) pcs2
457               -> let hst2      = addToUFM hst1 mod_name details
458                      hit2      = addToUFM hit1 mod_name new_iface
459                      threaded2 = ModThreaded pcs2 hst2 hit2
460                  in  return (True, threaded2, Just new_linkable)
461
462            -- Compilation failed.  compile may still have updated
463            -- the PCS, tho.
464            CompErrs pcs2
465               -> let threaded2 = ModThreaded pcs2 hst1 hit1
466                  in  return (False, threaded2, Nothing)
467
468
469 removeFromTopLevelEnvs :: [ModuleName]
470                        -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
471                        -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
472 removeFromTopLevelEnvs zap_these (hst, hit, ui)
473    = (delListFromUFM hst zap_these,
474       delListFromUFM hit zap_these,
475       filterModuleLinkables (`notElem` zap_these) ui
476      )
477
478 topological_sort :: [ModSummary] -> [SCC ModSummary]
479 topological_sort summaries
480    = let 
481          toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
482          toEdge summ
483              = (summ, name_of_summary summ, deps_of_summary summ)
484          
485          mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
486          mash_edge (summ, m, m_imports)
487             = case lookup m key_map of
488                  Nothing -> panic "reverse_topological_sort"
489                  Just mk -> (summ, mk, 
490                                 -- ignore imports not from the home package
491                                 catMaybes (map (flip lookup key_map) m_imports))
492
493          edges     = map toEdge summaries
494          key_map   = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
495          scc_input = map mash_edge edges
496          sccs      = stronglyConnComp scc_input
497      in
498          sccs
499
500 -- NB: ignores import-sources for the time being
501 downsweep :: ModuleName          -- module to chase from
502           -> IO [ModSummary]
503 downsweep rootNm
504    = do rootLoc <- getSummary rootNm
505         loop [rootLoc]
506      where
507         getSummary :: ModuleName -> IO ModSummary
508         getSummary nm
509            | trace ("getSummary: "++ showSDoc (ppr nm)) True
510            = do found <- findModule nm
511                 case found of
512                    Just (mod, location) -> summarise preprocess mod location
513                    Nothing -> throwDyn (OtherError 
514                                    ("no signs of life for module `" 
515                                      ++ showSDoc (ppr nm) ++ "'"))
516                                  
517
518         -- loop invariant: homeSummaries doesn't contain package modules
519         loop :: [ModSummary] -> IO [ModSummary]
520         loop homeSummaries
521            = do let allImps :: [ModuleName]
522                     allImps   -- all imports
523                        = (nub . map mimp_name 
524                               . concat . map ms_get_imports)
525                          homeSummaries
526                 let allHome   -- all modules currently in homeSummaries
527                        = map (moduleName.ms_mod) homeSummaries
528                 let neededImps
529                        = filter (`notElem` allHome) allImps
530                 neededSummaries
531                        <- mapM getSummary neededImps
532                 let newHomeSummaries
533                        = filter (isModuleInThisPackage.ms_mod) neededSummaries
534                 if null newHomeSummaries
535                  then return homeSummaries
536                  else loop (newHomeSummaries ++ homeSummaries)
537 \end{code}