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 removeContext -- removeContext probably belongs somewhere else
18 #include "HsVersions.h"
20 import DriverUtil ( splitFilename )
21 import CmdLineOpts ( opt_IgnoreIfacePragmas )
22 import HscTypes ( ModuleLocation(..),
23 ModIface(..), emptyModIface,
24 VersionInfo(..), ImportedModuleInfo,
26 ImportVersion, WhetherHasOrphans, IsBootInterface,
27 DeclsMap, GatedDecl, IfaceInsts, IfaceRules,
28 AvailInfo, GenAvailInfo(..), Avails, Deprecations(..)
30 import HsSyn ( TyClDecl(..), InstDecl(..),
31 HsType(..), FixitySig(..), RuleDecl(..),
32 tyClDeclNames, tyClDeclSysNames
34 import RdrHsSyn ( RdrNameTyClDecl, RdrNameInstDecl, RdrNameRuleDecl,
37 import BasicTypes ( Version, defaultFixity )
40 import ParseIface ( parseIface )
42 import Name ( Name {-instance NamedThing-},
43 nameModule, isLocalName, nameIsLocalOrFrom
46 import Module ( Module,
47 moduleName, isHomeModule,
48 ModuleName, WhereFrom(..),
49 extendModuleEnv, mkVanillaModule
51 import RdrName ( rdrNameOcc )
52 import SrcLoc ( mkSrcLoc )
53 import Maybes ( maybeToBool, orElse )
54 import StringBuffer ( hGetStringBuffer )
55 import FastString ( mkFastString )
56 import ErrUtils ( Message )
57 import Finder ( findModule )
68 %*********************************************************
70 \subsection{Loading a new interface file}
72 %*********************************************************
75 loadHomeInterface :: SDoc -> Name -> RnM d ModIface
76 loadHomeInterface doc_str name
77 = ASSERT2( not (isLocalName name), ppr name <+> parens doc_str )
78 loadInterface doc_str (moduleName (nameModule name)) ImportBySystem
80 loadOrphanModules :: [ModuleName] -> RnM d ()
81 loadOrphanModules mods
82 | null mods = returnRn ()
83 | otherwise = traceRn (text "Loading orphan modules:" <+>
84 fsep (map ppr mods)) `thenRn_`
85 mapRn_ load mods `thenRn_`
88 load mod = loadInterface (mk_doc mod) mod ImportBySystem
89 mk_doc mod = ppr mod <+> ptext SLIT("is a orphan-instance module")
91 loadInterface :: SDoc -> ModuleName -> WhereFrom -> RnM d ModIface
92 loadInterface doc mod from
93 = tryLoadInterface doc mod from `thenRn` \ (ifaces, maybe_err) ->
95 Nothing -> returnRn ifaces
96 Just err -> failWithRn ifaces (elaborate err)
98 elaborate err = hang (ptext SLIT("failed to load interface for") <+> quotes (ppr mod) <> colon)
101 tryLoadInterface :: SDoc -> ModuleName -> WhereFrom -> RnM d (ModIface, Maybe Message)
102 -- Returns (Just err) if an error happened
103 -- It *doesn't* add an error to the monad, because sometimes it's ok to fail...
104 -- Specifically, when we read the usage information from an interface file,
105 -- we try to read the interfaces it mentions. But it's OK to fail; perhaps
106 -- the module has changed, and that interface is no longer used.
108 -- tryLoadInterface guarantees to return with iImpModInfo m --> (..., True)
109 -- (If the load fails, we plug in a vanilla placeholder)
110 tryLoadInterface doc_str mod_name from
111 = getHomeIfaceTableRn `thenRn` \ hit ->
112 getModuleRn `thenRn` \ this_mod ->
113 getIfacesRn `thenRn` \ ifaces@(Ifaces { iPIT = pit }) ->
115 -- CHECK WHETHER WE HAVE IT ALREADY
116 case lookupIfaceByModName hit pit mod_name of {
117 Just iface | case from of
118 ImportByUser -> not (mi_boot iface)
119 ImportByUserSource -> mi_boot iface
120 ImportBySystem -> True
121 ImportByCmdLine -> True
122 -> returnRn (iface, Nothing) ; -- Already loaded
123 -- The not (mi_boot iface) test checks that the already-loaded
124 -- interface isn't a boot iface. This can conceivably happen,
125 -- if the version checking happened to load a boot interface
126 -- before we got to real imports.
130 mod_map = iImpModInfo ifaces
131 mod_info = lookupFM mod_map mod_name
134 = case (from, mod_info) of
135 (ImportByUser, _) -> False -- Not hi-boot
136 (ImportByUserSource, _) -> True -- hi-boot
137 (ImportByCmdLine, _) -> False
138 (ImportBySystem, Just (_, is_boot)) -> is_boot
139 (ImportBySystem, Nothing) -> False
140 -- We're importing a module we know absolutely
141 -- nothing about, so we assume it's from
142 -- another package, where we aren't doing
143 -- dependency tracking. So it won't be a hi-boot file.
145 redundant_source_import
146 = case (from, mod_info) of
147 (ImportByUserSource, Just (_,False)) -> True
150 home_allowed | ImportByCmdLine <- from = 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 home_allowed
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_version = version,
231 mi_orphan = has_orphans, mi_boot = hi_boot_file,
233 mi_fixities = fix_env, mi_deprecs = deprec_env,
234 mi_usages = [], -- Will be filled in later
235 mi_decls = panic "No mi_decls in PIT",
236 mi_globals = mkIfaceGlobalRdrEnv avails
239 new_ifaces = ifaces { iPIT = new_pit,
243 iImpModInfo = mod_map2 }
245 setIfacesRn new_ifaces `thenRn_`
246 returnRn (mod_iface, Nothing)
249 -----------------------------------------------------
250 -- Adding module dependencies from the
251 -- import decls in the interface file
252 -----------------------------------------------------
255 -> (ModuleName -> Bool) -- True for modules that are already loaded
257 -> ImportedModuleInfo -> ImportedModuleInfo
258 -- (addModDeps M ivs deps)
259 -- We are importing module M, and M.hi contains 'import' decls given by ivs
260 addModDeps mod is_loaded new_deps mod_deps
261 = foldr add mod_deps filtered_new_deps
263 -- Don't record dependencies when importing a module from another package
264 -- Except for its descendents which contain orphans,
265 -- and in that case, forget about the boot indicator
266 filtered_new_deps :: [(ModuleName, (WhetherHasOrphans, IsBootInterface))]
268 | isHomeModule mod = [ (imp_mod, (has_orphans, is_boot))
269 | (imp_mod, has_orphans, is_boot, _) <- new_deps,
270 not (is_loaded imp_mod)
272 | otherwise = [ (imp_mod, (True, False))
273 | (imp_mod, has_orphans, _, _) <- new_deps,
274 not (is_loaded imp_mod) && has_orphans
276 add (imp_mod, dep) deps = addToFM_C combine deps imp_mod dep
278 combine old@(old_has_orphans, old_is_boot) new@(new_has_orphans, new_is_boot)
279 | old_is_boot = new -- Record the best is_boot info
282 -----------------------------------------------------
283 -- Loading the export list
284 -----------------------------------------------------
286 loadExports :: (Version, [ExportItem]) -> RnM d (Version, [(ModuleName,Avails)])
287 loadExports (vers, items)
288 = mapRn loadExport items `thenRn` \ avails_s ->
289 returnRn (vers, avails_s)
292 loadExport :: ExportItem -> RnM d (ModuleName, Avails)
293 loadExport (mod, entities)
294 = mapRn (load_entity mod) entities `thenRn` \ avails ->
295 returnRn (mod, avails)
297 load_entity mod (Avail occ)
298 = newGlobalName mod occ `thenRn` \ name ->
299 returnRn (Avail name)
300 load_entity mod (AvailTC occ occs)
301 = newGlobalName mod occ `thenRn` \ name ->
302 mapRn (newGlobalName mod) occs `thenRn` \ names ->
303 returnRn (AvailTC name names)
306 -----------------------------------------------------
307 -- Loading type/class/value decls
308 -----------------------------------------------------
312 -> [(Version, RdrNameTyClDecl)]
313 -> RnM d (NameEnv Version, DeclsMap)
314 loadDecls mod (decls_map, n_slurped) decls
315 = foldlRn (loadDecl mod) (emptyNameEnv, decls_map) decls `thenRn` \ (vers, decls_map') ->
316 returnRn (vers, (decls_map', n_slurped))
318 loadDecl mod (version_map, decls_map) (version, decl)
319 = getTyClDeclBinders mod decl `thenRn` \ (avail, sys_names) ->
321 full_avail = case avail of
323 AvailTC n ns -> AvailTC n (sys_names ++ ns)
324 main_name = availName full_avail
325 new_decls_map = extendNameEnvList decls_map stuff
326 stuff = [ (name, (full_avail, name==main_name, (mod, decl)))
327 | name <- availNames full_avail]
329 new_version_map = extendNameEnv version_map main_name version
331 returnRn (new_version_map, new_decls_map)
333 -----------------------------------------------------
334 -- Loading fixity decls
335 -----------------------------------------------------
337 loadFixDecls mod decls
338 = mapRn (loadFixDecl mod_name) decls `thenRn` \ to_add ->
339 returnRn (mkNameEnv to_add)
341 mod_name = moduleName mod
343 loadFixDecl mod_name sig@(FixitySig rdr_name fixity loc)
344 = newGlobalName mod_name (rdrNameOcc rdr_name) `thenRn` \ name ->
345 returnRn (name, fixity)
348 -----------------------------------------------------
349 -- Loading instance decls
350 -----------------------------------------------------
352 loadInstDecls :: Module
356 loadInstDecls mod (insts, n_slurped) decls
358 foldlRn (loadInstDecl mod) insts decls `thenRn` \ insts' ->
359 returnRn (insts', n_slurped)
362 loadInstDecl mod insts decl@(InstDecl inst_ty _ _ _ _)
363 = -- Find out what type constructors and classes are "gates" for the
364 -- instance declaration. If all these "gates" are slurped in then
365 -- we should slurp the instance decl too.
367 -- We *don't* want to count names in the context part as gates, though.
369 -- instance Foo a => Baz (T a) where ...
371 -- Here the gates are Baz and T, but *not* Foo.
373 munged_inst_ty = removeContext inst_ty
374 free_names = extractHsTyRdrNames munged_inst_ty
376 mapRn lookupIfaceName free_names `thenRn` \ gate_names ->
377 returnRn ((gate_names, (mod, decl)) `consBag` insts)
380 -- In interface files, the instance decls now look like
381 -- forall a. Foo a -> Baz (T a)
382 -- so we have to strip off function argument types as well
383 -- as the bit before the '=>' (which is always empty in interface files)
384 removeContext (HsForAllTy tvs cxt ty) = HsForAllTy tvs [] (removeFuns ty)
385 removeContext ty = removeFuns ty
387 removeFuns (HsFunTy _ ty) = removeFuns ty
391 -----------------------------------------------------
393 -----------------------------------------------------
395 loadRules :: Module -> IfaceRules
396 -> (Version, [RdrNameRuleDecl])
397 -> RnM d (Version, IfaceRules)
398 loadRules mod (rule_bag, n_slurped) (version, rules)
399 | null rules || opt_IgnoreIfacePragmas
400 = returnRn (version, (rule_bag, n_slurped))
403 mapRn (loadRule mod) rules `thenRn` \ new_rules ->
404 returnRn (version, (rule_bag `unionBags` listToBag new_rules, n_slurped))
406 loadRule :: Module -> RdrNameRuleDecl -> RnM d (GatedDecl RdrNameRuleDecl)
407 -- "Gate" the rule simply by whether the rule variable is
408 -- needed. We can refine this later.
409 loadRule mod decl@(IfaceRule _ _ var _ _ src_loc)
410 = lookupIfaceName var `thenRn` \ var_name ->
411 returnRn ([var_name], (mod, decl))
414 -----------------------------------------------------
415 -- Loading Deprecations
416 -----------------------------------------------------
418 loadDeprecs :: Module -> IfaceDeprecs -> RnM d Deprecations
419 loadDeprecs m Nothing = returnRn NoDeprecs
420 loadDeprecs m (Just (Left txt)) = returnRn (DeprecAll txt)
421 loadDeprecs m (Just (Right prs)) = setModuleRn m $
422 foldlRn loadDeprec emptyNameEnv prs `thenRn` \ env ->
423 returnRn (DeprecSome env)
424 loadDeprec deprec_env (n, txt)
425 = lookupIfaceName n `thenRn` \ name ->
426 traceRn (text "Loaded deprecation(s) for" <+> ppr name <> colon <+> ppr txt) `thenRn_`
427 returnRn (extendNameEnv deprec_env name (name,txt))
431 %*********************************************************
433 \subsection{Getting binders out of a declaration}
435 %*********************************************************
437 @getDeclBinders@ returns the names for a @RdrNameHsDecl@.
438 It's used for both source code (from @availsFromDecl@) and interface files
441 It doesn't deal with source-code specific things: @ValD@, @DefD@. They
442 are handled by the sourc-code specific stuff in @RnNames@.
444 *** See "THE NAMING STORY" in HsDecls ****
451 -> RnM d (AvailInfo, [Name]) -- The [Name] are the system names
454 getTyClDeclBinders mod (IfaceSig {tcdName = var, tcdLoc = src_loc})
455 = newTopBinder mod var src_loc `thenRn` \ var_name ->
456 returnRn (Avail var_name, [])
458 getTyClDeclBinders mod tycl_decl
459 = new_top_bndrs mod (tyClDeclNames tycl_decl) `thenRn` \ names@(main_name:_) ->
460 new_top_bndrs mod (tyClDeclSysNames tycl_decl) `thenRn` \ sys_names ->
461 returnRn (AvailTC main_name names, sys_names)
464 new_top_bndrs mod names_w_locs
465 = sequenceRn [newTopBinder mod name loc | (name,loc) <- names_w_locs]
469 %*********************************************************
471 \subsection{Reading an interface file}
473 %*********************************************************
476 findAndReadIface :: SDoc -> ModuleName
477 -> IsBootInterface -- True <=> Look for a .hi-boot file
478 -- False <=> Look for .hi file
479 -> Bool -- True <=> can read home interface
480 -> RnM d (Either Message (Module, ParsedIface))
481 -- Nothing <=> file not found, or unreadable, or illegible
482 -- Just x <=> successfully found and parsed
484 findAndReadIface doc_str mod_name hi_boot_file home_allowed
485 = traceRn trace_msg `thenRn_`
487 ioToRnM (findModule mod_name) `thenRn` \ maybe_found ->
490 Right (Just (wanted_mod,locn))
491 -> -- in CmdLineMode, we cannot demand-load home interfaces
492 -- because the corresponding code won't be loaded, so we
493 -- check for this here and emit an error message.
494 if (home_allowed && isHomeModule wanted_mod)
495 then returnRn (Left (notLoaded wanted_mod))
498 mkHiPath hi_boot_file locn `thenRn` \ file ->
499 readIface file `thenRn` \ read_result ->
501 Left bad -> returnRn (Left bad)
503 -> let read_mod = pi_mod iface
504 in warnCheckRn (wanted_mod == read_mod)
505 (hiModuleNameMismatchWarn wanted_mod
507 returnRn (Right (wanted_mod, iface))
509 other -> traceRn (ptext SLIT("...not found")) `thenRn_`
510 returnRn (Left (noIfaceErr mod_name hi_boot_file))
513 trace_msg = sep [hsep [ptext SLIT("Reading"),
514 if hi_boot_file then ptext SLIT("[boot]") else empty,
515 ptext SLIT("interface for"),
516 ppr mod_name <> semi],
517 nest 4 (ptext SLIT("reason:") <+> doc_str)]
519 mkHiPath hi_boot_file locn
521 ioToRnM_no_fail (doesFileExist hi_boot_ver_path) `thenRn` \ b ->
522 if b then returnRn hi_boot_ver_path
523 else returnRn hi_boot_path
524 | otherwise = returnRn hi_path
525 where (Just hi_path) = ml_hi_file locn
526 (hi_base, _hi_suf) = splitFilename hi_path
527 hi_boot_path = hi_base ++ ".hi-boot"
528 hi_boot_ver_path = hi_base ++ ".hi-boot-" ++ cHscIfaceFileVersion
531 @readIface@ tries just the one file.
534 readIface :: String -> RnM d (Either Message ParsedIface)
535 -- Nothing <=> file not found, or unreadable, or illegible
536 -- Just x <=> successfully found and parsed
538 = --ioToRnM (putStrLn ("reading iface " ++ file_path)) `thenRn_`
539 traceRn (ptext SLIT("readIFace") <+> text file_path) `thenRn_`
541 ioToRnM (hGetStringBuffer False file_path) `thenRn` \ read_result ->
542 case read_result of {
543 Left io_error -> bale_out (text (show io_error)) ;
546 case parseIface contents init_parser_state of
547 POk _ iface -> returnRn (Right iface)
548 PFailed err -> bale_out err
551 init_parser_state = PState{ bol = 0#, atbol = 1#,
554 loc = mkSrcLoc (mkFastString file_path) 1 }
556 bale_out err = returnRn (Left (badIfaceFile file_path err))
560 %*********************************************************
562 \subsection{Looking up fixities}
564 %*********************************************************
566 @lookupFixityRn@ has to be in RnIfaces (or RnHiFiles) because
567 it calls @loadHomeInterface@.
569 lookupFixity is a bit strange.
571 * Nested local fixity decls are put in the local fixity env, which we
572 find with getFixtyEnv
574 * Imported fixities are found in the HIT or PIT
576 * Top-level fixity decls in this module may be for Names that are
577 either Global (constructors, class operations)
578 or Local/Exported (everything else)
579 (See notes with RnNames.getLocalDeclBinders for why we have this split.)
580 We put them all in the local fixity environment
583 lookupFixityRn :: Name -> RnMS Fixity
585 = getModuleRn `thenRn` \ this_mod ->
586 if nameIsLocalOrFrom this_mod name
587 then -- It's defined in this module
588 getFixityEnv `thenRn` \ local_fix_env ->
589 returnRn (lookupLocalFixity local_fix_env name)
591 else -- It's imported
592 -- For imported names, we have to get their fixities by doing a loadHomeInterface,
593 -- and consulting the Ifaces that comes back from that, because the interface
594 -- file for the Name might not have been loaded yet. Why not? Suppose you import module A,
595 -- which exports a function 'f', which is defined in module B. Then B isn't loaded
596 -- right away (after all, it's possible that nothing from B will be used).
597 -- When we come across a use of 'f', we need to know its fixity, and it's then,
598 -- and only then, that we load B.hi. That is what's happening here.
599 loadHomeInterface doc name `thenRn` \ iface ->
600 returnRn (lookupNameEnv (mi_fixities iface) name `orElse` defaultFixity)
602 doc = ptext SLIT("Checking fixity for") <+> ppr name
606 %*********************************************************
610 %*********************************************************
613 noIfaceErr mod_name boot_file
614 = ptext SLIT("Could not find interface file for") <+> quotes (ppr mod_name)
615 -- We used to print the search path, but we can't do that
616 -- now, because it's hidden inside the finder.
617 -- Maybe the finder should expose more functions.
619 badIfaceFile file err
620 = vcat [ptext SLIT("Bad interface file:") <+> text file,
623 hiModuleNameMismatchWarn :: Module -> Module -> Message
624 hiModuleNameMismatchWarn requested_mod read_mod =
625 hsep [ ptext SLIT("Something is amiss; requested module name")
626 , ppr (moduleName requested_mod)
627 , ptext SLIT("differs from name found in the interface file")
631 warnRedundantSourceImport mod_name
632 = ptext SLIT("Unnecessary {- SOURCE -} in the import of module")
633 <+> quotes (ppr mod_name)
636 = ptext SLIT("Module") <+> quotes (ppr mod) <+> ptext SLIT("is not loaded")
639 = ptext SLIT("Importing my own interface: module") <+> ppr mod