d1e4174635b5dbcb503d7b7a34588f83695cb286
[ghc-hetmet.git] / ghc / compiler / rename / RnIfaces.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[RnIfaces]{Cacheing and Renaming of Interfaces}
5
6 \begin{code}
7 module RnIfaces
8      (
9         getInterfaceExports,
10         recordLocalSlurps, 
11         mkImportInfo, 
12
13         slurpImpDecls, closeDecls,
14
15         RecompileRequired, outOfDate, upToDate, recompileRequired
16        )
17 where
18
19 #include "HsVersions.h"
20
21 import CmdLineOpts      ( opt_IgnoreIfacePragmas, opt_NoPruneDecls )
22 import HscTypes
23 import HsSyn            ( HsDecl(..), Sig(..), TyClDecl(..), ConDecl(..), ConDetails(..),
24                           InstDecl(..), HsType(..), hsTyVarNames, getBangType
25                         )
26 import HsImpExp         ( ImportDecl(..) )
27 import RdrHsSyn         ( RdrNameTyClDecl, RdrNameInstDecl, RdrNameRuleDecl )
28 import RnHsSyn          ( RenamedHsDecl, RenamedTyClDecl,
29                           extractHsTyNames, extractHsCtxtTyNames, 
30                           tyClDeclFVs, ruleDeclFVs, instDeclFVs
31                         )
32 import RnHiFiles        ( tryLoadInterface, loadHomeInterface, loadInterface, 
33                           loadOrphanModules
34                         )
35 import RnSource         ( rnTyClDecl, rnInstDecl, rnIfaceRuleDecl )
36 import RnEnv
37 import RnMonad
38 import Id               ( idType )
39 import Type             ( namesOfType )
40 import TyCon            ( isSynTyCon, getSynTyConDefn )
41 import Name             ( Name {-instance NamedThing-}, nameOccName,
42                           nameModule, isLocalName, nameUnique,
43                           NamedThing(..)
44                          )
45 import Name             ( elemNameEnv, delFromNameEnv )
46 import Module           ( Module, ModuleEnv, 
47                           moduleName, isHomeModule,
48                           ModuleName, WhereFrom(..),
49                           emptyModuleEnv, 
50                           extendModuleEnv_C, foldModuleEnv, lookupModuleEnv,
51                           elemModuleSet, extendModuleSet
52                         )
53 import NameSet
54 import PrelInfo         ( wiredInThingEnv, fractionalClassKeys )
55 import TysWiredIn       ( doubleTyCon )
56 import Maybes           ( orElse )
57 import FiniteMap
58 import Outputable
59 import Bag
60 import Util             ( sortLt )
61 \end{code}
62
63
64 %*********************************************************
65 %*                                                      *
66 \subsection{Getting what a module exports}
67 %*                                                      *
68 %*********************************************************
69
70 @getInterfaceExports@ is called only for directly-imported modules.
71
72 \begin{code}
73 getInterfaceExports :: ModuleName -> WhereFrom -> RnMG (Module, [(ModuleName,Avails)])
74 getInterfaceExports mod_name from
75   = loadInterface doc_str mod_name from `thenRn` \ iface ->
76     returnRn (mi_module iface, mi_exports iface)
77   where
78       doc_str = sep [ppr mod_name, ptext SLIT("is directly imported")]
79 \end{code}
80
81
82 %*********************************************************
83 %*                                                      *
84 \subsection{Keeping track of what we've slurped, and version numbers}
85 %*                                                      *
86 %*********************************************************
87
88 mkImportInof figures out what the ``usage information'' for this
89 moudule is; that is, what it must record in its interface file as the
90 things it uses.  
91
92 We produce a line for every module B below the module, A, currently being
93 compiled:
94         import B <n> ;
95 to record the fact that A does import B indireclty.  This is used to decide
96 to look to look for B.hi rather than B.hi-boot when compiling a module that
97 imports A.  This line says that A imports B, but uses nothing in it.
98 So we'll get an early bale-out when compiling A if B's version changes.
99
100 \begin{code}
101 mkImportInfo :: ModuleName                      -- Name of this module
102              -> [ImportDecl n]                  -- The import decls
103              -> RnMG [ImportVersion Name]
104
105 mkImportInfo this_mod imports
106   = getIfacesRn                                 `thenRn` \ ifaces ->
107     getHomeIfaceTableRn                         `thenRn` \ hit -> 
108     let
109         (imp_pkg_mods, imp_home_names) = iVSlurp ifaces
110         pit                            = iPIT    ifaces
111
112         import_all_mods :: [ModuleName]
113                 -- Modules where we imported all the names
114                 -- (apart from hiding some, perhaps)
115         import_all_mods = [ m | ImportDecl m _ _ _ imp_list _ <- imports,
116                                 import_all imp_list ]
117                         where
118                           import_all (Just (False, _)) = False  -- Imports are specified explicitly
119                           import_all other             = True   -- Everything is imported
120
121         -- mv_map groups together all the things imported and used
122         -- from a particular module in this package
123         -- We use a finite map because we want the domain
124         mv_map :: ModuleEnv [Name]
125         mv_map  = foldNameSet add_mv emptyModuleEnv imp_home_names
126         add_mv name mv_map = extendModuleEnv_C add_item mv_map mod [name]
127                            where
128                              mod = nameModule name
129                              add_item names _ = name:names
130
131         -- In our usage list we record
132         --      a) Specifically: Detailed version info for imports from modules in this package
133         --                       Gotten from iVSlurp plus import_all_mods
134         --
135         --      b) Everything:   Just the module version for imports from modules in other packages
136         --                       Gotten from iVSlurp plus import_all_mods
137         --
138         --      c) NothingAtAll: The name only of modules, Baz, in this package that are 'below' us, 
139         --                       but which we didn't need at all (this is needed only to decide whether
140         --                       to open Baz.hi or Baz.hi-boot higher up the tree).
141         --                       This happens when a module, Foo, that we explicitly imported has 
142         --                       'import Baz' in its interface file, recording that Baz is below
143         --                       Foo in the module dependency hierarchy.  We want to propagate this info.
144         --                       These modules are in a combination of HIT/PIT and iImpModInfo
145         --
146         --      d) NothingAtAll: The name only of all orphan modules we know of (this is needed
147         --                       so that anyone who imports us can find the orphan modules)
148         --                       These modules are in a combination of HIT/PIT and iImpModInfo
149
150         import_info0 = foldModuleEnv mk_imp_info  []           pit
151         import_info1 = foldModuleEnv mk_imp_info  import_info0 hit
152         import_info  = [ (mod_name, orphans, is_boot, NothingAtAll) 
153                        | (mod_name, (orphans, is_boot)) <- fmToList (iImpModInfo ifaces) ] ++ 
154                        import_info1
155         
156         mk_imp_info :: ModIface -> [ImportVersion Name] -> [ImportVersion Name]
157         mk_imp_info iface so_far
158
159           | Just ns <- lookupModuleEnv mv_map mod       -- Case (a)
160           = go_for_it (Specifically mod_vers maybe_export_vers 
161                                     (mk_import_items ns) rules_vers)
162
163           | mod `elemModuleSet` imp_pkg_mods            -- Case (b)
164           = go_for_it (Everything mod_vers)
165
166           | import_all_mod                              -- Case (a) and (b); the import-all part
167           = if is_home_pkg_mod then
168                 go_for_it (Specifically mod_vers (Just export_vers) [] rules_vers)
169             else
170                 go_for_it (Everything mod_vers)
171                 
172           | is_home_pkg_mod || has_orphans              -- Case (c) or (d)
173           = go_for_it NothingAtAll
174
175           | otherwise = so_far
176           where
177             go_for_it exports = (mod_name, has_orphans, mi_boot iface, exports) : so_far
178
179             mod             = mi_module iface
180             mod_name        = moduleName mod
181             is_home_pkg_mod = isHomeModule mod
182             version_info    = mi_version iface
183             version_env     = vers_decls   version_info
184             mod_vers        = vers_module  version_info
185             rules_vers      = vers_rules   version_info
186             export_vers     = vers_exports version_info
187             import_all_mod  = mod_name `elem` import_all_mods
188             has_orphans     = mi_orphan iface
189             
190                 -- The sort is to put them into canonical order
191             mk_import_items ns = [(n,v) | n <- sortLt lt_occ ns, 
192                                           let v = lookupNameEnv version_env n `orElse` 
193                                                   pprPanic "mk_whats_imported" (ppr n)
194                                  ]
195                          where
196                            lt_occ n1 n2 = nameOccName n1 < nameOccName n2
197
198             maybe_export_vers | import_all_mod = Just (vers_exports version_info)
199                               | otherwise      = Nothing
200     in
201     returnRn import_info
202 \end{code}
203
204 %*********************************************************
205 %*                                                       *
206 \subsection{Slurping declarations}
207 %*                                                       *
208 %*********************************************************
209
210 \begin{code}
211 -------------------------------------------------------
212 slurpImpDecls source_fvs
213   = traceRn (text "slurpImp" <+> fsep (map ppr (nameSetToList source_fvs))) `thenRn_`
214
215         -- The current slurped-set records all local things
216     getSlurped                                  `thenRn` \ source_binders ->
217     slurpSourceRefs source_binders source_fvs   `thenRn` \ (decls, needed) ->
218
219         -- Then get everything else
220     closeDecls decls needed
221
222
223 -------------------------------------------------------
224 slurpSourceRefs :: NameSet                      -- Variables defined in source
225                 -> FreeVars                     -- Variables referenced in source
226                 -> RnMG ([RenamedHsDecl],
227                          FreeVars)              -- Un-satisfied needs
228 -- The declaration (and hence home module) of each gate has
229 -- already been loaded
230
231 slurpSourceRefs source_binders source_fvs
232   = go_outer []                         -- Accumulating decls
233              emptyFVs                   -- Unsatisfied needs
234              emptyFVs                   -- Accumulating gates
235              (nameSetToList source_fvs) -- Things whose defn hasn't been loaded yet
236   where
237         -- The outer loop repeatedly slurps the decls for the current gates
238         -- and the instance decls 
239
240         -- The outer loop is needed because consider
241
242     go_outer decls fvs all_gates []     
243         = returnRn (decls, fvs)
244
245     go_outer decls fvs all_gates refs   -- refs are not necessarily slurped yet
246         = traceRn (text "go_outer" <+> ppr refs)                `thenRn_`
247           foldlRn go_inner (decls, fvs, emptyFVs) refs          `thenRn` \ (decls1, fvs1, gates1) ->
248           getImportedInstDecls (all_gates `plusFV` gates1)      `thenRn` \ inst_decls ->
249           rnIfaceInstDecls decls1 fvs1 gates1 inst_decls        `thenRn` \ (decls2, fvs2, gates2) ->
250           go_outer decls2 fvs2 (all_gates `plusFV` gates2)
251                                (nameSetToList (gates2 `minusNameSet` all_gates))
252                 -- Knock out the all_gates because even if we don't slurp any new
253                 -- decls we can get some apparently-new gates from wired-in names
254
255     go_inner (decls, fvs, gates) wanted_name
256         = importDecl wanted_name                `thenRn` \ import_result ->
257           case import_result of
258             AlreadySlurped     -> returnRn (decls, fvs, gates)
259             InTypeEnv ty_thing -> returnRn (decls, fvs, gates `plusFV` getWiredInGates ty_thing)
260                         
261             HereItIs decl -> rnIfaceTyClDecl decl               `thenRn` \ (new_decl, fvs1) ->
262                              returnRn (TyClD new_decl : decls, 
263                                        fvs1 `plusFV` fvs,
264                                        gates `plusFV` getGates source_fvs new_decl)
265 \end{code}
266
267
268 \begin{code}
269 -------------------------------------------------------
270 -- closeDecls keeps going until the free-var set is empty
271 closeDecls decls needed
272   | not (isEmptyFVs needed)
273   = slurpDecls decls needed     `thenRn` \ (decls1, needed1) ->
274     closeDecls decls1 needed1
275
276   | otherwise
277   = getImportedRules                    `thenRn` \ rule_decls ->
278     case rule_decls of
279         []    -> returnRn decls -- No new rules, so we are done
280         other -> rnIfaceDecls rnIfaceRuleDecl rule_decls        `thenRn` \ rule_decls' ->
281                  let
282                         rule_fvs = plusFVs (map ruleDeclFVs rule_decls')
283                  in
284                  traceRn (text "closeRules" <+> ppr rule_decls' $$ fsep (map ppr (nameSetToList rule_fvs)))     `thenRn_`
285                  closeDecls (map RuleD rule_decls' ++ decls) rule_fvs
286
287                  
288
289 -------------------------------------------------------
290 -- Augment decls with any decls needed by needed.
291 -- Return also free vars of the new decls (only)
292 slurpDecls decls needed
293   = go decls emptyFVs (nameSetToList needed) 
294   where
295     go decls fvs []         = returnRn (decls, fvs)
296     go decls fvs (ref:refs) = slurpDecl decls fvs ref   `thenRn` \ (decls1, fvs1) ->
297                               go decls1 fvs1 refs
298
299 -------------------------------------------------------
300 slurpDecl decls fvs wanted_name
301   = importDecl wanted_name              `thenRn` \ import_result ->
302     case import_result of
303         -- Found a declaration... rename it
304         HereItIs decl -> rnIfaceTyClDecl decl           `thenRn` \ (new_decl, fvs1) ->
305                          returnRn (TyClD new_decl:decls, fvs1 `plusFV` fvs)
306
307         -- No declaration... (wired in thing, or deferred, or already slurped)
308         other -> returnRn (decls, fvs)
309
310
311 -------------------------------------------------------
312 rnIfaceDecls rn decls      = mapRn (rnIfaceDecl rn) decls
313 rnIfaceDecl rn (mod, decl) = initIfaceRnMS mod (rn decl)        
314
315 rnIfaceInstDecls decls fvs gates inst_decls
316   = rnIfaceDecls rnInstDecl inst_decls  `thenRn` \ inst_decls' ->
317     returnRn (map InstD inst_decls' ++ decls,
318               fvs `plusFV` plusFVs (map instDeclFVs inst_decls'),
319               gates `plusFV` plusFVs (map getInstDeclGates inst_decls'))
320
321 rnIfaceTyClDecl (mod, decl) = initIfaceRnMS mod (rnTyClDecl decl)       `thenRn` \ decl' ->
322                               returnRn (decl', tyClDeclFVs decl')
323 \end{code}
324
325
326 \begin{code}
327 getSlurped
328   = getIfacesRn         `thenRn` \ ifaces ->
329     returnRn (iSlurp ifaces)
330
331 recordSlurp ifaces@(Ifaces { iDecls = (decls_map, n_slurped),
332                              iSlurp = slurped_names, 
333                              iVSlurp = (imp_mods, imp_names) })
334             avail
335   = ASSERT2( not (isLocalName (availName avail)), ppr avail )
336     ifaces { iDecls = (decls_map', n_slurped+1),
337              iSlurp  = new_slurped_names, 
338              iVSlurp = new_vslurp }
339   where
340     decls_map' = foldl delFromNameEnv decls_map (availNames avail)
341     main_name  = availName avail
342     mod        = nameModule main_name
343     new_slurped_names = addAvailToNameSet slurped_names avail
344     new_vslurp | isHomeModule mod = (imp_mods, addOneToNameSet imp_names main_name)
345                | otherwise        = (extendModuleSet imp_mods mod, imp_names)
346
347 recordLocalSlurps new_names
348   = getIfacesRn         `thenRn` \ ifaces ->
349     setIfacesRn (ifaces { iSlurp  = iSlurp ifaces `unionNameSets` new_names })
350 \end{code}
351
352
353
354 %*********************************************************
355 %*                                                       *
356 \subsection{Extracting the `gates'}
357 %*                                                       *
358 %*********************************************************
359
360 The gating story
361 ~~~~~~~~~~~~~~~~~
362 We want to avoid sucking in too many instance declarations.
363 An instance decl is only useful if the types and classes mentioned in
364 its 'head' are all available in the program being compiled.  E.g.
365
366         instance (..) => C (T1 a) (T2 b) where ...
367
368 is only useful if C, T1 and T2 are all "available".  So we keep
369 instance decls that have been parsed from .hi files, but not yet
370 slurped in, in a pool called the 'gated instance pool'.
371 Each has its set of 'gates': {C, T1, T2} in the above example.
372
373 More precisely, the gates of a module are the types and classes 
374 that are mentioned in:
375
376         a) the source code
377         b) the type of an Id that's mentioned in the source code
378            [includes constructors and selectors]
379         c) the RHS of a type synonym that is a gate
380         d) the superclasses of a class that is a gate
381         e) the context of an instance decl that is slurped in
382
383 We slurp in an instance decl from the gated instance pool iff
384         
385         all its gates are either in the gates of the module, 
386         or are a previously-loaded class.  
387
388 The latter constraint is because there might have been an instance
389 decl slurped in during an earlier compilation, like this:
390
391         instance Foo a => Baz (Maybe a) where ...
392
393 In the module being compiled we might need (Baz (Maybe T)), where T
394 is defined in this module, and hence we need (Foo T).  So @Foo@ becomes
395 a gate.  But there's no way to 'see' that, so we simply treat all 
396 previously-loaded classes as gates.
397
398 Consructors and class operations
399 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
400 When we import a declaration like
401
402         data T = T1 Wibble | T2 Wobble
403
404 we don't want to treat @Wibble@ and @Wobble@ as gates {\em unless}
405 @T1@, @T2@ respectively are mentioned by the user program. If only
406 @T@ is mentioned we want only @T@ to be a gate; that way we don't suck
407 in useless instance decls for (say) @Eq Wibble@, when they can't
408 possibly be useful.
409
410 And that's just what (b) says: we only treat T1's type as a gate if
411 T1 is mentioned.  getGates, which deals with decls we are slurping in,
412 has to be a bit careful, because a mention of T1 will slurp in T's whole
413 declaration.
414
415 -----------------------------
416 @getGates@ takes a newly imported (and renamed) decl, and the free
417 vars of the source program, and extracts from the decl the gate names.
418
419 \begin{code}
420 getGates :: FreeVars            -- Things mentioned in the source program
421          -> RenamedTyClDecl
422          -> FreeVars
423
424 getGates source_fvs decl 
425   = get_gates (\n -> n `elemNameSet` source_fvs) decl
426
427 get_gates is_used (IfaceSig _ ty _ _)
428   = extractHsTyNames ty
429
430 get_gates is_used (ClassDecl ctxt cls tvs _ sigs _ _ _ )
431   = (delListFromNameSet (foldr (plusFV . get) (extractHsCtxtTyNames ctxt) sigs)
432                         (hsTyVarNames tvs)
433      `addOneToNameSet` cls)
434     `plusFV` maybe_double
435   where
436     get (ClassOpSig n _ ty _) 
437         | is_used n = extractHsTyNames ty
438         | otherwise = emptyFVs
439
440         -- If we load any numeric class that doesn't have
441         -- Int as an instance, add Double to the gates. 
442         -- This takes account of the fact that Double might be needed for
443         -- defaulting, but we don't want to load Double (and all its baggage)
444         -- if the more exotic classes aren't used at all.
445     maybe_double | nameUnique cls `elem` fractionalClassKeys 
446                  = unitFV (getName doubleTyCon)
447                  | otherwise
448                  = emptyFVs
449
450 get_gates is_used (TySynonym tycon tvs ty _)
451   = delListFromNameSet (extractHsTyNames ty) (hsTyVarNames tvs)
452         -- A type synonym type constructor isn't a "gate" for instance decls
453
454 get_gates is_used (TyData _ ctxt tycon tvs cons _ _ _ _ _)
455   = delListFromNameSet (foldr (plusFV . get) (extractHsCtxtTyNames ctxt) cons)
456                        (hsTyVarNames tvs)
457     `addOneToNameSet` tycon
458   where
459     get (ConDecl n _ tvs ctxt details _)
460         | is_used n
461                 -- If the constructor is method, get fvs from all its fields
462         = delListFromNameSet (get_details details `plusFV` 
463                               extractHsCtxtTyNames ctxt)
464                              (hsTyVarNames tvs)
465     get (ConDecl n _ tvs ctxt (RecCon fields) _)
466                 -- Even if the constructor isn't mentioned, the fields
467                 -- might be, as selectors.  They can't mention existentially
468                 -- bound tyvars (typechecker checks for that) so no need for 
469                 -- the deleteListFromNameSet part
470         = foldr (plusFV . get_field) emptyFVs fields
471         
472     get other_con = emptyFVs
473
474     get_details (VanillaCon tys) = plusFVs (map get_bang tys)
475     get_details (InfixCon t1 t2) = get_bang t1 `plusFV` get_bang t2
476     get_details (RecCon fields)  = plusFVs [get_bang t | (_, t) <- fields]
477
478     get_field (fs,t) | any is_used fs = get_bang t
479                      | otherwise      = emptyFVs
480
481     get_bang bty = extractHsTyNames (getBangType bty)
482 \end{code}
483
484 @getWiredInGates@ is just like @getGates@, but it sees a previously-loaded
485 thing rather than a declaration.
486
487 \begin{code}
488 getWiredInGates :: TyThing -> FreeVars
489 -- The TyThing is one that we already have in our type environment, either
490 --      a) because the TyCon or Id is wired in, or
491 --      b) from a previous compile
492 -- Either way, we might have instance decls in the (persistent) collection
493 -- of parsed-but-not-slurped instance decls that should be slurped in.
494 -- This might be the first module that mentions both the type and the class
495 -- for that instance decl, even though both the type and the class were
496 -- mentioned in other modules, and hence are in the type environment
497
498 getWiredInGates (AnId the_id) = namesOfType (idType the_id)
499 getWiredInGates (AClass cl)   = emptyFVs        -- The superclasses must also be previously
500                                                 -- loaded, and hence are automatically gates
501 getWiredInGates (ATyCon tc)
502   | isSynTyCon tc = delListFromNameSet (namesOfType ty) (map getName tyvars)
503   | otherwise     = unitFV (getName tc)
504   where
505     (tyvars,ty)  = getSynTyConDefn tc
506
507 getInstDeclGates (InstDecl inst_ty _ _ _ _) = extractHsTyNames inst_ty
508 \end{code}
509
510 \begin{code}
511 getImportedInstDecls :: NameSet -> RnMG [(Module,RdrNameInstDecl)]
512 getImportedInstDecls gates
513   =     -- First, load any orphan-instance modules that aren't aready loaded
514         -- Orphan-instance modules are recorded in the module dependecnies
515     getIfacesRn                                         `thenRn` \ ifaces ->
516     let
517         orphan_mods =
518           [mod | (mod, (True, _)) <- fmToList (iImpModInfo ifaces)]
519     in
520     loadOrphanModules orphan_mods                       `thenRn_` 
521
522         -- Now we're ready to grab the instance declarations
523         -- Find the un-gated ones and return them, 
524         -- removing them from the bag kept in Ifaces
525     getIfacesRn                                         `thenRn` \ ifaces ->
526     getTypeEnvRn                                        `thenRn` \ lookup ->
527     let
528         (decls, new_insts) = selectGated gates lookup (iInsts ifaces)
529     in
530     setIfacesRn (ifaces { iInsts = new_insts })         `thenRn_`
531
532     traceRn (sep [text "getImportedInstDecls:", 
533                   nest 4 (fsep (map ppr gate_list)),
534                   text "Slurped" <+> int (length decls) <+> text "instance declarations",
535                   nest 4 (vcat (map ppr_brief_inst_decl decls))])       `thenRn_`
536     returnRn decls
537   where
538     gate_list      = nameSetToList gates
539
540 ppr_brief_inst_decl (mod, InstDecl inst_ty _ _ _ _)
541   = case inst_ty of
542         HsForAllTy _ _ tau -> ppr tau
543         other              -> ppr inst_ty
544
545 getImportedRules :: RnMG [(Module,RdrNameRuleDecl)]
546 getImportedRules 
547   | opt_IgnoreIfacePragmas = returnRn []
548   | otherwise
549   = getIfacesRn         `thenRn` \ ifaces ->
550     getTypeEnvRn        `thenRn` \ lookup ->
551     let
552         gates              = iSlurp ifaces      -- Anything at all that's been slurped
553         rules              = iRules ifaces
554         (decls, new_rules) = selectGated gates lookup rules
555     in
556     if null decls then
557         returnRn []
558     else
559     setIfacesRn (ifaces { iRules = new_rules })              `thenRn_`
560     traceRn (sep [text "getImportedRules:", 
561                   text "Slurped" <+> int (length decls) <+> text "rules"])   `thenRn_`
562     returnRn decls
563
564 selectGated gates lookup (decl_bag, n_slurped)
565         -- Select only those decls whose gates are *all* in 'gates'
566         -- or are a class in 'lookup'
567 #ifdef DEBUG
568   | opt_NoPruneDecls    -- Just to try the effect of not gating at all
569   = let
570         decls = foldrBag (\ (_,d) ds -> d:ds) [] decl_bag       -- Grab them all
571     in
572     (decls, (emptyBag, n_slurped + length decls))
573
574   | otherwise
575 #endif
576   = case foldrBag select ([], emptyBag) decl_bag of
577         (decls, new_bag) -> (decls, (new_bag, n_slurped + length decls))
578   where
579     available n = n `elemNameSet` gates 
580                 || case lookup n of { Just (AClass c) -> True; other -> False }
581
582     select (reqd, decl) (yes, no)
583         | all available reqd = (decl:yes, no)
584         | otherwise          = (yes,      (reqd,decl) `consBag` no)
585 \end{code}
586
587
588 %*********************************************************
589 %*                                                      *
590 \subsection{Getting in a declaration}
591 %*                                                      *
592 %*********************************************************
593
594 \begin{code}
595 importDecl :: Name -> RnMG ImportDeclResult
596
597 data ImportDeclResult
598   = AlreadySlurped
599   | InTypeEnv TyThing
600   | HereItIs (Module, RdrNameTyClDecl)
601
602 importDecl name
603   =     -- STEP 1: Check if we've slurped it in while compiling this module
604     getIfacesRn                         `thenRn` \ ifaces ->
605     if name `elemNameSet` iSlurp ifaces then    
606         returnRn AlreadySlurped 
607     else
608
609         -- STEP 2: Check if it's already in the type environment
610     getTypeEnvRn                        `thenRn` \ lookup ->
611     case lookup name of {
612         Just ty_thing | name `elemNameEnv` wiredInThingEnv
613                       ->        -- When we find a wired-in name we must load its home
614                                 -- module so that we find any instance decls lurking therein
615                          loadHomeInterface wi_doc name  `thenRn_`
616                          returnRn (InTypeEnv ty_thing)
617
618                       | otherwise
619                       -> returnRn (InTypeEnv ty_thing) ;
620
621         Nothing -> 
622
623         -- STEP 3: OK, we have to slurp it in from an interface file
624         --         First load the interface file
625     traceRn nd_doc                      `thenRn_`
626     loadHomeInterface nd_doc name       `thenRn_`
627     getIfacesRn                         `thenRn` \ ifaces ->
628
629         -- STEP 4: Get the declaration out
630     let
631         (decls_map, _) = iDecls ifaces
632     in
633     case lookupNameEnv decls_map name of
634       Just (avail,_,decl)
635         -> setIfacesRn (recordSlurp ifaces avail)       `thenRn_`
636            returnRn (HereItIs decl)
637
638       Nothing 
639         -> addErrRn (getDeclErr name)   `thenRn_` 
640            returnRn AlreadySlurped
641     }
642   where
643     wi_doc = ptext SLIT("need home module for wired in thing") <+> ppr name
644     nd_doc = ptext SLIT("need decl for") <+> ppr name
645
646 \end{code}
647
648
649 %********************************************************
650 %*                                                      *
651 \subsection{Checking usage information}
652 %*                                                      *
653 %********************************************************
654
655 @recompileRequired@ is called from the HscMain.   It checks whether
656 a recompilation is required.  It needs access to the persistent state,
657 finder, etc, because it may have to load lots of interface files to
658 check their versions.
659
660 \begin{code}
661 type RecompileRequired = Bool
662 upToDate  = False       -- Recompile not required
663 outOfDate = True        -- Recompile required
664
665 recompileRequired :: FilePath           -- Only needed for debug msgs
666                   -> Bool               -- Source unchanged
667                   -> ModIface           -- Old interface
668                   -> RnMG RecompileRequired
669 recompileRequired iface_path source_unchanged iface
670   = traceHiDiffsRn (text "Considering whether compilation is required for" <+> text iface_path <> colon)        `thenRn_`
671
672         -- CHECK WHETHER THE SOURCE HAS CHANGED
673     if not source_unchanged then
674         traceHiDiffsRn (nest 4 (text "Source file changed or recompilation check turned off"))  `thenRn_` 
675         returnRn outOfDate
676     else
677
678         -- Source code unchanged and no errors yet... carry on 
679     checkList [checkModUsage u | u <- mi_usages iface]
680
681 checkList :: [RnMG RecompileRequired] -> RnMG RecompileRequired
682 checkList []             = returnRn upToDate
683 checkList (check:checks) = check        `thenRn` \ recompile ->
684                            if recompile then 
685                                 returnRn outOfDate
686                            else
687                                 checkList checks
688 \end{code}
689         
690 \begin{code}
691 checkModUsage :: ImportVersion Name -> RnMG RecompileRequired
692 -- Given the usage information extracted from the old
693 -- M.hi file for the module being compiled, figure out
694 -- whether M needs to be recompiled.
695
696 checkModUsage (mod_name, _, _, NothingAtAll)
697         -- If CurrentModule.hi contains 
698         --      import Foo :: ;
699         -- then that simply records that Foo lies below CurrentModule in the
700         -- hierarchy, but CurrentModule doesn't depend in any way on Foo.
701         -- In this case we don't even want to open Foo's interface.
702   = up_to_date (ptext SLIT("Nothing used from:") <+> ppr mod_name)
703
704 checkModUsage (mod_name, _, is_boot, whats_imported)
705   =     -- Load the imported interface is possible
706         -- We use tryLoadInterface, because failure is not an error
707         -- (might just be that the old .hi file for this module is out of date)
708         -- We use ImportByUser/ImportByUserSource as the 'from' flag, 
709         --      a) because we need to know whether to load the .hi-boot file
710         --      b) because loadInterface things matters are amiss if we 
711         --         ImportBySystem an interface it knows nothing about
712     let
713         doc_str = sep [ptext SLIT("need version info for"), ppr mod_name]
714         from    | is_boot   = ImportByUserSource
715                 | otherwise = ImportByUser
716     in
717     tryLoadInterface doc_str mod_name from      `thenRn` \ (iface, maybe_err) ->
718
719     case maybe_err of {
720         Just err -> out_of_date (sep [ptext SLIT("Can't find version number for module"), 
721                                       ppr mod_name]) ;
722                 -- Couldn't find or parse a module mentioned in the
723                 -- old interface file.  Don't complain -- it might just be that
724                 -- the current module doesn't need that import and it's been deleted
725
726         Nothing -> 
727     let
728         new_vers      = mi_version iface
729         new_decl_vers = vers_decls new_vers
730     in
731     case whats_imported of {    -- NothingAtAll dealt with earlier
732
733       Everything old_mod_vers -> checkModuleVersion old_mod_vers new_vers       `thenRn` \ recompile ->
734                                  if recompile then
735                                         out_of_date (ptext SLIT("...and I needed the whole module"))
736                                  else
737                                         returnRn upToDate ;
738
739       Specifically old_mod_vers maybe_old_export_vers old_decl_vers old_rule_vers ->
740
741         -- CHECK MODULE
742     checkModuleVersion old_mod_vers new_vers    `thenRn` \ recompile ->
743     if not recompile then
744         returnRn upToDate
745     else
746                                  
747         -- CHECK EXPORT LIST
748     if checkExportList maybe_old_export_vers new_vers then
749         out_of_date (ptext SLIT("Export list changed"))
750     else
751
752         -- CHECK RULES
753     if old_rule_vers /= vers_rules new_vers then
754         out_of_date (ptext SLIT("Rules changed"))
755     else
756
757         -- CHECK ITEMS ONE BY ONE
758     checkList [checkEntityUsage new_decl_vers u | u <- old_decl_vers]   `thenRn` \ recompile ->
759     if recompile then
760         returnRn outOfDate      -- This one failed, so just bail out now
761     else
762         up_to_date (ptext SLIT("...but the bits I use haven't."))
763
764     }}
765
766 ------------------------
767 checkModuleVersion old_mod_vers new_vers
768   | vers_module new_vers == old_mod_vers
769   = up_to_date (ptext SLIT("Module version unchanged"))
770
771   | otherwise
772   = out_of_date (ptext SLIT("Module version has changed"))
773
774 ------------------------
775 checkExportList Nothing  new_vers = upToDate
776 checkExportList (Just v) new_vers = v /= vers_exports new_vers
777
778 ------------------------
779 checkEntityUsage new_vers (name,old_vers)
780   = case lookupNameEnv new_vers name of
781
782         Nothing       ->        -- We used it before, but it ain't there now
783                           out_of_date (sep [ptext SLIT("No longer exported:"), ppr name])
784
785         Just new_vers   -- It's there, but is it up to date?
786           | new_vers == old_vers -> returnRn upToDate
787           | otherwise            -> out_of_date (sep [ptext SLIT("Out of date:"), ppr name])
788
789 up_to_date  msg = traceHiDiffsRn msg `thenRn_` returnRn upToDate
790 out_of_date msg = traceHiDiffsRn msg `thenRn_` returnRn outOfDate
791 \end{code}
792
793
794 %*********************************************************
795 %*                                                       *
796 \subsection{Errors}
797 %*                                                       *
798 %*********************************************************
799
800 \begin{code}
801 getDeclErr name
802   = vcat [ptext SLIT("Failed to find interface decl for") <+> quotes (ppr name),
803           ptext SLIT("from module") <+> quotes (ppr (nameModule name))
804          ]
805 \end{code}