[project @ 2000-04-13 11:56:35 by simonpj]
[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, getImportedRules,
10         lookupFixity, loadHomeInterface,
11         importDecl, recordSlurp,
12         getImportVersions, getSlurped,
13
14         checkUpToDate,
15
16         getDeclBinders, getDeclSysBinders,
17         removeContext           -- removeContext probably belongs somewhere else
18     ) where
19
20 #include "HsVersions.h"
21
22 import CmdLineOpts      ( opt_NoPruneDecls, opt_IgnoreIfacePragmas )
23 import HsSyn            ( HsDecl(..), TyClDecl(..), InstDecl(..), IfaceSig(..), 
24                           HsType(..), ConDecl(..), IE(..), ConDetails(..), Sig(..),
25                           ForeignDecl(..), ForKind(..), isDynamicExtName,
26                           FixitySig(..), RuleDecl(..),
27                           isClassOpSig, Deprecation(..)
28                         )
29 import BasicTypes       ( Version, NewOrData(..), defaultFixity )
30 import RdrHsSyn         ( RdrNameHsDecl, RdrNameInstDecl, RdrNameTyClDecl, RdrNameRuleDecl,
31                           extractHsTyRdrNames, RdrNameDeprecation
32                         )
33 import RnEnv            ( mkImportedGlobalName, newImportedBinder, mkImportedGlobalFromRdrName,
34                           lookupOccRn, lookupImplicitOccRn,
35                           pprAvail,
36                           availName, availNames, addAvailToNameSet, addSysAvails,
37                           FreeVars, emptyFVs
38                         )
39 import RnMonad
40 import RnHsSyn          ( RenamedHsDecl, RenamedDeprecation )
41 import ParseIface       ( parseIface, IfaceStuff(..) )
42
43 import FiniteMap        ( FiniteMap, sizeFM, emptyFM, delFromFM, listToFM,
44                           lookupFM, addToFM, addToFM_C, addListToFM, 
45                           fmToList, elemFM, foldFM
46                         )
47 import Name             ( Name {-instance NamedThing-},
48                           nameModule, isLocallyDefined,
49                           isWiredInName, nameUnique, NamedThing(..)
50                          )
51 import Module           ( Module, moduleString, pprModule,
52                           mkVanillaModule, pprModuleName,
53                           moduleUserString, moduleName, isLocalModule,
54                           ModuleName, WhereFrom(..),
55                         )
56 import RdrName          ( RdrName, rdrNameOcc )
57 import NameSet
58 import Var              ( Id )
59 import SrcLoc           ( mkSrcLoc, SrcLoc )
60 import PrelMods         ( pREL_GHC )
61 import PrelInfo         ( cCallishTyKeys )
62 import Bag
63 import Maybes           ( MaybeErr(..), maybeToBool, orElse )
64 import ListSetOps       ( unionLists )
65 import Outputable
66 import Unique           ( Unique )
67 import StringBuffer     ( StringBuffer, hGetStringBuffer )
68 import FastString       ( mkFastString )
69 import ErrUtils         ( Message )
70 import Lex
71 import Outputable
72
73 import IO       ( isDoesNotExistError )
74 import List     ( nub )
75 \end{code}
76
77
78 %*********************************************************
79 %*                                                      *
80 \subsection{Loading a new interface file}
81 %*                                                      *
82 %*********************************************************
83
84 \begin{code}
85 loadHomeInterface :: SDoc -> Name -> RnM d Ifaces
86 loadHomeInterface doc_str name
87   = loadInterface doc_str (moduleName (nameModule name)) ImportBySystem         `thenRn` \ (_, ifaces) ->
88     returnRn ifaces
89
90 loadOrphanModules :: [ModuleName] -> RnM d ()
91 loadOrphanModules mods
92   | null mods = returnRn ()
93   | otherwise = traceRn (text "Loading orphan modules:" <+> fsep (map pprModuleName mods))      `thenRn_` 
94                 mapRn_ load mods        `thenRn_`
95                 returnRn ()
96   where
97     load mod = loadInterface (pprModuleName mod <+> ptext SLIT("is a orphan-instance module")) mod ImportBySystem
98
99 loadInterface :: SDoc -> ModuleName -> WhereFrom -> RnM d (Module, Ifaces)
100 loadInterface doc_str mod_name from
101  = getIfacesRn                  `thenRn` \ ifaces ->
102    let
103         mod_map  = iImpModInfo ifaces
104         mod_info = lookupFM mod_map mod_name
105
106         hi_boot_file = case from of {
107                          ImportByUser       -> False ;          -- Not hi-boot
108                          ImportByUserSource -> True ;           -- hi-boot
109                          ImportBySystem     -> 
110                        case mod_info of
111                          Just (_, _, is_boot, _) -> is_boot
112
113                          Nothing -> False
114                                 -- We're importing a module we know absolutely
115                                 -- nothing about, so we assume it's from
116                                 -- another package, where we aren't doing 
117                                 -- dependency tracking. So it won't be a hi-boot file.
118                        }
119         redundant_source_import 
120           = case (from, mod_info) of 
121                 (ImportByUserSource, Just (_,_,False,_)) -> True
122                 other                                    -> False
123    in
124         -- CHECK WHETHER WE HAVE IT ALREADY
125    case mod_info of {
126         Just (_, _, _, Just (load_mod, _, _))
127                 ->      -- We're read it already so don't re-read it
128                     returnRn (load_mod, ifaces) ;
129
130         _ ->
131
132         -- Issue a warning for a redundant {- SOURCE -} import
133         -- NB that we arrange to read all the ordinary imports before 
134         -- any of the {- SOURCE -} imports
135    warnCheckRn  (not redundant_source_import)
136                 (warnRedundantSourceImport mod_name)    `thenRn_`
137
138         -- READ THE MODULE IN
139    findAndReadIface doc_str mod_name hi_boot_file   `thenRn` \ read_result ->
140    case read_result of {
141         Nothing ->      -- Not found, so add an empty export env to the Ifaces map
142                         -- so that we don't look again
143            let
144                 mod         = mkVanillaModule mod_name
145                 new_mod_map = addToFM mod_map mod_name (0, False, False, Just (mod, from, []))
146                 new_ifaces  = ifaces { iImpModInfo = new_mod_map }
147            in
148            setIfacesRn new_ifaces               `thenRn_`
149            failWithRn (mod, new_ifaces) (noIfaceErr mod hi_boot_file) ;
150
151         -- Found and parsed!
152         Just iface ->
153
154         -- LOAD IT INTO Ifaces
155
156         -- NB: *first* we do loadDecl, so that the provenance of all the locally-defined
157         ---    names is done correctly (notably, whether this is an .hi file or .hi-boot file).
158         --     If we do loadExport first the wrong info gets into the cache (unless we
159         --      explicitly tag each export which seems a bit of a bore)
160
161     getModuleRn                 `thenRn` \ this_mod_nm ->
162     let
163         rd_decls = pi_decls iface
164         mod      = pi_mod   iface
165     in
166         -- Sanity check.  If we're system-importing a module we know nothing at all
167         -- about, it should be from a different package to this one
168     WARN( not (maybeToBool mod_info) && 
169           case from of { ImportBySystem -> True; other -> False } &&
170           isLocalModule mod,
171           ppr mod )
172     foldlRn (loadDecl mod)            (iDecls ifaces) rd_decls                  `thenRn` \ new_decls ->
173     foldlRn (loadInstDecl mod)        (iInsts ifaces) (pi_insts iface)          `thenRn` \ new_insts ->
174     (if opt_IgnoreIfacePragmas
175         then returnRn emptyBag
176         else foldlRn (loadRule mod)   (iRules ifaces) (pi_rules iface))         `thenRn` \ new_rules ->
177     (if opt_IgnoreIfacePragmas
178         then returnRn emptyNameEnv
179         else foldlRn (loadDeprec mod) (iDeprecs ifaces) (pi_deprecs iface))     `thenRn` \ new_deprecs ->
180     foldlRn (loadFixDecl mod_name)    (iFixes ifaces) rd_decls                  `thenRn` \ new_fixities ->
181     mapRn   (loadExport this_mod_nm)  (pi_exports iface)                        `thenRn` \ avails_s ->
182     let
183         -- For an explicit user import, add to mod_map info about
184         -- the things the imported module depends on, extracted
185         -- from its usage info.
186         mod_map1 = case from of
187                         ImportByUser -> addModDeps mod (pi_usages iface) mod_map
188                         other        -> mod_map
189
190         -- Now add info about this module
191         mod_map2    = addToFM mod_map1 mod_name mod_details
192         cts         = (pi_mod iface, from, concat avails_s)
193         mod_details = (pi_vers iface, pi_orphan iface, hi_boot_file, Just cts)
194
195         new_ifaces = ifaces { iImpModInfo = mod_map2,
196                               iDecls      = new_decls,
197                               iFixes      = new_fixities,
198                               iInsts      = new_insts,
199                               iRules      = new_rules,
200                               iDeprecs    = new_deprecs }
201     in
202     setIfacesRn new_ifaces              `thenRn_`
203     returnRn (mod, new_ifaces)
204     }}
205
206 addModDeps :: Module -> [ImportVersion a] 
207            -> ImportedModuleInfo -> ImportedModuleInfo
208 -- (addModDeps M ivs deps)
209 -- We are importing module M, and M.hi contains 'import' decls given by ivs
210 addModDeps mod new_deps mod_deps
211   = foldr add mod_deps filtered_new_deps
212   where
213         -- Don't record dependencies when importing a module from another package
214         -- Except for its descendents which contain orphans,
215         -- and in that case, forget about the boot indicator
216     filtered_new_deps
217         | isLocalModule mod = [ (imp_mod, (version, has_orphans, is_boot, Nothing))
218                               | (imp_mod, version, has_orphans, is_boot, _) <- new_deps 
219                               ]                       
220         | otherwise         = [ (imp_mod, (version, True, False, Nothing))
221                               | (imp_mod, version, has_orphans, _, _) <- new_deps, 
222                                 has_orphans
223                               ]
224     add (imp_mod, dep) deps = addToFM_C combine deps imp_mod dep
225
226     combine old@(_, _, old_is_boot, cts) new
227         | maybeToBool cts || not old_is_boot = old      -- Keep the old info if it's already loaded
228                                                         -- or if it's a non-boot pending load
229         | otherwise                          = new      -- Otherwise pick new info
230
231 loadExport :: ModuleName -> ExportItem -> RnM d [AvailInfo]
232 loadExport this_mod (mod, entities)
233   | mod == this_mod = returnRn []
234         -- If the module exports anything defined in this module, just ignore it.
235         -- Reason: otherwise it looks as if there are two local definition sites
236         -- for the thing, and an error gets reported.  Easiest thing is just to
237         -- filter them out up front. This situation only arises if a module
238         -- imports itself, or another module that imported it.  (Necessarily,
239         -- this invoves a loop.)  Consequence: if you say
240         --      module A where
241         --         import B( AType )
242         --         type AType = ...
243         --
244         --      module B( AType ) where
245         --         import {-# SOURCE #-} A( AType )
246         --
247         -- then you'll get a 'B does not export AType' message.  A bit bogus
248         -- but it's a bogus thing to do!
249
250   | otherwise
251   = mapRn (load_entity mod) entities
252   where
253     new_name mod occ = mkImportedGlobalName mod occ
254
255     load_entity mod (Avail occ)
256       = new_name mod occ        `thenRn` \ name ->
257         returnRn (Avail name)
258     load_entity mod (AvailTC occ occs)
259       = new_name mod occ              `thenRn` \ name ->
260         mapRn (new_name mod) occs     `thenRn` \ names ->
261         returnRn (AvailTC name names)
262
263
264 loadFixDecl :: ModuleName -> FixityEnv
265             -> (Version, RdrNameHsDecl)
266             -> RnM d FixityEnv
267 loadFixDecl mod_name fixity_env (version, FixD sig@(FixitySig rdr_name fixity loc))
268   =     -- Ignore the version; when the fixity changes the version of
269         -- its 'host' entity changes, so we don't need a separate version
270         -- number for fixities
271     mkImportedGlobalName mod_name (rdrNameOcc rdr_name)         `thenRn` \ name ->
272     let
273         new_fixity_env = addToNameEnv fixity_env name (FixitySig name fixity loc)
274     in
275     returnRn new_fixity_env
276
277         -- Ignore the other sorts of decl
278 loadFixDecl mod_name fixity_env other_decl = returnRn fixity_env
279
280 loadDecl :: Module 
281          -> DeclsMap
282          -> (Version, RdrNameHsDecl)
283          -> RnM d DeclsMap
284
285 loadDecl mod decls_map (version, decl)
286   = getDeclBinders new_name decl        `thenRn` \ maybe_avail ->
287     case maybe_avail of {
288         Nothing -> returnRn decls_map;  -- No bindings
289         Just avail ->
290
291     getDeclSysBinders new_name decl     `thenRn` \ sys_bndrs ->
292     let
293         full_avail    = addSysAvails avail sys_bndrs
294                 -- Add the sys-binders to avail.  When we import the decl,
295                 -- it's full_avail that will get added to the 'already-slurped' set (iSlurp)
296                 -- If we miss out sys-binders, we'll read the decl multiple times!
297
298         main_name     = availName avail
299         new_decls_map = foldl add_decl decls_map
300                                        [ (name, (version, full_avail, name==main_name, (mod, decl'))) 
301                                        | name <- availNames full_avail]
302         add_decl decls_map (name, stuff)
303           = WARN( name `elemNameEnv` decls_map, ppr name )
304             addToNameEnv decls_map name stuff
305     in
306     returnRn new_decls_map
307     }
308   where
309         -- newImportedBinder puts into the cache the binder with the
310         -- module information set correctly.  When the decl is later renamed,
311         -- the binding site will thereby get the correct module.
312     new_name rdr_name loc = newImportedBinder mod rdr_name
313
314     {-
315       If a signature decl is being loaded, and optIgnoreIfacePragmas is on,
316       we toss away unfolding information.
317
318       Also, if the signature is loaded from a module we're importing from source,
319       we do the same. This is to avoid situations when compiling a pair of mutually
320       recursive modules, peering at unfolding info in the interface file of the other, 
321       e.g., you compile A, it looks at B's interface file and may as a result change
322       its interface file. Hence, B is recompiled, maybe changing its interface file,
323       which will the unfolding info used in A to become invalid. Simple way out is to
324       just ignore unfolding info.
325
326       [Jan 99: I junked the second test above.  If we're importing from an hi-boot
327        file there isn't going to *be* any pragma info.  Maybe the above comment
328        dates from a time where we picked up a .hi file first if it existed?]
329     -}
330     decl' = case decl of
331                SigD (IfaceSig name tp ls loc) | opt_IgnoreIfacePragmas
332                          ->  SigD (IfaceSig name tp [] loc)
333                other     -> decl
334
335 loadInstDecl :: Module
336              -> Bag GatedDecl
337              -> RdrNameInstDecl
338              -> RnM d (Bag GatedDecl)
339 loadInstDecl mod insts decl@(InstDecl inst_ty binds uprags dfun_name src_loc)
340   = 
341         -- Find out what type constructors and classes are "gates" for the
342         -- instance declaration.  If all these "gates" are slurped in then
343         -- we should slurp the instance decl too.
344         -- 
345         -- We *don't* want to count names in the context part as gates, though.
346         -- For example:
347         --              instance Foo a => Baz (T a) where ...
348         --
349         -- Here the gates are Baz and T, but *not* Foo.
350     let 
351         munged_inst_ty = removeContext inst_ty
352         free_names     = extractHsTyRdrNames munged_inst_ty
353     in
354     setModuleRn (moduleName mod) $
355     mapRn mkImportedGlobalFromRdrName free_names        `thenRn` \ gate_names ->
356     returnRn ((mkNameSet gate_names, (mod, InstD decl)) `consBag` insts)
357
358
359 -- In interface files, the instance decls now look like
360 --      forall a. Foo a -> Baz (T a)
361 -- so we have to strip off function argument types as well
362 -- as the bit before the '=>' (which is always empty in interface files)
363 removeContext (HsForAllTy tvs cxt ty) = HsForAllTy tvs [] (removeFuns ty)
364 removeContext ty                      = removeFuns ty
365
366 removeFuns (MonoFunTy _ ty) = removeFuns ty
367 removeFuns ty               = ty
368
369
370 loadRule :: Module -> Bag GatedDecl 
371          -> RdrNameRuleDecl -> RnM d (Bag GatedDecl)
372 -- "Gate" the rule simply by whether the rule variable is
373 -- needed.  We can refine this later.
374 loadRule mod rules decl@(IfaceRuleDecl var body src_loc)
375   = setModuleRn (moduleName mod) $
376     mkImportedGlobalFromRdrName var             `thenRn` \ var_name ->
377     returnRn ((unitNameSet var_name, (mod, RuleD decl)) `consBag` rules)
378
379 -- SUP: TEMPORARY HACK, ignoring module deprecations for now
380 loadDeprec :: Module -> DeprecationEnv -> RdrNameDeprecation -> RnM d DeprecationEnv
381 loadDeprec mod deprec_env (Deprecation (IEModuleContents _) txt)
382   = traceRn (text "module deprecation not yet implemented:" <+> ppr mod <> colon <+> ppr txt) `thenRn_`
383     returnRn deprec_env
384 loadDeprec mod deprec_env (Deprecation ie txt)
385   = setModuleRn (moduleName mod) $
386     mapRn mkImportedGlobalFromRdrName (namesFromIE ie) `thenRn` \ names ->
387     traceRn (text "loaded deprecation(s) for" <+> hcat (punctuate comma (map ppr names)) <> colon <+> ppr txt) `thenRn_`
388     returnRn (extendNameEnv deprec_env (zip names (repeat txt)))
389
390 namesFromIE :: IE a -> [a]
391 namesFromIE (IEVar            n   ) = [n]
392 namesFromIE (IEThingAbs       n   ) = [n]
393 namesFromIE (IEThingAll       n   ) = [n]
394 namesFromIE (IEThingWith      n ns) = n:ns
395 namesFromIE (IEModuleContents _   ) = []
396 \end{code}
397
398
399 %********************************************************
400 %*                                                      *
401 \subsection{Loading usage information}
402 %*                                                      *
403 %********************************************************
404
405 \begin{code}
406 upToDate  = True
407 outOfDate = False
408
409 checkUpToDate :: ModuleName -> RnMG Bool        -- True <=> no need to recompile
410         -- When this guy is called, we already know that the
411         -- source code is unchanged from last time
412 checkUpToDate mod_name
413   = getIfacesRn                                 `thenRn` \ ifaces ->
414     findAndReadIface doc_str mod_name 
415                      False {- Not hi-boot -}    `thenRn` \ read_result ->
416
417         -- CHECK WHETHER WE HAVE IT ALREADY
418     case read_result of
419         Nothing ->      -- Old interface file not found, so we'd better bail out
420                     traceRn (sep [ptext SLIT("Didnt find old iface"), 
421                                   pprModuleName mod_name])      `thenRn_`
422                     returnRn outOfDate
423
424         Just iface
425                 ->      -- Found it, so now check it
426                     checkModUsage (pi_usages iface)
427   where
428         -- Only look in current directory, with suffix .hi
429     doc_str = sep [ptext SLIT("need usage info from"), pprModuleName mod_name]
430
431 checkModUsage [] = returnRn upToDate            -- Yes!  Everything is up to date!
432
433 checkModUsage ((mod_name, old_mod_vers, _, _, Specifically []) : rest)
434         -- If CurrentModule.hi contains 
435         --      import Foo :: ;
436         -- then that simply records that Foo lies below CurrentModule in the
437         -- hierarchy, but CurrentModule doesn't depend in any way on Foo.
438         -- In this case we don't even want to open Foo's interface.
439   = traceRn (ptext SLIT("Nothing used from:") <+> ppr mod_name) `thenRn_`
440     checkModUsage rest  -- This one's ok, so check the rest
441
442 checkModUsage ((mod_name, old_mod_vers, _, _, whats_imported)  : rest)
443   = loadInterface doc_str mod_name ImportBySystem       `thenRn` \ (mod, ifaces) ->
444     let
445         maybe_mod_vers = case lookupFM (iImpModInfo ifaces) mod_name of
446                            Just (version, _, _, Just (_, _, _)) -> Just version
447                            other                                -> Nothing
448     in
449     case maybe_mod_vers of {
450         Nothing ->      -- If we can't find a version number for the old module then
451                         -- bail out saying things aren't up to date
452                 traceRn (sep [ptext SLIT("Can't find version number for module"), 
453                               pprModuleName mod_name])
454                 `thenRn_` returnRn outOfDate ;
455
456         Just new_mod_vers ->
457
458         -- If the module version hasn't changed, just move on
459     if new_mod_vers == old_mod_vers then
460         traceRn (sep [ptext SLIT("Module version unchanged:"), pprModuleName mod_name])
461         `thenRn_` checkModUsage rest
462     else
463     traceRn (sep [ptext SLIT("Module version has changed:"), pprModuleName mod_name])
464     `thenRn_`
465         -- Module version changed, so check entities inside
466
467         -- If the usage info wants to say "I imported everything from this module"
468         --     it does so by making whats_imported equal to Everything
469         -- In that case, we must recompile
470     case whats_imported of {
471       Everything -> traceRn (ptext SLIT("...and I needed the whole module"))    `thenRn_`
472                     returnRn outOfDate;            -- Bale out
473
474       Specifically old_local_vers ->
475
476         -- Non-empty usage list, so check item by item
477     checkEntityUsage mod_name (iDecls ifaces) old_local_vers    `thenRn` \ up_to_date ->
478     if up_to_date then
479         traceRn (ptext SLIT("...but the bits I use haven't."))  `thenRn_`
480         checkModUsage rest      -- This one's ok, so check the rest
481     else
482         returnRn outOfDate              -- This one failed, so just bail out now
483     }}
484   where
485     doc_str = sep [ptext SLIT("need version info for"), pprModuleName mod_name]
486
487
488 checkEntityUsage mod decls [] 
489   = returnRn upToDate   -- Yes!  All up to date!
490
491 checkEntityUsage mod decls ((occ_name,old_vers) : rest)
492   = mkImportedGlobalName mod occ_name   `thenRn` \ name ->
493     case lookupNameEnv decls name of
494
495         Nothing       ->        -- We used it before, but it ain't there now
496                           traceRn (sep [ptext SLIT("No longer exported:"), ppr name])
497                           `thenRn_` returnRn outOfDate
498
499         Just (new_vers,_,_,_)   -- It's there, but is it up to date?
500                 | new_vers == old_vers
501                         -- Up to date, so check the rest
502                 -> checkEntityUsage mod decls rest
503
504                 | otherwise
505                         -- Out of date, so bale out
506                 -> traceRn (sep [ptext SLIT("Out of date:"), ppr name])  `thenRn_`
507                    returnRn outOfDate
508 \end{code}
509
510
511 %*********************************************************
512 %*                                                      *
513 \subsection{Getting in a declaration}
514 %*                                                      *
515 %*********************************************************
516
517 \begin{code}
518 importDecl :: Name -> RnMG (Maybe (Module, RdrNameHsDecl))
519         -- Returns Nothing for 
520         --      (a) wired in name
521         --      (b) local decl
522         --      (c) already slurped
523
524 importDecl name
525   | isWiredInName name
526   = returnRn Nothing
527   | otherwise
528   = getSlurped                          `thenRn` \ already_slurped ->
529     if name `elemNameSet` already_slurped then
530         returnRn Nothing        -- Already dealt with
531     else
532         if isLocallyDefined name then   -- Don't bring in decls from
533                                         -- the renamed module's own interface file
534                   addWarnRn (importDeclWarn name) `thenRn_`
535                   returnRn Nothing
536         else
537         getNonWiredInDecl name
538 \end{code}
539
540 \begin{code}
541 getNonWiredInDecl :: Name -> RnMG (Maybe (Module, RdrNameHsDecl))
542 getNonWiredInDecl needed_name 
543   = traceRn doc_str                             `thenRn_`
544     loadHomeInterface doc_str needed_name       `thenRn` \ ifaces ->
545     case lookupNameEnv (iDecls ifaces) needed_name of
546
547       Just (version,avail,_,decl)
548         -> recordSlurp (Just version) avail     `thenRn_`
549            returnRn (Just decl)
550
551       Nothing           -- Can happen legitimately for "Optional" occurrences
552         -> addErrRn (getDeclErr needed_name)    `thenRn_` 
553            returnRn Nothing
554   where
555      doc_str = ptext SLIT("need decl for") <+> ppr needed_name
556 \end{code}
557
558 @getWiredInDecl@ maps a wired-in @Name@ to what it makes available.
559 It behaves exactly as if the wired in decl were actually in an interface file.
560 Specifically,
561 \begin{itemize}
562 \item   if the wired-in name is a data type constructor or a data constructor, 
563         it brings in the type constructor and all the data constructors; and
564         marks as ``occurrences'' any free vars of the data con.
565
566 \item   similarly for synonum type constructor
567
568 \item   if the wired-in name is another wired-in Id, it marks as ``occurrences''
569         the free vars of the Id's type.
570
571 \item   it loads the interface file for the wired-in thing for the
572         sole purpose of making sure that its instance declarations are available
573 \end{itemize}
574 All this is necessary so that we know all types that are ``in play'', so
575 that we know just what instances to bring into scope.
576         
577
578
579     
580 %*********************************************************
581 %*                                                      *
582 \subsection{Getting what a module exports}
583 %*                                                      *
584 %*********************************************************
585
586 @getInterfaceExports@ is called only for directly-imported modules.
587
588 \begin{code}
589 getInterfaceExports :: ModuleName -> WhereFrom -> RnMG (Module, Avails)
590 getInterfaceExports mod_name from
591   = loadInterface doc_str mod_name from `thenRn` \ (mod, ifaces) ->
592     case lookupFM (iImpModInfo ifaces) mod_name of
593         Nothing -> -- Not there; it must be that the interface file wasn't found;
594                    -- the error will have been reported already.
595                    -- (Actually loadInterface should put the empty export env in there
596                    --  anyway, but this does no harm.)
597                    returnRn (mod, [])
598
599         Just (_, _, _, Just (mod, _, avails)) -> returnRn (mod, avails)
600   where
601     doc_str = sep [pprModuleName mod_name, ptext SLIT("is directly imported")]
602 \end{code}
603
604
605 %*********************************************************
606 %*                                                      *
607 \subsection{Instance declarations are handled specially}
608 %*                                                      *
609 %*********************************************************
610
611 \begin{code}
612 getImportedInstDecls :: NameSet -> RnMG [(Module,RdrNameHsDecl)]
613 getImportedInstDecls gates
614   =     -- First, load any orphan-instance modules that aren't aready loaded
615         -- Orphan-instance modules are recorded in the module dependecnies
616     getIfacesRn                                         `thenRn` \ ifaces ->
617     let
618         orphan_mods =
619           [mod | (mod, (_, True, _, Nothing)) <- fmToList (iImpModInfo ifaces)]
620     in
621     loadOrphanModules orphan_mods                       `thenRn_` 
622
623         -- Now we're ready to grab the instance declarations
624         -- Find the un-gated ones and return them, 
625         -- removing them from the bag kept in Ifaces
626     getIfacesRn                                         `thenRn` \ ifaces ->
627     let
628         (decls, new_insts) = selectGated gates (iInsts ifaces)
629     in
630     setIfacesRn (ifaces { iInsts = new_insts })         `thenRn_`
631
632     traceRn (sep [text "getImportedInstDecls:", 
633                   nest 4 (fsep (map ppr gate_list)),
634                   text "Slurped" <+> int (length decls) <+> text "instance declarations",
635                   nest 4 (vcat (map ppr_brief_inst_decl decls))])       `thenRn_`
636     returnRn decls
637   where
638     gate_list      = nameSetToList gates
639
640 ppr_brief_inst_decl (mod, InstD (InstDecl inst_ty _ _ _ _))
641   = case inst_ty of
642         HsForAllTy _ _ tau -> ppr tau
643         other              -> ppr inst_ty
644
645 getImportedRules :: RnMG [(Module,RdrNameHsDecl)]
646 getImportedRules 
647   | opt_IgnoreIfacePragmas = returnRn []
648   | otherwise
649   = getIfacesRn         `thenRn` \ ifaces ->
650     let
651         gates              = iSlurp ifaces      -- Anything at all that's been slurped
652         (decls, new_rules) = selectGated gates (iRules ifaces)
653     in
654     setIfacesRn (ifaces { iRules = new_rules })         `thenRn_`
655     traceRn (sep [text "getImportedRules:", 
656                   text "Slurped" <+> int (length decls) <+> text "rules"])      `thenRn_`
657     returnRn decls
658
659 selectGated gates decl_bag
660         -- Select only those decls whose gates are *all* in 'gates'
661 #ifdef DEBUG
662   | opt_NoPruneDecls    -- Just to try the effect of not gating at all
663   = (foldrBag (\ (_,d) ds -> d:ds) [] decl_bag, emptyBag)       -- Grab them all
664
665   | otherwise
666 #endif
667   = foldrBag select ([], emptyBag) decl_bag
668   where
669     select (reqd, decl) (yes, no)
670         | isEmptyNameSet (reqd `minusNameSet` gates) = (decl:yes, no)
671         | otherwise                                  = (yes,      (reqd,decl) `consBag` no)
672
673 lookupFixity :: Name -> RnMS Fixity
674 lookupFixity name
675   | isLocallyDefined name
676   = getFixityEnv                        `thenRn` \ local_fix_env ->
677     case lookupNameEnv local_fix_env name of 
678         Just (FixitySig _ fix _) -> returnRn fix
679         Nothing                  -> returnRn defaultFixity
680
681   | otherwise   -- Imported
682       -- For imported names, we have to get their fixities by doing a loadHomeInterface,
683       -- and consulting the Ifaces that comes back from that, because the interface
684       -- file for the Name might not have been loaded yet.  Why not?  Suppose you import module A,
685       -- which exports a function 'f', which is defined in module B.  Then B isn't loaded
686       -- right away (after all, it's possible that nothing from B will be used).
687       -- When we come across a use of 'f', we need to know its fixity, and it's then,
688       -- and only then, that we load B.hi.  That is what's happening here.
689   = loadHomeInterface doc name          `thenRn` \ ifaces ->
690     case lookupNameEnv (iFixes ifaces) name of
691         Just (FixitySig _ fix _) -> returnRn fix 
692         Nothing                  -> returnRn defaultFixity
693   where
694     doc = ptext SLIT("Checking fixity for") <+> ppr name
695 \end{code}
696
697
698 %*********************************************************
699 %*                                                      *
700 \subsection{Keeping track of what we've slurped, and version numbers}
701 %*                                                      *
702 %*********************************************************
703
704 getImportVersions figures out what the ``usage information'' for this
705 moudule is; that is, what it must record in its interface file as the
706 things it uses.  It records:
707
708 \begin{itemize}
709 \item   (a) anything reachable from its body code
710 \item   (b) any module exported with a @module Foo@
711 \item   (c) anything reachable from an exported item
712 \end{itemize}
713
714 Why (b)?  Because if @Foo@ changes then this module's export list
715 will change, so we must recompile this module at least as far as
716 making a new interface file --- but in practice that means complete
717 recompilation.
718
719 Why (c)?  Consider this:
720 \begin{verbatim}
721         module A( f, g ) where  |       module B( f ) where
722           import B( f )         |         f = h 3
723           g = ...               |         h = ...
724 \end{verbatim}
725
726 Here, @B.f@ isn't used in A.  Should we nevertheless record @B.f@ in
727 @A@'s usages?  Our idea is that we aren't going to touch A.hi if it is
728 *identical* to what it was before.  If anything about @B.f@ changes
729 than anyone who imports @A@ should be recompiled in case they use
730 @B.f@ (they'll get an early exit if they don't).  So, if anything
731 about @B.f@ changes we'd better make sure that something in A.hi
732 changes, and the convenient way to do that is to record the version
733 number @B.f@ in A.hi in the usage list.  If B.f changes that'll force a
734 complete recompiation of A, which is overkill but it's the only way to 
735 write a new, slightly different, A.hi.
736
737 But the example is tricker.  Even if @B.f@ doesn't change at all,
738 @B.h@ may do so, and this change may not be reflected in @f@'s version
739 number.  But with -O, a module that imports A must be recompiled if
740 @B.h@ changes!  So A must record a dependency on @B.h@.  So we treat
741 the occurrence of @B.f@ in the export list *just as if* it were in the
742 code of A, and thereby haul in all the stuff reachable from it.
743
744 [NB: If B was compiled with -O, but A isn't, we should really *still*
745 haul in all the unfoldings for B, in case the module that imports A *is*
746 compiled with -O.  I think this is the case.]
747
748 Even if B is used at all we get a usage line for B
749         import B <n> :: ... ;
750 in A.hi, to record the fact that A does import B.  This is used to decide
751 to look to look for B.hi rather than B.hi-boot when compiling a module that
752 imports A.  This line says that A imports B, but uses nothing in it.
753 So we'll get an early bale-out when compiling A if B's version changes.
754
755 \begin{code}
756 getImportVersions :: ModuleName                 -- Name of this module
757                   -> ExportEnv                  -- Info about exports 
758                   -> RnMG (VersionInfo Name)    -- Version info for these names
759
760 getImportVersions this_mod (ExportEnv _ _ export_all_mods)
761   = getIfacesRn                                 `thenRn` \ ifaces ->
762     let
763         mod_map   = iImpModInfo ifaces
764         imp_names = iVSlurp     ifaces
765
766         -- mv_map groups together all the things imported from a particular module.
767         mv_map :: FiniteMap ModuleName [(Name,Version)]
768         mv_map = foldr add_mv emptyFM imp_names
769
770         -- Build the result list by adding info for each module.
771         -- For (a) a library module, we don't record it at all unless it contains orphans
772         --         (We must never lose track of orphans.)
773         -- 
774         --     (b) a source-imported module, don't record the dependency at all
775         --      
776         -- (b) may seem a bit strange.  The idea is that the usages in a .hi file records
777         -- *all* the module's dependencies other than the loop-breakers.  We use
778         -- this info in findAndReadInterface to decide whether to look for a .hi file or
779         -- a .hi-boot file.  
780         --
781         -- This means we won't track version changes, or orphans, from .hi-boot files.
782         -- The former is potentially rather bad news.  It could be fixed by recording
783         -- whether something is a boot file along with the usage info for it, but 
784         -- I can't be bothered just now.
785
786         mk_version_info mod_name (version, has_orphans, is_boot, contents) so_far
787            | mod_name == this_mod       -- Check if M appears in the set of modules 'below' M
788                                         -- This seems like a convenient place to check
789            = WARN( not is_boot, ptext SLIT("Wierd:") <+> ppr this_mod <+> 
790                                 ptext SLIT("imports itself (perhaps indirectly)") )
791              so_far
792  
793            | otherwise
794            = let
795                 go_for_it exports = (mod_name, version, has_orphans, is_boot, exports) 
796                                     : so_far
797              in 
798              case contents of
799                 Nothing ->      -- We didn't even open the interface
800                         -- This happens when a module, Foo, that we explicitly imported has 
801                         -- 'import Baz' in its interface file, recording that Baz is below
802                         -- Foo in the module dependency hierarchy.  We want to propagate this
803                         -- information.  The Nothing says that we didn't even open the interface
804                         -- file but we must still propagate the dependeny info.
805                         -- The module in question must be a local module (in the same package)
806                    go_for_it (Specifically [])
807
808                 Just (mod, how_imported, _)
809                    |  is_sys_import && is_lib_module && not has_orphans
810                    -> so_far            
811            
812                    |  is_lib_module                     -- Record the module but not detailed
813                    || mod_name `elem` export_all_mods   -- version information for the imports
814                    -> go_for_it Everything
815
816                    |  otherwise
817                    -> case lookupFM mv_map mod_name of
818                         Just whats_imported -> go_for_it (Specifically whats_imported)
819                         Nothing             -> go_for_it (Specifically [])
820                                                 -- This happens if you have
821                                                 --      import Foo
822                                                 -- but don't actually *use* anything from Foo
823                                                 -- In which case record an empty dependency list
824                    where
825                      is_lib_module = not (isLocalModule mod)
826                      is_sys_import = case how_imported of
827                                         ImportBySystem -> True
828                                         other          -> False
829              
830     in
831
832     returnRn (foldFM mk_version_info [] mod_map)
833   where
834      add_mv v@(name, version) mv_map
835       = addToFM_C add_item mv_map mod [v] 
836       where
837          mod = moduleName (nameModule name)
838          add_item vs _ = (v:vs)
839 \end{code}
840
841 \begin{code}
842 getSlurped
843   = getIfacesRn         `thenRn` \ ifaces ->
844     returnRn (iSlurp ifaces)
845
846 recordSlurp maybe_version avail
847 -- Nothing      for locally defined names
848 -- Just version for imported names
849   = getIfacesRn         `thenRn` \ ifaces@(Ifaces { iSlurp  = slurped_names,
850                                                     iVSlurp = imp_names }) ->
851     let
852         new_slurped_names = addAvailToNameSet slurped_names avail
853
854         new_imp_names = case maybe_version of
855                            Just version -> (availName avail, version) : imp_names
856                            Nothing      -> imp_names
857     in
858     setIfacesRn (ifaces { iSlurp  = new_slurped_names,
859                           iVSlurp = new_imp_names })
860 \end{code}
861
862
863 %*********************************************************
864 %*                                                      *
865 \subsection{Getting binders out of a declaration}
866 %*                                                      *
867 %*********************************************************
868
869 @getDeclBinders@ returns the names for a @RdrNameHsDecl@.
870 It's used for both source code (from @availsFromDecl@) and interface files
871 (from @loadDecl@).
872
873 It doesn't deal with source-code specific things: @ValD@, @DefD@.  They
874 are handled by the sourc-code specific stuff in @RnNames@.
875
876 \begin{code}
877 getDeclBinders :: (RdrName -> SrcLoc -> RnM d Name)     -- New-name function
878                 -> RdrNameHsDecl
879                 -> RnM d (Maybe AvailInfo)
880
881 getDeclBinders new_name (TyClD (TyData _ _ tycon _ condecls _ _ src_loc))
882   = new_name tycon src_loc                      `thenRn` \ tycon_name ->
883     getConFieldNames new_name condecls          `thenRn` \ sub_names ->
884     returnRn (Just (AvailTC tycon_name (tycon_name : nub sub_names)))
885         -- The "nub" is because getConFieldNames can legitimately return duplicates,
886         -- when a record declaration has the same field in multiple constructors
887
888 getDeclBinders new_name (TyClD (TySynonym tycon _ _ src_loc))
889   = new_name tycon src_loc              `thenRn` \ tycon_name ->
890     returnRn (Just (AvailTC tycon_name [tycon_name]))
891
892 getDeclBinders new_name (TyClD (ClassDecl _ cname _ _ sigs _ _ _ _ _ _ src_loc))
893   = new_name cname src_loc                      `thenRn` \ class_name ->
894
895         -- Record the names for the class ops
896     let
897         -- just want class-op sigs
898         op_sigs = filter isClassOpSig sigs
899     in
900     mapRn (getClassOpNames new_name) op_sigs    `thenRn` \ sub_names ->
901
902     returnRn (Just (AvailTC class_name (class_name : sub_names)))
903
904 getDeclBinders new_name (SigD (IfaceSig var ty prags src_loc))
905   = new_name var src_loc                        `thenRn` \ var_name ->
906     returnRn (Just (Avail var_name))
907
908 getDeclBinders new_name (FixD _)  = returnRn Nothing
909
910     -- foreign declarations
911 getDeclBinders new_name (ForD (ForeignDecl nm kind _ dyn _ loc))
912   | binds_haskell_name kind dyn
913   = new_name nm loc                 `thenRn` \ name ->
914     returnRn (Just (Avail name))
915
916   | otherwise -- a foreign export
917   = lookupImplicitOccRn nm `thenRn_` 
918     returnRn Nothing
919
920 getDeclBinders new_name (DefD _)  = returnRn Nothing
921 getDeclBinders new_name (InstD _) = returnRn Nothing
922 getDeclBinders new_name (RuleD _) = returnRn Nothing
923
924 binds_haskell_name (FoImport _) _   = True
925 binds_haskell_name FoLabel      _   = True
926 binds_haskell_name FoExport  ext_nm = isDynamicExtName ext_nm
927
928 ----------------
929 getConFieldNames new_name (ConDecl con _ _ _ (RecCon fielddecls) src_loc : rest)
930   = mapRn (\n -> new_name n src_loc) (con:fields)       `thenRn` \ cfs ->
931     getConFieldNames new_name rest                      `thenRn` \ ns  -> 
932     returnRn (cfs ++ ns)
933   where
934     fields = concat (map fst fielddecls)
935
936 getConFieldNames new_name (ConDecl con _ _ _ condecl src_loc : rest)
937   = new_name con src_loc                `thenRn` \ n ->
938     (case condecl of
939       NewCon _ (Just f) -> 
940         new_name f src_loc `thenRn` \ new_f ->
941         returnRn [n,new_f]
942       _ -> returnRn [n])                `thenRn` \ nn ->
943     getConFieldNames new_name rest      `thenRn` \ ns -> 
944     returnRn (nn ++ ns)
945
946 getConFieldNames new_name [] = returnRn []
947
948 getClassOpNames new_name (ClassOpSig op _ _ _ src_loc) = new_name op src_loc
949 \end{code}
950
951 @getDeclSysBinders@ gets the implicit binders introduced by a decl.
952 A the moment that's just the tycon and datacon that come with a class decl.
953 They aren't returned by @getDeclBinders@ because they aren't in scope;
954 but they {\em should} be put into the @DeclsMap@ of this module.
955
956 Note that this excludes the default-method names of a class decl,
957 and the dict fun of an instance decl, because both of these have 
958 bindings of their own elsewhere.
959
960 \begin{code}
961 getDeclSysBinders new_name (TyClD (ClassDecl _ cname _ _ sigs _ _ tname dname dwname snames src_loc))
962   = sequenceRn [new_name n src_loc | n <- (tname : dname : dwname : snames)]
963
964 getDeclSysBinders new_name (TyClD (TyData _ _ _ _ cons _ _ _))
965   = sequenceRn [new_name wkr_name src_loc | ConDecl _ wkr_name _ _ _ src_loc <- cons]
966
967 getDeclSysBinders new_name other_decl
968   = returnRn []
969 \end{code}
970
971 %*********************************************************
972 %*                                                      *
973 \subsection{Reading an interface file}
974 %*                                                      *
975 %*********************************************************
976
977 \begin{code}
978 findAndReadIface :: SDoc -> ModuleName 
979                  -> IsBootInterface     -- True  <=> Look for a .hi-boot file
980                                         -- False <=> Look for .hi file
981                  -> RnM d (Maybe ParsedIface)
982         -- Nothing <=> file not found, or unreadable, or illegible
983         -- Just x  <=> successfully found and parsed 
984
985 findAndReadIface doc_str mod_name hi_boot_file
986   = traceRn trace_msg                   `thenRn_`
987       -- we keep two maps for interface files,
988       -- one for 'normal' ones, the other for .hi-boot files,
989       -- hence the need to signal which kind we're interested.
990
991     getHiMaps                   `thenRn` \ (hi_map, hiboot_map) ->
992     let
993         relevant_map | hi_boot_file = hiboot_map
994                      | otherwise    = hi_map
995     in  
996     case lookupFM relevant_map mod_name of
997         -- Found the file
998       Just fpath -> traceRn (ptext SLIT("...reading from") <+> text fpath)      `thenRn_`
999                     readIface mod_name fpath
1000         
1001         -- Can't find it
1002       Nothing    -> traceRn (ptext SLIT("...not found"))        `thenRn_`
1003                     returnRn Nothing
1004   where
1005     trace_msg = sep [hsep [ptext SLIT("Reading"), 
1006                            if hi_boot_file then ptext SLIT("[boot]") else empty,
1007                            ptext SLIT("interface for"), 
1008                            pprModuleName mod_name <> semi],
1009                      nest 4 (ptext SLIT("reason:") <+> doc_str)]
1010 \end{code}
1011
1012 @readIface@ tries just the one file.
1013
1014 \begin{code}
1015 readIface :: ModuleName -> String -> RnM d (Maybe ParsedIface)
1016         -- Nothing <=> file not found, or unreadable, or illegible
1017         -- Just x  <=> successfully found and parsed 
1018 readIface wanted_mod file_path
1019   = ioToRnM (hGetStringBuffer False file_path)       `thenRn` \ read_result ->
1020     case read_result of
1021         Right contents    -> 
1022              case parseIface contents
1023                         PState{ bol = 0#, atbol = 1#,
1024                                 context = [],
1025                                 glasgow_exts = 1#,
1026                                 loc = mkSrcLoc (mkFastString file_path) 1 } of
1027                   POk _  (PIface iface) ->
1028                       warnCheckRn (read_mod == wanted_mod)
1029                                   (hiModuleNameMismatchWarn wanted_mod read_mod) `thenRn_`
1030                       returnRn (Just iface)
1031                     where
1032                       read_mod = moduleName (pi_mod iface)
1033
1034                   PFailed err   -> failWithRn Nothing err 
1035                   other         -> failWithRn Nothing (ptext SLIT("Unrecognisable interface file"))
1036                                 -- This last case can happen if the interface file is (say) empty
1037                                 -- in which case the parser thinks it looks like an IdInfo or
1038                                 -- something like that.  Just an artefact of the fact that the
1039                                 -- parser is used for several purposes at once.
1040
1041         Left err
1042           | isDoesNotExistError err -> returnRn Nothing
1043           | otherwise               -> failWithRn Nothing (cannaeReadFile file_path err)
1044 \end{code}
1045
1046 %*********************************************************
1047 %*                                                       *
1048 \subsection{Errors}
1049 %*                                                       *
1050 %*********************************************************
1051
1052 \begin{code}
1053 noIfaceErr filename boot_file
1054   = hsep [ptext SLIT("Could not find valid"), boot, 
1055           ptext SLIT("interface file"), quotes (pprModule filename)]
1056   where
1057     boot | boot_file = ptext SLIT("[boot]")
1058          | otherwise = empty
1059
1060 cannaeReadFile file err
1061   = hcat [ptext SLIT("Failed in reading file: "), 
1062           text file, 
1063           ptext SLIT("; error="), 
1064           text (show err)]
1065
1066 getDeclErr name
1067   = vcat [ptext SLIT("Failed to find interface decl for") <+> quotes (ppr name),
1068           ptext SLIT("from module") <+> quotes (ppr (nameModule name))
1069          ]
1070
1071 getDeclWarn name loc
1072   = sep [ptext SLIT("Failed to find (optional) interface decl for") <+> quotes (ppr name),
1073          ptext SLIT("desired at") <+> ppr loc]
1074
1075 importDeclWarn name
1076   = sep [ptext SLIT(
1077     "Compiler tried to import decl from interface file with same name as module."), 
1078          ptext SLIT(
1079     "(possible cause: module name clashes with interface file already in scope.)")
1080         ] $$
1081     hsep [ptext SLIT("name:"), quotes (ppr name)]
1082
1083 warnRedundantSourceImport mod_name
1084   = ptext SLIT("Unnecessary {- SOURCE -} in the import of module")
1085           <+> quotes (pprModuleName mod_name)
1086
1087 hiModuleNameMismatchWarn :: ModuleName -> ModuleName  -> Message
1088 hiModuleNameMismatchWarn requested_mod read_mod = 
1089     hsep [ ptext SLIT("Something is amiss; requested module name")
1090          , pprModuleName requested_mod
1091          , ptext SLIT("differs from name found in the interface file")
1092          , pprModuleName read_mod
1093          ]
1094
1095 \end{code}