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