5b3c299cc1a74084f9a32b481236a9c9b4f5099c
[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         getInterfaceExports,
9         getImportedInstDecls,
10         getSpecialInstModules, getDeferredDataDecls,
11         importDecl, recordSlurp,
12         getImportVersions, getSlurpedNames, getRnStats, getImportedFixities,
13
14         checkUpToDate,
15
16         getDeclBinders,
17         mkSearchPath
18     ) where
19
20 #include "HsVersions.h"
21
22 import CmdLineOpts      ( opt_PruneTyDecls,  opt_PruneInstDecls, 
23                           opt_D_show_rn_imports, opt_IgnoreIfacePragmas
24                         )
25 import HsSyn            ( HsDecl(..), TyClDecl(..), InstDecl(..), IfaceSig(..), 
26                           HsType(..), ConDecl(..), IE(..), ConDetails(..), Sig(..),
27                           FixitySig(..),
28                           hsDeclName, countTyClDecls, isDataDecl, nonFixitySigs
29                         )
30 import BasicTypes       ( Version, NewOrData(..) )
31 import RdrHsSyn         ( RdrNameHsDecl, RdrNameInstDecl, RdrNameTyClDecl,
32                         )
33 import RnEnv            ( newImportedGlobalName, newImportedGlobalFromRdrName, 
34                           addImplicitOccsRn, pprAvail,
35                           availName, availNames, addAvailToNameSet
36                         )
37 import RnSource         ( rnHsSigType )
38 import RnMonad
39 import RnHsSyn          ( RenamedHsDecl )
40 import ParseIface       ( parseIface, IfaceStuff(..) )
41
42 import FiniteMap        ( FiniteMap, sizeFM, emptyFM, delFromFM,
43                           lookupFM, addToFM, addToFM_C, addListToFM, 
44                           fmToList
45                         )
46 import Name             ( Name {-instance NamedThing-},
47                           nameModule, moduleUserString, pprModule, isLocallyDefined,
48                           isWiredInName, maybeWiredInTyConName,  pprModule,
49                           maybeWiredInIdName, nameUnique, NamedThing(..)
50                          )
51 import OccName          ( Module, mkBootModule, 
52                           moduleIfaceFlavour, bootFlavour, hiFile
53                         )
54 import RdrName          ( RdrName, rdrNameOcc )
55 import NameSet
56 import Id               ( idType, isDataConId_maybe )
57 import DataCon          ( dataConTyCon, dataConType )
58 import TyCon            ( TyCon, tyConDataCons, isSynTyCon, getSynTyConDefn )
59 import Type             ( namesOfType )
60 import Var              ( Id )
61 import SrcLoc           ( mkSrcLoc, SrcLoc )
62 import PrelMods         ( pREL_GHC )
63 import PrelInfo         ( cCallishTyKeys, thinAirModules )
64 import Bag
65 import Maybes           ( MaybeErr(..), maybeToBool )
66 import ListSetOps       ( unionLists )
67 import Outputable
68 import Unique           ( Unique )
69 import StringBuffer     ( StringBuffer, hGetStringBuffer )
70 import FastString       ( mkFastString )
71 import Outputable
72
73 import IO       ( isDoesNotExistError )
74 import List     ( nub )
75 \end{code}
76
77
78
79 %*********************************************************
80 %*                                                      *
81 \subsection{Statistics}
82 %*                                                      *
83 %*********************************************************
84
85 \begin{code}
86 getRnStats :: [RenamedHsDecl] -> RnMG SDoc
87 getRnStats all_decls
88   = getIfacesRn                 `thenRn` \ ifaces ->
89     let
90         n_mods      = sizeFM (iModMap ifaces)
91
92         decls_imported = filter is_imported_decl all_decls
93
94         decls_read     = [decl | (_, avail, decl, True) <- nameEnvElts (iDecls ifaces),
95                                         -- Data, newtype, and class decls are in the decls_fm
96                                         -- under multiple names; the tycon/class, and each
97                                         -- constructor/class op too.
98                                         -- The 'True' selects just the 'main' decl
99                                  not (isLocallyDefined (availName avail))
100                              ]
101
102         (cd_rd, dd_rd, add_rd, nd_rd, and_rd, sd_rd, vd_rd,     _) = count_decls decls_read
103         (cd_sp, dd_sp, add_sp, nd_sp, and_sp, sd_sp, vd_sp, id_sp) = count_decls decls_imported
104
105         (unslurped_insts, _)  = iDefInsts ifaces
106         inst_decls_unslurped  = length (bagToList unslurped_insts)
107         inst_decls_read       = id_sp + inst_decls_unslurped
108
109         stats = vcat 
110                 [int n_mods <> text " interfaces read",
111                  hsep [ int cd_sp, text "class decls imported, out of", 
112                         int cd_rd, text "read"],
113                  hsep [ int dd_sp, text "data decls imported (of which", int add_sp, 
114                         text "abstractly), out of",  
115                         int dd_rd, text "read"],
116                  hsep [ int nd_sp, text "newtype decls imported (of which", int and_sp, 
117                         text "abstractly), out of",  
118                         int nd_rd, text "read"],
119                  hsep [int sd_sp, text "type synonym decls imported, out of",  
120                         int sd_rd, text "read"],
121                  hsep [int vd_sp, text "value signatures imported, out of",  
122                         int vd_rd, text "read"],
123                  hsep [int id_sp, text "instance decls imported, out of",  
124                         int inst_decls_read, text "read"]
125                 ]
126     in
127     returnRn (hcat [text "Renamer stats: ", stats])
128
129 is_imported_decl (DefD _) = False
130 is_imported_decl (ValD _) = False
131 is_imported_decl decl     = not (isLocallyDefined (hsDeclName decl))
132
133 count_decls decls
134   = -- pprTrace "count_decls" (ppr  decls
135     --
136     --                      $$
137     --                      text "========="
138     --                      $$
139     --                      ppr imported_decls
140     --  ) $
141     (class_decls, 
142      data_decls,    abstract_data_decls,
143      newtype_decls, abstract_newtype_decls,
144      syn_decls, 
145      val_decls, 
146      inst_decls)
147   where
148     tycl_decls = [d | TyClD d <- decls]
149     (class_decls, data_decls, newtype_decls, syn_decls) = countTyClDecls tycl_decls
150     abstract_data_decls    = length [() | TyData DataType _ _ _ [] _ _ _ <- tycl_decls]
151     abstract_newtype_decls = length [() | TyData NewType  _ _ _ [] _ _ _ <- tycl_decls]
152
153     val_decls     = length [() | SigD _   <- decls]
154     inst_decls    = length [() | InstD _  <- decls]
155
156 \end{code}    
157
158 %*********************************************************
159 %*                                                      *
160 \subsection{Loading a new interface file}
161 %*                                                      *
162 %*********************************************************
163
164 \begin{code}
165 loadHomeInterface :: SDoc -> Name -> RnMG Ifaces
166 loadHomeInterface doc_str name
167   = loadInterface doc_str (nameModule name)
168
169 loadInterface :: SDoc -> Module -> RnMG Ifaces
170 loadInterface doc_str load_mod
171  = getIfacesRn          `thenRn` \ ifaces ->
172    let
173         new_hif              = moduleIfaceFlavour load_mod
174         this_mod             = iMod ifaces
175         mod_map              = iModMap ifaces
176         (insts, tycls_names) = iDefInsts ifaces
177    in
178         -- CHECK WHETHER WE HAVE IT ALREADY
179    case lookupFM mod_map load_mod of {
180         Just (existing_hif, _, _) 
181                 | bootFlavour new_hif || not (bootFlavour existing_hif)
182                 ->      -- Already in the cache, and new version is no better than old,
183                         -- so don't re-read it
184                     returnRn ifaces ;
185         other ->
186
187         -- READ THE MODULE IN
188    findAndReadIface doc_str load_mod            `thenRn` \ read_result ->
189    case read_result of {
190         -- Check for not found
191         Nothing ->      -- Not found, so add an empty export env to the Ifaces map
192                         -- so that we don't look again
193                    let
194                         new_mod_map = addToFM mod_map load_mod (hiFile, 0, [])
195                         new_ifaces = ifaces { iModMap = new_mod_map }
196                    in
197                    setIfacesRn new_ifaces               `thenRn_`
198                    failWithRn new_ifaces (noIfaceErr load_mod) ;
199
200         -- Found and parsed!
201         Just (ParsedIface _ mod_vers usages exports rd_inst_mods rd_decls rd_insts) ->
202
203         -- LOAD IT INTO Ifaces
204         -- First set the module
205
206         -- NB: *first* we do loadDecl, so that the provenance of all the locally-defined
207         ---    names is done correctly (notably, whether this is an .hi file or .hi-boot file).
208         --     If we do loadExport first the wrong info gets into the cache (unless we
209         --      explicitly tag each export which seems a bit of a bore)
210
211     getModuleRn                 `thenRn` \ this_mod ->
212     setModuleRn load_mod  $     -- First set the module name of the module being loaded,
213                                 -- so that unqualified occurrences in the interface file
214                                 -- get the right qualifer
215     foldlRn loadDecl (iDecls ifaces) rd_decls           `thenRn` \ new_decls ->
216     foldlRn loadFixDecl (iFixes ifaces) rd_decls        `thenRn` \ new_fixities ->
217     foldlRn loadInstDecl insts rd_insts                 `thenRn` \ new_insts ->
218
219     mapRn (loadExport this_mod) exports                 `thenRn` \ avails_s ->
220     let
221          mod_details = (new_hif, mod_vers, concat avails_s)
222
223                         -- Exclude this module from the "special-inst" modules
224          new_inst_mods = iInstMods ifaces `unionLists` (filter (/= this_mod) rd_inst_mods)
225
226          new_ifaces = ifaces { iModMap   = addToFM mod_map load_mod mod_details,
227                                iDecls    = new_decls,
228                                iFixes    = new_fixities,
229                                iDefInsts = (new_insts, tycls_names),
230                                iInstMods = new_inst_mods  }
231     in
232     setIfacesRn new_ifaces              `thenRn_`
233     returnRn new_ifaces
234     }}
235
236 loadExport :: Module -> ExportItem -> RnMG [AvailInfo]
237 loadExport this_mod (mod, entities)
238   | mod == this_mod = returnRn []
239         -- If the module exports anything defined in this module, just ignore it.
240         -- Reason: otherwise it looks as if there are two local definition sites
241         -- for the thing, and an error gets reported.  Easiest thing is just to
242         -- filter them out up front. This situation only arises if a module
243         -- imports itself, or another module that imported it.  (Necessarily,
244         -- this invoves a loop.)  Consequence: if you say
245         --      module A where
246         --         import B( AType )
247         --         type AType = ...
248         --
249         --      module B( AType ) where
250         --         import {-# SOURCE #-} A( AType )
251         --
252         -- then you'll get a 'B does not export AType' message.  A bit bogus
253         -- but it's a bogus thing to do!
254
255   | otherwise
256   = mapRn load_entity entities
257   where
258     new_name occ = newImportedGlobalName mod occ
259
260     load_entity (Avail occ)
261       = new_name occ            `thenRn` \ name ->
262         returnRn (Avail name)
263     load_entity (AvailTC occ occs)
264       = new_name occ            `thenRn` \ name ->
265         mapRn new_name occs     `thenRn` \ names ->
266         returnRn (AvailTC name names)
267
268
269 loadFixDecl :: FixityEnv 
270             -> (Version, RdrNameHsDecl)
271             -> RnMG FixityEnv
272 loadFixDecl fixity_env (version, FixD (FixitySig rdr_name fixity loc))
273   =     -- Ignore the version; when the fixity changes the version of
274         -- its 'host' entity changes, so we don't need a separate version
275         -- number for fixities
276     newImportedGlobalFromRdrName rdr_name       `thenRn` \ name ->
277     let
278         new_fixity_env = addToNameEnv fixity_env name (FixitySig name fixity loc)
279     in
280     returnRn new_fixity_env
281
282         -- Ignore the other sorts of decl
283 loadFixDecl fixity_env other_decl = returnRn fixity_env
284
285 loadDecl :: DeclsMap
286          -> (Version, RdrNameHsDecl)
287          -> RnMG DeclsMap
288
289 loadDecl decls_map (version, decl)
290   = getDeclBinders new_name decl        `thenRn` \ maybe_avail ->
291     case maybe_avail of {
292         Nothing -> returnRn decls_map;  -- No bindings
293         Just avail ->
294
295     getDeclSysBinders new_name decl     `thenRn` \ sys_bndrs ->
296     let
297         main_name     = availName avail
298         new_decls_map = foldl add_decl decls_map
299                                        [ (name, (version,avail,decl',name==main_name)) 
300                                        | name <- sys_bndrs ++ availNames avail]
301         add_decl decls_map (name, stuff)
302           = WARN( name `elemNameEnv` decls_map, ppr name )
303             addToNameEnv decls_map name stuff
304     in
305     returnRn new_decls_map
306     }
307   where
308     new_name rdr_name loc = newImportedGlobalFromRdrName rdr_name
309     {-
310       If a signature decl is being loaded, and optIgnoreIfacePragmas is on,
311       we toss away unfolding information.
312
313       Also, if the signature is loaded from a module we're importing from source,
314       we do the same. This is to avoid situations when compiling a pair of mutually
315       recursive modules, peering at unfolding info in the interface file of the other, 
316       e.g., you compile A, it looks at B's interface file and may as a result change
317       its interface file. Hence, B is recompiled, maybe changing its interface file,
318       which will the unfolding info used in A to become invalid. Simple way out is to
319       just ignore unfolding info.
320
321       [Jan 99: I junked the second test above.  If we're importing from an hi-boot
322        file there isn't going to *be* any pragma info.  Maybe the above comment
323        dates from a time where we picked up a .hi file first if it existed?]
324     -}
325     decl' = 
326      case decl of
327        SigD (IfaceSig name tp ls loc) | opt_IgnoreIfacePragmas -> 
328             SigD (IfaceSig name tp [] loc)
329        _ -> decl
330
331 loadInstDecl :: Bag IfaceInst
332              -> RdrNameInstDecl
333              -> RnMG (Bag IfaceInst)
334 loadInstDecl insts decl@(InstDecl inst_ty binds uprags dfun_name src_loc)
335   = 
336         -- Find out what type constructors and classes are "gates" for the
337         -- instance declaration.  If all these "gates" are slurped in then
338         -- we should slurp the instance decl too.
339         -- 
340         -- We *don't* want to count names in the context part as gates, though.
341         -- For example:
342         --              instance Foo a => Baz (T a) where ...
343         --
344         -- Here the gates are Baz and T, but *not* Foo.
345     let 
346         munged_inst_ty = case inst_ty of
347                                 HsForAllTy tvs cxt ty -> HsForAllTy tvs [] ty
348                                 other                 -> inst_ty
349     in
350         -- We find the gates by renaming the instance type with in a 
351         -- and returning the free variables of the type
352     initRnMS emptyRnEnv vanillaInterfaceMode (
353         discardOccurrencesRn (rnHsSigType (text "an instance decl") munged_inst_ty)
354     )                                           `thenRn` \ (_, gate_names) ->
355     getModuleRn                                 `thenRn` \ mod_name -> 
356     returnRn (((mod_name, decl), gate_names) `consBag` insts)
357
358 vanillaInterfaceMode = InterfaceMode Compulsory
359 \end{code}
360
361
362 %********************************************************
363 %*                                                      *
364 \subsection{Loading usage information}
365 %*                                                      *
366 %********************************************************
367
368 \begin{code}
369 checkUpToDate :: Module -> RnMG Bool            -- True <=> no need to recompile
370 checkUpToDate mod_name
371   = findAndReadIface doc_str mod_name           `thenRn` \ read_result ->
372
373         -- CHECK WHETHER WE HAVE IT ALREADY
374     case read_result of
375         Nothing ->      -- Old interface file not found, so we'd better bail out
376                     traceRn (sep [ptext SLIT("Didnt find old iface"), 
377                                     pprModule mod_name])        `thenRn_`
378                     returnRn False
379
380         Just (ParsedIface _ _ usages _ _ _ _) 
381                 ->      -- Found it, so now check it
382                     checkModUsage usages
383   where
384         -- Only look in current directory, with suffix .hi
385     doc_str = sep [ptext SLIT("need usage info from"), pprModule mod_name]
386
387 checkModUsage [] = returnRn True                -- Yes!  Everything is up to date!
388
389 checkModUsage ((mod, old_mod_vers, whats_imported) : rest)
390   = loadInterface doc_str mod           `thenRn` \ ifaces ->
391     let
392         maybe_new_mod_vers        = lookupFM (iModMap ifaces) mod
393         Just (_, new_mod_vers, _) = maybe_new_mod_vers
394     in
395         -- If we can't find a version number for the old module then
396         -- bail out saying things aren't up to date
397     if not (maybeToBool maybe_new_mod_vers) then
398         traceRn (sep [ptext SLIT("Can't find version number for module"), pprModule mod]) `thenRn_`
399         returnRn False
400     else
401
402         -- If the module version hasn't changed, just move on
403     if new_mod_vers == old_mod_vers then
404         traceRn (sep [ptext SLIT("Module version unchanged:"), pprModule mod])  `thenRn_`
405         checkModUsage rest
406     else
407     traceRn (sep [ptext SLIT("Module version has changed:"), pprModule mod])    `thenRn_`
408
409         -- Module version changed, so check entities inside
410
411         -- If the usage info wants to say "I imported everything from this module"
412         --     it does so by making whats_imported equal to Everything
413         -- In that case, we must recompile
414     case whats_imported of {
415       Everything -> traceRn (ptext SLIT("...and I needed the whole module"))    `thenRn_`
416                     returnRn False;                -- Bale out
417
418       Specifically old_local_vers ->
419
420         -- Non-empty usage list, so check item by item
421     checkEntityUsage mod (iDecls ifaces) old_local_vers `thenRn` \ up_to_date ->
422     if up_to_date then
423         traceRn (ptext SLIT("...but the bits I use haven't."))  `thenRn_`
424         checkModUsage rest      -- This one's ok, so check the rest
425     else
426         returnRn False          -- This one failed, so just bail out now
427     }
428   where
429     doc_str = sep [ptext SLIT("need version info for"), pprModule mod]
430
431
432 checkEntityUsage mod decls [] 
433   = returnRn True       -- Yes!  All up to date!
434
435 checkEntityUsage mod decls ((occ_name,old_vers) : rest)
436   = newImportedGlobalName mod occ_name          `thenRn` \ name ->
437     case lookupNameEnv decls name of
438
439         Nothing       ->        -- We used it before, but it ain't there now
440                           putDocRn (sep [ptext SLIT("No longer exported:"), ppr name])  `thenRn_`
441                           returnRn False
442
443         Just (new_vers,_,_,_)   -- It's there, but is it up to date?
444                 | new_vers == old_vers
445                         -- Up to date, so check the rest
446                 -> checkEntityUsage mod decls rest
447
448                 | otherwise
449                         -- Out of date, so bale out
450                 -> putDocRn (sep [ptext SLIT("Out of date:"), ppr name])  `thenRn_`
451                    returnRn False
452 \end{code}
453
454
455 %*********************************************************
456 %*                                                      *
457 \subsection{Getting in a declaration}
458 %*                                                      *
459 %*********************************************************
460
461 \begin{code}
462 importDecl :: Occurrence -> RnMode -> RnMG (Maybe RdrNameHsDecl)
463         -- Returns Nothing for a wired-in or already-slurped decl
464
465 importDecl (name, loc) mode
466   = checkSlurped name                   `thenRn` \ already_slurped ->
467     if already_slurped then
468 --      traceRn (sep [text "Already slurped:", ppr name])       `thenRn_`
469         returnRn Nothing        -- Already dealt with
470     else
471     if isWiredInName name then
472         getWiredInDecl name mode
473     else 
474        getIfacesRn              `thenRn` \ ifaces ->
475        let
476          mod = nameModule name
477        in
478        if mod == iMod ifaces then    -- Don't bring in decls from
479           addWarnRn (importDeclWarn mod name loc) `thenRn_`
480 --        pprTrace "importDecl wierdness:" (ppr name) $
481           returnRn Nothing         -- the renamed module's own interface file
482                                    -- 
483        else
484        getNonWiredInDecl name loc mode
485 \end{code}
486
487 \begin{code}
488 getNonWiredInDecl :: Name -> SrcLoc -> RnMode -> RnMG (Maybe RdrNameHsDecl)
489 getNonWiredInDecl needed_name loc mode
490   = traceRn doc_str                             `thenRn_`
491     loadHomeInterface doc_str needed_name       `thenRn` \ ifaces ->
492     case lookupNameEnv (iDecls ifaces) needed_name of
493
494         -- Special case for data/newtype type declarations
495       Just (version, avail, TyClD tycl_decl, _) | isDataDecl tycl_decl
496         -> getNonWiredDataDecl needed_name version avail tycl_decl      `thenRn` \ (avail', maybe_decl) ->
497            recordSlurp (Just version) necessity avail'                  `thenRn_`
498            returnRn maybe_decl
499
500       Just (version,avail,decl,_)
501         -> recordSlurp (Just version) necessity avail   `thenRn_`
502            returnRn (Just decl)
503
504       Nothing ->        -- Can happen legitimately for "Optional" occurrences
505                    case necessity of { 
506                         Optional -> addWarnRn (getDeclWarn needed_name loc);
507                         other    -> addErrRn  (getDeclErr  needed_name loc)
508                    }                                            `thenRn_` 
509                    returnRn Nothing
510   where
511      necessity = modeToNecessity mode
512      doc_str = sep [ptext SLIT("need decl for"), ppr needed_name, ptext SLIT("needed at"), ppr loc]
513 \end{code}
514
515 @getWiredInDecl@ maps a wired-in @Name@ to what it makes available.
516 It behaves exactly as if the wired in decl were actually in an interface file.
517 Specifically,
518
519   *     if the wired-in name is a data type constructor or a data constructor, 
520         it brings in the type constructor and all the data constructors; and
521         marks as "occurrences" any free vars of the data con.
522
523   *     similarly for synonum type constructor
524
525   *     if the wired-in name is another wired-in Id, it marks as "occurrences"
526         the free vars of the Id's type.
527
528   *     it loads the interface file for the wired-in thing for the
529         sole purpose of making sure that its instance declarations are available
530
531 All this is necessary so that we know all types that are "in play", so
532 that we know just what instances to bring into scope.
533         
534 \begin{code}
535 getWiredInDecl name mode
536   = setModuleRn mod_name (
537         initRnMS emptyRnEnv new_mode get_wired
538     )                                           `thenRn` \ avail ->
539     recordSlurp Nothing necessity avail         `thenRn_`
540
541         -- Force in the home module in case it has instance decls for
542         -- the thing we are interested in.
543         --
544         -- Mini hack 1: no point for non-tycons/class; and if we
545         -- do this we find PrelNum trying to import PackedString,
546         -- because PrelBase's .hi file mentions PackedString.unpackString
547         -- But PackedString.hi isn't built by that point!
548         --
549         -- Mini hack 2; GHC is guaranteed not to have
550         -- instance decls, so it's a waste of time to read it
551         --
552         -- NB: We *must* look at the availName of the slurped avail, 
553         -- not the name passed to getWiredInDecl!  Why?  Because if a data constructor 
554         -- or class op is passed to getWiredInDecl we'll pull in the whole data/class
555         -- decl, and recordSlurp will record that fact.  But since the data constructor
556         -- isn't a tycon/class we won't force in the home module.  And even if the
557         -- type constructor/class comes along later, loadDecl will say that it's already
558         -- been slurped, so getWiredInDecl won't even be called.  Pretty obscure bug, this was.
559     let
560         main_name  = availName avail
561         main_is_tc = case avail of { AvailTC _ _ -> True; Avail _ -> False }
562         mod        = nameModule main_name
563         doc_str    = sep [ptext SLIT("need home module for wired in thing"), ppr name]
564     in
565     (if not main_is_tc || mod == pREL_GHC then
566         returnRn ()             
567     else
568         loadHomeInterface doc_str main_name     `thenRn_`
569         returnRn ()
570     )                                           `thenRn_`
571
572     returnRn Nothing            -- No declaration to process further
573   where
574     necessity = modeToNecessity mode
575     new_mode = case mode of 
576                         InterfaceMode _ -> mode
577                         SourceMode      -> vanillaInterfaceMode
578
579     get_wired | is_tycon                        -- ... a type constructor
580               = get_wired_tycon the_tycon
581
582               | maybeToBool maybe_data_con              -- ... a wired-in data constructor
583               = get_wired_tycon (dataConTyCon data_con)
584
585               | otherwise                       -- ... a wired-in non data-constructor
586               = get_wired_id the_id
587
588     mod_name             = nameModule name
589     maybe_wired_in_tycon = maybeWiredInTyConName name
590     is_tycon             = maybeToBool maybe_wired_in_tycon
591     maybe_wired_in_id    = maybeWiredInIdName    name
592     Just the_tycon       = maybe_wired_in_tycon
593     Just the_id          = maybe_wired_in_id
594     maybe_data_con       = isDataConId_maybe the_id
595     Just data_con        = maybe_data_con
596
597
598 get_wired_id id
599   = addImplicitOccsRn id_mentions       `thenRn_`
600     returnRn (Avail (getName id))
601   where
602     id_mentions = nameSetToList (namesOfType ty)
603     ty = idType id
604
605 get_wired_tycon tycon 
606   | isSynTyCon tycon
607   = addImplicitOccsRn (nameSetToList mentioned)         `thenRn_`
608     returnRn (AvailTC tc_name [tc_name])
609   where
610     tc_name     = getName tycon
611     (tyvars,ty) = getSynTyConDefn tycon
612     mentioned   = namesOfType ty `minusNameSet` mkNameSet (map getName tyvars)
613
614 get_wired_tycon tycon 
615   | otherwise           -- data or newtype
616   = addImplicitOccsRn (nameSetToList mentioned)         `thenRn_`
617     returnRn (AvailTC tycon_name (tycon_name : map getName data_cons))
618   where
619     tycon_name = getName tycon
620     data_cons  = tyConDataCons tycon
621     mentioned  = foldr (unionNameSets . namesOfType . dataConType) emptyNameSet data_cons
622 \end{code}
623
624
625     
626 %*********************************************************
627 %*                                                      *
628 \subsection{Getting what a module exports}
629 %*                                                      *
630 %*********************************************************
631
632 \begin{code}
633 getInterfaceExports :: Module -> RnMG Avails
634 getInterfaceExports mod
635   = loadInterface doc_str mod   `thenRn` \ ifaces ->
636     case lookupFM (iModMap ifaces) mod of
637         Nothing ->      -- Not there; it must be that the interface file wasn't found;
638                         -- the error will have been reported already.
639                         -- (Actually loadInterface should put the empty export env in there
640                         --  anyway, but this does no harm.)
641                       returnRn []
642
643         Just (_, _, avails) -> returnRn avails
644   where
645     doc_str = sep [pprModule mod, ptext SLIT("is directly imported")]
646 \end{code}
647
648
649 %*********************************************************
650 %*                                                      *
651 \subsection{Data type declarations are handled specially}
652 %*                                                      *
653 %*********************************************************
654
655 Data type declarations get special treatment.  If we import a data type decl
656 with all its constructors, we end up importing all the types mentioned in 
657 the constructors' signatures, and hence {\em their} data type decls, and so on.
658 In effect, we get the transitive closure of data type decls.  Worse, this drags
659 in tons on instance decls, and their unfoldings, and so on.
660
661 If only the type constructor is mentioned, then all this is a waste of time.
662 If any of the data constructors are mentioned then we really have to 
663 drag in the whole declaration.
664
665 So when we import the type constructor for a @data@ or @newtype@ decl, we
666 put it in the "deferred data/newtype decl" pile in Ifaces.  Right at the end
667 we slurp these decls, if they havn't already been dragged in by an occurrence
668 of a constructor.
669
670 \begin{code}
671 getNonWiredDataDecl needed_name 
672                     version
673                     avail@(AvailTC tycon_name _) 
674                     ty_decl@(TyData new_or_data context tycon tyvars condecls derivings pragmas src_loc)
675   |  needed_name == tycon_name
676   && opt_PruneTyDecls
677         -- don't prune newtypes, as the code generator may
678         -- want to peer inside a newtype type constructor
679         -- (ClosureInfo.fun_result_ty is the culprit.)
680   && not (new_or_data == NewType)
681   && not (nameUnique needed_name `elem` cCallishTyKeys)         
682         -- Hack!  Don't prune these tycons whose constructors
683         -- the desugarer must be able to see when desugaring
684         -- a CCall.  Ugh!
685
686   =     -- Need the type constructor; so put it in the deferred set for now
687     getIfacesRn                 `thenRn` \ ifaces ->
688     let
689         deferred_data_decls = iDefData ifaces
690         new_ifaces          = ifaces {iDefData = new_deferred_data_decls}
691
692         no_constr_ty_decl       = TyData new_or_data [] tycon tyvars [] derivings pragmas src_loc
693         new_deferred_data_decls = addToNameEnv deferred_data_decls tycon_name 
694                                                (nameModule tycon_name, no_constr_ty_decl)
695                 -- Nota bene: we nuke both the constructors and the context in the deferred decl.
696                 -- If we don't nuke the context then renaming the deferred data decls can give
697                 -- new unresolved names (for the classes).  This could be handled, but there's
698                 -- no point.  If the data type is completely abstract then we aren't interested
699                 -- its context.
700     in
701     setIfacesRn new_ifaces      `thenRn_`
702     returnRn (AvailTC tycon_name [tycon_name], Nothing)
703
704   | otherwise
705   =     -- Need a data constructor, so delete the data decl from the deferred set if it's there
706     getIfacesRn                 `thenRn` \ ifaces ->
707     let
708         deferred_data_decls = iDefData ifaces
709         new_ifaces          = ifaces {iDefData = new_deferred_data_decls}
710
711         new_deferred_data_decls = delFromNameEnv deferred_data_decls tycon_name
712     in
713     setIfacesRn new_ifaces      `thenRn_`
714     returnRn (avail, Just (TyClD ty_decl))
715 \end{code}
716
717 \begin{code}
718 getDeferredDataDecls :: RnMG [(Module, RdrNameTyClDecl)]
719 getDeferredDataDecls 
720   = getIfacesRn                 `thenRn` \ ifaces ->
721     let
722         deferred_list = nameEnvElts (iDefData ifaces)
723         trace_msg = hang (text "Slurping abstract data/newtype decls for: ")
724                         4 (ppr (map fst deferred_list))
725     in
726     traceRn trace_msg                   `thenRn_`
727     returnRn deferred_list
728 \end{code}
729
730
731 %*********************************************************
732 %*                                                      *
733 \subsection{Instance declarations are handled specially}
734 %*                                                      *
735 %*********************************************************
736
737 \begin{code}
738 getImportedInstDecls :: RnMG [(Module,RdrNameInstDecl)]
739 getImportedInstDecls
740   =     -- First load any special-instance modules that aren't aready loaded
741     getSpecialInstModules                       `thenRn` \ inst_mods ->
742     mapRn load_it inst_mods                     `thenRn_`
743
744         -- Now we're ready to grab the instance declarations
745         -- Find the un-gated ones and return them, 
746         -- removing them from the bag kept in Ifaces
747     getIfacesRn         `thenRn` \ ifaces ->
748     let
749         (insts, tycls_names) = iDefInsts ifaces
750
751                 -- An instance decl is ungated if all its gates have been slurped
752         select_ungated :: IfaceInst                                     -- A gated inst decl
753
754                        -> ([(Module, RdrNameInstDecl)], [IfaceInst])    -- Accumulator
755
756                        -> ([(Module, RdrNameInstDecl)],                 -- The ungated ones
757                            [IfaceInst])                                 -- Still gated, but with
758                                                                         -- depeleted gates
759         select_ungated (decl,gates) (ungated_decls, gated_decls)
760           | isEmptyNameSet remaining_gates
761           = (decl : ungated_decls, gated_decls)
762           | otherwise
763           = (ungated_decls, (decl, remaining_gates) : gated_decls)
764           where
765             remaining_gates = gates `minusNameSet` tycls_names
766
767         (un_gated_insts, still_gated_insts) = foldrBag select_ungated ([], []) insts
768         
769         new_ifaces = ifaces {iDefInsts = (listToBag still_gated_insts, tycls_names)}
770                                 -- NB: don't throw away tycls_names;
771                                 -- we may comre across more instance decls
772     in
773     traceRn (sep [text "getInstDecls:", fsep (map ppr (nameSetToList tycls_names))])    `thenRn_`
774     setIfacesRn new_ifaces      `thenRn_`
775     returnRn un_gated_insts
776   where
777     load_it mod = loadInterface (doc_str mod) mod
778     doc_str mod = sep [pprModule mod, ptext SLIT("is a special-instance module")]
779
780
781 getSpecialInstModules :: RnMG [Module]
782 getSpecialInstModules 
783   = getIfacesRn                                         `thenRn` \ ifaces ->
784     returnRn (iInstMods ifaces)
785
786 getImportedFixities :: GlobalRdrEnv -> RnMG FixityEnv
787         -- Get all imported fixities
788         -- We first make sure that all the home modules
789         -- of all in-scope variables are loaded.
790 getImportedFixities gbl_env
791   = let
792         home_modules = [ nameModule name | names <- rdrEnvElts gbl_env,
793                                            name <- names,
794                                            not (isLocallyDefined name)
795                        ]
796     in
797     mapRn load (nub home_modules)       `thenRn_`
798
799         -- Now we can snaffle the fixity env
800     getIfacesRn                                         `thenRn` \ ifaces ->
801     returnRn (iFixes ifaces)
802   where
803     load mod = loadInterface doc_str mod
804              where
805                doc_str = ptext SLIT("Need fixities from") <+> ppr mod
806 \end{code}
807
808
809 %*********************************************************
810 %*                                                      *
811 \subsection{Keeping track of what we've slurped, and version numbers}
812 %*                                                      *
813 %*********************************************************
814
815 getImportVersions figures out what the "usage information" for this moudule is;
816 that is, what it must record in its interface file as the things it uses.
817 It records:
818         - anything reachable from its body code
819         - any module exported with a "module Foo".
820
821 Why the latter?  Because if Foo changes then this module's export list
822 will change, so we must recompile this module at least as far as
823 making a new interface file --- but in practice that means complete
824 recompilation.
825
826 What about this? 
827         module A( f, g ) where          module B( f ) where
828           import B( f )                   f = h 3
829           g = ...                         h = ...
830
831 Should we record B.f in A's usages?  In fact we don't.  Certainly, if
832 anything about B.f changes than anyone who imports A should be recompiled;
833 they'll get an early exit if they don't use B.f.  However, even if B.f
834 doesn't change at all, B.h may do so, and this change may not be reflected
835 in f's version number.  So there are two things going on when compiling module A:
836
837 1.  Are A.o and A.hi correct?  Then we can bale out early.
838 2.  Should modules that import A be recompiled?
839
840 For (1) it is slightly harmful to record B.f in A's usages, because a change in
841 B.f's version will provoke full recompilation of A, producing an identical A.o,
842 and A.hi differing only in its usage-version of B.f (which isn't used by any importer).
843
844 For (2), because of the tricky B.h question above, we ensure that A.hi is touched
845 (even if identical to its previous version) if A's recompilation was triggered by
846 an imported .hi file date change.  Given that, there's no need to record B.f in
847 A's usages.
848
849 On the other hand, if A exports "module B" then we *do* count module B among
850 A's usages, because we must recompile A to ensure that A.hi changes appropriately.
851
852 \begin{code}
853 getImportVersions :: Module                     -- Name of this module
854                   -> Maybe [IE any]             -- Export list for this module
855                   -> RnMG (VersionInfo Name)    -- Version info for these names
856
857 getImportVersions this_mod exports
858   = getIfacesRn                                 `thenRn` \ ifaces ->
859     let
860         mod_map   = iModMap ifaces
861         imp_names = iVSlurp ifaces
862
863         -- mv_map groups together all the things imported from a particular module.
864         mv_map, mv_map_mod :: FiniteMap Module (WhatsImported Name)
865
866         mv_map_mod = foldl add_mod emptyFM export_mods
867                 -- mv_map_mod records all the modules that have a "module M"
868                 -- in this module's export list with an "Everything" 
869
870         mv_map = foldl add_mv mv_map_mod imp_names
871                 -- mv_map adds the version numbers of things exported individually
872
873         mk_version_info (mod, local_versions)
874            = case lookupFM mod_map mod of
875                 Just (hif, version, _) -> (mod, version, local_versions)
876     in
877     returnRn (map mk_version_info (fmToList mv_map))
878   where
879      export_mods = case exports of
880                         Nothing -> []
881                         Just es -> [mod | IEModuleContents mod <- es, mod /= this_mod]
882
883      add_mv mv_map v@(name, version) 
884       = addToFM_C add_item mv_map mod (Specifically [v]) 
885         where
886          mod = nameModule name
887
888          add_item Everything        _ = Everything
889          add_item (Specifically xs) _ = Specifically (v:xs)
890
891      add_mod mv_map mod = addToFM mv_map mod Everything
892 \end{code}
893
894 \begin{code}
895 checkSlurped name
896   = getIfacesRn         `thenRn` \ ifaces ->
897     returnRn (name `elemNameSet` iSlurp ifaces)
898
899 getSlurpedNames :: RnMG NameSet
900 getSlurpedNames
901   = getIfacesRn         `thenRn` \ ifaces ->
902     returnRn (iSlurp ifaces)
903
904 recordSlurp maybe_version necessity avail
905   = {- traceRn (hsep [text "Record slurp:", pprAvail avail, 
906                                         -- NB PprForDebug prints export flag, which is too
907                                         -- strict; it's a knot-tied thing in RnNames
908                   case necessity of {Compulsory -> text "comp"; Optional -> text "opt" } ])     `thenRn_` 
909     -}
910     getIfacesRn         `thenRn` \ ifaces ->
911     let
912         Ifaces { iSlurp    = slurped_names,
913                  iVSlurp   = imp_names,
914                  iDefInsts = (insts, tycls_names) } = ifaces
915
916         new_slurped_names = addAvailToNameSet slurped_names avail
917
918         new_imp_names = case maybe_version of
919                            Just version -> (availName avail, version) : imp_names
920                            Nothing      -> imp_names
921
922                 -- Add to the names that will let in instance declarations;
923                 -- but only (a) if it's a type/class
924                 --          (b) if it's compulsory (unless the test flag opt_PruneInstDecls is off)
925         new_tycls_names = case avail of
926                                 AvailTC tc _  | not opt_PruneInstDecls || 
927                                                 case necessity of {Optional -> False; Compulsory -> True }
928                                               -> tycls_names `addOneToNameSet` tc
929                                 otherwise     -> tycls_names
930
931         new_ifaces = ifaces { iSlurp    = new_slurped_names,
932                               iVSlurp   = new_imp_names,
933                               iDefInsts = (insts, new_tycls_names) }
934     in
935     setIfacesRn new_ifaces
936 \end{code}
937
938
939 %*********************************************************
940 %*                                                      *
941 \subsection{Getting binders out of a declaration}
942 %*                                                      *
943 %*********************************************************
944
945 @getDeclBinders@ returns the names for a @RdrNameHsDecl@.
946 It's used for both source code (from @availsFromDecl@) and interface files
947 (from @loadDecl@).
948
949 It doesn't deal with source-code specific things: ValD, DefD.  They
950 are handled by the sourc-code specific stuff in RnNames.
951
952 \begin{code}
953 getDeclBinders :: (RdrName -> SrcLoc -> RnMG Name)      -- New-name function
954                 -> RdrNameHsDecl
955                 -> RnMG (Maybe AvailInfo)
956
957 getDeclBinders new_name (TyClD (TyData _ _ tycon _ condecls _ _ src_loc))
958   = new_name tycon src_loc                      `thenRn` \ tycon_name ->
959     getConFieldNames new_name condecls          `thenRn` \ sub_names ->
960     returnRn (Just (AvailTC tycon_name (tycon_name : nub sub_names)))
961         -- The "nub" is because getConFieldNames can legitimately return duplicates,
962         -- when a record declaration has the same field in multiple constructors
963
964 getDeclBinders new_name (TyClD (TySynonym tycon _ _ src_loc))
965   = new_name tycon src_loc              `thenRn` \ tycon_name ->
966     returnRn (Just (AvailTC tycon_name [tycon_name]))
967
968 getDeclBinders new_name (TyClD (ClassDecl _ cname _ sigs _ _ tname dname src_loc))
969   = new_name cname src_loc                      `thenRn` \ class_name ->
970
971         -- Record the names for the class ops
972     let
973         -- ignoring fixity declarations
974         nonfix_sigs = nonFixitySigs sigs
975     in
976     mapRn (getClassOpNames new_name) nonfix_sigs        `thenRn` \ sub_names ->
977
978     returnRn (Just (AvailTC class_name (class_name : sub_names)))
979
980 getDeclBinders new_name (SigD (IfaceSig var ty prags src_loc))
981   = new_name var src_loc                        `thenRn` \ var_name ->
982     returnRn (Just (Avail var_name))
983
984 getDeclBinders new_name (FixD _)  = returnRn Nothing
985 getDeclBinders new_name (ForD _)  = returnRn Nothing
986 getDeclBinders new_name (DefD _)  = returnRn Nothing
987 getDeclBinders new_name (InstD _) = returnRn Nothing
988
989 ----------------
990 getConFieldNames new_name (ConDecl con _ _ (RecCon fielddecls) src_loc : rest)
991   = mapRn (\n -> new_name n src_loc) (con:fields)       `thenRn` \ cfs ->
992     getConFieldNames new_name rest                      `thenRn` \ ns  -> 
993     returnRn (cfs ++ ns)
994   where
995     fields = concat (map fst fielddecls)
996
997 getConFieldNames new_name (ConDecl con _ _ condecl src_loc : rest)
998   = new_name con src_loc                `thenRn` \ n ->
999     (case condecl of
1000       NewCon _ (Just f) -> 
1001         new_name f src_loc `thenRn` \ new_f ->
1002         returnRn [n,new_f]
1003       _ -> returnRn [n])                `thenRn` \ nn ->
1004     getConFieldNames new_name rest      `thenRn` \ ns -> 
1005     returnRn (nn ++ ns)
1006
1007 getConFieldNames new_name [] = returnRn []
1008
1009 getClassOpNames new_name (ClassOpSig op _ _ src_loc) = new_name op src_loc
1010 \end{code}
1011
1012 @getDeclSysBinders@ gets the implicit binders introduced by a decl.
1013 A the moment that's just the tycon and datacon that come with a class decl.
1014 They aren'te returned by getDeclBinders because they aren't in scope;
1015 but they *should* be put into the DeclsMap of this module.
1016
1017 \begin{code}
1018 getDeclSysBinders new_name (TyClD (ClassDecl _ cname _ sigs _ _ tname dname src_loc))
1019   = new_name dname src_loc                      `thenRn` \ datacon_name ->
1020     new_name tname src_loc                      `thenRn` \ tycon_name ->
1021     returnRn [tycon_name, datacon_name]
1022
1023 getDeclSysBinders new_name other_decl
1024   = returnRn []
1025 \end{code}
1026
1027 %*********************************************************
1028 %*                                                      *
1029 \subsection{Reading an interface file}
1030 %*                                                      *
1031 %*********************************************************
1032
1033 \begin{code}
1034 findAndReadIface :: SDoc -> Module -> RnMG (Maybe ParsedIface)
1035         -- Nothing <=> file not found, or unreadable, or illegible
1036         -- Just x  <=> successfully found and parsed 
1037
1038 findAndReadIface doc_str mod_name
1039   = traceRn trace_msg                   `thenRn_`
1040       -- we keep two maps for interface files,
1041       -- one for 'normal' ones, the other for .hi-boot files,
1042       -- hence the need to signal which kind we're interested.
1043     getModuleHiMap from_hi_boot         `thenRn` \ himap ->
1044     case (lookupFM himap (moduleUserString mod_name)) of
1045          -- Found the file
1046        Just fpath -> readIface fpath
1047          -- Hack alert!  When compiling PrelBase we have to load the
1048          -- decls for packCString# and friends; they are 'thin-air' Ids
1049          -- (see PrelInfo.lhs).  So if we don't find the HiFile we quietly
1050          -- look for a .hi-boot file instead, and use that
1051        Nothing |  not from_hi_boot && mod_name `elem` thinAirModules
1052                -> findAndReadIface doc_str (mkBootModule mod_name)
1053                | otherwise               
1054                -> traceRn (ptext SLIT("...failed"))     `thenRn_`
1055                   returnRn Nothing
1056   where
1057     hif          = moduleIfaceFlavour mod_name
1058     from_hi_boot = bootFlavour hif
1059
1060     trace_msg = sep [hsep [ptext SLIT("Reading"), 
1061                            if from_hi_boot then ptext SLIT("[boot]") else empty,
1062                            ptext SLIT("interface for"), 
1063                            pprModule mod_name <> semi],
1064                      nest 4 (ptext SLIT("reason:") <+> doc_str)]
1065 \end{code}
1066
1067 @readIface@ tries just the one file.
1068
1069 \begin{code}
1070 readIface :: String -> RnMG (Maybe ParsedIface) 
1071         -- Nothing <=> file not found, or unreadable, or illegible
1072         -- Just x  <=> successfully found and parsed 
1073 readIface file_path
1074   = ioToRnMG (hGetStringBuffer file_path)       `thenRn` \ read_result ->
1075     case read_result of
1076         Right contents    -> 
1077              case parseIface contents (mkSrcLoc (mkFastString file_path) 1) of
1078                   Failed err      -> failWithRn Nothing err 
1079                   Succeeded (PIface iface) -> 
1080                         if opt_D_show_rn_imports then
1081                            putDocRn (hcat[ptext SLIT("Read "), text file_path]) `thenRn_`
1082                            returnRn (Just iface)
1083                         else
1084                            returnRn (Just iface)
1085
1086         Left err ->
1087           if isDoesNotExistError err then
1088              returnRn Nothing
1089           else
1090              failWithRn Nothing (cannaeReadFile file_path err)
1091 \end{code}
1092
1093 %*********************************************************
1094 %*                                                       *
1095 \subsection{Utils}
1096 %*                                                       *
1097 %*********************************************************
1098
1099 @mkSearchPath@ takes a string consisting of a colon-separated list
1100 of directories and corresponding suffixes, and turns it into a list
1101 of (directory, suffix) pairs.  For example:
1102
1103 \begin{verbatim}
1104  mkSearchPath "foo%.hi:.%.p_hi:baz%.mc_hi"
1105    = [("foo",".hi"),( ".", ".p_hi"), ("baz",".mc_hi")]
1106 \begin{verbatim}
1107
1108 \begin{code}
1109 mkSearchPath :: Maybe String -> SearchPath
1110 mkSearchPath Nothing = [(".",".hi")]
1111 mkSearchPath (Just s)
1112   = go s
1113   where
1114     go "" = []
1115     go s  = 
1116       case span (/= '%') s of
1117        (dir,'%':rs) ->
1118          case span (/= ':') rs of
1119           (hisuf,_:rest) -> (dir,hisuf):go rest
1120           (hisuf,[])     -> [(dir,hisuf)]
1121 \end{code}
1122
1123 %*********************************************************
1124 %*                                                       *
1125 \subsection{Errors}
1126 %*                                                       *
1127 %*********************************************************
1128
1129 \begin{code}
1130 noIfaceErr filename
1131   = hcat [ptext SLIT("Could not find valid interface file "), 
1132           quotes (pprModule filename)]
1133
1134 cannaeReadFile file err
1135   = hcat [ptext SLIT("Failed in reading file: "), 
1136           text file, 
1137           ptext SLIT("; error="), 
1138           text (show err)]
1139
1140 getDeclErr name loc
1141   = sep [ptext SLIT("Failed to find interface decl for") <+> quotes (ppr name), 
1142          ptext SLIT("needed at") <+> ppr loc]
1143
1144 getDeclWarn name loc
1145   = sep [ptext SLIT("Failed to find (optional) interface decl for") <+> quotes (ppr name),
1146          ptext SLIT("desired at") <+> ppr loc]
1147
1148 importDeclWarn mod name loc
1149   = sep [ptext SLIT("Compiler tried to import decl from interface file with same name as module."), 
1150          ptext SLIT("(possible cause: module name clashes with interface file already in scope.)")
1151         ] $$
1152     hsep [ptext SLIT("Interface:"), quotes (pprModule mod), comma, ptext SLIT("name:"), quotes (ppr name), 
1153           comma, ptext SLIT("desired at:"), ppr loc
1154          ]
1155
1156 \end{code}