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