[project @ 2003-02-21 13:27:53 by simonpj]
[ghc-hetmet.git] / ghc / compiler / rename / RnIfaces.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 section
4 \%[RnIfaces]{Cacheing and Renaming of Interfaces}
5
6 \begin{code}
7 module RnIfaces
8      (  slurpImpDecls, importSupportingDecls,
9         RecompileRequired, outOfDate, upToDate, checkVersions
10        )
11 where
12
13 #include "HsVersions.h"
14
15 import CmdLineOpts      ( opt_IgnoreIfacePragmas, opt_NoPruneDecls )
16 import HscTypes
17 import HsSyn            ( HsDecl(..), Sig(..), TyClDecl(..), ConDecl(..), HsConDetails(..),
18                           InstDecl(..), HsType(..), hsTyVarNames, getBangType
19                         )
20 import RdrHsSyn         ( RdrNameTyClDecl, RdrNameInstDecl, RdrNameRuleDecl )
21 import RnHsSyn          ( RenamedHsDecl, RenamedTyClDecl,
22                           extractHsTyNames, extractHsCtxtTyNames, 
23                           tyClDeclFVs, ruleDeclFVs, impDeclFVs
24                         )
25 import RnHiFiles        ( loadInterface, loadHomeInterface, loadOrphanModules )
26 import RnNames          ( mkModDeps )
27 import RnSource         ( rnTyClDecl, rnInstDecl, rnIfaceRuleDecl )
28 import TcEnv            ( getInGlobalScope, tcLookupGlobal_maybe )
29 import TcRnMonad
30 import Id               ( idType, idName, globalIdDetails )
31 import IdInfo           ( GlobalIdDetails(..) )
32 import TcType           ( tyClsNamesOfType, classNamesOfTheta )
33 import FieldLabel       ( fieldLabelTyCon )
34 import DataCon          ( dataConTyCon, dataConWrapId )
35 import TyCon            ( visibleDataCons, isSynTyCon, getSynTyConDefn, tyConClass_maybe, tyConName )
36 import Class            ( className, classSCTheta )
37 import Name             ( Name {-instance NamedThing-}, isWiredInName, nameIsLocalOrFrom, 
38                           nameModule, NamedThing(..) )
39 import NameEnv          ( delFromNameEnv, lookupNameEnv )
40 import NameSet
41 import Module           ( Module, isHomeModule )
42 import PrelNames        ( hasKey, fractionalClassKey, numClassKey, 
43                           integerTyConName, doubleTyConName )
44 import Outputable
45 import Bag
46 import Maybe( fromJust )
47 \end{code}
48
49
50 %*********************************************************
51 %*                                                       *
52 \subsection{Slurping declarations}
53 %*                                                       *
54 %*********************************************************
55
56 \begin{code}
57 -------------------------------------------------------
58 slurpImpDecls :: FreeVars -> TcRn m [RenamedHsDecl]
59 slurpImpDecls source_fvs
60   = traceRn (text "slurpImp" <+> fsep (map ppr (nameSetToList source_fvs))) `thenM_`
61
62         -- Slurp in things which might be 'gates' for instance
63         -- declarations, plus the instance declarations themselves
64     slurpSourceRefs source_fvs                          `thenM` \ (gate_decls, bndrs) ->
65
66         -- Then get everything else
67     let
68         needed = foldr (plusFV . impDeclFVs) emptyFVs gate_decls
69     in  
70     import_supporting_decls (gate_decls, bndrs) needed
71
72
73 -------------------------------------------------------
74 slurpSourceRefs :: FreeVars                     -- Variables referenced in source
75                 -> TcRn m ([RenamedHsDecl],     -- Needed declarations
76                          NameSet)               -- Names bound by those declarations
77 -- Slurp imported declarations needed directly by the source code;
78 -- and some of the ones they need.  The goal is to find all the 'gates'
79 -- for instance declarations.
80
81 slurpSourceRefs source_fvs
82   = go_outer [] emptyFVs                -- Accumulating decls
83              (nameSetToList source_fvs) -- Things whose defn hasn't been loaded yet
84   where
85         -- The outer loop repeatedly slurps the decls for the current gates
86         -- and the instance decls 
87
88         -- The outer loop is needed because consider
89         --      instance Foo a => Baz (Maybe a) where ...
90         -- It may be that Baz and Maybe are used in the source module,
91         -- but not Foo; so we need to chase Foo too.
92         --
93         -- We also need to follow superclass refs.  In particular, 'chasing Foo' must
94         -- include actually getting in Foo's class decl
95         --      class Wib a => Foo a where ..
96         -- so that its superclasses are discovered.  The point is that Wib is a gate too.
97         -- We do this for tycons too, so that we look through type synonyms.
98
99     go_outer decls bndrs [] = returnM (decls, bndrs)
100
101     go_outer decls bndrs refs           -- 'refs' are not necessarily slurped yet
102         = traceRn (text "go_outer" <+> ppr refs)        `thenM_`
103           foldlM go_inner (decls, bndrs, emptyFVs) refs `thenM` \ (decls1, bndrs1, gates1) ->
104           getImportedInstDecls gates1                   `thenM` \ (inst_decls, new_gates) ->
105           rnIfaceDecls rnInstDecl inst_decls            `thenM` \ inst_decls' ->
106           go_outer (map InstD inst_decls' ++ decls1) 
107                    bndrs1
108                    (nameSetToList (new_gates `plusFV` plusFVs (map getInstDeclGates inst_decls')))
109                 -- NB: we go round again to fetch the decls for any gates of any decls
110                 --     we have loaded.  For example, if we mention
111                 --              print :: Show a => a -> String
112                 --     then we must load the decl for Show before stopping, to ensure
113                 --     that instances from its home module are available
114
115     go_inner (decls, bndrs, gates) wanted_name
116         = importDecl bndrs wanted_name          `thenM` \ import_result ->
117           case import_result of
118             AlreadySlurped -> returnM (decls, bndrs, gates)
119
120             InTypeEnv ty_thing 
121                 -> returnM (decls, 
122                             bndrs `addOneFV` wanted_name,       -- Avoid repeated calls to getWiredInGates
123                             gates `plusFV` getWiredInGates ty_thing)
124
125             HereItIs decl new_bndrs 
126                 -> rnIfaceDecl rnTyClDecl decl          `thenM` \ new_decl ->
127                    returnM (TyClD new_decl : decls, 
128                             bndrs `plusFV` new_bndrs,
129                             gates `plusFV` getGates source_fvs new_decl)
130 \end{code}
131
132 \begin{code}
133 -------------------------------------------------------
134 -- import_supporting_decls keeps going until the free-var set is empty
135 importSupportingDecls needed
136  = import_supporting_decls ([], emptyNameSet) needed
137
138 import_supporting_decls 
139         :: ([RenamedHsDecl], NameSet)   -- Some imported decls, with their binders
140         -> FreeVars                     -- Remaining un-slurped names
141         -> TcRn m [RenamedHsDecl]
142 import_supporting_decls decls needed
143   = slurpIfaceDecls decls needed        `thenM` \ (decls1, bndrs1) ->
144     getImportedRules bndrs1             `thenM` \ rule_decls ->
145     case rule_decls of
146         []    -> returnM decls1 -- No new rules, so we are done
147         other -> rnIfaceDecls rnIfaceRuleDecl rule_decls        `thenM` \ rule_decls' ->
148                  let
149                     rule_fvs = plusFVs (map ruleDeclFVs rule_decls')
150                     decls2   = decls1 ++ map RuleD rule_decls'
151                  in
152                  traceRn (text "closeRules" <+> ppr rule_decls' $$ 
153                           fsep (map ppr (nameSetToList rule_fvs)))      `thenM_`
154                  import_supporting_decls (decls2, bndrs1) rule_fvs
155
156
157 -------------------------------------------------------
158 -- Augment decls with any decls needed by needed,
159 -- and so on transitively
160 slurpIfaceDecls :: ([RenamedHsDecl], NameSet)   -- Already slurped
161                 -> FreeVars                     -- Still needed
162                 -> TcRn m ([RenamedHsDecl], NameSet)
163 slurpIfaceDecls (decls, bndrs) needed
164   = slurp decls bndrs (nameSetToList needed) 
165   where
166     slurp decls bndrs [] = returnM (decls, bndrs)
167     slurp decls bndrs (n:ns) 
168       = importDecl bndrs n              `thenM` \ import_result ->
169         case import_result of
170           HereItIs decl new_bndrs       -- Found a declaration... rename it
171             ->  rnIfaceDecl rnTyClDecl decl     `thenM` \ new_decl ->
172                 slurp (TyClD new_decl : decls) 
173                       (bndrs `plusFV` new_bndrs)
174                       (nameSetToList (tyClDeclFVs new_decl) ++ ns)
175   
176           
177           other ->      -- No declaration... (wired in thing, or deferred, 
178                         --                    or already slurped)
179                 slurp decls (bndrs `addOneFV` n) ns
180
181 -------------------------------------------------------
182 rnIfaceDecls rn decls      = mappM (rnIfaceDecl rn) decls
183 rnIfaceDecl rn (mod, decl) = initRn (InterfaceMode mod) (rn decl)       
184 \end{code}
185
186
187 \begin{code}
188         -- Tiresomely, we must get the "main" name for the 
189         -- thing, because that's what VSlurp contains, and what
190         -- is recorded in the usage information
191 get_main_name (AClass cl)   = className cl
192 get_main_name (ADataCon dc) = tyConName (dataConTyCon dc)
193 get_main_name (ATyCon tc)
194   | Just clas <- tyConClass_maybe tc = get_main_name (AClass clas)
195   | otherwise                        = tyConName tc
196 get_main_name (AnId id)
197   = case globalIdDetails id of
198         DataConWorkId dc -> get_main_name (ATyCon (dataConTyCon dc))
199         DataConWrapId dc -> get_main_name (ATyCon (dataConTyCon dc))
200         RecordSelId lbl  -> get_main_name (ATyCon (fieldLabelTyCon lbl))
201         GenericOpId tc   -> get_main_name (ATyCon tc)
202         ClassOpId cl     -> className cl
203         other            -> idName id
204
205
206 recordUsage :: Name -> TcRn m ()
207 -- Record that the Name has been used, for 
208 -- later generation of usage info in the interface file
209 recordUsage name = updUsages (upd_usg name)
210
211 upd_usg name usages
212   | isHomeModule mod = addOneToNameSet usages name
213   | otherwise        = usages
214   where
215     mod = nameModule name
216 \end{code}
217
218
219 %*********************************************************
220 %*                                                      *
221 \subsection{Getting in a declaration}
222 %*                                                      *
223 %*********************************************************
224
225 \begin{code}
226 importDecl :: NameSet -> Name -> TcRn m ImportDeclResult
227
228 data ImportDeclResult
229   = AlreadySlurped
230   | InTypeEnv TyThing
231   | HereItIs (Module, RdrNameTyClDecl) NameSet  
232         -- The NameSet is the bunch of names bound by this decl
233
234 importDecl already_slurped name
235   =     -- STEP 0: Check if it's from this module
236         -- Doing this catches a common case quickly
237     getModule                           `thenM` \ this_mod ->
238     if nameIsLocalOrFrom this_mod name then
239         -- Variables defined on the GHCi command line (e.g. let x = 3)
240         -- are Internal names (which don't have a Module)
241         returnM AlreadySlurped
242     else
243
244         -- STEP 1: Check if we've slurped it in while compiling this module
245     if name `elemNameSet` already_slurped then  
246         returnM AlreadySlurped  
247     else
248
249         -- STEP 2: Check if it's already in the type environment
250     tcLookupGlobal_maybe name           `thenM` \ maybe_thing ->
251     case maybe_thing of {
252
253       Just ty_thing 
254         | isWiredInName name 
255         ->  -- When we find a wired-in name we must load its home
256             -- module so that we find any instance decls lurking therein
257             loadHomeInterface wi_doc name       `thenM_`
258             returnM (InTypeEnv ty_thing)
259
260         | otherwise
261         ->  -- We have slurp something that's already in the type environment, 
262             -- that was not slurped in an earlier compilation.
263             -- Must still record it in the Usages info, because that's used to
264             -- generate usage information
265
266             traceRn (text "not wired in" <+> ppr name)  `thenM_`
267             recordUsage (get_main_name ty_thing)        `thenM_`
268             returnM (InTypeEnv ty_thing) ;
269
270         Nothing -> 
271
272         -- STEP 4: OK, we have to slurp it in from an interface file
273         --         First load the interface file
274     traceRn nd_doc                      `thenM_`
275     loadHomeInterface nd_doc name       `thenM_`
276
277         -- STEP 4: Get the declaration out
278     getEps                              `thenM` \ eps ->
279     let
280         (decls_map, n_slurped) = eps_decls eps
281     in
282     case lookupNameEnv decls_map name of
283       Just (avail,_,decl) -> setEps eps'                        `thenM_` 
284                              recordUsage (availName avail)      `thenM_`
285                              returnM (HereItIs decl (mkFVs avail_names))
286         where
287            avail_names   = availNames avail
288            new_decls_map = foldl delFromNameEnv decls_map avail_names
289            eps'          = eps { eps_decls = (new_decls_map, n_slurped+1) }
290
291       Nothing -> addErr (getDeclErr name)       `thenM_` 
292                  returnM AlreadySlurped
293     }
294   where
295     wi_doc = ptext SLIT("need home module for wired in thing") <+> ppr name
296     nd_doc = ptext SLIT("need decl for") <+> ppr name
297
298 \end{code}
299
300
301 %*********************************************************
302 %*                                                       *
303 \subsection{Extracting the `gates'}
304 %*                                                       *
305 %*********************************************************
306
307 The gating story
308 ~~~~~~~~~~~~~~~~~
309 We want to avoid sucking in too many instance declarations.
310 An instance decl is only useful if the types and classes mentioned in
311 its 'head' are all available in the program being compiled.  E.g.
312
313         instance (..) => C (T1 a) (T2 b) where ...
314
315 is only useful if C, T1 and T2 are all "available".  So we keep
316 instance decls that have been parsed from .hi files, but not yet
317 slurped in, in a pool called the 'gated instance pool'.
318 Each has its set of 'gates': {C, T1, T2} in the above example.
319
320 More precisely, the gates of a module are the types and classes 
321 that are mentioned in:
322
323         a) the source code      [Note: in fact these don't seem
324                                 to be treated as gates, perhaps
325                                 because no imported instance decl
326                                 can mention them; mutter mutter
327                                 recursive modules.]
328         b) the type of an Id that's mentioned in the source code
329            [includes constructors and selectors]
330         c) the RHS of a type synonym that is a gate
331         d) the superclasses of a class that is a gate
332         e) the context of an instance decl that is slurped in
333
334 We slurp in an instance decl from the gated instance pool iff
335         
336         all its gates are either in the gates of the module,
337         or the gates of a previously-loaded module
338
339 The latter constraint is because there might have been an instance
340 decl slurped in during an earlier compilation, like this:
341
342         instance Foo a => Baz (Maybe a) where ...
343
344 In the module being compiled we might need (Baz (Maybe T)), where T is
345 defined in this module, and hence we need the instance for (Foo T).
346 So @Foo@ becomes a gate.  But there's no way to 'see' that.  More
347 generally, types might be involved as well:
348
349         instance Foo2 S a => Baz2 a where ...
350
351 Now we must treat S as a gate too, as well as Foo2.  So the solution
352 we adopt is:
353
354         we simply treat the gates of all previously-loaded 
355         modules as gates of this one
356
357 So the gates are remembered across invocations of the renamer in the
358 PersistentRenamerState.  This gloss mainly affects ghc --make and ghc
359 --interactive.
360
361 (We used to use the persistent type environment for this purpose,
362 but it has too much.  For a start, it contains all tuple types, 
363 because they are in the wired-in type env!)
364
365
366 Consructors and class operations
367 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
368 When we import a declaration like
369
370         data T = T1 Wibble | T2 Wobble
371
372 we don't want to treat @Wibble@ and @Wobble@ as gates {\em unless}
373 @T1@, @T2@ respectively are mentioned by the user program. If only
374 @T@ is mentioned we want only @T@ to be a gate; that way we don't suck
375 in useless instance decls for (say) @Eq Wibble@, when they can't
376 possibly be useful.
377
378 And that's just what (b) says: we only treat T1's type as a gate if
379 T1 is mentioned.  getGates, which deals with decls we are slurping in,
380 has to be a bit careful, because a mention of T1 will slurp in T's whole
381 declaration.
382
383 -----------------------------
384 @getGates@ takes a newly imported (and renamed) decl, and the free
385 vars of the source program, and extracts from the decl the gate names.
386
387 \begin{code}
388 getGates :: FreeVars            -- Things mentioned in the source program
389                                 -- Used for the cunning "constructors and 
390                                 -- class ops" story described 10 lines above.
391          -> RenamedTyClDecl
392          -> FreeVars
393
394 getGates source_fvs decl 
395   = get_gates (\n -> n `elemNameSet` source_fvs) decl
396
397 get_gates is_used (ForeignType {tcdName = tycon}) = unitNameSet tycon
398 get_gates is_used (IfaceSig    {tcdType = ty})    = extractHsTyNames ty
399
400 get_gates is_used (ClassDecl { tcdCtxt = ctxt, tcdName = cls, tcdTyVars = tvs, tcdSigs = sigs})
401   = (super_cls_and_sigs `addOneToNameSet` cls) `unionNameSets` 
402     implicitClassGates cls
403   where
404     super_cls_and_sigs = delListFromNameSet (foldr (plusFV . get) (extractHsCtxtTyNames ctxt) sigs)
405                                             (hsTyVarNames tvs)
406     get (ClassOpSig n _ ty _) 
407         | is_used n = extractHsTyNames ty
408         | otherwise = emptyFVs
409
410 get_gates is_used (TySynonym {tcdTyVars = tvs, tcdSynRhs = ty})
411   = delListFromNameSet (extractHsTyNames ty) (hsTyVarNames tvs)
412         -- A type synonym type constructor isn't a "gate" for instance decls
413
414 get_gates is_used (TyData {tcdCtxt = ctxt, tcdName = tycon, tcdTyVars = tvs, tcdCons = cons})
415   = delListFromNameSet (foldr (plusFV . get) (extractHsCtxtTyNames ctxt) 
416                                              (visibleDataCons cons))
417                        (hsTyVarNames tvs)
418     `addOneToNameSet` tycon
419   where
420     get (ConDecl n tvs ctxt details _)
421         | is_used n
422                 -- If the constructor is method, get fvs from all its fields
423         = delListFromNameSet (get_details details `plusFV` 
424                               extractHsCtxtTyNames ctxt)
425                              (hsTyVarNames tvs)
426     get (ConDecl n tvs ctxt (RecCon fields) _)
427                 -- Even if the constructor isn't mentioned, the fields
428                 -- might be, as selectors.  They can't mention existentially
429                 -- bound tyvars (typechecker checks for that) so no need for 
430                 -- the deleteListFromNameSet part
431         = foldr (plusFV . get_field) emptyFVs fields
432         
433     get other_con = emptyFVs
434
435     get_details (PrefixCon tys)  = plusFVs (map get_bang tys)
436     get_details (InfixCon t1 t2) = get_bang t1 `plusFV` get_bang t2
437     get_details (RecCon fields)  = plusFVs [get_bang t | (_, t) <- fields]
438
439     get_field (f,t) | is_used f = get_bang t
440                     | otherwise = emptyFVs
441
442     get_bang bty = extractHsTyNames (getBangType bty)
443
444 implicitClassGates :: Name -> FreeVars
445 implicitClassGates cls
446         -- If we load class Num, add Integer to the free gates
447         -- This takes account of the fact that Integer might be needed for
448         -- defaulting, but we don't want to load Integer (and all its baggage)
449         -- if there's no numeric stuff needed.
450         -- Similarly for class Fractional and Double
451         --
452         -- NB: adding T to the gates will force T to be loaded
453         --
454         -- NB: If we load (say) Floating, we'll end up loading Fractional too,
455         --     since Fractional is a superclass of Floating
456   | cls `hasKey` numClassKey        = unitFV integerTyConName
457   | cls `hasKey` fractionalClassKey = unitFV doubleTyConName
458   | otherwise                       = emptyFVs
459 \end{code}
460
461 @getWiredInGates@ is just like @getGates@, but it sees a previously-loaded
462 thing rather than a declaration.
463
464 \begin{code}
465 getWiredInGates :: TyThing -> FreeVars
466 -- The TyThing is one that we already have in our type environment, either
467 --      a) because the TyCon or Id is wired in, or
468 --      b) from a previous compile
469 --
470 -- Either way, we might have instance decls in the (persistent) collection
471 -- of parsed-but-not-slurped instance decls that should be slurped in.
472 -- This might be the first module that mentions both the type and the class
473 -- for that instance decl, even though both the type and the class were
474 -- mentioned in other modules, and hence are in the type environment
475
476 getWiredInGates (AClass cl)
477   = unitFV (getName cl) `plusFV` mkFVs super_classes
478   where
479     super_classes = classNamesOfTheta (classSCTheta cl)
480
481 getWiredInGates (AnId the_id) = tyClsNamesOfType (idType the_id)
482 getWiredInGates (ADataCon dc) = tyClsNamesOfType (idType (dataConWrapId dc))
483 getWiredInGates (ATyCon tc)
484   | isSynTyCon tc = tyClsNamesOfType ty
485   | otherwise     = unitFV (getName tc)
486   where
487     (_,ty)  = getSynTyConDefn tc
488
489 getInstDeclGates (InstDecl inst_ty _ _ _ _) = extractHsTyNames inst_ty
490 \end{code}
491
492 \begin{code}
493 getImportedInstDecls :: NameSet -> TcRn m ([(Module,RdrNameInstDecl)], NameSet)
494         -- Returns the gates that are new since last time
495 getImportedInstDecls gates
496   =     -- First, load any orphan-instance modules that aren't aready loaded
497         -- Orphan-instance modules are recorded in the module dependecnies
498     getImports                  `thenM` \ imports ->
499     getEps                      `thenM` \ eps ->
500     let
501         old_gates = eps_inst_gates eps
502         new_gates = gates `minusNameSet` old_gates
503         all_gates = new_gates `unionNameSets` old_gates
504         orphan_mods = imp_orphs imports
505     in
506     loadOrphanModules orphan_mods                       `thenM_` 
507
508         -- Now we're ready to grab the instance declarations
509         -- Find the un-gated ones and return them, 
510         -- removing them from the bag kept in EPS
511         -- Don't foget to get the EPS a second time... 
512         --      loadOrphanModules may have side-effected it!
513     getEps                                      `thenM` \ eps ->
514     let
515         available n        = n `elemNameSet` all_gates 
516         (decls, new_insts) = selectGated available (eps_insts eps)
517     in
518     setEps (eps { eps_insts = new_insts,
519                   eps_inst_gates = all_gates })         `thenM_`
520
521     traceRn (sep [text "getImportedInstDecls:", 
522                   nest 4 (fsep (map ppr (nameSetToList gates))),
523                   nest 4 (fsep (map ppr (nameSetToList all_gates))),
524                   nest 4 (fsep (map ppr (nameSetToList new_gates))),
525                   text "Slurped" <+> int (length decls) <+> text "instance declarations",
526                   nest 4 (vcat (map ppr_brief_inst_decl decls))])       `thenM_`
527     returnM (decls, new_gates)
528
529 ppr_brief_inst_decl (mod, InstDecl inst_ty _ _ _ _)
530   = case inst_ty of
531         HsForAllTy _ _ tau -> ppr tau
532         other              -> ppr inst_ty
533
534 getImportedRules :: NameSet     -- Slurped already
535                  -> TcRn m [(Module,RdrNameRuleDecl)]
536 getImportedRules slurped
537   | opt_IgnoreIfacePragmas = returnM []
538   | otherwise
539   = getEps              `thenM` \ eps ->
540     getInGlobalScope    `thenM` \ in_type_env ->
541     let         -- Slurp rules for anything that is slurped, 
542                 -- either now, or previously
543         available n        = n `elemNameSet` slurped || in_type_env n
544         (decls, new_rules) = selectGated available (eps_rules eps)
545     in
546     if null decls then
547         returnM []
548     else
549     setEps (eps { eps_rules = new_rules })                   `thenM_`
550     traceRn (sep [text "getImportedRules:", 
551                   text "Slurped" <+> int (length decls) <+> text "rules"])   `thenM_`
552     returnM decls
553
554 selectGated :: (Name->Bool) -> GatedDecls d
555             -> ([(Module,d)], GatedDecls d)
556 selectGated available (decl_bag, n_slurped)
557         -- Select only those decls whose gates are *all* available
558 #ifdef DEBUG
559   | opt_NoPruneDecls    -- Just to try the effect of not gating at all
560   = let
561         decls = foldrBag (\ (_,d) ds -> d:ds) [] decl_bag       -- Grab them all
562     in
563     (decls, (emptyBag, n_slurped + length decls))
564
565   | otherwise
566 #endif
567   = case foldrBag select ([], emptyBag) decl_bag of
568         (decls, new_bag) -> (decls, (new_bag, n_slurped + length decls))
569   where
570     select (gate_fn, decl) (yes, no)
571         | gate_fn available  = (decl:yes, no)
572         | otherwise          = (yes,      (gate_fn,decl) `consBag` no)
573 \end{code}
574
575
576 %********************************************************
577 %*                                                      *
578 \subsection{Checking usage information}
579 %*                                                      *
580 %********************************************************
581
582 @recompileRequired@ is called from the HscMain.   It checks whether
583 a recompilation is required.  It needs access to the persistent state,
584 finder, etc, because it may have to load lots of interface files to
585 check their versions.
586
587 \begin{code}
588 type RecompileRequired = Bool
589 upToDate  = False       -- Recompile not required
590 outOfDate = True        -- Recompile required
591
592 checkVersions :: Bool           -- True <=> source unchanged
593               -> ModIface       -- Old interface
594               -> TcRn m RecompileRequired
595 checkVersions source_unchanged iface
596   | not source_unchanged
597   = returnM outOfDate
598   | otherwise
599   = traceHiDiffs (text "Considering whether compilation is required for" <+> 
600                   ppr (mi_module iface) <> colon)       `thenM_`
601
602         -- Source code unchanged and no errors yet... carry on 
603         -- First put the dependent-module info in the envt, just temporarily,
604         -- so that when we look for interfaces we look for the right one (.hi or .hi-boot)
605         -- It's just temporary because either the usage check will succeed 
606         -- (in which case we are done with this module) or it'll fail (in which
607         -- case we'll compile the module from scratch anyhow).
608     updGblEnv (\ gbl -> gbl { tcg_imports = mod_deps }) (
609         checkList [checkModUsage u | u <- mi_usages iface]
610     )
611
612   where
613         -- This is a bit of a hack really
614     mod_deps = emptyImportAvails { imp_dep_mods = mkModDeps (dep_mods (mi_deps iface)) }
615
616 checkList :: [TcRn m RecompileRequired] -> TcRn m RecompileRequired
617 checkList []             = returnM upToDate
618 checkList (check:checks) = check        `thenM` \ recompile ->
619                            if recompile then 
620                                 returnM outOfDate
621                            else
622                                 checkList checks
623 \end{code}
624         
625 \begin{code}
626 checkModUsage :: Usage Name -> TcRn m RecompileRequired
627 -- Given the usage information extracted from the old
628 -- M.hi file for the module being compiled, figure out
629 -- whether M needs to be recompiled.
630
631 checkModUsage (Usage { usg_name = mod_name, usg_mod = old_mod_vers,
632                        usg_rules = old_rule_vers,
633                        usg_exports = maybe_old_export_vers, 
634                        usg_entities = old_decl_vers })
635   =     -- Load the imported interface is possible
636     let
637         doc_str = sep [ptext SLIT("need version info for"), ppr mod_name]
638     in
639     traceHiDiffs (text "Checking usages for module" <+> ppr mod_name) `thenM_`
640
641     tryM (loadInterface doc_str mod_name ImportBySystem)        `thenM` \ mb_iface ->
642
643     case mb_iface of {
644         Left exn ->  (out_of_date (sep [ptext SLIT("Can't find version number for module"), 
645                                        ppr mod_name]));
646                 -- Couldn't find or parse a module mentioned in the
647                 -- old interface file.  Don't complain -- it might just be that
648                 -- the current module doesn't need that import and it's been deleted
649
650         Right iface -> 
651     let
652         new_vers        = mi_version iface
653         new_mod_vers    = vers_module  new_vers
654         new_decl_vers   = vers_decls   new_vers
655         new_export_vers = vers_exports new_vers
656         new_rule_vers   = vers_rules   new_vers
657     in
658         -- CHECK MODULE
659     checkModuleVersion old_mod_vers new_mod_vers        `thenM` \ recompile ->
660     if not recompile then
661         returnM upToDate
662     else
663                                  
664         -- CHECK EXPORT LIST
665     if checkExportList maybe_old_export_vers new_export_vers then
666         out_of_date_vers (ptext SLIT("  Export list changed"))
667                          (fromJust maybe_old_export_vers) 
668                          new_export_vers
669     else
670
671         -- CHECK RULES
672     if old_rule_vers /= new_rule_vers then
673         out_of_date_vers (ptext SLIT("  Rules changed")) 
674                          old_rule_vers new_rule_vers
675     else
676
677         -- CHECK ITEMS ONE BY ONE
678     checkList [checkEntityUsage new_decl_vers u | u <- old_decl_vers]   `thenM` \ recompile ->
679     if recompile then
680         returnM outOfDate       -- This one failed, so just bail out now
681     else
682         up_to_date (ptext SLIT("  Great!  The bits I use are up to date"))
683
684     }
685
686 ------------------------
687 checkModuleVersion old_mod_vers new_mod_vers
688   | new_mod_vers == old_mod_vers
689   = up_to_date (ptext SLIT("Module version unchanged"))
690
691   | otherwise
692   = out_of_date_vers (ptext SLIT("  Module version has changed"))
693                      old_mod_vers new_mod_vers
694
695 ------------------------
696 checkExportList Nothing  new_vers = upToDate
697 checkExportList (Just v) new_vers = v /= new_vers
698
699 ------------------------
700 checkEntityUsage new_vers (name,old_vers)
701   = case lookupNameEnv new_vers name of
702
703         Nothing       ->        -- We used it before, but it ain't there now
704                           out_of_date (sep [ptext SLIT("No longer exported:"), ppr name])
705
706         Just new_vers   -- It's there, but is it up to date?
707           | new_vers == old_vers -> traceHiDiffs (text "  Up to date" <+> ppr name <+> parens (ppr new_vers)) `thenM_`
708                                     returnM upToDate
709           | otherwise            -> out_of_date_vers (ptext SLIT("  Out of date:") <+> ppr name)
710                                                      old_vers new_vers
711
712 up_to_date  msg = traceHiDiffs msg `thenM_` returnM upToDate
713 out_of_date msg = traceHiDiffs msg `thenM_` returnM outOfDate
714 out_of_date_vers msg old_vers new_vers 
715   = out_of_date (hsep [msg, ppr old_vers, ptext SLIT("->"), ppr new_vers])
716 \end{code}
717
718
719 %*********************************************************
720 %*                                                       *
721 \subsection{Errors}
722 %*                                                       *
723 %*********************************************************
724
725 \begin{code}
726 getDeclErr name
727   = vcat [ptext SLIT("Failed to find interface decl for") <+> quotes (ppr name),
728           ptext SLIT("from module") <+> quotes (ppr (nameModule name))
729          ]
730 \end{code}