2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section{Dealing with interface files}
8 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 -- Guarantees to return with iImpModInfo m --> (..., True)
92 -- (If the load fails, we plug in a vanilla placeholder)
93 tryLoadInterface doc_str mod_name from
94 = getHomeIfaceTableRn `thenRn` \ hit ->
95 getIfacesRn `thenRn` \ ifaces ->
97 -- Check whether we have it already in the home package
98 case lookupModuleEnvByName hit mod_name of {
99 Just _ -> returnRn (ifaces, Nothing) ; -- In the home package
103 mod_map = iImpModInfo ifaces
104 mod_info = lookupFM mod_map mod_name
107 = case (from, mod_info) of
108 (ImportByUser, _) -> False -- Not hi-boot
109 (ImportByUserSource, _) -> True -- hi-boot
110 (ImportBySystem, Just (_, is_boot, _)) -> is_boot --
111 (ImportBySystem, Nothing) -> False
112 -- We're importing a module we know absolutely
113 -- nothing about, so we assume it's from
114 -- another package, where we aren't doing
115 -- dependency tracking. So it won't be a hi-boot file.
117 redundant_source_import
118 = case (from, mod_info) of
119 (ImportByUserSource, Just (_,False,_)) -> True
122 -- CHECK WHETHER WE HAVE IT ALREADY
125 -> -- We're read it already so don't re-read it
126 returnRn (ifaces, Nothing) ;
130 -- Issue a warning for a redundant {- SOURCE -} import
131 -- NB that we arrange to read all the ordinary imports before
132 -- any of the {- SOURCE -} imports
133 warnCheckRn (not redundant_source_import)
134 (warnRedundantSourceImport mod_name) `thenRn_`
136 -- READ THE MODULE IN
137 findAndReadIface doc_str mod_name hi_boot_file `thenRn` \ read_result ->
138 case read_result of {
139 Left err -> -- Not found, so add an empty export env to the Ifaces map
140 -- so that we don't look again
142 new_mod_map = addToFM mod_map mod_name (False, False, True)
143 new_ifaces = ifaces { iImpModInfo = new_mod_map }
145 setIfacesRn new_ifaces `thenRn_`
146 returnRn (new_ifaces, Just err) ;
149 Right (mod, iface) ->
151 -- LOAD IT INTO Ifaces
153 -- NB: *first* we do loadDecl, so that the provenance of all the locally-defined
154 --- names is done correctly (notably, whether this is an .hi file or .hi-boot file).
155 -- If we do loadExport first the wrong info gets into the cache (unless we
156 -- explicitly tag each export which seems a bit of a bore)
159 -- Sanity check. If we're system-importing a module we know nothing at all
160 -- about, it should be from a different package to this one
161 WARN( not (maybeToBool mod_info) &&
162 case from of { ImportBySystem -> True; other -> False } &&
163 isModuleInThisPackage mod,
166 loadDecls mod (iDecls ifaces) (pi_decls iface) `thenRn` \ (decls_vers, new_decls) ->
167 loadRules mod (iRules ifaces) (pi_rules iface) `thenRn` \ (rule_vers, new_rules) ->
168 foldlRn (loadInstDecl mod) (iInsts ifaces) (pi_insts iface) `thenRn` \ new_insts ->
169 loadExports (pi_exports iface) `thenRn` \ (export_vers, avails) ->
170 loadFixDecls mod (pi_fixity iface) `thenRn` \ fix_env ->
171 loadDeprecs mod (pi_deprecs iface) `thenRn` \ deprec_env ->
173 version = VersionInfo { vers_module = pi_vers iface,
174 vers_exports = export_vers,
175 vers_rules = rule_vers,
176 vers_decls = decls_vers }
178 -- For an explicit user import, add to mod_map info about
179 -- the things the imported module depends on, extracted
180 -- from its usage info.
181 mod_map1 = case from of
182 ImportByUser -> addModDeps mod (pi_usages iface) mod_map
184 mod_map2 = addToFM mod_map1 mod_name (has_orphans, hi_boot_file, True)
186 -- Now add info about this module to the PIT
187 has_orphans = pi_orphan iface
188 new_pit = extendModuleEnv (iPIT ifaces) mod mod_iface
189 mod_iface = ModIface { mi_module = mod, mi_version = version,
190 mi_exports = avails, mi_orphan = has_orphans,
191 mi_fixities = fix_env, mi_deprecs = deprec_env,
192 mi_usages = [], -- Will be filled in later
193 mi_decls = panic "No mi_decls in PIT",
194 mi_globals = panic "No mi_globals in PIT"
197 new_ifaces = ifaces { iPIT = new_pit,
201 iImpModInfo = mod_map2 }
203 setIfacesRn new_ifaces `thenRn_`
204 returnRn (new_ifaces, Nothing)
207 -----------------------------------------------------
208 -- Adding module dependencies from the
209 -- import decls in the interface file
210 -----------------------------------------------------
212 addModDeps :: Module -> [ImportVersion a]
213 -> ImportedModuleInfo -> ImportedModuleInfo
214 -- (addModDeps M ivs deps)
215 -- We are importing module M, and M.hi contains 'import' decls given by ivs
216 addModDeps mod new_deps mod_deps
217 = foldr add mod_deps filtered_new_deps
219 -- Don't record dependencies when importing a module from another package
220 -- Except for its descendents which contain orphans,
221 -- and in that case, forget about the boot indicator
222 filtered_new_deps :: [(ModuleName, (WhetherHasOrphans, IsBootInterface, IsLoaded))]
224 | isModuleInThisPackage mod
225 = [ (imp_mod, (has_orphans, is_boot, False))
226 | (imp_mod, has_orphans, is_boot, _) <- new_deps
228 | otherwise = [ (imp_mod, (True, False, False))
229 | (imp_mod, has_orphans, _, _) <- new_deps,
232 add (imp_mod, dep) deps = addToFM_C combine deps imp_mod dep
234 combine old@(_, old_is_boot, old_is_loaded) new
235 | old_is_loaded || not old_is_boot = old -- Keep the old info if it's already loaded
236 -- or if it's a non-boot pending load
237 | otherwise = new -- Otherwise pick new info
240 -----------------------------------------------------
241 -- Loading the export list
242 -----------------------------------------------------
244 loadExports :: (Version, [ExportItem]) -> RnM d (Version, [(ModuleName,Avails)])
245 loadExports (vers, items)
246 = getModuleRn `thenRn` \ this_mod ->
247 mapRn (loadExport this_mod) items `thenRn` \ avails_s ->
248 returnRn (vers, avails_s)
251 loadExport :: Module -> ExportItem -> RnM d (ModuleName, Avails)
252 loadExport this_mod (mod, entities)
253 | mod == moduleName this_mod = returnRn (mod, [])
254 -- If the module exports anything defined in this module, just ignore it.
255 -- Reason: otherwise it looks as if there are two local definition sites
256 -- for the thing, and an error gets reported. Easiest thing is just to
257 -- filter them out up front. This situation only arises if a module
258 -- imports itself, or another module that imported it. (Necessarily,
259 -- this invoves a loop.) Consequence: if you say
264 -- module B( AType ) where
265 -- import {-# SOURCE #-} A( AType )
267 -- then you'll get a 'B does not export AType' message. A bit bogus
268 -- but it's a bogus thing to do!
271 = mapRn (load_entity mod) entities `thenRn` \ avails ->
272 returnRn (mod, avails)
274 new_name mod occ = newGlobalName mod occ
276 load_entity mod (Avail occ)
277 = new_name mod occ `thenRn` \ name ->
278 returnRn (Avail name)
279 load_entity mod (AvailTC occ occs)
280 = new_name mod occ `thenRn` \ name ->
281 mapRn (new_name mod) occs `thenRn` \ names ->
282 returnRn (AvailTC name names)
285 -----------------------------------------------------
286 -- Loading type/class/value decls
287 -----------------------------------------------------
291 -> [(Version, RdrNameTyClDecl)]
292 -> RnM d (NameEnv Version, DeclsMap)
293 loadDecls mod decls_map decls
294 = foldlRn (loadDecl mod) (emptyNameEnv, decls_map) decls
297 -> (NameEnv Version, DeclsMap)
298 -> (Version, RdrNameTyClDecl)
299 -> RnM d (NameEnv Version, DeclsMap)
300 loadDecl mod (version_map, decls_map) (version, decl)
301 = getIfaceDeclBinders new_name decl `thenRn` \ full_avail ->
303 main_name = availName full_avail
304 new_decls_map = extendNameEnvList decls_map stuff
305 stuff = [ (name, (full_avail, name==main_name, (mod, decl)))
306 | name <- availNames full_avail]
308 new_version_map = extendNameEnv version_map main_name version
310 returnRn (new_version_map, new_decls_map)
312 -- newTopBinder puts into the cache the binder with the
313 -- module information set correctly. When the decl is later renamed,
314 -- the binding site will thereby get the correct module.
315 -- There maybe occurrences that don't have the correct Module, but
316 -- by the typechecker will propagate the binding definition to all
317 -- the occurrences, so that doesn't matter
318 new_name rdr_name loc = newTopBinder mod rdr_name loc
321 -----------------------------------------------------
322 -- Loading fixity decls
323 -----------------------------------------------------
325 loadFixDecls mod decls
326 = mapRn (loadFixDecl mod_name) decls `thenRn` \ to_add ->
327 returnRn (mkNameEnv to_add)
329 mod_name = moduleName mod
331 loadFixDecl mod_name sig@(FixitySig rdr_name fixity loc)
332 = newGlobalName mod_name (rdrNameOcc rdr_name) `thenRn` \ name ->
333 returnRn (name, fixity)
336 -----------------------------------------------------
337 -- Loading instance decls
338 -----------------------------------------------------
340 loadInstDecl :: Module
344 loadInstDecl mod insts decl@(InstDecl inst_ty binds uprags dfun_name src_loc)
346 -- Find out what type constructors and classes are "gates" for the
347 -- instance declaration. If all these "gates" are slurped in then
348 -- we should slurp the instance decl too.
350 -- We *don't* want to count names in the context part as gates, though.
352 -- instance Foo a => Baz (T a) where ...
354 -- Here the gates are Baz and T, but *not* Foo.
356 munged_inst_ty = removeContext inst_ty
357 free_names = extractHsTyRdrNames munged_inst_ty
360 mapRn lookupOrigName free_names `thenRn` \ gate_names ->
361 returnRn ((mkNameSet gate_names, (mod, InstD decl)) `consBag` insts)
364 -- In interface files, the instance decls now look like
365 -- forall a. Foo a -> Baz (T a)
366 -- so we have to strip off function argument types as well
367 -- as the bit before the '=>' (which is always empty in interface files)
368 removeContext (HsForAllTy tvs cxt ty) = HsForAllTy tvs [] (removeFuns ty)
369 removeContext ty = removeFuns ty
371 removeFuns (HsFunTy _ ty) = removeFuns ty
375 -----------------------------------------------------
377 -----------------------------------------------------
379 loadRules :: Module -> IfaceRules
380 -> (Version, [RdrNameRuleDecl])
381 -> RnM d (Version, IfaceRules)
382 loadRules mod rule_bag (version, rules)
383 | null rules || opt_IgnoreIfacePragmas
384 = returnRn (version, rule_bag)
387 mapRn (loadRule mod) rules `thenRn` \ new_rules ->
388 returnRn (version, rule_bag `unionBags` listToBag new_rules)
390 loadRule :: Module -> RdrNameRuleDecl -> RnM d GatedDecl
391 -- "Gate" the rule simply by whether the rule variable is
392 -- needed. We can refine this later.
393 loadRule mod decl@(IfaceRule _ _ var _ _ src_loc)
394 = lookupOrigName var `thenRn` \ var_name ->
395 returnRn (unitNameSet var_name, (mod, RuleD decl))
398 -----------------------------------------------------
399 -- Loading Deprecations
400 -----------------------------------------------------
402 loadDeprecs :: Module -> IfaceDeprecs -> RnM d Deprecations
403 loadDeprecs m Nothing = returnRn NoDeprecs
404 loadDeprecs m (Just (Left txt)) = returnRn (DeprecAll txt)
405 loadDeprecs m (Just (Right prs)) = setModuleRn m $
406 foldlRn loadDeprec emptyNameEnv prs `thenRn` \ env ->
407 returnRn (DeprecSome env)
408 loadDeprec deprec_env (n, txt)
409 = lookupOrigName n `thenRn` \ name ->
410 traceRn (text "Loaded deprecation(s) for" <+> ppr name <> colon <+> ppr txt) `thenRn_`
411 returnRn (extendNameEnv deprec_env name (name,txt))
415 %*********************************************************
417 \subsection{Getting binders out of a declaration}
419 %*********************************************************
421 @getDeclBinders@ returns the names for a @RdrNameHsDecl@.
422 It's used for both source code (from @availsFromDecl@) and interface files
425 It doesn't deal with source-code specific things: @ValD@, @DefD@. They
426 are handled by the sourc-code specific stuff in @RnNames@.
429 getIfaceDeclBinders, getTyClDeclBinders
430 :: (RdrName -> SrcLoc -> RnM d Name) -- New-name function
434 getIfaceDeclBinders new_name tycl_decl
435 = getTyClDeclBinders new_name tycl_decl `thenRn` \ avail ->
436 getSysTyClDeclBinders new_name tycl_decl `thenRn` \ extras ->
437 returnRn (addSysAvails avail extras)
438 -- Add the sys-binders to avail. When we import the decl,
439 -- it's full_avail that will get added to the 'already-slurped' set (iSlurp)
440 -- If we miss out sys-binders, we'll read the decl multiple times!
442 getTyClDeclBinders new_name (IfaceSig var ty prags src_loc)
443 = new_name var src_loc `thenRn` \ var_name ->
444 returnRn (Avail var_name)
446 getTyClDeclBinders new_name tycl_decl
447 = mapRn do_one (tyClDeclNames tycl_decl) `thenRn` \ (main_name:sub_names) ->
448 returnRn (AvailTC main_name (main_name : sub_names))
450 do_one (name,loc) = new_name name loc
453 @getDeclSysBinders@ gets the implicit binders introduced by a decl.
454 A the moment that's just the tycon and datacon that come with a class decl.
455 They aren't returned by @getDeclBinders@ because they aren't in scope;
456 but they {\em should} be put into the @DeclsMap@ of this module.
458 Note that this excludes the default-method names of a class decl,
459 and the dict fun of an instance decl, because both of these have
460 bindings of their own elsewhere.
463 getSysTyClDeclBinders new_name (ClassDecl _ cname _ _ sigs _ names src_loc)
464 = sequenceRn [new_name n src_loc | n <- names]
466 getSysTyClDeclBinders new_name (TyData _ _ _ _ cons _ _ _ _ _)
467 = sequenceRn [new_name wkr_name src_loc | ConDecl _ wkr_name _ _ _ src_loc <- cons]
469 getSysTyClDeclBinders new_name other_decl
475 %*********************************************************
477 \subsection{Reading an interface file}
479 %*********************************************************
482 findAndReadIface :: SDoc -> ModuleName
483 -> IsBootInterface -- True <=> Look for a .hi-boot file
484 -- False <=> Look for .hi file
485 -> RnM d (Either Message (Module, ParsedIface))
486 -- Nothing <=> file not found, or unreadable, or illegible
487 -- Just x <=> successfully found and parsed
489 findAndReadIface doc_str mod_name hi_boot_file
490 = traceRn trace_msg `thenRn_`
491 ioToRnM (findModule mod_name) `thenRn` \ maybe_found ->
494 Right (Just (mod,locn))
495 | hi_boot_file -> readIface mod (hi_file locn ++ "-boot")
496 | otherwise -> readIface mod (hi_file locn)
499 other -> traceRn (ptext SLIT("...not found")) `thenRn_`
500 returnRn (Left (noIfaceErr mod_name hi_boot_file))
503 trace_msg = sep [hsep [ptext SLIT("Reading"),
504 if hi_boot_file then ptext SLIT("[boot]") else empty,
505 ptext SLIT("interface for"),
506 ppr mod_name <> semi],
507 nest 4 (ptext SLIT("reason:") <+> doc_str)]
510 @readIface@ tries just the one file.
513 readIface :: Module -> String -> RnM d (Either Message (Module, ParsedIface))
514 -- Nothing <=> file not found, or unreadable, or illegible
515 -- Just x <=> successfully found and parsed
516 readIface wanted_mod file_path
517 = traceRn (ptext SLIT("...reading from") <+> text file_path) `thenRn_`
518 ioToRnM (hGetStringBuffer False file_path) `thenRn` \ read_result ->
521 case parseIface contents
522 PState{ bol = 0#, atbol = 1#,
525 loc = mkSrcLoc (mkFastString file_path) 1 } of
526 POk _ (PIface iface) ->
527 warnCheckRn (wanted_mod == read_mod)
528 (hiModuleNameMismatchWarn wanted_mod read_mod) `thenRn_`
529 returnRn (Right (wanted_mod, iface))
531 read_mod = pi_mod iface
533 PFailed err -> bale_out err
534 parse_result -> bale_out empty
535 -- This last case can happen if the interface file is (say) empty
536 -- in which case the parser thinks it looks like an IdInfo or
537 -- something like that. Just an artefact of the fact that the
538 -- parser is used for several purposes at once.
540 Left io_err -> bale_out (text (show io_err))
542 bale_out err = returnRn (Left (badIfaceFile file_path err))
546 %*********************************************************
548 \subsection{Looking up fixities}
550 %*********************************************************
552 This has to be in RnIfaces (or RnHiFiles) because it calls loadHomeInterface
555 lookupFixityRn :: Name -> RnMS Fixity
557 | isLocallyDefined name
558 = getFixityEnv `thenRn` \ local_fix_env ->
559 returnRn (lookupLocalFixity local_fix_env name)
561 | otherwise -- Imported
562 -- For imported names, we have to get their fixities by doing a loadHomeInterface,
563 -- and consulting the Ifaces that comes back from that, because the interface
564 -- file for the Name might not have been loaded yet. Why not? Suppose you import module A,
565 -- which exports a function 'f', which is defined in module B. Then B isn't loaded
566 -- right away (after all, it's possible that nothing from B will be used).
567 -- When we come across a use of 'f', we need to know its fixity, and it's then,
568 -- and only then, that we load B.hi. That is what's happening here.
569 = getHomeIfaceTableRn `thenRn` \ hit ->
570 loadHomeInterface doc name `thenRn` \ ifaces ->
571 case lookupTable hit (iPIT ifaces) name of
572 Just iface -> returnRn (lookupNameEnv (mi_fixities iface) name `orElse` defaultFixity)
573 Nothing -> returnRn defaultFixity
575 doc = ptext SLIT("Checking fixity for") <+> ppr name
579 %*********************************************************
583 %*********************************************************
586 noIfaceErr mod_name boot_file
587 = ptext SLIT("Could not find interface file for") <+> quotes (ppr mod_name)
588 -- We used to print the search path, but we can't do that
589 -- now, because it's hidden inside the finder.
590 -- Maybe the finder should expose more functions.
592 badIfaceFile file err
593 = vcat [ptext SLIT("Bad interface file:") <+> text file,
596 hiModuleNameMismatchWarn :: Module -> Module -> Message
597 hiModuleNameMismatchWarn requested_mod read_mod =
598 hsep [ ptext SLIT("Something is amiss; requested module name")
599 , ppr (moduleName requested_mod)
600 , ptext SLIT("differs from name found in the interface file")
604 warnRedundantSourceImport mod_name
605 = ptext SLIT("Unnecessary {- SOURCE -} in the import of module")
606 <+> quotes (ppr mod_name)