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