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