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 )
22 import HsSyn ( HsDecl(..), TyClDecl(..), InstDecl(..),
23 HsType(..), ConDecl(..),
24 FixitySig(..), RuleDecl(..),
27 import RdrHsSyn ( RdrNameTyClDecl, RdrNameInstDecl, RdrNameRuleDecl,
30 import BasicTypes ( Version, defaultFixity )
33 import ParseIface ( parseIface, IfaceStuff(..) )
35 import Name ( Name {-instance NamedThing-}, nameOccName,
36 nameModule, isLocallyDefined,
38 mkNameEnv, extendNameEnv
40 import Module ( Module,
41 moduleName, isModuleInThisPackage,
42 ModuleName, WhereFrom(..),
43 extendModuleEnv, lookupModuleEnvByName,
45 import RdrName ( RdrName, rdrNameOcc )
47 import SrcLoc ( mkSrcLoc, SrcLoc )
48 import Maybes ( maybeToBool, orElse )
49 import StringBuffer ( hGetStringBuffer )
50 import FastString ( mkFastString )
51 import ErrUtils ( Message )
52 import Finder ( findModule )
60 %*********************************************************
62 \subsection{Loading a new interface file}
64 %*********************************************************
67 loadHomeInterface :: SDoc -> Name -> RnM d Ifaces
68 loadHomeInterface doc_str name
69 = loadInterface doc_str (moduleName (nameModule name)) ImportBySystem
71 loadOrphanModules :: [ModuleName] -> RnM d ()
72 loadOrphanModules mods
73 | null mods = returnRn ()
74 | otherwise = traceRn (text "Loading orphan modules:" <+>
75 fsep (map ppr mods)) `thenRn_`
76 mapRn_ load mods `thenRn_`
79 load mod = loadInterface (mk_doc mod) mod ImportBySystem
80 mk_doc mod = ppr mod <+> ptext SLIT("is a orphan-instance module")
82 loadInterface :: SDoc -> ModuleName -> WhereFrom -> RnM d Ifaces
83 loadInterface doc mod from
84 = tryLoadInterface doc mod from `thenRn` \ (ifaces, maybe_err) ->
86 Nothing -> returnRn ifaces
87 Just err -> failWithRn ifaces err
89 tryLoadInterface :: SDoc -> ModuleName -> WhereFrom -> RnM d (Ifaces, Maybe Message)
90 -- Returns (Just err) if an error happened
91 -- It *doesn't* add an error to the monad, because sometimes it's ok to fail...
92 -- Specifically, when we read the usage information from an interface file,
93 -- we try to read the interfaces it mentions. But it's OK to fail; perhaps
94 -- the module has changed, and that interface is no longer used.
96 -- tryLoadInterface guarantees to return with iImpModInfo m --> (..., True)
97 -- (If the load fails, we plug in a vanilla placeholder)
98 tryLoadInterface doc_str mod_name from
99 = getHomeIfaceTableRn `thenRn` \ hit ->
100 getIfacesRn `thenRn` \ ifaces ->
102 -- Check whether we have it already in the home package
103 case lookupModuleEnvByName hit mod_name of {
104 Just _ -> returnRn (ifaces, Nothing) ; -- In the home package
108 mod_map = iImpModInfo ifaces
109 mod_info = lookupFM mod_map mod_name
112 = case (from, mod_info) of
113 (ImportByUser, _) -> False -- Not hi-boot
114 (ImportByUserSource, _) -> True -- hi-boot
115 (ImportBySystem, Just (_, is_boot, _)) -> is_boot --
116 (ImportBySystem, Nothing) -> False
117 -- We're importing a module we know absolutely
118 -- nothing about, so we assume it's from
119 -- another package, where we aren't doing
120 -- dependency tracking. So it won't be a hi-boot file.
122 redundant_source_import
123 = case (from, mod_info) of
124 (ImportByUserSource, Just (_,False,_)) -> True
127 -- CHECK WHETHER WE HAVE IT ALREADY
130 -> -- We're read it already so don't re-read it
131 returnRn (ifaces, Nothing) ;
135 -- Issue a warning for a redundant {- SOURCE -} import
136 -- NB that we arrange to read all the ordinary imports before
137 -- any of the {- SOURCE -} imports
138 warnCheckRn (not redundant_source_import)
139 (warnRedundantSourceImport mod_name) `thenRn_`
141 -- READ THE MODULE IN
142 findAndReadIface doc_str mod_name hi_boot_file `thenRn` \ read_result ->
143 case read_result of {
144 Left err -> -- Not found, so add an empty export env to the Ifaces map
145 -- so that we don't look again
147 new_mod_map = addToFM mod_map mod_name (False, False, True)
148 new_ifaces = ifaces { iImpModInfo = new_mod_map }
150 setIfacesRn new_ifaces `thenRn_`
151 returnRn (new_ifaces, Just err) ;
154 Right (mod, iface) ->
156 -- LOAD IT INTO Ifaces
158 -- NB: *first* we do loadDecl, so that the provenance of all the locally-defined
159 --- names is done correctly (notably, whether this is an .hi file or .hi-boot file).
160 -- If we do loadExport first the wrong info gets into the cache (unless we
161 -- explicitly tag each export which seems a bit of a bore)
164 -- Sanity check. If we're system-importing a module we know nothing at all
165 -- about, it should be from a different package to this one
166 WARN( not (maybeToBool mod_info) &&
167 case from of { ImportBySystem -> True; other -> False } &&
168 isModuleInThisPackage mod,
171 loadDecls mod (iDecls ifaces) (pi_decls iface) `thenRn` \ (decls_vers, new_decls) ->
172 loadRules mod (iRules ifaces) (pi_rules iface) `thenRn` \ (rule_vers, new_rules) ->
173 foldlRn (loadInstDecl mod) (iInsts ifaces) (pi_insts iface) `thenRn` \ new_insts ->
174 loadExports (pi_exports iface) `thenRn` \ (export_vers, avails) ->
175 loadFixDecls mod (pi_fixity iface) `thenRn` \ fix_env ->
176 loadDeprecs mod (pi_deprecs iface) `thenRn` \ deprec_env ->
178 version = VersionInfo { vers_module = pi_vers iface,
179 vers_exports = export_vers,
180 vers_rules = rule_vers,
181 vers_decls = decls_vers }
183 -- For an explicit user import, add to mod_map info about
184 -- the things the imported module depends on, extracted
185 -- from its usage info.
186 mod_map1 = case from of
187 ImportByUser -> addModDeps mod (pi_usages iface) mod_map
189 mod_map2 = addToFM mod_map1 mod_name (has_orphans, hi_boot_file, True)
191 -- Now add info about this module to the PIT
192 has_orphans = pi_orphan iface
193 new_pit = extendModuleEnv (iPIT ifaces) mod mod_iface
194 mod_iface = ModIface { mi_module = mod, mi_version = version,
195 mi_exports = avails, mi_orphan = has_orphans,
196 mi_fixities = fix_env, mi_deprecs = deprec_env,
197 mi_usages = [], -- Will be filled in later
198 mi_decls = panic "No mi_decls in PIT",
199 mi_globals = panic "No mi_globals in PIT"
202 new_ifaces = ifaces { iPIT = new_pit,
206 iImpModInfo = mod_map2 }
208 setIfacesRn new_ifaces `thenRn_`
209 returnRn (new_ifaces, Nothing)
212 -----------------------------------------------------
213 -- Adding module dependencies from the
214 -- import decls in the interface file
215 -----------------------------------------------------
217 addModDeps :: Module -> [ImportVersion a]
218 -> ImportedModuleInfo -> ImportedModuleInfo
219 -- (addModDeps M ivs deps)
220 -- We are importing module M, and M.hi contains 'import' decls given by ivs
221 addModDeps mod new_deps mod_deps
222 = foldr add mod_deps filtered_new_deps
224 -- Don't record dependencies when importing a module from another package
225 -- Except for its descendents which contain orphans,
226 -- and in that case, forget about the boot indicator
227 filtered_new_deps :: [(ModuleName, (WhetherHasOrphans, IsBootInterface, IsLoaded))]
229 | isModuleInThisPackage mod
230 = [ (imp_mod, (has_orphans, is_boot, False))
231 | (imp_mod, has_orphans, is_boot, _) <- new_deps
233 | otherwise = [ (imp_mod, (True, False, False))
234 | (imp_mod, has_orphans, _, _) <- new_deps,
237 add (imp_mod, dep) deps = addToFM_C combine deps imp_mod dep
239 combine old@(_, old_is_boot, old_is_loaded) new
240 | old_is_loaded || not old_is_boot = old -- Keep the old info if it's already loaded
241 -- or if it's a non-boot pending load
242 | otherwise = new -- Otherwise pick new info
245 -----------------------------------------------------
246 -- Loading the export list
247 -----------------------------------------------------
249 loadExports :: (Version, [ExportItem]) -> RnM d (Version, [(ModuleName,Avails)])
250 loadExports (vers, items)
251 = getModuleRn `thenRn` \ this_mod ->
252 mapRn (loadExport this_mod) items `thenRn` \ avails_s ->
253 returnRn (vers, avails_s)
256 loadExport :: Module -> ExportItem -> RnM d (ModuleName, Avails)
257 loadExport this_mod (mod, entities)
258 | mod == moduleName this_mod = returnRn (mod, [])
259 -- If the module exports anything defined in this module, just ignore it.
260 -- Reason: otherwise it looks as if there are two local definition sites
261 -- for the thing, and an error gets reported. Easiest thing is just to
262 -- filter them out up front. This situation only arises if a module
263 -- imports itself, or another module that imported it. (Necessarily,
264 -- this invoves a loop.) Consequence: if you say
269 -- module B( AType ) where
270 -- import {-# SOURCE #-} A( AType )
272 -- then you'll get a 'B does not export AType' message. A bit bogus
273 -- but it's a bogus thing to do!
276 = mapRn (load_entity mod) entities `thenRn` \ avails ->
277 returnRn (mod, avails)
279 load_entity mod (Avail occ)
280 = newGlobalName mod occ `thenRn` \ name ->
281 returnRn (Avail name)
282 load_entity mod (AvailTC occ occs)
283 = newGlobalName mod occ `thenRn` \ name ->
284 mapRn (newGlobalName mod) occs `thenRn` \ names ->
285 returnRn (AvailTC name names)
288 -----------------------------------------------------
289 -- Loading type/class/value decls
290 -----------------------------------------------------
294 -> [(Version, RdrNameTyClDecl)]
295 -> RnM d (NameEnv Version, DeclsMap)
296 loadDecls mod decls_map decls
297 = foldlRn (loadDecl mod) (emptyNameEnv, decls_map) decls
300 -> (NameEnv Version, DeclsMap)
301 -> (Version, RdrNameTyClDecl)
302 -> RnM d (NameEnv Version, DeclsMap)
303 loadDecl mod (version_map, decls_map) (version, decl)
304 = getIfaceDeclBinders mod decl `thenRn` \ full_avail ->
306 main_name = availName full_avail
307 new_decls_map = extendNameEnvList decls_map stuff
308 stuff = [ (name, (full_avail, name==main_name, (mod, decl)))
309 | name <- availNames full_avail]
311 new_version_map = extendNameEnv version_map main_name version
313 returnRn (new_version_map, new_decls_map)
315 -----------------------------------------------------
316 -- Loading fixity decls
317 -----------------------------------------------------
319 loadFixDecls mod decls
320 = mapRn (loadFixDecl mod_name) decls `thenRn` \ to_add ->
321 returnRn (mkNameEnv to_add)
323 mod_name = moduleName mod
325 loadFixDecl mod_name sig@(FixitySig rdr_name fixity loc)
326 = newGlobalName mod_name (rdrNameOcc rdr_name) `thenRn` \ name ->
327 returnRn (name, fixity)
330 -----------------------------------------------------
331 -- Loading instance decls
332 -----------------------------------------------------
334 loadInstDecl :: Module
338 loadInstDecl mod insts decl@(InstDecl inst_ty binds uprags dfun_name src_loc)
340 -- Find out what type constructors and classes are "gates" for the
341 -- instance declaration. If all these "gates" are slurped in then
342 -- we should slurp the instance decl too.
344 -- We *don't* want to count names in the context part as gates, though.
346 -- instance Foo a => Baz (T a) where ...
348 -- Here the gates are Baz and T, but *not* Foo.
350 munged_inst_ty = removeContext inst_ty
351 free_names = extractHsTyRdrNames munged_inst_ty
354 mapRn lookupOrigName free_names `thenRn` \ gate_names ->
355 returnRn ((mkNameSet gate_names, (mod, InstD decl)) `consBag` insts)
358 -- In interface files, the instance decls now look like
359 -- forall a. Foo a -> Baz (T a)
360 -- so we have to strip off function argument types as well
361 -- as the bit before the '=>' (which is always empty in interface files)
362 removeContext (HsForAllTy tvs cxt ty) = HsForAllTy tvs [] (removeFuns ty)
363 removeContext ty = removeFuns ty
365 removeFuns (HsFunTy _ ty) = removeFuns ty
369 -----------------------------------------------------
371 -----------------------------------------------------
373 loadRules :: Module -> IfaceRules
374 -> (Version, [RdrNameRuleDecl])
375 -> RnM d (Version, IfaceRules)
376 loadRules mod rule_bag (version, rules)
377 | null rules || opt_IgnoreIfacePragmas
378 = returnRn (version, rule_bag)
381 mapRn (loadRule mod) rules `thenRn` \ new_rules ->
382 returnRn (version, rule_bag `unionBags` listToBag new_rules)
384 loadRule :: Module -> RdrNameRuleDecl -> RnM d GatedDecl
385 -- "Gate" the rule simply by whether the rule variable is
386 -- needed. We can refine this later.
387 loadRule mod decl@(IfaceRule _ _ var _ _ src_loc)
388 = lookupOrigName var `thenRn` \ var_name ->
389 returnRn (unitNameSet var_name, (mod, RuleD decl))
392 -----------------------------------------------------
393 -- Loading Deprecations
394 -----------------------------------------------------
396 loadDeprecs :: Module -> IfaceDeprecs -> RnM d Deprecations
397 loadDeprecs m Nothing = returnRn NoDeprecs
398 loadDeprecs m (Just (Left txt)) = returnRn (DeprecAll txt)
399 loadDeprecs m (Just (Right prs)) = setModuleRn m $
400 foldlRn loadDeprec emptyNameEnv prs `thenRn` \ env ->
401 returnRn (DeprecSome env)
402 loadDeprec deprec_env (n, txt)
403 = lookupOrigName n `thenRn` \ name ->
404 traceRn (text "Loaded deprecation(s) for" <+> ppr name <> colon <+> ppr txt) `thenRn_`
405 returnRn (extendNameEnv deprec_env name (name,txt))
409 %*********************************************************
411 \subsection{Getting binders out of a declaration}
413 %*********************************************************
415 @getDeclBinders@ returns the names for a @RdrNameHsDecl@.
416 It's used for both source code (from @availsFromDecl@) and interface files
419 It doesn't deal with source-code specific things: @ValD@, @DefD@. They
420 are handled by the sourc-code specific stuff in @RnNames@.
423 getIfaceDeclBinders, getTyClDeclBinders
428 getIfaceDeclBinders mod tycl_decl
429 = getTyClDeclBinders mod tycl_decl `thenRn` \ avail ->
430 getSysTyClDeclBinders mod tycl_decl `thenRn` \ extras ->
431 returnRn (addSysAvails avail extras)
432 -- Add the sys-binders to avail. When we import the decl,
433 -- it's full_avail that will get added to the 'already-slurped' set (iSlurp)
434 -- If we miss out sys-binders, we'll read the decl multiple times!
436 getTyClDeclBinders mod (IfaceSig var ty prags src_loc)
437 = newTopBinder mod var src_loc `thenRn` \ var_name ->
438 returnRn (Avail var_name)
440 getTyClDeclBinders mod tycl_decl
441 = mapRn do_one (tyClDeclNames tycl_decl) `thenRn` \ (main_name:sub_names) ->
442 returnRn (AvailTC main_name (main_name : sub_names))
444 do_one (name,loc) = newTopBinder mod name loc
447 @getDeclSysBinders@ gets the implicit binders introduced by a decl.
448 A the moment that's just the tycon and datacon that come with a class decl.
449 They aren't returned by @getDeclBinders@ because they aren't in scope;
450 but they {\em should} be put into the @DeclsMap@ of this module.
452 Note that this excludes the default-method names of a class decl,
453 and the dict fun of an instance decl, because both of these have
454 bindings of their own elsewhere.
457 getSysTyClDeclBinders mod (ClassDecl _ cname _ _ sigs _ names src_loc)
458 = sequenceRn [newTopBinder mod n src_loc | n <- names]
460 getSysTyClDeclBinders mod (TyData _ _ _ _ cons _ _ _ _ _)
461 = sequenceRn [newTopBinder mod wkr_name src_loc | ConDecl _ wkr_name _ _ _ src_loc <- cons]
463 getSysTyClDeclBinders mod other_decl
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 -> RnM d (Either Message (Module, ParsedIface))
480 -- Nothing <=> file not found, or unreadable, or illegible
481 -- Just x <=> successfully found and parsed
483 findAndReadIface doc_str mod_name hi_boot_file
484 = traceRn trace_msg `thenRn_`
485 ioToRnM (findModule mod_name) `thenRn` \ maybe_found ->
488 Right (Just (wanted_mod,locn))
489 -> readIface (hi_file locn ++ if hi_boot_file then "-boot" else "")
490 `thenRn` \ read_result ->
492 Left bad -> returnRn (Left bad)
494 -> let read_mod = pi_mod iface
495 in warnCheckRn (wanted_mod == read_mod)
496 (hiModuleNameMismatchWarn wanted_mod read_mod)
498 returnRn (Right (wanted_mod, iface))
500 other -> traceRn (ptext SLIT("...not found")) `thenRn_`
501 returnRn (Left (noIfaceErr mod_name hi_boot_file))
504 trace_msg = sep [hsep [ptext SLIT("Reading"),
505 if hi_boot_file then ptext SLIT("[boot]") else empty,
506 ptext SLIT("interface for"),
507 ppr mod_name <> semi],
508 nest 4 (ptext SLIT("reason:") <+> doc_str)]
511 @readIface@ tries just the one file.
514 readIface :: String -> RnM d (Either Message ParsedIface)
515 -- Nothing <=> file not found, or unreadable, or illegible
516 -- Just x <=> successfully found and parsed
518 = traceRn (ptext SLIT("readIFace") <+> text file_path) `thenRn_`
519 ioToRnM (hGetStringBuffer False file_path) `thenRn` \ read_result ->
522 case parseIface contents
523 PState{ bol = 0#, atbol = 1#,
526 loc = mkSrcLoc (mkFastString file_path) 1 } of
527 POk _ (PIface iface) -> returnRn (Right iface)
528 PFailed err -> bale_out err
529 parse_result -> bale_out empty
530 -- This last case can happen if the interface file is (say) empty
531 -- in which case the parser thinks it looks like an IdInfo or
532 -- something like that. Just an artefact of the fact that the
533 -- parser is used for several purposes at once.
535 Left io_err -> bale_out (text (show io_err))
537 bale_out err = returnRn (Left (badIfaceFile file_path err))
541 %*********************************************************
543 \subsection{Looking up fixities}
545 %*********************************************************
547 This has to be in RnIfaces (or RnHiFiles) because it calls loadHomeInterface
550 lookupFixityRn :: Name -> RnMS Fixity
552 | isLocallyDefined name
553 = getFixityEnv `thenRn` \ local_fix_env ->
554 returnRn (lookupLocalFixity local_fix_env name)
556 | otherwise -- Imported
557 -- For imported names, we have to get their fixities by doing a loadHomeInterface,
558 -- and consulting the Ifaces that comes back from that, because the interface
559 -- file for the Name might not have been loaded yet. Why not? Suppose you import module A,
560 -- which exports a function 'f', which is defined in module B. Then B isn't loaded
561 -- right away (after all, it's possible that nothing from B will be used).
562 -- When we come across a use of 'f', we need to know its fixity, and it's then,
563 -- and only then, that we load B.hi. That is what's happening here.
564 = getHomeIfaceTableRn `thenRn` \ hit ->
565 loadHomeInterface doc name `thenRn` \ ifaces ->
566 case lookupTable hit (iPIT ifaces) name of
567 Just iface -> returnRn (lookupNameEnv (mi_fixities iface) name `orElse` defaultFixity)
568 Nothing -> returnRn defaultFixity
570 doc = ptext SLIT("Checking fixity for") <+> ppr name
574 %*********************************************************
578 %*********************************************************
581 noIfaceErr mod_name boot_file
582 = ptext SLIT("Could not find interface file for") <+> quotes (ppr mod_name)
583 -- We used to print the search path, but we can't do that
584 -- now, because it's hidden inside the finder.
585 -- Maybe the finder should expose more functions.
587 badIfaceFile file err
588 = vcat [ptext SLIT("Bad interface file:") <+> text file,
591 hiModuleNameMismatchWarn :: Module -> Module -> Message
592 hiModuleNameMismatchWarn requested_mod read_mod =
593 hsep [ ptext SLIT("Something is amiss; requested module name")
594 , ppr (moduleName requested_mod)
595 , ptext SLIT("differs from name found in the interface file")
599 warnRedundantSourceImport mod_name
600 = ptext SLIT("Unnecessary {- SOURCE -} in the import of module")
601 <+> quotes (ppr mod_name)