[project @ 2003-01-08 15:28:04 by simonmar]
[ghc-hetmet.git] / ghc / compiler / rename / RnHiFiles.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section{Dealing with interface files}
5
6 \begin{code}
7 module RnHiFiles (
8         readIface, loadInterface, loadHomeInterface, 
9         loadOrphanModules,
10         loadOldIface,
11         ParsedIface(..)
12    ) where
13
14 #include "HsVersions.h"
15
16 import DriverState      ( v_GhcMode, isCompManagerMode )
17 import DriverUtil       ( replaceFilenameSuffix )
18 import CmdLineOpts      ( opt_IgnoreIfacePragmas, verbosity )
19 import Parser           ( parseIface )
20 import HscTypes         ( ModIface(..), emptyModIface,
21                           ExternalPackageState(..), noDependencies,
22                           VersionInfo(..), Usage(..),
23                           lookupIfaceByModName, RdrExportItem, 
24                           IsBootInterface,
25                           DeclsMap, GatedDecl, IfaceInsts, IfaceRules, mkIfaceDecls,
26                           AvailInfo, GenAvailInfo(..), ParsedIface(..), IfaceDeprecs,
27                           Avails, availNames, availName, Deprecations(..)
28                          )
29 import HsSyn            ( TyClDecl(..), InstDecl(..), RuleDecl(..), ConDecl(..),
30                           hsTyVarNames, splitHsInstDeclTy, tyClDeclName, tyClDeclNames
31                         )
32 import RdrHsSyn         ( RdrNameTyClDecl, RdrNameInstDecl, RdrNameRuleDecl )
33 import RnHsSyn          ( RenamedInstDecl, RenamedRuleDecl, RenamedTyClDecl,
34                           extractHsTyNames_s )
35 import BasicTypes       ( Version, FixitySig(..), Fixity(..), FixityDirection(..) )
36 import RnSource         ( rnIfaceRuleDecl, rnTyClDecl, rnInstDecl )
37 import RnTypes          ( rnHsType )
38 import RnEnv
39 import TcRnMonad
40
41 import PrelNames        ( gHC_PRIM_Name, gHC_PRIM )
42 import PrelInfo         ( ghcPrimExports, cCallableClassDecl, cReturnableClassDecl )
43 import Name             ( Name {-instance NamedThing-}, 
44                           nameModule, isInternalName )
45 import NameEnv
46 import NameSet
47 import Id               ( idName )
48 import MkId             ( seqId )
49 import Packages         ( basePackage )
50 import Module           ( Module, ModuleName, ModLocation(ml_hi_file),
51                           moduleName, isHomeModule, mkPackageModule,
52                           extendModuleEnv, lookupModuleEnvByName
53                         )
54 import RdrName          ( RdrName, mkRdrUnqual, rdrNameOcc, nameRdrName )
55 import OccName          ( OccName, mkWorkerOcc, mkClassTyConOcc, mkClassDataConOcc,
56                           mkSuperDictSelOcc, mkGenOcc1, mkGenOcc2 )
57 import TyCon            ( DataConDetails(..) )
58 import SrcLoc           ( noSrcLoc, mkSrcLoc )
59 import Maybes           ( maybeToBool )
60 import StringBuffer     ( hGetStringBuffer )
61 import FastString       ( mkFastString )
62 import ErrUtils         ( Message )
63 import Finder           ( findModule, findPackageModule, 
64                           hiBootExt, hiBootVerExt )
65 import Lex
66 import FiniteMap
67 import ListSetOps       ( minusList )
68 import Outputable
69 import Bag
70 import BinIface         ( readBinIface )
71 import Panic
72
73 import EXCEPTION as Exception
74 import DATA_IOREF       ( readIORef )
75
76 import Directory
77 \end{code}
78
79
80 %*********************************************************
81 %*                                                      *
82 \subsection{Loading a new interface file}
83 %*                                                      *
84 %*********************************************************
85
86 \begin{code}
87 loadHomeInterface :: SDoc -> Name -> TcRn m ModIface
88 loadHomeInterface doc_str name
89   = ASSERT2( not (isInternalName name), ppr name <+> parens doc_str )
90     loadInterface doc_str (moduleName (nameModule name)) ImportBySystem
91
92 loadOrphanModules :: [ModuleName] -> TcRn m ()
93 loadOrphanModules mods
94   | null mods = returnM ()
95   | otherwise = traceRn (text "Loading orphan modules:" <+> 
96                          fsep (map ppr mods))                   `thenM_` 
97                 mappM_ load mods                                `thenM_`
98                 returnM ()
99   where
100     load mod   = loadInterface (mk_doc mod) mod ImportBySystem
101     mk_doc mod = ppr mod <+> ptext SLIT("is a orphan-instance module")
102
103 loadInterface :: SDoc -> ModuleName -> WhereFrom -> TcRn m ModIface
104   -- Returns Nothing if failed
105   -- If we can't find an interface file, and we are doing ImportForUsage,
106   --    just fail in the monad, and modify anything else
107   -- Otherwise, if we can't find an interface file, 
108   --    add an error message to the monad (the first time only) 
109   --    and return emptyIface
110   -- The "first time only" part is done by modifying the PackageIfaceTable
111   --            to have an empty entry
112   --
113   -- The ImportForUsage case is because when we read the usage information from 
114   -- an interface file, we try to read the interfaces it mentions.  
115   -- But it's OK to fail; perhaps the module has changed, and that interface 
116   -- is no longer used.
117   
118 loadInterface doc_str mod_name from
119  = getHpt               `thenM` \ hpt ->
120    getModule            `thenM` \ this_mod ->
121    getImports           `thenM` \ import_avails ->
122    getEps               `thenM` \ eps@(EPS { eps_PIT = pit }) ->
123
124         -- CHECK WHETHER WE HAVE IT ALREADY
125    case lookupIfaceByModName hpt pit mod_name of {
126         Just iface |  case from of
127                         ImportByUser   src_imp -> src_imp == mi_boot iface
128                         ImportForUsage src_imp -> src_imp == mi_boot iface
129                         ImportBySystem         -> True
130                    -> returnM iface ;           -- Already loaded
131                         -- The not (mi_boot iface) test checks that the already-loaded
132                         -- interface isn't a boot iface.  This can conceivably happen,
133                         -- if the version checking happened to load a boot interface
134                         -- before we got to real imports.  
135         other       -> 
136
137    let
138         mod_map  = imp_dep_mods import_avails
139         mod_info = lookupModuleEnvByName mod_map mod_name
140
141         hi_boot_file 
142           = case (from, mod_info) of
143                 (ImportByUser   is_boot, _)         -> is_boot
144                 (ImportForUsage is_boot, _)         -> is_boot
145                 (ImportBySystem, Just (_, is_boot)) -> is_boot
146                 (ImportBySystem, Nothing)           -> False
147                         -- We're importing a module we know absolutely
148                         -- nothing about, so we assume it's from
149                         -- another package, where we aren't doing 
150                         -- dependency tracking. So it won't be a hi-boot file.
151
152         redundant_source_import 
153           = case (from, mod_info) of 
154                 (ImportByUser True, Just (_, False)) -> True
155                 other                                -> False
156    in
157
158         -- Issue a warning for a redundant {- SOURCE -} import
159         -- NB that we arrange to read all the ordinary imports before 
160         -- any of the {- SOURCE -} imports
161    warnIf       redundant_source_import
162                 (warnRedundantSourceImport mod_name)    `thenM_`
163
164         -- Check that we aren't importing ourselves. 
165         -- That only happens in Rename.checkOldIface, 
166         -- which doesn't call loadInterface
167    warnIf
168         (isHomeModule this_mod && moduleName this_mod == mod_name)
169         (warnSelfImport this_mod)               `thenM_`
170
171         -- READ THE MODULE IN
172    findAndReadIface doc_str mod_name hi_boot_file
173                                             `thenM` \ read_result ->
174    case read_result of {
175         Left err
176           | case from of { ImportForUsage _ -> True ; other -> False }
177           -> failM      -- Fail with no error messages
178
179           |  otherwise  
180           -> let        -- Not found, so add an empty export env to 
181                         -- the EPS map so that we don't look again
182                 fake_mod   = mkPackageModule mod_name
183                 fake_iface = emptyModIface fake_mod
184                 new_eps    = eps { eps_PIT = extendModuleEnv pit fake_mod fake_iface }
185              in
186              setEps new_eps             `thenM_`
187              addErr (elaborate err)     `thenM_`
188              returnM fake_iface 
189           where
190             elaborate err = hang (ptext SLIT("Failed to load interface for") <+> 
191                                   quotes (ppr mod_name) <> colon) 4 err
192           ;
193
194         -- Found and parsed!
195         Right (mod, iface) ->
196
197         -- LOAD IT INTO EPS
198
199         -- NB: *first* we do loadDecl, so that the provenance of all the locally-defined
200         ---    names is done correctly (notably, whether this is an .hi file or .hi-boot file).
201         --     If we do loadExport first the wrong info gets into the cache (unless we
202         --      explicitly tag each export which seems a bit of a bore)
203
204
205         -- Sanity check.  If we're system-importing a module we know nothing at all
206         -- about, it should be from a different package to this one
207     WARN( not (maybeToBool mod_info) && 
208           case from of { ImportBySystem -> True; other -> False } &&
209           isHomeModule mod,
210           ppr mod )
211
212     initRn (InterfaceMode mod)                                  $
213         -- Set the module, for use when looking up occurrences
214         -- of names in interface decls and rules
215     loadDecls mod       (eps_decls eps)   (pi_decls iface)      `thenM` \ (decls_vers, new_decls) ->
216     loadRules     mod   (eps_rules eps)   (pi_rules iface)      `thenM` \ (rule_vers, new_rules) ->
217     loadInstDecls mod   (eps_insts eps)   (pi_insts iface)      `thenM` \ new_insts ->
218     loadExports                           (pi_exports iface)    `thenM` \ (export_vers, avails) ->
219     loadFixDecls                          (pi_fixity iface)     `thenM` \ fix_env ->
220     loadDeprecs                           (pi_deprecs iface)    `thenM` \ deprec_env ->
221    let
222         version = VersionInfo { vers_module  = pi_vers iface, 
223                                 vers_exports = export_vers,
224                                 vers_rules = rule_vers,
225                                 vers_decls = decls_vers }
226
227         -- Now add info about this module to the PIT
228         -- Even home modules loaded by this route (which only 
229         -- happens in OneShot mode) are put in the PIT
230         has_orphans = pi_orphan iface
231         new_pit   = extendModuleEnv pit mod mod_iface
232         mod_iface = ModIface { mi_module = mod, mi_package = pi_pkg iface,
233                                mi_version = version,
234                                mi_orphan = has_orphans, mi_boot = hi_boot_file,
235                                mi_exports = avails, 
236                                mi_fixities = fix_env, mi_deprecs = deprec_env,
237                                mi_deps     = pi_deps iface,
238                                mi_usages   = panic "No mi_usages in PIT",
239                                mi_decls    = panic "No mi_decls in PIT",
240                                mi_globals  = Nothing
241                     }
242
243         new_eps = eps { eps_PIT      = new_pit,
244                         eps_decls    = new_decls,
245                         eps_insts    = new_insts,
246                         eps_rules    = new_rules }
247     in
248     setEps new_eps              `thenM_`
249     returnM mod_iface
250     }}
251
252 -----------------------------------------------------
253 --      Loading the export list
254 -----------------------------------------------------
255
256 loadExports :: (Version, [RdrExportItem]) -> TcRn m (Version, [(ModuleName,Avails)])
257 loadExports (vers, items)
258   = mappM loadExport items      `thenM` \ avails_s ->
259     returnM (vers, avails_s)
260
261
262 loadExport :: RdrExportItem -> TcRn m (ModuleName, Avails)
263 loadExport (mod, entities)
264   = mappM (load_entity mod) entities    `thenM` \ avails ->
265     returnM (mod, avails)
266   where
267     load_entity mod (Avail occ)
268       = newGlobalName2 mod occ  `thenM` \ name ->
269         returnM (Avail name)
270     load_entity mod (AvailTC occ occs)
271       = newGlobalName2 mod occ          `thenM` \ name ->
272         mappM (newGlobalName2 mod) occs `thenM` \ names ->
273         returnM (AvailTC name names)
274
275
276 -----------------------------------------------------
277 --      Loading type/class/value decls
278 -----------------------------------------------------
279
280 loadDecls :: Module 
281           -> DeclsMap
282           -> [(Version, RdrNameTyClDecl)]
283           -> TcRn m (NameEnv Version, DeclsMap)
284 loadDecls mod (decls_map, n_slurped) decls
285   = foldlM (loadDecl mod) (emptyNameEnv, decls_map) decls       `thenM` \ (vers, decls_map') -> 
286     returnM (vers, (decls_map', n_slurped))
287
288 loadDecl mod (version_map, decls_map) (version, decl)
289   = getTyClDeclBinders mod decl         `thenM` \ avail ->
290     getSysBinders mod decl              `thenM` \ sys_names ->
291     let
292         full_avail    = case avail of
293                           Avail n -> avail
294                           AvailTC n ns -> AvailTC n (sys_names ++ ns)
295         main_name     = availName full_avail
296         new_decls_map = extendNameEnvList decls_map stuff
297         stuff         = [ (name, (full_avail, name==main_name, (mod, decl))) 
298                         | name <- availNames full_avail]
299
300         new_version_map = extendNameEnv version_map main_name version
301     in
302 --    traceRn (text "Loading" <+> ppr full_avail) `thenM_`
303     returnM (new_version_map, new_decls_map)
304
305
306
307 -----------------
308 getTyClDeclBinders :: Module -> RdrNameTyClDecl -> TcRn m AvailInfo     
309
310 getTyClDeclBinders mod (IfaceSig {tcdName = var, tcdLoc = src_loc})
311   = newTopBinder mod var src_loc                        `thenM` \ var_name ->
312     returnM (Avail var_name)
313
314 getTyClDeclBinders mod tycl_decl
315   = mapM new (tyClDeclNames tycl_decl)  `thenM` \ names@(main_name:_) ->
316     returnM (AvailTC main_name names)
317   where
318     new (nm,loc) = newTopBinder mod nm loc
319
320 --------------------------------
321 -- The "system names" are extra implicit names *bound* by the decl.
322
323 getSysBinders :: Module -> TyClDecl RdrName -> TcRn m [Name]
324 -- Similar to tyClDeclNames, but returns the "implicit" 
325 -- or "system" names of the declaration.  And it only works
326 -- on RdrNames, returning OccNames
327
328 getSysBinders mod (ClassDecl {tcdName = cname, tcdCtxt = cxt, tcdLoc = loc})
329   = sequenceM [new_sys_bndr mod n loc | n <- sys_occs]
330   where
331         -- C.f. TcClassDcl.tcClassDecl1
332     sys_occs    = tc_occ : data_occ : dw_occ : sc_sel_occs
333     cls_occ     = rdrNameOcc cname
334     data_occ    = mkClassDataConOcc cls_occ
335     dw_occ      = mkWorkerOcc data_occ
336     tc_occ      = mkClassTyConOcc   cls_occ
337     sc_sel_occs = [mkSuperDictSelOcc n cls_occ | n <- [1..length cxt]]
338
339 getSysBinders mod (TyData {tcdName = tc_name, tcdCons = DataCons cons,  
340                            tcdGeneric = Just want_generic, tcdLoc = loc})
341         -- The 'Just' is because this is an interface-file decl
342         -- so it will say whether to derive generic stuff for it or not
343   = sequenceM ([new_sys_bndr mod n loc | n <- gen_occs] ++ 
344                map con_sys_occ cons)
345   where
346         -- c.f. TcTyDecls.tcTyDecl
347     tc_occ = rdrNameOcc tc_name
348     gen_occs | want_generic = [mkGenOcc1 tc_occ, mkGenOcc2 tc_occ]
349              | otherwise    = []
350     con_sys_occ (ConDecl name _ _ _ loc) 
351         = new_sys_bndr mod (mkWorkerOcc (rdrNameOcc name)) loc
352     
353 getSysBinders mod decl = returnM []
354
355 new_sys_bndr mod occ loc = newTopBinder mod (mkRdrUnqual occ) loc
356
357
358 -----------------------------------------------------
359 --      Loading fixity decls
360 -----------------------------------------------------
361
362 loadFixDecls decls
363   = mappM loadFixDecl decls     `thenM` \ to_add ->
364     returnM (mkNameEnv to_add)
365
366 loadFixDecl (FixitySig rdr_name fixity loc)
367   = lookupGlobalOccRn rdr_name          `thenM` \ name ->
368     returnM (name, FixitySig name fixity loc)
369
370
371 -----------------------------------------------------
372 --      Loading instance decls
373 -----------------------------------------------------
374
375 loadInstDecls :: Module -> IfaceInsts
376               -> [RdrNameInstDecl]
377               -> RnM IfaceInsts
378 loadInstDecls mod (insts, n_slurped) decls
379   = foldlM (loadInstDecl mod) insts decls       `thenM` \ insts' ->
380     returnM (insts', n_slurped)
381
382
383 loadInstDecl mod insts decl@(InstDecl inst_ty _ _ _ _)
384   =     -- Find out what type constructors and classes are "gates" for the
385         -- instance declaration.  If all these "gates" are slurped in then
386         -- we should slurp the instance decl too.
387         -- 
388         -- We *don't* want to count names in the context part as gates, though.
389         -- For example:
390         --              instance Foo a => Baz (T a) where ...
391         --
392         -- Here the gates are Baz and T, but *not* Foo.
393         -- 
394         -- HOWEVER: functional dependencies make things more complicated
395         --      class C a b | a->b where ...
396         --      instance C Foo Baz where ...
397         -- Here, the gates are really only C and Foo, *not* Baz.
398         -- That is, if C and Foo are visible, even if Baz isn't, we must
399         -- slurp the decl.
400         --
401         -- Rather than take fundeps into account "properly", we just slurp
402         -- if C is visible and *any one* of the Names in the types
403         -- This is a slightly brutal approximation, but most instance decls
404         -- are regular H98 ones and it's perfect for them.
405         --
406         -- NOTICE that we rename the type before extracting its free
407         -- variables.  The free-variable finder for a renamed HsType 
408         -- does the Right Thing for built-in syntax like [] and (,).
409     rnHsType (text "In an interface instance decl") inst_ty     `thenM` \ inst_ty' ->
410     let 
411         (tvs,_,cls,tys) = splitHsInstDeclTy inst_ty'
412         free_tcs  = nameSetToList (extractHsTyNames_s tys) `minusList` hsTyVarNames tvs
413
414         gate_fn vis_fn = vis_fn cls && (null free_tcs || any vis_fn free_tcs)
415         -- The 'vis_fn' returns True for visible names
416         -- Here is the implementation of HOWEVER above
417         -- (Note that we do let the inst decl in if it mentions 
418         --  no tycons at all.  Hence the null free_ty_names.)
419     in
420 --    traceRn ((text "Load instance for" <+> ppr inst_ty') $$ ppr free_tcs)     `thenM_`
421     returnM ((gate_fn, (mod, decl)) `consBag` insts)
422
423
424
425 -----------------------------------------------------
426 --      Loading Rules
427 -----------------------------------------------------
428
429 loadRules :: Module
430           -> IfaceRules 
431           -> (Version, [RdrNameRuleDecl])
432           -> RnM (Version, IfaceRules)
433 loadRules mod (rule_bag, n_slurped) (version, rules)
434   | null rules || opt_IgnoreIfacePragmas 
435   = returnM (version, (rule_bag, n_slurped))
436   | otherwise
437   = mappM (loadRule mod) rules          `thenM` \ new_rules ->
438     returnM (version, (rule_bag `unionBags` listToBag new_rules, n_slurped))
439
440 loadRule :: Module -> RdrNameRuleDecl -> RnM (GatedDecl RdrNameRuleDecl)
441 -- "Gate" the rule simply by whether the rule variable is
442 -- needed.  We can refine this later.
443 loadRule mod decl@(IfaceRule _ _ _ var _ _ src_loc)
444   = lookupGlobalOccRn var               `thenM` \ var_name ->
445     returnM (\vis_fn -> vis_fn var_name, (mod, decl))
446
447
448 -----------------------------------------------------
449 --      Loading Deprecations
450 -----------------------------------------------------
451
452 loadDeprecs :: IfaceDeprecs -> RnM Deprecations
453 loadDeprecs Nothing            = returnM NoDeprecs
454 loadDeprecs (Just (Left txt))  = returnM (DeprecAll txt)
455 loadDeprecs (Just (Right prs)) = foldlM loadDeprec emptyNameEnv prs     `thenM` \ env ->
456                                  returnM (DeprecSome env)
457 loadDeprec deprec_env (n, txt)
458   = lookupGlobalOccRn n         `thenM` \ name ->
459 --    traceRn (text "Loaded deprecation(s) for" <+> ppr name <> colon <+> ppr txt) `thenM_`
460     returnM (extendNameEnv deprec_env name (name,txt))
461 \end{code}
462
463
464 %********************************************************
465 %*                                                      *
466         Load the ParsedIface for the *current* module
467         into a ModIface; then it can be checked
468         for up-to-date-ness
469 %*                                                      *
470 %********************************************************
471
472 \begin{code}
473 loadOldIface :: ParsedIface -> RnM ModIface
474
475 loadOldIface iface
476   = loadHomeDecls       (pi_decls iface)        `thenM` \ (decls_vers, new_decls) ->
477     loadHomeRules       (pi_rules iface)        `thenM` \ (rule_vers, new_rules) -> 
478     loadHomeInsts       (pi_insts iface)        `thenM` \ new_insts ->
479     mappM loadHomeUsage (pi_usages iface)       `thenM` \ usages ->
480     loadExports         (pi_exports iface)      `thenM` \ (export_vers, avails) ->
481     loadFixDecls        (pi_fixity iface)       `thenM` \ fix_env ->
482     loadDeprecs         (pi_deprecs iface)      `thenM` \ deprec_env ->
483
484     getModeRn                                   `thenM` \ (InterfaceMode mod) ->
485                 -- Caller sets the module before the call; also needed
486                 -- by the newGlobalName stuff in some of the loadHomeX calls
487     let
488         version = VersionInfo { vers_module  = pi_vers iface, 
489                                 vers_exports = export_vers,
490                                 vers_rules   = rule_vers,
491                                 vers_decls   = decls_vers }
492
493         decls = mkIfaceDecls new_decls new_rules new_insts
494
495         mod_iface = ModIface { mi_module = mod, mi_package = pi_pkg iface,
496                                mi_version = version, mi_deps = pi_deps iface,
497                                mi_exports = avails, mi_usages = usages,
498                                mi_boot = False, mi_orphan = pi_orphan iface, 
499                                mi_fixities = fix_env, mi_deprecs = deprec_env,
500                                mi_decls   = decls,
501                                mi_globals = Nothing
502                     }
503     in
504     returnM mod_iface
505 \end{code}
506
507 \begin{code}
508 loadHomeDecls :: [(Version, RdrNameTyClDecl)]
509               -> RnM (NameEnv Version, [RenamedTyClDecl])
510 loadHomeDecls decls = foldlM loadHomeDecl (emptyNameEnv, []) decls
511
512 loadHomeDecl :: (NameEnv Version, [RenamedTyClDecl])
513              -> (Version, RdrNameTyClDecl)
514              -> RnM (NameEnv Version, [RenamedTyClDecl])
515 loadHomeDecl (version_map, decls) (version, decl)
516   = rnTyClDecl decl     `thenM` \ decl' ->
517     returnM (extendNameEnv version_map (tyClDeclName decl') version, decl':decls)
518
519 ------------------
520 loadHomeRules :: (Version, [RdrNameRuleDecl])
521               -> RnM (Version, [RenamedRuleDecl])
522 loadHomeRules (version, rules)
523   = mappM rnIfaceRuleDecl rules `thenM` \ rules' ->
524     returnM (version, rules')
525
526 ------------------
527 loadHomeInsts :: [RdrNameInstDecl]
528               -> RnM [RenamedInstDecl]
529 loadHomeInsts insts = mappM rnInstDecl insts
530
531 ------------------
532 loadHomeUsage :: Usage OccName -> TcRn m (Usage Name)
533 loadHomeUsage usage
534   = mappM rn_imp (usg_entities usage)   `thenM` \ entities' ->
535     returnM (usage { usg_entities = entities' })
536   where
537     mod_name = usg_name usage 
538     rn_imp (occ,vers) = newGlobalName2 mod_name occ     `thenM` \ name ->
539                         returnM (name,vers)
540 \end{code}
541
542
543 %*********************************************************
544 %*                                                      *
545 \subsection{Reading an interface file}
546 %*                                                      *
547 %*********************************************************
548
549 \begin{code}
550 findAndReadIface :: SDoc -> ModuleName 
551                  -> IsBootInterface     -- True  <=> Look for a .hi-boot file
552                                         -- False <=> Look for .hi file
553                  -> TcRn m (Either Message (Module, ParsedIface))
554         -- Nothing <=> file not found, or unreadable, or illegible
555         -- Just x  <=> successfully found and parsed 
556
557         -- It *doesn't* add an error to the monad, because 
558         -- sometimes it's ok to fail... see notes with loadInterface
559
560 findAndReadIface doc_str mod_name hi_boot_file
561   = traceRn trace_msg                   `thenM_`
562
563     -- Check for GHC.Prim, and return its static interface
564     if mod_name == gHC_PRIM_Name
565         then returnM (Right (gHC_PRIM, ghcPrimIface))
566         else
567
568     ioToTcRn (findHiFile mod_name hi_boot_file) `thenM` \ maybe_found ->
569
570     case maybe_found of
571       Left files -> 
572         traceRn (ptext SLIT("...not found"))    `thenM_`
573         getDOpts                                `thenM` \ dflags ->
574         returnM (Left (noIfaceErr dflags mod_name hi_boot_file files))
575
576       Right (wanted_mod, file_path) -> 
577         traceRn (ptext SLIT("readIFace") <+> text file_path)    `thenM_` 
578
579         readIface wanted_mod file_path hi_boot_file     `thenM` \ read_result ->
580                 -- Catch exceptions here 
581
582         case read_result of
583           Left exn    -> returnM (Left (badIfaceFile file_path 
584                                           (text (showException exn))))
585
586           Right iface -> returnM (Right (wanted_mod, iface))
587
588   where
589     trace_msg = sep [hsep [ptext SLIT("Reading"), 
590                            if hi_boot_file then ptext SLIT("[boot]") else empty,
591                            ptext SLIT("interface for"), 
592                            ppr mod_name <> semi],
593                      nest 4 (ptext SLIT("reason:") <+> doc_str)]
594
595 findHiFile :: ModuleName -> IsBootInterface
596            -> IO (Either [FilePath] (Module, FilePath))
597 findHiFile mod_name hi_boot_file
598  = do { 
599         -- In interactive or --make mode, we are *not allowed* to demand-load
600         -- a home package .hi file.  So don't even look for them.
601         -- This helps in the case where you are sitting in eg. ghc/lib/std
602         -- and start up GHCi - it won't complain that all the modules it tries
603         -- to load are found in the home location.
604         ghci_mode <- readIORef v_GhcMode ;
605         let { home_allowed = hi_boot_file || 
606                              not (isCompManagerMode ghci_mode) } ;
607         maybe_found <-  if home_allowed 
608                         then findModule mod_name
609                         else findPackageModule mod_name ;
610
611         case maybe_found of {
612           Left files -> return (Left files) ;
613
614           Right (mod,loc) -> do {
615
616         -- Return the path to M.hi, M.hi-boot, or M.hi-boot-n as appropriate
617         let { hi_path            = ml_hi_file loc ;
618               hi_boot_path       = replaceFilenameSuffix hi_path hiBootExt ;
619               hi_boot_ver_path   = replaceFilenameSuffix hi_path hiBootVerExt 
620             };
621
622         if not hi_boot_file then
623            return (Right (mod, hi_path))
624         else do {
625                 hi_ver_exists <- doesFileExist hi_boot_ver_path ;
626                 if hi_ver_exists then return (Right (mod, hi_boot_ver_path))
627                                  else return (Right (mod, hi_boot_path))
628         }}}}
629 \end{code}
630
631 @readIface@ tries just the one file.
632
633 \begin{code}
634 readIface :: Module -> String -> IsBootInterface -> TcRn m (Either Exception ParsedIface)
635         -- Nothing <=> file not found, or unreadable, or illegible
636         -- Just x  <=> successfully found and parsed 
637
638 readIface mod file_path is_hi_boot_file
639   = ioToTcRn (tryMost (read_iface mod file_path is_hi_boot_file))
640
641 read_iface mod file_path is_hi_boot_file
642  | is_hi_boot_file              -- Read ascii
643  = do { buffer <- hGetStringBuffer file_path ;
644         case parseIface buffer (mkPState loc exts) of
645           POk _ iface | wanted_mod_name == actual_mod_name
646                       -> return iface
647                       | otherwise
648                       -> throwDyn (ProgramError (showSDoc err)) 
649                                 -- 'showSDoc' is a bit yukky
650                 where
651                   wanted_mod_name = moduleName mod
652                   actual_mod_name = pi_mod iface
653                   err = hiModuleNameMismatchWarn wanted_mod_name actual_mod_name
654
655           PFailed err -> throwDyn (ProgramError (showSDoc err))
656      }
657
658  | otherwise            -- Read binary
659  = readBinIface file_path
660
661  where
662     exts = ExtFlags {glasgowExtsEF = True,
663                      ffiEF         = True,
664                      withEF        = True,
665                      parrEF        = True}
666     loc  = mkSrcLoc (mkFastString file_path) 1
667 \end{code}
668
669
670 %*********************************************************
671 %*                                                       *
672         Wired-in interface for GHC.Prim
673 %*                                                       *
674 %*********************************************************
675
676 \begin{code}
677 ghcPrimIface :: ParsedIface
678 ghcPrimIface = ParsedIface {
679       pi_mod     = gHC_PRIM_Name,
680       pi_pkg     = basePackage,
681       pi_deps    = noDependencies,
682       pi_vers    = 1,
683       pi_orphan  = False,
684       pi_usages  = [],
685       pi_exports = (1, [(gHC_PRIM_Name, ghcPrimExports)]),
686       pi_decls   = [(1,cCallableClassDecl), 
687                     (1,cReturnableClassDecl)],
688       pi_fixity  = [FixitySig (nameRdrName (idName seqId)) 
689                               (Fixity 0 InfixR) noSrcLoc],
690                 -- seq is infixr 0
691       pi_insts   = [],
692       pi_rules   = (1,[]),
693       pi_deprecs = Nothing
694  }
695 \end{code}
696
697 %*********************************************************
698 %*                                                       *
699 \subsection{Errors}
700 %*                                                       *
701 %*********************************************************
702
703 \begin{code}
704 badIfaceFile file err
705   = vcat [ptext SLIT("Bad interface file:") <+> text file, 
706           nest 4 err]
707
708 hiModuleNameMismatchWarn :: ModuleName -> ModuleName -> Message
709 hiModuleNameMismatchWarn requested_mod read_mod = 
710     hsep [ ptext SLIT("Something is amiss; requested module name")
711          , ppr requested_mod
712          , ptext SLIT("differs from name found in the interface file")
713          , ppr read_mod
714          ]
715
716 warnRedundantSourceImport mod_name
717   = ptext SLIT("Unnecessary {- SOURCE -} in the import of module")
718           <+> quotes (ppr mod_name)
719
720 warnSelfImport mod
721   = ptext SLIT("Importing my own interface: module") <+> ppr mod
722 \end{code}