[project @ 2002-11-06 12:49:47 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, 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 )
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         this_mod_name = moduleName this_mod
228         is_loaded m   =  m == this_mod_name 
229                       || maybeToBool (lookupIfaceByModName hpt pit m)
230                 -- We treat the currently-being-compiled module as 'loaded' because
231                 -- even though it isn't yet in the HIT or PIT; otherwise it gets
232                 -- put into iImpModInfo, and then spat out into its own interface
233                 -- file as a dependency
234
235         -- Now add info about this module to the PIT
236         has_orphans = pi_orphan iface
237         new_pit   = extendModuleEnv pit mod mod_iface
238         mod_iface = ModIface { mi_module = mod, mi_package = pi_pkg iface,
239                                mi_version = version,
240                                mi_orphan = has_orphans, mi_boot = hi_boot_file,
241                                mi_exports = avails, 
242                                mi_fixities = fix_env, mi_deprecs = deprec_env,
243                                mi_deps     = pi_deps iface,
244                                mi_usages   = panic "No mi_usages in PIT",
245                                mi_decls    = panic "No mi_decls in PIT",
246                                mi_globals  = Nothing
247                     }
248
249         new_eps = eps { eps_PIT      = new_pit,
250                         eps_decls    = new_decls,
251                         eps_insts    = new_insts,
252                         eps_rules    = new_rules }
253     in
254     setEps new_eps              `thenM_`
255     returnM mod_iface
256     }}
257
258 -----------------------------------------------------
259 --      Loading the export list
260 -----------------------------------------------------
261
262 loadExports :: (Version, [RdrExportItem]) -> TcRn m (Version, [(ModuleName,Avails)])
263 loadExports (vers, items)
264   = mappM loadExport items      `thenM` \ avails_s ->
265     returnM (vers, avails_s)
266
267
268 loadExport :: RdrExportItem -> TcRn m (ModuleName, Avails)
269 loadExport (mod, entities)
270   = mappM (load_entity mod) entities    `thenM` \ avails ->
271     returnM (mod, avails)
272   where
273     load_entity mod (Avail occ)
274       = newGlobalName2 mod occ  `thenM` \ name ->
275         returnM (Avail name)
276     load_entity mod (AvailTC occ occs)
277       = newGlobalName2 mod occ          `thenM` \ name ->
278         mappM (newGlobalName2 mod) occs `thenM` \ names ->
279         returnM (AvailTC name names)
280
281
282 -----------------------------------------------------
283 --      Loading type/class/value decls
284 -----------------------------------------------------
285
286 loadDecls :: Module 
287           -> DeclsMap
288           -> [(Version, RdrNameTyClDecl)]
289           -> TcRn m (NameEnv Version, DeclsMap)
290 loadDecls mod (decls_map, n_slurped) decls
291   = foldlM (loadDecl mod) (emptyNameEnv, decls_map) decls       `thenM` \ (vers, decls_map') -> 
292     returnM (vers, (decls_map', n_slurped))
293
294 loadDecl mod (version_map, decls_map) (version, decl)
295   = getTyClDeclBinders mod decl         `thenM` \ avail ->
296     getSysBinders mod decl              `thenM` \ sys_names ->
297     let
298         full_avail    = case avail of
299                           Avail n -> avail
300                           AvailTC n ns -> AvailTC n (sys_names ++ ns)
301         main_name     = availName full_avail
302         new_decls_map = extendNameEnvList decls_map stuff
303         stuff         = [ (name, (full_avail, name==main_name, (mod, decl))) 
304                         | name <- availNames full_avail]
305
306         new_version_map = extendNameEnv version_map main_name version
307     in
308     traceRn (text "Loading" <+> ppr full_avail) `thenM_`
309     returnM (new_version_map, new_decls_map)
310
311
312
313 -----------------
314 getTyClDeclBinders :: Module -> RdrNameTyClDecl -> TcRn m AvailInfo     
315
316 getTyClDeclBinders mod (IfaceSig {tcdName = var, tcdLoc = src_loc})
317   = newTopBinder mod var src_loc                        `thenM` \ var_name ->
318     returnM (Avail var_name)
319
320 getTyClDeclBinders mod tycl_decl
321   = mapM new (tyClDeclNames tycl_decl)  `thenM` \ names@(main_name:_) ->
322     returnM (AvailTC main_name names)
323   where
324     new (nm,loc) = newTopBinder mod nm loc
325
326 --------------------------------
327 -- The "system names" are extra implicit names *bound* by the decl.
328
329 getSysBinders :: Module -> TyClDecl RdrName -> TcRn m [Name]
330 -- Similar to tyClDeclNames, but returns the "implicit" 
331 -- or "system" names of the declaration.  And it only works
332 -- on RdrNames, returning OccNames
333
334 getSysBinders mod (ClassDecl {tcdName = cname, tcdCtxt = cxt, tcdLoc = loc})
335   = sequenceM [new_sys_bndr mod n loc | n <- sys_occs]
336   where
337         -- C.f. TcClassDcl.tcClassDecl1
338     sys_occs    = tc_occ : data_occ : dw_occ : sc_sel_occs
339     cls_occ     = rdrNameOcc cname
340     data_occ    = mkClassDataConOcc cls_occ
341     dw_occ      = mkWorkerOcc data_occ
342     tc_occ      = mkClassTyConOcc   cls_occ
343     sc_sel_occs = [mkSuperDictSelOcc n cls_occ | n <- [1..length cxt]]
344
345 getSysBinders mod (TyData {tcdName = tc_name, tcdCons = DataCons cons,  
346                            tcdGeneric = Just want_generic, tcdLoc = loc})
347         -- The 'Just' is because this is an interface-file decl
348         -- so it will say whether to derive generic stuff for it or not
349   = sequenceM ([new_sys_bndr mod n loc | n <- gen_occs] ++ 
350                map con_sys_occ cons)
351   where
352         -- c.f. TcTyDecls.tcTyDecl
353     tc_occ = rdrNameOcc tc_name
354     gen_occs | want_generic = [mkGenOcc1 tc_occ, mkGenOcc2 tc_occ]
355              | otherwise    = []
356     con_sys_occ (ConDecl name _ _ _ loc) 
357         = new_sys_bndr mod (mkWorkerOcc (rdrNameOcc name)) loc
358     
359 getSysBinders mod decl = returnM []
360
361 new_sys_bndr mod occ loc = newTopBinder mod (mkRdrUnqual occ) loc
362
363
364 -----------------------------------------------------
365 --      Loading fixity decls
366 -----------------------------------------------------
367
368 loadFixDecls decls
369   = mappM loadFixDecl decls     `thenM` \ to_add ->
370     returnM (mkNameEnv to_add)
371
372 loadFixDecl (FixitySig rdr_name fixity loc)
373   = lookupGlobalOccRn rdr_name          `thenM` \ name ->
374     returnM (name, FixitySig name fixity loc)
375
376
377 -----------------------------------------------------
378 --      Loading instance decls
379 -----------------------------------------------------
380
381 loadInstDecls :: Module -> IfaceInsts
382               -> [RdrNameInstDecl]
383               -> RnM IfaceInsts
384 loadInstDecls mod (insts, n_slurped) decls
385   = foldlM (loadInstDecl mod) insts decls       `thenM` \ insts' ->
386     returnM (insts', n_slurped)
387
388
389 loadInstDecl mod insts decl@(InstDecl inst_ty _ _ _ _)
390   =     -- Find out what type constructors and classes are "gates" for the
391         -- instance declaration.  If all these "gates" are slurped in then
392         -- we should slurp the instance decl too.
393         -- 
394         -- We *don't* want to count names in the context part as gates, though.
395         -- For example:
396         --              instance Foo a => Baz (T a) where ...
397         --
398         -- Here the gates are Baz and T, but *not* Foo.
399         -- 
400         -- HOWEVER: functional dependencies make things more complicated
401         --      class C a b | a->b where ...
402         --      instance C Foo Baz where ...
403         -- Here, the gates are really only C and Foo, *not* Baz.
404         -- That is, if C and Foo are visible, even if Baz isn't, we must
405         -- slurp the decl.
406         --
407         -- Rather than take fundeps into account "properly", we just slurp
408         -- if C is visible and *any one* of the Names in the types
409         -- This is a slightly brutal approximation, but most instance decls
410         -- are regular H98 ones and it's perfect for them.
411         --
412         -- NOTICE that we rename the type before extracting its free
413         -- variables.  The free-variable finder for a renamed HsType 
414         -- does the Right Thing for built-in syntax like [] and (,).
415     rnHsType (text "In an interface instance decl") inst_ty     `thenM` \ inst_ty' ->
416     let 
417         (tvs,_,cls,tys) = splitHsInstDeclTy inst_ty'
418         free_tcs  = nameSetToList (extractHsTyNames_s tys) `minusList` hsTyVarNames tvs
419
420         gate_fn vis_fn = vis_fn cls && (null free_tcs || any vis_fn free_tcs)
421         -- The 'vis_fn' returns True for visible names
422         -- Here is the implementation of HOWEVER above
423         -- (Note that we do let the inst decl in if it mentions 
424         --  no tycons at all.  Hence the null free_ty_names.)
425     in
426     traceRn ((text "Load instance for" <+> ppr inst_ty') $$ ppr free_tcs)       `thenM_`
427     returnM ((gate_fn, (mod, decl)) `consBag` insts)
428
429
430
431 -----------------------------------------------------
432 --      Loading Rules
433 -----------------------------------------------------
434
435 loadRules :: Module
436           -> IfaceRules 
437           -> (Version, [RdrNameRuleDecl])
438           -> RnM (Version, IfaceRules)
439 loadRules mod (rule_bag, n_slurped) (version, rules)
440   | null rules || opt_IgnoreIfacePragmas 
441   = returnM (version, (rule_bag, n_slurped))
442   | otherwise
443   = mappM (loadRule mod) rules          `thenM` \ new_rules ->
444     returnM (version, (rule_bag `unionBags` listToBag new_rules, n_slurped))
445
446 loadRule :: Module -> RdrNameRuleDecl -> RnM (GatedDecl RdrNameRuleDecl)
447 -- "Gate" the rule simply by whether the rule variable is
448 -- needed.  We can refine this later.
449 loadRule mod decl@(IfaceRule _ _ _ var _ _ src_loc)
450   = lookupGlobalOccRn var               `thenM` \ var_name ->
451     returnM (\vis_fn -> vis_fn var_name, (mod, decl))
452
453
454 -----------------------------------------------------
455 --      Loading Deprecations
456 -----------------------------------------------------
457
458 loadDeprecs :: IfaceDeprecs -> RnM Deprecations
459 loadDeprecs Nothing            = returnM NoDeprecs
460 loadDeprecs (Just (Left txt))  = returnM (DeprecAll txt)
461 loadDeprecs (Just (Right prs)) = foldlM loadDeprec emptyNameEnv prs     `thenM` \ env ->
462                                  returnM (DeprecSome env)
463 loadDeprec deprec_env (n, txt)
464   = lookupGlobalOccRn n         `thenM` \ name ->
465     traceRn (text "Loaded deprecation(s) for" <+> ppr name <> colon <+> ppr txt) `thenM_`
466     returnM (extendNameEnv deprec_env name (name,txt))
467 \end{code}
468
469
470 %********************************************************
471 %*                                                      *
472         Load the ParsedIface for the *current* module
473         into a ModIface; then it can be checked
474         for up-to-date-ness
475 %*                                                      *
476 %********************************************************
477
478 \begin{code}
479 loadOldIface :: ParsedIface -> RnM ModIface
480
481 loadOldIface iface
482   = loadHomeDecls       (pi_decls iface)        `thenM` \ (decls_vers, new_decls) ->
483     loadHomeRules       (pi_rules iface)        `thenM` \ (rule_vers, new_rules) -> 
484     loadHomeInsts       (pi_insts iface)        `thenM` \ new_insts ->
485     mappM loadHomeUsage (pi_usages iface)       `thenM` \ usages ->
486     loadExports         (pi_exports iface)      `thenM` \ (export_vers, avails) ->
487     loadFixDecls        (pi_fixity iface)       `thenM` \ fix_env ->
488     loadDeprecs         (pi_deprecs iface)      `thenM` \ deprec_env ->
489
490     getModeRn                                   `thenM` \ (InterfaceMode mod) ->
491                 -- Caller sets the module before the call; also needed
492                 -- by the newGlobalName stuff in some of the loadHomeX calls
493     let
494         version = VersionInfo { vers_module  = pi_vers iface, 
495                                 vers_exports = export_vers,
496                                 vers_rules   = rule_vers,
497                                 vers_decls   = decls_vers }
498
499         decls = mkIfaceDecls new_decls new_rules new_insts
500
501         mod_iface = ModIface { mi_module = mod, mi_package = pi_pkg iface,
502                                mi_version = version, mi_deps = pi_deps iface,
503                                mi_exports = avails, mi_usages = usages,
504                                mi_boot = False, mi_orphan = pi_orphan iface, 
505                                mi_fixities = fix_env, mi_deprecs = deprec_env,
506                                mi_decls   = decls,
507                                mi_globals = Nothing
508                     }
509     in
510     returnM mod_iface
511 \end{code}
512
513 \begin{code}
514 loadHomeDecls :: [(Version, RdrNameTyClDecl)]
515               -> RnM (NameEnv Version, [RenamedTyClDecl])
516 loadHomeDecls decls = foldlM loadHomeDecl (emptyNameEnv, []) decls
517
518 loadHomeDecl :: (NameEnv Version, [RenamedTyClDecl])
519              -> (Version, RdrNameTyClDecl)
520              -> RnM (NameEnv Version, [RenamedTyClDecl])
521 loadHomeDecl (version_map, decls) (version, decl)
522   = rnTyClDecl decl     `thenM` \ decl' ->
523     returnM (extendNameEnv version_map (tyClDeclName decl') version, decl':decls)
524
525 ------------------
526 loadHomeRules :: (Version, [RdrNameRuleDecl])
527               -> RnM (Version, [RenamedRuleDecl])
528 loadHomeRules (version, rules)
529   = mappM rnIfaceRuleDecl rules `thenM` \ rules' ->
530     returnM (version, rules')
531
532 ------------------
533 loadHomeInsts :: [RdrNameInstDecl]
534               -> RnM [RenamedInstDecl]
535 loadHomeInsts insts = mappM rnInstDecl insts
536
537 ------------------
538 loadHomeUsage :: Usage OccName -> TcRn m (Usage Name)
539 loadHomeUsage usage
540   = mappM rn_imp (usg_entities usage)   `thenM` \ entities' ->
541     returnM (usage { usg_entities = entities' })
542   where
543     mod_name = usg_name usage 
544     rn_imp (occ,vers) = newGlobalName2 mod_name occ     `thenM` \ name ->
545                         returnM (name,vers)
546 \end{code}
547
548
549 %*********************************************************
550 %*                                                      *
551 \subsection{Reading an interface file}
552 %*                                                      *
553 %*********************************************************
554
555 \begin{code}
556 findAndReadIface :: SDoc -> ModuleName 
557                  -> IsBootInterface     -- True  <=> Look for a .hi-boot file
558                                         -- False <=> Look for .hi file
559                  -> TcRn m (Either Message (Module, ParsedIface))
560         -- Nothing <=> file not found, or unreadable, or illegible
561         -- Just x  <=> successfully found and parsed 
562
563         -- It *doesn't* add an error to the monad, because 
564         -- sometimes it's ok to fail... see notes with loadInterface
565
566 findAndReadIface doc_str mod_name hi_boot_file
567   = traceRn trace_msg                   `thenM_`
568
569     -- Check for GHC.Prim, and return its static interface
570     if mod_name == gHC_PRIM_Name
571         then returnM (Right (gHC_PRIM, ghcPrimIface))
572         else
573
574     ioToTcRn (findHiFile mod_name hi_boot_file) `thenM` \ maybe_found ->
575
576     case maybe_found of
577       Nothing -> 
578         traceRn (ptext SLIT("...not found"))    `thenM_`
579         returnM (Left (noIfaceErr mod_name hi_boot_file))
580
581       Just (wanted_mod, file_path) -> 
582         traceRn (ptext SLIT("readIFace") <+> text file_path)    `thenM_` 
583
584         readIface wanted_mod file_path hi_boot_file     `thenM` \ read_result ->
585                 -- Catch exceptions here 
586
587         case read_result of
588           Left exn    -> returnM (Left (badIfaceFile file_path 
589                                           (text (showException exn))))
590
591           Right iface -> returnM (Right (wanted_mod, iface))
592
593   where
594     trace_msg = sep [hsep [ptext SLIT("Reading"), 
595                            if hi_boot_file then ptext SLIT("[boot]") else empty,
596                            ptext SLIT("interface for"), 
597                            ppr mod_name <> semi],
598                      nest 4 (ptext SLIT("reason:") <+> doc_str)]
599
600 findHiFile :: ModuleName -> IsBootInterface -> IO (Maybe (Module, FilePath))
601 findHiFile mod_name hi_boot_file
602  = do { 
603         -- In interactive or --make mode, we are *not allowed* to demand-load
604         -- a home package .hi file.  So don't even look for them.
605         -- This helps in the case where you are sitting in eg. ghc/lib/std
606         -- and start up GHCi - it won't complain that all the modules it tries
607         -- to load are found in the home location.
608         ghci_mode <- readIORef v_GhcMode ;
609         let { home_allowed = hi_boot_file || 
610                              not (isCompManagerMode ghci_mode) } ;
611         maybe_found <-  if home_allowed 
612                         then findModule mod_name
613                         else findPackageModule mod_name ;
614
615         case maybe_found of {
616           Nothing -> return Nothing ;
617
618           Just (mod,loc) -> do {
619
620         -- Return the path to M.hi, M.hi-boot, or M.hi-boot-n as appropriate
621         let { hi_path            = ml_hi_file loc ;
622               hi_boot_path       = replaceFilenameSuffix hi_path hiBootExt ;
623               hi_boot_ver_path   = replaceFilenameSuffix hi_path hiBootVerExt 
624             };
625
626         if not hi_boot_file then
627            return (Just (mod, hi_path))
628         else do {
629                 hi_ver_exists <- doesFileExist hi_boot_ver_path ;
630                 if hi_ver_exists then return (Just (mod, hi_boot_ver_path))
631                                  else return (Just (mod, hi_boot_path))
632         }}}}
633 \end{code}
634
635 @readIface@ tries just the one file.
636
637 \begin{code}
638 readIface :: Module -> String -> IsBootInterface -> TcRn m (Either Exception ParsedIface)
639         -- Nothing <=> file not found, or unreadable, or illegible
640         -- Just x  <=> successfully found and parsed 
641
642 readIface mod file_path is_hi_boot_file
643   = ioToTcRn (tryMost (read_iface mod file_path is_hi_boot_file))
644
645 read_iface mod file_path is_hi_boot_file
646  | is_hi_boot_file              -- Read ascii
647  = do { buffer <- hGetStringBuffer file_path ;
648         case parseIface buffer (mkPState loc exts) of
649           POk _ iface | wanted_mod_name == actual_mod_name
650                       -> return iface
651                       | otherwise
652                       -> throwDyn (ProgramError (showSDoc err)) 
653                                 -- 'showSDoc' is a bit yukky
654                 where
655                   wanted_mod_name = moduleName mod
656                   actual_mod_name = pi_mod iface
657                   err = hiModuleNameMismatchWarn wanted_mod_name actual_mod_name
658
659           PFailed err -> throwDyn (ProgramError (showSDoc err))
660      }
661
662  | otherwise            -- Read binary
663  = readBinIface file_path
664
665  where
666     exts = ExtFlags {glasgowExtsEF = True,
667                      ffiEF         = True,
668                      withEF        = True,
669                      parrEF        = True}
670     loc  = mkSrcLoc (mkFastString file_path) 1
671 \end{code}
672
673
674 %*********************************************************
675 %*                                                       *
676         Wired-in interface for GHC.Prim
677 %*                                                       *
678 %*********************************************************
679
680 \begin{code}
681 ghcPrimIface :: ParsedIface
682 ghcPrimIface = ParsedIface {
683       pi_mod     = gHC_PRIM_Name,
684       pi_pkg     = basePackage,
685       pi_deps    = noDependencies,
686       pi_vers    = 1,
687       pi_orphan  = False,
688       pi_usages  = [],
689       pi_exports = (1, [(gHC_PRIM_Name, ghcPrimExports)]),
690       pi_decls   = [(1,cCallableClassDecl), 
691                     (1,cReturnableClassDecl)],
692       pi_fixity  = [FixitySig (nameRdrName (idName seqId)) 
693                               (Fixity 0 InfixR) noSrcLoc],
694                 -- seq is infixr 0
695       pi_insts   = [],
696       pi_rules   = (1,[]),
697       pi_deprecs = Nothing
698  }
699 \end{code}
700
701 %*********************************************************
702 %*                                                       *
703 \subsection{Errors}
704 %*                                                       *
705 %*********************************************************
706
707 \begin{code}
708 noIfaceErr mod_name boot_file
709   = ptext SLIT("Could not find interface file for") <+> quotes (ppr mod_name)
710         -- We used to print the search path, but we can't do that
711         -- now, because it's hidden inside the finder.
712         -- Maybe the finder should expose more functions.
713
714 badIfaceFile file err
715   = vcat [ptext SLIT("Bad interface file:") <+> text file, 
716           nest 4 err]
717
718 hiModuleNameMismatchWarn :: ModuleName -> ModuleName -> Message
719 hiModuleNameMismatchWarn requested_mod read_mod = 
720     hsep [ ptext SLIT("Something is amiss; requested module name")
721          , ppr requested_mod
722          , ptext SLIT("differs from name found in the interface file")
723          , ppr read_mod
724          ]
725
726 warnRedundantSourceImport mod_name
727   = ptext SLIT("Unnecessary {- SOURCE -} in the import of module")
728           <+> quotes (ppr mod_name)
729
730 warnSelfImport mod
731   = ptext SLIT("Importing my own interface: module") <+> ppr mod
732 \end{code}