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 CmdLineOpts ( opt_IgnoreIfacePragmas )
21 import HscTypes ( ModuleLocation(..),
22 ModIface(..), emptyModIface,
25 ImportVersion, WhetherHasOrphans, IsBootInterface,
26 DeclsMap, GatedDecl, IfaceInsts, IfaceRules,
27 AvailInfo, GenAvailInfo(..), Avails, Deprecations(..)
29 import HsSyn ( TyClDecl(..), InstDecl(..),
30 HsType(..), FixitySig(..), RuleDecl(..),
31 tyClDeclNames, tyClDeclSysNames
33 import RdrHsSyn ( RdrNameTyClDecl, RdrNameInstDecl, RdrNameRuleDecl,
36 import BasicTypes ( Version, defaultFixity )
39 import ParseIface ( parseIface, IfaceStuff(..) )
41 import Name ( Name {-instance NamedThing-}, nameOccName,
42 nameModule, isLocalName, nameIsLocalOrFrom,
45 import Name ( mkNameEnv, extendNameEnv )
46 import Module ( Module,
47 moduleName, isHomeModule,
48 ModuleName, WhereFrom(..),
49 extendModuleEnv, mkVanillaModule
51 import RdrName ( 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 err
98 tryLoadInterface :: SDoc -> ModuleName -> WhereFrom -> RnM d (ModIface, Maybe Message)
99 -- Returns (Just err) if an error happened
100 -- It *doesn't* add an error to the monad, because sometimes it's ok to fail...
101 -- Specifically, when we read the usage information from an interface file,
102 -- we try to read the interfaces it mentions. But it's OK to fail; perhaps
103 -- the module has changed, and that interface is no longer used.
105 -- tryLoadInterface guarantees to return with iImpModInfo m --> (..., True)
106 -- (If the load fails, we plug in a vanilla placeholder)
107 tryLoadInterface doc_str mod_name from
108 = getHomeIfaceTableRn `thenRn` \ hit ->
109 getIfacesRn `thenRn` \ ifaces@(Ifaces { iPIT = pit }) ->
111 -- CHECK WHETHER WE HAVE IT ALREADY
112 case lookupIfaceByModName hit pit mod_name of {
113 Just iface | case from of
114 ImportByUser -> not (mi_boot iface)
115 ImportByUserSource -> mi_boot iface
116 ImportBySystem -> True
117 -> returnRn (iface, Nothing) ; -- Already loaded
118 -- The not (mi_boot iface) test checks that the already-loaded
119 -- interface isn't a boot iface. This can conceivably happen,
120 -- if the version checking happened to load a boot interface
121 -- before we got to real imports.
125 mod_map = iImpModInfo ifaces
126 mod_info = lookupFM mod_map mod_name
129 = case (from, mod_info) of
130 (ImportByUser, _) -> False -- Not hi-boot
131 (ImportByUserSource, _) -> True -- hi-boot
132 (ImportBySystem, Just (_, is_boot)) -> is_boot
133 (ImportBySystem, Nothing) -> False
134 -- We're importing a module we know absolutely
135 -- nothing about, so we assume it's from
136 -- another package, where we aren't doing
137 -- dependency tracking. So it won't be a hi-boot file.
139 redundant_source_import
140 = case (from, mod_info) of
141 (ImportByUserSource, Just (_,False)) -> True
145 -- Issue a warning for a redundant {- SOURCE -} import
146 -- NB that we arrange to read all the ordinary imports before
147 -- any of the {- SOURCE -} imports
148 warnCheckRn (not redundant_source_import)
149 (warnRedundantSourceImport mod_name) `thenRn_`
151 -- READ THE MODULE IN
152 findAndReadIface doc_str mod_name hi_boot_file `thenRn` \ read_result ->
153 case read_result of {
154 Left err -> -- Not found, so add an empty export env to the Ifaces map
155 -- so that we don't look again
157 fake_mod = mkVanillaModule mod_name
158 fake_iface = emptyModIface fake_mod
159 new_ifaces = ifaces { iPIT = extendModuleEnv pit fake_mod fake_iface }
161 setIfacesRn new_ifaces `thenRn_`
162 returnRn (fake_iface, Just err) ;
165 Right (mod, iface) ->
167 -- LOAD IT INTO Ifaces
169 -- NB: *first* we do loadDecl, so that the provenance of all the locally-defined
170 --- names is done correctly (notably, whether this is an .hi file or .hi-boot file).
171 -- If we do loadExport first the wrong info gets into the cache (unless we
172 -- explicitly tag each export which seems a bit of a bore)
175 -- Sanity check. If we're system-importing a module we know nothing at all
176 -- about, it should be from a different package to this one
177 WARN( not (maybeToBool mod_info) &&
178 case from of { ImportBySystem -> True; other -> False } &&
182 loadDecls mod (iDecls ifaces) (pi_decls iface) `thenRn` \ (decls_vers, new_decls) ->
183 loadRules mod (iRules ifaces) (pi_rules iface) `thenRn` \ (rule_vers, new_rules) ->
184 loadInstDecls mod (iInsts ifaces) (pi_insts iface) `thenRn` \ new_insts ->
185 loadExports (pi_exports iface) `thenRn` \ (export_vers, avails) ->
186 loadFixDecls mod (pi_fixity iface) `thenRn` \ fix_env ->
187 loadDeprecs mod (pi_deprecs iface) `thenRn` \ deprec_env ->
189 version = VersionInfo { vers_module = pi_vers iface,
190 vers_exports = export_vers,
191 vers_rules = rule_vers,
192 vers_decls = decls_vers }
194 -- For an explicit user import, add to mod_map info about
195 -- the things the imported module depends on, extracted
196 -- from its usage info; and delete the module itself, which is now in the PIT
197 mod_map1 = case from of
198 ImportByUser -> addModDeps mod is_loaded (pi_usages iface) mod_map
200 mod_map2 = delFromFM mod_map1 mod_name
201 is_loaded m = maybeToBool (lookupIfaceByModName hit pit m)
203 -- Now add info about this module to the PIT
204 has_orphans = pi_orphan iface
205 new_pit = extendModuleEnv pit mod mod_iface
206 mod_iface = ModIface { mi_module = mod, mi_version = version,
207 mi_orphan = has_orphans, mi_boot = hi_boot_file,
209 mi_fixities = fix_env, mi_deprecs = deprec_env,
210 mi_usages = [], -- Will be filled in later
211 mi_decls = panic "No mi_decls in PIT",
212 mi_globals = mkIfaceGlobalRdrEnv avails
215 new_ifaces = ifaces { iPIT = new_pit,
219 iImpModInfo = mod_map2 }
221 setIfacesRn new_ifaces `thenRn_`
222 returnRn (mod_iface, Nothing)
225 -----------------------------------------------------
226 -- Adding module dependencies from the
227 -- import decls in the interface file
228 -----------------------------------------------------
231 -> (ModuleName -> Bool) -- True for module interfaces
233 -> ImportedModuleInfo -> ImportedModuleInfo
234 -- (addModDeps M ivs deps)
235 -- We are importing module M, and M.hi contains 'import' decls given by ivs
236 addModDeps mod is_loaded new_deps mod_deps
237 = foldr add mod_deps filtered_new_deps
239 -- Don't record dependencies when importing a module from another package
240 -- Except for its descendents which contain orphans,
241 -- and in that case, forget about the boot indicator
242 filtered_new_deps :: [(ModuleName, (WhetherHasOrphans, IsBootInterface))]
245 = [ (imp_mod, (has_orphans, is_boot))
246 | (imp_mod, has_orphans, is_boot, _) <- new_deps,
247 not (is_loaded imp_mod)
249 | otherwise = [ (imp_mod, (True, False))
250 | (imp_mod, has_orphans, _, _) <- new_deps,
251 not (is_loaded imp_mod) && has_orphans
253 add (imp_mod, dep) deps = addToFM_C combine deps imp_mod dep
255 combine old@(old_has_orphans, old_is_boot) new@(new_has_orphans, new_is_boot)
256 | old_is_boot = new -- Record the best is_boot info
259 -----------------------------------------------------
260 -- Loading the export list
261 -----------------------------------------------------
263 loadExports :: (Version, [ExportItem]) -> RnM d (Version, [(ModuleName,Avails)])
264 loadExports (vers, items)
265 = getModuleRn `thenRn` \ this_mod ->
266 mapRn (loadExport this_mod) items `thenRn` \ avails_s ->
267 returnRn (vers, avails_s)
270 loadExport :: Module -> ExportItem -> RnM d (ModuleName, Avails)
271 loadExport this_mod (mod, entities)
272 = mapRn (load_entity mod) entities `thenRn` \ avails ->
273 returnRn (mod, avails)
275 load_entity mod (Avail occ)
276 = newGlobalName mod occ `thenRn` \ name ->
277 returnRn (Avail name)
278 load_entity mod (AvailTC occ occs)
279 = newGlobalName mod occ `thenRn` \ name ->
280 mapRn (newGlobalName mod) occs `thenRn` \ names ->
281 returnRn (AvailTC name names)
284 -----------------------------------------------------
285 -- Loading type/class/value decls
286 -----------------------------------------------------
290 -> [(Version, RdrNameTyClDecl)]
291 -> RnM d (NameEnv Version, DeclsMap)
292 loadDecls mod (decls_map, n_slurped) decls
293 = foldlRn (loadDecl mod) (emptyNameEnv, decls_map) decls `thenRn` \ (vers, decls_map') ->
294 returnRn (vers, (decls_map', n_slurped))
296 loadDecl mod (version_map, decls_map) (version, decl)
297 = getIfaceDeclBinders mod decl `thenRn` \ full_avail ->
299 main_name = availName full_avail
300 new_decls_map = extendNameEnvList decls_map stuff
301 stuff = [ (name, (full_avail, name==main_name, (mod, decl)))
302 | name <- availNames full_avail]
304 new_version_map = extendNameEnv version_map main_name version
306 returnRn (new_version_map, new_decls_map)
308 -----------------------------------------------------
309 -- Loading fixity decls
310 -----------------------------------------------------
312 loadFixDecls mod decls
313 = mapRn (loadFixDecl mod_name) decls `thenRn` \ to_add ->
314 returnRn (mkNameEnv to_add)
316 mod_name = moduleName mod
318 loadFixDecl mod_name sig@(FixitySig rdr_name fixity loc)
319 = newGlobalName mod_name (rdrNameOcc rdr_name) `thenRn` \ name ->
320 returnRn (name, fixity)
323 -----------------------------------------------------
324 -- Loading instance decls
325 -----------------------------------------------------
327 loadInstDecls :: Module
331 loadInstDecls mod (insts, n_slurped) decls
333 foldlRn (loadInstDecl mod) insts decls `thenRn` \ insts' ->
334 returnRn (insts', n_slurped)
337 loadInstDecl mod insts decl@(InstDecl inst_ty _ _ _ _)
338 = -- Find out what type constructors and classes are "gates" for the
339 -- instance declaration. If all these "gates" are slurped in then
340 -- we should slurp the instance decl too.
342 -- We *don't* want to count names in the context part as gates, though.
344 -- instance Foo a => Baz (T a) where ...
346 -- Here the gates are Baz and T, but *not* Foo.
348 munged_inst_ty = removeContext inst_ty
349 free_names = extractHsTyRdrNames munged_inst_ty
351 mapRn lookupIfaceName free_names `thenRn` \ gate_names ->
352 returnRn ((gate_names, (mod, decl)) `consBag` insts)
355 -- In interface files, the instance decls now look like
356 -- forall a. Foo a -> Baz (T a)
357 -- so we have to strip off function argument types as well
358 -- as the bit before the '=>' (which is always empty in interface files)
359 removeContext (HsForAllTy tvs cxt ty) = HsForAllTy tvs [] (removeFuns ty)
360 removeContext ty = removeFuns ty
362 removeFuns (HsFunTy _ ty) = removeFuns ty
366 -----------------------------------------------------
368 -----------------------------------------------------
370 loadRules :: Module -> IfaceRules
371 -> (Version, [RdrNameRuleDecl])
372 -> RnM d (Version, IfaceRules)
373 loadRules mod (rule_bag, n_slurped) (version, rules)
374 | null rules || opt_IgnoreIfacePragmas
375 = returnRn (version, (rule_bag, n_slurped))
378 mapRn (loadRule mod) rules `thenRn` \ new_rules ->
379 returnRn (version, (rule_bag `unionBags` listToBag new_rules, n_slurped))
381 loadRule :: Module -> RdrNameRuleDecl -> RnM d (GatedDecl RdrNameRuleDecl)
382 -- "Gate" the rule simply by whether the rule variable is
383 -- needed. We can refine this later.
384 loadRule mod decl@(IfaceRule _ _ var _ _ src_loc)
385 = lookupIfaceName var `thenRn` \ var_name ->
386 returnRn ([var_name], (mod, decl))
389 -----------------------------------------------------
390 -- Loading Deprecations
391 -----------------------------------------------------
393 loadDeprecs :: Module -> IfaceDeprecs -> RnM d Deprecations
394 loadDeprecs m Nothing = returnRn NoDeprecs
395 loadDeprecs m (Just (Left txt)) = returnRn (DeprecAll txt)
396 loadDeprecs m (Just (Right prs)) = setModuleRn m $
397 foldlRn loadDeprec emptyNameEnv prs `thenRn` \ env ->
398 returnRn (DeprecSome env)
399 loadDeprec deprec_env (n, txt)
400 = lookupIfaceName n `thenRn` \ name ->
401 traceRn (text "Loaded deprecation(s) for" <+> ppr name <> colon <+> ppr txt) `thenRn_`
402 returnRn (extendNameEnv deprec_env name (name,txt))
406 %*********************************************************
408 \subsection{Getting binders out of a declaration}
410 %*********************************************************
412 @getDeclBinders@ returns the names for a @RdrNameHsDecl@.
413 It's used for both source code (from @availsFromDecl@) and interface files
416 It doesn't deal with source-code specific things: @ValD@, @DefD@. They
417 are handled by the sourc-code specific stuff in @RnNames@.
420 getIfaceDeclBinders, getTyClDeclBinders
426 getTyClDeclBinders mod (IfaceSig var ty prags src_loc)
427 = newTopBinder mod var src_loc `thenRn` \ var_name ->
428 returnRn (Avail var_name)
430 getTyClDeclBinders mod tycl_decl
431 = new_top_bndrs mod (tyClDeclNames tycl_decl) `thenRn` \ (main_name:sub_names) ->
432 returnRn (AvailTC main_name (main_name : sub_names))
435 getIfaceDeclBinders mod (IfaceSig var ty prags src_loc)
436 = newTopBinder mod var src_loc `thenRn` \ var_name ->
437 returnRn (Avail var_name)
439 getIfaceDeclBinders mod tycl_decl
440 = new_top_bndrs mod (tyClDeclNames tycl_decl) `thenRn` \ (main_name:sub_names) ->
441 new_top_bndrs mod (tyClDeclSysNames tycl_decl) `thenRn` \ sys_names ->
442 returnRn (AvailTC main_name (main_name : (sys_names ++ sub_names)))
445 new_top_bndrs mod names_w_locs
446 = sequenceRn [newTopBinder mod name loc | (name,loc) <- names_w_locs]
450 %*********************************************************
452 \subsection{Reading an interface file}
454 %*********************************************************
457 findAndReadIface :: SDoc -> ModuleName
458 -> IsBootInterface -- True <=> Look for a .hi-boot file
459 -- False <=> Look for .hi file
460 -> RnM d (Either Message (Module, ParsedIface))
461 -- Nothing <=> file not found, or unreadable, or illegible
462 -- Just x <=> successfully found and parsed
464 findAndReadIface doc_str mod_name hi_boot_file
465 = traceRn trace_msg `thenRn_`
467 ioToRnM (findModule mod_name) `thenRn` \ maybe_found ->
470 Right (Just (wanted_mod,locn))
471 -> mkHiPath hi_boot_file locn `thenRn` \ file ->
472 readIface file `thenRn` \ read_result ->
474 Left bad -> returnRn (Left bad)
476 -> let read_mod = pi_mod iface
477 in warnCheckRn (wanted_mod == read_mod)
478 (hiModuleNameMismatchWarn wanted_mod
480 returnRn (Right (wanted_mod, iface))
482 other -> traceRn (ptext SLIT("...not found")) `thenRn_`
483 returnRn (Left (noIfaceErr mod_name hi_boot_file))
486 trace_msg = sep [hsep [ptext SLIT("Reading"),
487 if hi_boot_file then ptext SLIT("[boot]") else empty,
488 ptext SLIT("interface for"),
489 ppr mod_name <> semi],
490 nest 4 (ptext SLIT("reason:") <+> doc_str)]
492 mkHiPath hi_boot_file locn
494 ioToRnM_no_fail (doesFileExist hi_boot_ver_path) `thenRn` \ b ->
495 if b then returnRn hi_boot_ver_path
496 else returnRn hi_boot_path
497 | otherwise = returnRn hi_path
498 where (Just hi_path) = ml_hi_file locn
499 hi_boot_path = hi_path ++ "-boot"
500 hi_boot_ver_path = hi_path ++ "-boot-" ++ cHscIfaceFileVersion
503 @readIface@ tries just the one file.
506 readIface :: String -> RnM d (Either Message ParsedIface)
507 -- Nothing <=> file not found, or unreadable, or illegible
508 -- Just x <=> successfully found and parsed
510 = traceRn (ptext SLIT("readIFace") <+> text file_path) `thenRn_`
512 ioToRnM (hGetStringBuffer False file_path) `thenRn` \ read_result ->
513 case read_result of {
514 Left io_error -> bale_out (text (show io_error)) ;
517 case parseIface contents init_parser_state of
518 POk _ (PIface iface) -> returnRn (Right iface)
519 PFailed err -> bale_out err
520 parse_result -> bale_out empty
521 -- This last case can happen if the interface file is (say) empty
522 -- in which case the parser thinks it looks like an IdInfo or
523 -- something like that. Just an artefact of the fact that the
524 -- parser is used for several purposes at once.
527 init_parser_state = PState{ bol = 0#, atbol = 1#,
530 loc = mkSrcLoc (mkFastString file_path) 1 }
532 bale_out err = returnRn (Left (badIfaceFile file_path err))
536 %*********************************************************
538 \subsection{Looking up fixities}
540 %*********************************************************
542 @lookupFixityRn@ has to be in RnIfaces (or RnHiFiles) because
543 it calls @loadHomeInterface@.
545 lookupFixity is a bit strange.
547 * Nested local fixity decls are put in the local fixity env, which we
548 find with getFixtyEnv
550 * Imported fixities are found in the HIT or PIT
552 * Top-level fixity decls in this module may be for Names that are
553 either Global (constructors, class operations)
554 or Local/Exported (everything else)
555 (See notes with RnNames.getLocalDeclBinders for why we have this split.)
556 We put them all in the local fixity environment
559 lookupFixityRn :: Name -> RnMS Fixity
561 = getModuleRn `thenRn` \ this_mod ->
562 if nameIsLocalOrFrom this_mod name
563 then -- It's defined in this module
564 getFixityEnv `thenRn` \ local_fix_env ->
565 returnRn (lookupLocalFixity local_fix_env name)
567 else -- It's imported
568 -- For imported names, we have to get their fixities by doing a loadHomeInterface,
569 -- and consulting the Ifaces that comes back from that, because the interface
570 -- file for the Name might not have been loaded yet. Why not? Suppose you import module A,
571 -- which exports a function 'f', which is defined in module B. Then B isn't loaded
572 -- right away (after all, it's possible that nothing from B will be used).
573 -- When we come across a use of 'f', we need to know its fixity, and it's then,
574 -- and only then, that we load B.hi. That is what's happening here.
575 loadHomeInterface doc name `thenRn` \ iface ->
576 returnRn (lookupNameEnv (mi_fixities iface) name `orElse` defaultFixity)
578 doc = ptext SLIT("Checking fixity for") <+> ppr name
582 %*********************************************************
586 %*********************************************************
589 noIfaceErr mod_name boot_file
590 = ptext SLIT("Could not find interface file for") <+> quotes (ppr mod_name)
591 -- We used to print the search path, but we can't do that
592 -- now, because it's hidden inside the finder.
593 -- Maybe the finder should expose more functions.
595 badIfaceFile file err
596 = vcat [ptext SLIT("Bad interface file:") <+> text file,
599 hiModuleNameMismatchWarn :: Module -> Module -> Message
600 hiModuleNameMismatchWarn requested_mod read_mod =
601 hsep [ ptext SLIT("Something is amiss; requested module name")
602 , ppr (moduleName requested_mod)
603 , ptext SLIT("differs from name found in the interface file")
607 warnRedundantSourceImport mod_name
608 = ptext SLIT("Unnecessary {- SOURCE -} in the import of module")
609 <+> quotes (ppr mod_name)