[project @ 2002-03-04 17:01:26 by simonmar]
[ghc-hetmet.git] / ghc / compiler / rename / RnHiFiles.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section{Dealing with interface files}
5
6 \begin{code}
7 module RnHiFiles (
8         readIface, findAndReadIface, loadInterface, loadHomeInterface, 
9         tryLoadInterface, loadOrphanModules,
10         loadExports, loadFixDecls, loadDeprecs,
11
12         lookupFixityRn, 
13
14         getTyClDeclBinders
15    ) where
16
17 #include "HsVersions.h"
18
19 import DriverState      ( v_GhcMode, isCompManagerMode )
20 import DriverUtil       ( splitFilename )
21 import CmdLineOpts      ( opt_IgnoreIfacePragmas )
22 import HscTypes         ( ModuleLocation(..),
23                           ModIface(..), emptyModIface,
24                           VersionInfo(..), ImportedModuleInfo,
25                           lookupIfaceByModName, RdrExportItem,
26                           ImportVersion, WhetherHasOrphans, IsBootInterface,
27                           DeclsMap, GatedDecl, IfaceInsts, IfaceRules,
28                           AvailInfo, GenAvailInfo(..), Avails, Deprecations(..)
29                          )
30 import HsSyn            ( TyClDecl(..), InstDecl(..), RuleDecl(..),
31                           tyClDeclNames, tyClDeclSysNames, hsTyVarNames, 
32                           getHsInstHead,
33                         )
34 import RdrHsSyn         ( RdrNameTyClDecl, RdrNameInstDecl, RdrNameRuleDecl )
35 import RnHsSyn          ( extractHsTyNames_s )
36 import BasicTypes       ( Version, defaultFixity )
37 import RnTypes          ( rnHsType )
38 import RnEnv
39 import RnMonad
40 import ParseIface       ( parseIface )
41
42 import Name             ( Name {-instance NamedThing-}, 
43                           nameModule, isLocalName, nameIsLocalOrFrom
44                          )
45 import NameEnv
46 import NameSet
47 import Module
48 import RdrName          ( rdrNameOcc )
49 import SrcLoc           ( mkSrcLoc )
50 import Maybes           ( maybeToBool, orElse )
51 import StringBuffer     ( hGetStringBuffer )
52 import FastString       ( mkFastString )
53 import ErrUtils         ( Message )
54 import Finder           ( findModule, findPackageModule )
55 import Lex
56 import FiniteMap
57 import ListSetOps       ( minusList )
58 import Outputable
59 import Bag
60 import BinIface         ( {- just instances -} )
61 import qualified Binary
62 import Panic
63 import Config
64
65 import IOExts
66 import Exception        ( tryAllIO, Exception(DynException) )
67 import Dynamic          ( fromDynamic )
68 import Directory
69 import List             ( isSuffixOf )
70 \end{code}
71
72
73 %*********************************************************
74 %*                                                      *
75 \subsection{Loading a new interface file}
76 %*                                                      *
77 %*********************************************************
78
79 \begin{code}
80 loadHomeInterface :: SDoc -> Name -> RnM d ModIface
81 loadHomeInterface doc_str name
82   = ASSERT2( not (isLocalName name), ppr name <+> parens doc_str )
83     loadInterface doc_str (moduleName (nameModule name)) ImportBySystem
84
85 loadOrphanModules :: [ModuleName] -> RnM d ()
86 loadOrphanModules mods
87   | null mods = returnRn ()
88   | otherwise = traceRn (text "Loading orphan modules:" <+> 
89                          fsep (map ppr mods))                   `thenRn_` 
90                 mapRn_ load mods                                `thenRn_`
91                 returnRn ()
92   where
93     load mod   = loadInterface (mk_doc mod) mod ImportBySystem
94     mk_doc mod = ppr mod <+> ptext SLIT("is a orphan-instance module")
95
96 loadInterface :: SDoc -> ModuleName -> WhereFrom -> RnM d ModIface
97 loadInterface doc mod from 
98   = tryLoadInterface doc mod from       `thenRn` \ (ifaces, maybe_err) ->
99     case maybe_err of
100         Nothing  -> returnRn ifaces
101         Just err -> failWithRn ifaces (elaborate err)
102   where
103     elaborate err = hang (ptext SLIT("failed to load interface for") <+> quotes (ppr mod) <> colon)
104                          4 err
105
106 tryLoadInterface :: SDoc -> ModuleName -> WhereFrom -> RnM d (ModIface, Maybe Message)
107   -- Returns (Just err) if an error happened
108   -- It *doesn't* add an error to the monad, because sometimes it's ok to fail...
109   -- Specifically, when we read the usage information from an interface file,
110   -- we try to read the interfaces it mentions.  But it's OK to fail; perhaps
111   -- the module has changed, and that interface is no longer used.
112   
113   -- tryLoadInterface guarantees to return with iImpModInfo m --> (..., True)
114   -- (If the load fails, we plug in a vanilla placeholder)
115 tryLoadInterface doc_str mod_name from
116  = getHomeIfaceTableRn          `thenRn` \ hit ->
117    getModuleRn                  `thenRn` \ this_mod ->
118    getIfacesRn                  `thenRn` \ ifaces@(Ifaces { iPIT = pit }) ->
119
120         -- CHECK WHETHER WE HAVE IT ALREADY
121    case lookupIfaceByModName hit pit mod_name of {
122         Just iface |  case from of
123                         ImportByUser       -> not (mi_boot iface)
124                         ImportByUserSource -> mi_boot iface
125                         ImportBySystem     -> True
126                    -> returnRn (iface, Nothing) ;       -- Already loaded
127                         -- The not (mi_boot iface) test checks that the already-loaded
128                         -- interface isn't a boot iface.  This can conceivably happen,
129                         -- if the version checking happened to load a boot interface
130                         -- before we got to real imports.  
131         other       -> 
132
133    let
134         mod_map  = iImpModInfo ifaces
135         mod_info = lookupFM mod_map mod_name
136
137         hi_boot_file 
138           = case (from, mod_info) of
139                 (ImportByUser,       _)             -> False    -- Not hi-boot
140                 (ImportByUserSource, _)             -> True     -- hi-boot
141                 (ImportBySystem, Just (_, is_boot)) -> is_boot
142                 (ImportBySystem, Nothing)           -> False
143                         -- We're importing a module we know absolutely
144                         -- nothing about, so we assume it's from
145                         -- another package, where we aren't doing 
146                         -- dependency tracking. So it won't be a hi-boot file.
147
148         redundant_source_import 
149           = case (from, mod_info) of 
150                 (ImportByUserSource, Just (_,False)) -> True
151                 other                                -> False
152    in
153
154         -- Issue a warning for a redundant {- SOURCE -} import
155         -- NB that we arrange to read all the ordinary imports before 
156         -- any of the {- SOURCE -} imports
157    warnCheckRn  (not redundant_source_import)
158                 (warnRedundantSourceImport mod_name)    `thenRn_`
159
160         -- Check that we aren't importing ourselves. 
161         -- That only happens in Rename.checkOldIface, 
162         -- which doesn't call tryLoadInterface
163    warnCheckRn  
164         (not (isHomeModule this_mod) || moduleName this_mod /= mod_name)
165         (warnSelfImport this_mod)               `thenRn_`
166
167         -- READ THE MODULE IN
168    findAndReadIface doc_str mod_name hi_boot_file
169                                             `thenRn` \ read_result ->
170    case read_result of {
171         Left err ->     -- Not found, so add an empty export env to the Ifaces map
172                         -- so that we don't look again
173            let
174                 fake_mod    = mkVanillaModule mod_name
175                 fake_iface  = emptyModIface fake_mod
176                 new_ifaces  = ifaces { iPIT = extendModuleEnv pit fake_mod fake_iface }
177            in
178            setIfacesRn new_ifaces               `thenRn_`
179            returnRn (fake_iface, Just err) ;
180
181         -- Found and parsed!
182         Right (mod, iface) ->
183
184         -- LOAD IT INTO Ifaces
185
186         -- NB: *first* we do loadDecl, so that the provenance of all the locally-defined
187         ---    names is done correctly (notably, whether this is an .hi file or .hi-boot file).
188         --     If we do loadExport first the wrong info gets into the cache (unless we
189         --      explicitly tag each export which seems a bit of a bore)
190
191
192         -- Sanity check.  If we're system-importing a module we know nothing at all
193         -- about, it should be from a different package to this one
194     WARN( not (maybeToBool mod_info) && 
195           case from of { ImportBySystem -> True; other -> False } &&
196           isHomeModule mod,
197           ppr mod )
198
199     loadDecls mod               (iDecls ifaces)   (pi_decls iface)      `thenRn` \ (decls_vers, new_decls) ->
200     loadRules mod               (iRules ifaces)   (pi_rules iface)      `thenRn` \ (rule_vers, new_rules) ->
201     loadInstDecls mod           (iInsts ifaces)   (pi_insts iface)      `thenRn` \ new_insts ->
202     loadExports                                   (pi_exports iface)    `thenRn` \ (export_vers, avails) ->
203     loadFixDecls mod                              (pi_fixity iface)     `thenRn` \ fix_env ->
204     loadDeprecs mod                               (pi_deprecs iface)    `thenRn` \ deprec_env ->
205     let
206         version = VersionInfo { vers_module  = pi_vers iface, 
207                                 vers_exports = export_vers,
208                                 vers_rules = rule_vers,
209                                 vers_decls = decls_vers }
210
211         -- For an explicit user import, add to mod_map info about
212         -- the things the imported module depends on, extracted
213         -- from its usage info; and delete the module itself, which is now in the PIT
214         mod_map1 = case from of
215                         ImportByUser -> addModDeps mod is_loaded (pi_usages iface) mod_map
216                         other        -> mod_map
217         mod_map2 = delFromFM mod_map1 mod_name
218
219         this_mod_name = moduleName this_mod
220         is_loaded m   =  m == this_mod_name 
221                       || maybeToBool (lookupIfaceByModName hit pit m)
222                 -- We treat the currently-being-compiled module as 'loaded' because
223                 -- even though it isn't yet in the HIT or PIT; otherwise it gets
224                 -- put into iImpModInfo, and then spat out into its own interface
225                 -- file as a dependency
226
227         -- Now add info about this module to the PIT
228         has_orphans = pi_orphan iface
229         new_pit   = extendModuleEnv pit mod mod_iface
230         mod_iface = ModIface { mi_module = mod, mi_package = pi_pkg iface,
231                                mi_version = version,
232                                mi_orphan = has_orphans, mi_boot = hi_boot_file,
233                                mi_exports = avails, 
234                                mi_fixities = fix_env, mi_deprecs = deprec_env,
235                                mi_usages  = [], -- Will be filled in later
236                                mi_decls   = panic "No mi_decls in PIT",
237                                mi_globals = Nothing
238                     }
239
240         new_ifaces = ifaces { iPIT        = new_pit,
241                               iDecls      = new_decls,
242                               iInsts      = new_insts,
243                               iRules      = new_rules,
244                               iImpModInfo = mod_map2  }
245     in
246     setIfacesRn new_ifaces              `thenRn_`
247     returnRn (mod_iface, Nothing)
248     }}
249
250 -----------------------------------------------------
251 --      Adding module dependencies from the 
252 --      import decls in the interface file
253 -----------------------------------------------------
254
255 addModDeps :: Module 
256            -> (ModuleName -> Bool)      -- True for modules that are already loaded
257            -> [ImportVersion a] 
258            -> ImportedModuleInfo -> ImportedModuleInfo
259 -- (addModDeps M ivs deps)
260 -- We are importing module M, and M.hi contains 'import' decls given by ivs
261 addModDeps mod is_loaded new_deps mod_deps
262   = foldr add mod_deps filtered_new_deps
263   where
264         -- Don't record dependencies when importing a module from another package
265         -- Except for its descendents which contain orphans,
266         -- and in that case, forget about the boot indicator
267     filtered_new_deps :: [(ModuleName, (WhetherHasOrphans, IsBootInterface))]
268     filtered_new_deps
269         | isHomeModule mod  = [ (imp_mod, (has_orphans, is_boot))
270                               | (imp_mod, has_orphans, is_boot, _) <- new_deps,
271                                 not (is_loaded imp_mod)
272                               ]                       
273         | otherwise         = [ (imp_mod, (True, False))
274                               | (imp_mod, has_orphans, _, _) <- new_deps,
275                                 not (is_loaded imp_mod) && has_orphans
276                               ]
277     add (imp_mod, dep) deps = addToFM_C combine deps imp_mod dep
278
279     combine old@(old_has_orphans, old_is_boot) new@(new_has_orphans, new_is_boot)
280         | old_is_boot = new     -- Record the best is_boot info
281         | otherwise   = old
282
283 -----------------------------------------------------
284 --      Loading the export list
285 -----------------------------------------------------
286
287 loadExports :: (Version, [RdrExportItem]) -> RnM d (Version, [(ModuleName,Avails)])
288 loadExports (vers, items)
289   = mapRn loadExport items      `thenRn` \ avails_s ->
290     returnRn (vers, avails_s)
291
292
293 loadExport :: RdrExportItem -> RnM d (ModuleName, Avails)
294 loadExport (mod, entities)
295   = mapRn (load_entity mod) entities    `thenRn` \ avails ->
296     returnRn (mod, avails)
297   where
298     load_entity mod (Avail occ)
299       = newGlobalName mod occ   `thenRn` \ name ->
300         returnRn (Avail name)
301     load_entity mod (AvailTC occ occs)
302       = newGlobalName mod occ           `thenRn` \ name ->
303         mapRn (newGlobalName mod) occs  `thenRn` \ names ->
304         returnRn (AvailTC name names)
305
306
307 -----------------------------------------------------
308 --      Loading type/class/value decls
309 -----------------------------------------------------
310
311 loadDecls :: Module 
312           -> DeclsMap
313           -> [(Version, RdrNameTyClDecl)]
314           -> RnM d (NameEnv Version, DeclsMap)
315 loadDecls mod (decls_map, n_slurped) decls
316   = foldlRn (loadDecl mod) (emptyNameEnv, decls_map) decls      `thenRn` \ (vers, decls_map') -> 
317     returnRn (vers, (decls_map', n_slurped))
318
319 loadDecl mod (version_map, decls_map) (version, decl)
320   = getTyClDeclBinders mod decl `thenRn` \ (avail, sys_names) ->
321     let
322         full_avail    = case avail of
323                           Avail n -> avail
324                           AvailTC n ns -> AvailTC n (sys_names ++ ns)
325         main_name     = availName full_avail
326         new_decls_map = extendNameEnvList decls_map stuff
327         stuff         = [ (name, (full_avail, name==main_name, (mod, decl))) 
328                         | name <- availNames full_avail]
329
330         new_version_map = extendNameEnv version_map main_name version
331     in
332     traceRn (text "Loading" <+> ppr full_avail) `thenRn_`
333     returnRn (new_version_map, new_decls_map)
334
335 -----------------------------------------------------
336 --      Loading fixity decls
337 -----------------------------------------------------
338
339 loadFixDecls mod decls
340   = mapRn (loadFixDecl mod_name) decls  `thenRn` \ to_add ->
341     returnRn (mkNameEnv to_add)
342   where
343     mod_name = moduleName mod
344
345 loadFixDecl mod_name (rdr_name, fixity)
346   = newGlobalName mod_name (rdrNameOcc rdr_name)        `thenRn` \ name ->
347     returnRn (name, fixity)
348
349
350 -----------------------------------------------------
351 --      Loading instance decls
352 -----------------------------------------------------
353
354 loadInstDecls :: Module
355               -> IfaceInsts
356               -> [RdrNameInstDecl]
357               -> RnM d IfaceInsts
358 loadInstDecls mod (insts, n_slurped) decls
359   = setModuleRn mod $
360     foldlRn (loadInstDecl mod) insts decls      `thenRn` \ insts' ->
361     returnRn (insts', n_slurped)
362
363
364 loadInstDecl mod insts decl@(InstDecl inst_ty _ _ _ _)
365   =     -- Find out what type constructors and classes are "gates" for the
366         -- instance declaration.  If all these "gates" are slurped in then
367         -- we should slurp the instance decl too.
368         -- 
369         -- We *don't* want to count names in the context part as gates, though.
370         -- For example:
371         --              instance Foo a => Baz (T a) where ...
372         --
373         -- Here the gates are Baz and T, but *not* Foo.
374         -- 
375         -- HOWEVER: functional dependencies make things more complicated
376         --      class C a b | a->b where ...
377         --      instance C Foo Baz where ...
378         -- Here, the gates are really only C and Foo, *not* Baz.
379         -- That is, if C and Foo are visible, even if Baz isn't, we must
380         -- slurp the decl.
381         --
382         -- Rather than take fundeps into account "properly", we just slurp
383         -- if C is visible and *any one* of the Names in the types
384         -- This is a slightly brutal approximation, but most instance decls
385         -- are regular H98 ones and it's perfect for them.
386         --
387         -- NOTICE that we rename the type before extracting its free
388         -- variables.  The free-variable finder for a renamed HsType 
389         -- does the Right Thing for built-in syntax like [] and (,).
390     initIfaceRnMS mod (
391         rnHsType (text "In an interface instance decl") inst_ty
392     )                                   `thenRn` \ inst_ty' ->
393     let 
394         (tvs,(cls,tys)) = getHsInstHead inst_ty'
395         free_tcs  = nameSetToList (extractHsTyNames_s tys) `minusList` hsTyVarNames tvs
396
397         gate_fn vis_fn = vis_fn cls && (null free_tcs || any vis_fn free_tcs)
398         -- Here is the implementation of HOWEVER above
399         -- (Note that we do let the inst decl in if it mentions 
400         --  no tycons at all.  Hence the null free_ty_names.)
401     in
402     returnRn ((gate_fn, (mod, decl)) `consBag` insts)
403
404
405
406 -----------------------------------------------------
407 --      Loading Rules
408 -----------------------------------------------------
409
410 loadRules :: Module -> IfaceRules 
411           -> (Version, [RdrNameRuleDecl])
412           -> RnM d (Version, IfaceRules)
413 loadRules mod (rule_bag, n_slurped) (version, rules)
414   | null rules || opt_IgnoreIfacePragmas 
415   = returnRn (version, (rule_bag, n_slurped))
416   | otherwise
417   = setModuleRn mod                     $
418     mapRn (loadRule mod) rules          `thenRn` \ new_rules ->
419     returnRn (version, (rule_bag `unionBags` listToBag new_rules, n_slurped))
420
421 loadRule :: Module -> RdrNameRuleDecl -> RnM d (GatedDecl RdrNameRuleDecl)
422 -- "Gate" the rule simply by whether the rule variable is
423 -- needed.  We can refine this later.
424 loadRule mod decl@(IfaceRule _ _ _ var _ _ src_loc)
425   = lookupIfaceName var         `thenRn` \ var_name ->
426     returnRn (\vis_fn -> vis_fn var_name, (mod, decl))
427
428
429 -----------------------------------------------------
430 --      Loading Deprecations
431 -----------------------------------------------------
432
433 loadDeprecs :: Module -> IfaceDeprecs -> RnM d Deprecations
434 loadDeprecs m Nothing                                  = returnRn NoDeprecs
435 loadDeprecs m (Just (Left txt))  = returnRn (DeprecAll txt)
436 loadDeprecs m (Just (Right prs)) = setModuleRn m                                $
437                                    foldlRn loadDeprec emptyNameEnv prs  `thenRn` \ env ->
438                                    returnRn (DeprecSome env)
439 loadDeprec deprec_env (n, txt)
440   = lookupIfaceName n           `thenRn` \ name ->
441     traceRn (text "Loaded deprecation(s) for" <+> ppr name <> colon <+> ppr txt) `thenRn_`
442     returnRn (extendNameEnv deprec_env name (name,txt))
443 \end{code}
444
445
446 %*********************************************************
447 %*                                                      *
448 \subsection{Getting binders out of a declaration}
449 %*                                                      *
450 %*********************************************************
451
452 @getDeclBinders@ returns the names for a @RdrNameHsDecl@.
453 It's used for both source code (from @availsFromDecl@) and interface files
454 (from @loadDecl@).
455
456 It doesn't deal with source-code specific things: @ValD@, @DefD@.  They
457 are handled by the sourc-code specific stuff in @RnNames@.
458
459         *** See "THE NAMING STORY" in HsDecls ****
460
461
462 \begin{code}
463 getTyClDeclBinders
464         :: Module
465         -> RdrNameTyClDecl
466         -> RnM d (AvailInfo, [Name])    -- The [Name] are the system names
467
468 -----------------
469 getTyClDeclBinders mod (IfaceSig {tcdName = var, tcdLoc = src_loc})
470   = newTopBinder mod var src_loc                        `thenRn` \ var_name ->
471     returnRn (Avail var_name, [])
472
473 getTyClDeclBinders mod tycl_decl
474   = new_top_bndrs mod (tyClDeclNames tycl_decl)         `thenRn` \ names@(main_name:_) ->
475     new_top_bndrs mod (tyClDeclSysNames tycl_decl)      `thenRn` \ sys_names ->
476     returnRn (AvailTC main_name names, sys_names)
477
478 -----------------
479 new_top_bndrs mod names_w_locs
480   = sequenceRn [newTopBinder mod name loc | (name,loc) <- names_w_locs]
481 \end{code}
482
483
484 %*********************************************************
485 %*                                                      *
486 \subsection{Reading an interface file}
487 %*                                                      *
488 %*********************************************************
489
490 \begin{code}
491 findAndReadIface :: SDoc -> ModuleName 
492                  -> IsBootInterface     -- True  <=> Look for a .hi-boot file
493                                         -- False <=> Look for .hi file
494                  -> RnM d (Either Message (Module, ParsedIface))
495         -- Nothing <=> file not found, or unreadable, or illegible
496         -- Just x  <=> successfully found and parsed 
497
498 findAndReadIface doc_str mod_name hi_boot_file
499   = traceRn trace_msg                   `thenRn_`
500
501     -- In interactive or --make mode, we are *not allowed* to demand-load
502     -- a home package .hi file.  So don't even look for them.
503     -- This helps in the case where you are sitting in eg. ghc/lib/std
504     -- and start up GHCi - it won't complain that all the modules it tries
505     -- to load are found in the home location.
506     ioToRnM_no_fail (readIORef v_GhcMode) `thenRn` \ mode ->
507     let home_allowed = hi_boot_file || not (isCompManagerMode mode)
508     in
509
510     ioToRnM (if home_allowed 
511                 then findModule mod_name
512                 else findPackageModule mod_name) `thenRn` \ maybe_found ->
513
514     case maybe_found of
515
516       Right (Just (wanted_mod,locn))
517         -> mkHiPath hi_boot_file locn `thenRn` \ file -> 
518            readIface file `thenRn` \ read_result ->
519            case read_result of
520                 Left bad -> returnRn (Left bad)
521                 Right iface ->  -- check that the module names agree
522                       let read_mod_name = pi_mod iface
523                           wanted_mod_name = moduleName wanted_mod
524                       in
525                       checkRn
526                           (wanted_mod_name == read_mod_name)
527                           (hiModuleNameMismatchWarn wanted_mod_name read_mod_name)
528                                         `thenRn_`
529                          returnRn (Right (wanted_mod, iface))
530         -- Can't find it
531       other   -> traceRn (ptext SLIT("...not found"))   `thenRn_`
532                  returnRn (Left (noIfaceErr mod_name hi_boot_file))
533
534   where
535     trace_msg = sep [hsep [ptext SLIT("Reading"), 
536                            if hi_boot_file then ptext SLIT("[boot]") else empty,
537                            ptext SLIT("interface for"), 
538                            ppr mod_name <> semi],
539                      nest 4 (ptext SLIT("reason:") <+> doc_str)]
540
541 mkHiPath hi_boot_file locn
542   | hi_boot_file = 
543         ioToRnM_no_fail (doesFileExist hi_boot_ver_path) `thenRn` \ b ->
544         if b then returnRn hi_boot_ver_path
545              else returnRn hi_boot_path
546   | otherwise    = returnRn hi_path
547         where hi_path            = ml_hi_file locn
548               (hi_base, _hi_suf) = splitFilename hi_path
549               hi_boot_path       = hi_base ++ ".hi-boot"
550               hi_boot_ver_path   = hi_base ++ ".hi-boot-" ++ cHscIfaceFileVersion
551 \end{code}
552
553 @readIface@ tries just the one file.
554
555 \begin{code}
556 readIface :: String -> RnM d (Either Message ParsedIface)
557         -- Nothing <=> file not found, or unreadable, or illegible
558         -- Just x  <=> successfully found and parsed 
559 readIface file_path
560   = --ioToRnM (putStrLn ("reading iface " ++ file_path)) `thenRn_`
561     traceRn (ptext SLIT("readIFace") <+> text file_path)        `thenRn_` 
562
563   let hi_boot_ver = "hi-boot-" ++ cHscIfaceFileVersion in
564   if ".hi-boot" `isSuffixOf` file_path
565      || hi_boot_ver `isSuffixOf` file_path then
566
567       ioToRnM (hGetStringBuffer False file_path) `thenRn` \ read_result ->
568       case read_result of {
569         Left io_error  -> bale_out (text (show io_error));
570         Right contents -> 
571
572       case parseIface contents (mkPState loc exts) of {
573         POk _ iface          -> returnRn (Right iface);
574         PFailed err          -> bale_out err
575      }}
576
577   else
578       ioToRnM_no_fail (tryAllIO (Binary.getBinFileWithDict file_path)) 
579           `thenRn` \ either_iface ->
580
581       case either_iface of
582         Right iface -> returnRn (Right iface)
583         Left (DynException d) | Just e <- fromDynamic d
584                 -> bale_out (text (show (e :: GhcException)))
585
586         Left err -> bale_out (text (show err))
587
588   where
589     exts = ExtFlags {glasgowExtsEF = True,
590                      parrEF        = True}
591     loc  = mkSrcLoc (mkFastString file_path) 1
592
593     bale_out err = returnRn (Left (badIfaceFile file_path err))
594 \end{code}
595
596 %*********************************************************
597 %*                                                      *
598 \subsection{Looking up fixities}
599 %*                                                      *
600 %*********************************************************
601
602 @lookupFixityRn@ has to be in RnIfaces (or RnHiFiles), instead of
603 its obvious home in RnEnv,  because it calls @loadHomeInterface@.
604
605 lookupFixity is a bit strange.  
606
607 * Nested local fixity decls are put in the local fixity env, which we
608   find with getFixtyEnv
609
610 * Imported fixities are found in the HIT or PIT
611
612 * Top-level fixity decls in this module may be for Names that are
613     either  Global         (constructors, class operations)
614     or      Local/Exported (everything else)
615   (See notes with RnNames.getLocalDeclBinders for why we have this split.)
616   We put them all in the local fixity environment
617
618 \begin{code}
619 lookupFixityRn :: Name -> RnMS Fixity
620 lookupFixityRn name
621   = getModuleRn                         `thenRn` \ this_mod ->
622     if nameIsLocalOrFrom this_mod name
623     then        -- It's defined in this module
624         getFixityEnv                    `thenRn` \ local_fix_env ->
625         returnRn (lookupLocalFixity local_fix_env name)
626
627     else        -- It's imported
628       -- For imported names, we have to get their fixities by doing a
629       -- loadHomeInterface, and consulting the Ifaces that comes back
630       -- from that, because the interface file for the Name might not
631       -- have been loaded yet.  Why not?  Suppose you import module A,
632       -- which exports a function 'f', thus;
633       --        module CurrentModule where
634       --          import A( f )
635       --        module A( f ) where
636       --          import B( f )
637       -- Then B isn't loaded right away (after all, it's possible that
638       -- nothing from B will be used).  When we come across a use of
639       -- 'f', we need to know its fixity, and it's then, and only
640       -- then, that we load B.hi.  That is what's happening here.
641         loadHomeInterface doc name              `thenRn` \ iface ->
642         returnRn (lookupNameEnv (mi_fixities iface) name `orElse` defaultFixity)
643   where
644     doc      = ptext SLIT("Checking fixity for") <+> ppr name
645 \end{code}
646
647
648 %*********************************************************
649 %*                                                       *
650 \subsection{Errors}
651 %*                                                       *
652 %*********************************************************
653
654 \begin{code}
655 noIfaceErr mod_name boot_file
656   = ptext SLIT("Could not find interface file for") <+> quotes (ppr mod_name)
657         -- We used to print the search path, but we can't do that
658         -- now, because it's hidden inside the finder.
659         -- Maybe the finder should expose more functions.
660
661 badIfaceFile file err
662   = vcat [ptext SLIT("Bad interface file:") <+> text file, 
663           nest 4 err]
664
665 hiModuleNameMismatchWarn :: ModuleName -> ModuleName -> Message
666 hiModuleNameMismatchWarn requested_mod read_mod = 
667     hsep [ ptext SLIT("Something is amiss; requested module name")
668          , ppr requested_mod
669          , ptext SLIT("differs from name found in the interface file")
670          , ppr read_mod
671          ]
672
673 warnRedundantSourceImport mod_name
674   = ptext SLIT("Unnecessary {- SOURCE -} in the import of module")
675           <+> quotes (ppr mod_name)
676
677 warnSelfImport mod
678   = ptext SLIT("Importing my own interface: module") <+> ppr mod
679 \end{code}