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