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