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 )
33 import ParseIface ( parseIface, IfaceStuff(..) )
35 import Name ( Name {-instance NamedThing-}, nameOccName,
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 )
49 import StringBuffer ( hGetStringBuffer )
50 import FastString ( mkFastString )
51 import ErrUtils ( Message )
59 %*********************************************************
61 \subsection{Loading a new interface file}
63 %*********************************************************
66 loadHomeInterface :: SDoc -> Name -> RnM d Ifaces
67 loadHomeInterface doc_str name
68 = loadInterface doc_str (moduleName (nameModule name)) ImportBySystem
70 loadOrphanModules :: [ModuleName] -> RnM d ()
71 loadOrphanModules mods
72 | null mods = returnRn ()
73 | otherwise = traceRn (text "Loading orphan modules:" <+>
74 fsep (map ppr mods)) `thenRn_`
75 mapRn_ load mods `thenRn_`
78 load mod = loadInterface (mk_doc mod) mod ImportBySystem
79 mk_doc mod = ppr mod <+> ptext SLIT("is a orphan-instance module")
81 loadInterface :: SDoc -> ModuleName -> WhereFrom -> RnM d Ifaces
82 loadInterface doc mod from
83 = tryLoadInterface doc mod from `thenRn` \ (ifaces, maybe_err) ->
85 Nothing -> returnRn ifaces
86 Just err -> failWithRn ifaces err
88 tryLoadInterface :: SDoc -> ModuleName -> WhereFrom -> RnM d (Ifaces, Maybe Message)
89 -- Returns (Just err) if an error happened
90 -- Guarantees to return with iImpModInfo m --> (..., True)
91 -- (If the load fails, we plug in a vanilla placeholder)
92 tryLoadInterface doc_str mod_name from
93 = getHomeIfaceTableRn `thenRn` \ hit ->
94 getIfacesRn `thenRn` \ ifaces ->
96 -- Check whether we have it already in the home package
97 case lookupModuleEnvByName hit mod_name of {
98 Just _ -> returnRn (ifaces, Nothing) ; -- In the home package
102 mod_map = iImpModInfo ifaces
103 mod_info = lookupFM mod_map mod_name
106 = case (from, mod_info) of
107 (ImportByUser, _) -> False -- Not hi-boot
108 (ImportByUserSource, _) -> True -- hi-boot
109 (ImportBySystem, Just (_, is_boot, _)) -> is_boot --
110 (ImportBySystem, Nothing) -> False
111 -- We're importing a module we know absolutely
112 -- nothing about, so we assume it's from
113 -- another package, where we aren't doing
114 -- dependency tracking. So it won't be a hi-boot file.
116 redundant_source_import
117 = case (from, mod_info) of
118 (ImportByUserSource, Just (_,False,_)) -> True
121 -- CHECK WHETHER WE HAVE IT ALREADY
124 -> -- We're read it already so don't re-read it
125 returnRn (ifaces, Nothing) ;
129 -- Issue a warning for a redundant {- SOURCE -} import
130 -- NB that we arrange to read all the ordinary imports before
131 -- any of the {- SOURCE -} imports
132 warnCheckRn (not redundant_source_import)
133 (warnRedundantSourceImport mod_name) `thenRn_`
135 -- READ THE MODULE IN
136 findAndReadIface doc_str mod_name hi_boot_file `thenRn` \ read_result ->
137 case read_result of {
138 Left err -> -- Not found, so add an empty export env to the Ifaces map
139 -- so that we don't look again
141 new_mod_map = addToFM mod_map mod_name (False, False, True)
142 new_ifaces = ifaces { iImpModInfo = new_mod_map }
144 setIfacesRn new_ifaces `thenRn_`
145 returnRn (new_ifaces, Just err) ;
148 Right (mod, iface) ->
150 -- LOAD IT INTO Ifaces
152 -- NB: *first* we do loadDecl, so that the provenance of all the locally-defined
153 --- names is done correctly (notably, whether this is an .hi file or .hi-boot file).
154 -- If we do loadExport first the wrong info gets into the cache (unless we
155 -- explicitly tag each export which seems a bit of a bore)
158 -- Sanity check. If we're system-importing a module we know nothing at all
159 -- about, it should be from a different package to this one
160 WARN( not (maybeToBool mod_info) &&
161 case from of { ImportBySystem -> True; other -> False } &&
162 isModuleInThisPackage mod,
165 loadDecls mod (iDecls ifaces) (pi_decls iface) `thenRn` \ (decls_vers, new_decls) ->
166 loadRules mod (iRules ifaces) (pi_rules iface) `thenRn` \ (rule_vers, new_rules) ->
167 foldlRn (loadInstDecl mod) (iInsts ifaces) (pi_insts iface) `thenRn` \ new_insts ->
168 loadExports (pi_exports iface) `thenRn` \ (export_vers, avails) ->
169 loadFixDecls mod (pi_fixity iface) `thenRn` \ fix_env ->
170 loadDeprecs mod (pi_deprecs iface) `thenRn` \ deprec_env ->
172 version = VersionInfo { vers_module = pi_vers iface,
173 vers_exports = export_vers,
174 vers_rules = rule_vers,
175 vers_decls = decls_vers }
177 -- For an explicit user import, add to mod_map info about
178 -- the things the imported module depends on, extracted
179 -- from its usage info.
180 mod_map1 = case from of
181 ImportByUser -> addModDeps mod (pi_usages iface) mod_map
183 mod_map2 = addToFM mod_map1 mod_name (has_orphans, hi_boot_file, True)
185 -- Now add info about this module to the PIT
186 has_orphans = pi_orphan iface
187 new_pit = extendModuleEnv (iPIT ifaces) mod mod_iface
188 mod_iface = ModIface { mi_module = mod, mi_version = version,
189 mi_exports = avails, mi_orphan = has_orphans,
190 mi_fixities = fix_env, mi_deprecs = deprec_env,
191 mi_usages = [], -- Will be filled in later
192 mi_decls = panic "No mi_decls in PIT",
193 mi_globals = panic "No mi_globals in PIT"
196 new_ifaces = ifaces { iPIT = new_pit,
200 iImpModInfo = mod_map2 }
202 setIfacesRn new_ifaces `thenRn_`
203 returnRn (new_ifaces, Nothing)
206 -----------------------------------------------------
207 -- Adding module dependencies from the
208 -- import decls in the interface file
209 -----------------------------------------------------
211 addModDeps :: Module -> [ImportVersion a]
212 -> ImportedModuleInfo -> ImportedModuleInfo
213 -- (addModDeps M ivs deps)
214 -- We are importing module M, and M.hi contains 'import' decls given by ivs
215 addModDeps mod new_deps mod_deps
216 = foldr add mod_deps filtered_new_deps
218 -- Don't record dependencies when importing a module from another package
219 -- Except for its descendents which contain orphans,
220 -- and in that case, forget about the boot indicator
221 filtered_new_deps :: [(ModuleName, (WhetherHasOrphans, IsBootInterface, IsLoaded))]
223 | isModuleInThisPackage mod
224 = [ (imp_mod, (has_orphans, is_boot, False))
225 | (imp_mod, has_orphans, is_boot, _) <- new_deps
227 | otherwise = [ (imp_mod, (True, False, False))
228 | (imp_mod, has_orphans, _, _) <- new_deps,
231 add (imp_mod, dep) deps = addToFM_C combine deps imp_mod dep
233 combine old@(_, old_is_boot, old_is_loaded) new
234 | old_is_loaded || not old_is_boot = old -- Keep the old info if it's already loaded
235 -- or if it's a non-boot pending load
236 | otherwise = new -- Otherwise pick new info
239 -----------------------------------------------------
240 -- Loading the export list
241 -----------------------------------------------------
243 loadExports :: (Version, [ExportItem]) -> RnM d (Version, Avails)
244 loadExports (vers, items)
245 = getModuleRn `thenRn` \ this_mod ->
246 mapRn (loadExport this_mod) items `thenRn` \ avails_s ->
247 returnRn (vers, concat avails_s)
250 loadExport :: Module -> ExportItem -> RnM d [AvailInfo]
251 loadExport this_mod (mod, entities)
252 | mod == moduleName this_mod = returnRn []
253 -- If the module exports anything defined in this module, just ignore it.
254 -- Reason: otherwise it looks as if there are two local definition sites
255 -- for the thing, and an error gets reported. Easiest thing is just to
256 -- filter them out up front. This situation only arises if a module
257 -- imports itself, or another module that imported it. (Necessarily,
258 -- this invoves a loop.) Consequence: if you say
263 -- module B( AType ) where
264 -- import {-# SOURCE #-} A( AType )
266 -- then you'll get a 'B does not export AType' message. A bit bogus
267 -- but it's a bogus thing to do!
270 = mapRn (load_entity mod) entities
272 new_name mod occ = newGlobalName mod occ
274 load_entity mod (Avail occ)
275 = new_name mod occ `thenRn` \ name ->
276 returnRn (Avail name)
277 load_entity mod (AvailTC occ occs)
278 = new_name mod occ `thenRn` \ name ->
279 mapRn (new_name mod) occs `thenRn` \ names ->
280 returnRn (AvailTC name names)
283 -----------------------------------------------------
284 -- Loading type/class/value decls
285 -----------------------------------------------------
289 -> [(Version, RdrNameTyClDecl)]
290 -> RnM d (NameEnv Version, DeclsMap)
291 loadDecls mod decls_map decls
292 = foldlRn (loadDecl mod) (emptyNameEnv, decls_map) decls
295 -> (NameEnv Version, DeclsMap)
296 -> (Version, RdrNameTyClDecl)
297 -> RnM d (NameEnv Version, DeclsMap)
298 loadDecl mod (version_map, decls_map) (version, decl)
299 = getIfaceDeclBinders new_name decl `thenRn` \ full_avail ->
301 main_name = availName full_avail
302 new_decls_map = extendNameEnvList decls_map stuff
303 stuff = [ (name, (full_avail, name==main_name, (mod, decl)))
304 | name <- availNames full_avail]
306 new_version_map = extendNameEnv version_map main_name version
308 returnRn (new_version_map, new_decls_map)
310 -- newTopBinder puts into the cache the binder with the
311 -- module information set correctly. When the decl is later renamed,
312 -- the binding site will thereby get the correct module.
313 -- There maybe occurrences that don't have the correct Module, but
314 -- by the typechecker will propagate the binding definition to all
315 -- the occurrences, so that doesn't matter
316 new_name rdr_name loc = newTopBinder mod rdr_name loc
319 -----------------------------------------------------
320 -- Loading fixity decls
321 -----------------------------------------------------
323 loadFixDecls mod decls
324 = mapRn (loadFixDecl mod_name) decls `thenRn` \ to_add ->
325 returnRn (mkNameEnv to_add)
327 mod_name = moduleName mod
329 loadFixDecl mod_name sig@(FixitySig rdr_name fixity loc)
330 = newGlobalName mod_name (rdrNameOcc rdr_name) `thenRn` \ name ->
331 returnRn (name, fixity)
334 -----------------------------------------------------
335 -- Loading instance decls
336 -----------------------------------------------------
338 loadInstDecl :: Module
342 loadInstDecl mod insts decl@(InstDecl inst_ty binds uprags dfun_name src_loc)
344 -- Find out what type constructors and classes are "gates" for the
345 -- instance declaration. If all these "gates" are slurped in then
346 -- we should slurp the instance decl too.
348 -- We *don't* want to count names in the context part as gates, though.
350 -- instance Foo a => Baz (T a) where ...
352 -- Here the gates are Baz and T, but *not* Foo.
354 munged_inst_ty = removeContext inst_ty
355 free_names = extractHsTyRdrNames munged_inst_ty
358 mapRn lookupOrigName free_names `thenRn` \ gate_names ->
359 returnRn ((mkNameSet gate_names, (mod, InstD decl)) `consBag` insts)
362 -- In interface files, the instance decls now look like
363 -- forall a. Foo a -> Baz (T a)
364 -- so we have to strip off function argument types as well
365 -- as the bit before the '=>' (which is always empty in interface files)
366 removeContext (HsForAllTy tvs cxt ty) = HsForAllTy tvs [] (removeFuns ty)
367 removeContext ty = removeFuns ty
369 removeFuns (HsFunTy _ ty) = removeFuns ty
373 -----------------------------------------------------
375 -----------------------------------------------------
377 loadRules :: Module -> IfaceRules
378 -> (Version, [RdrNameRuleDecl])
379 -> RnM d (Version, IfaceRules)
380 loadRules mod rule_bag (version, rules)
381 | null rules || opt_IgnoreIfacePragmas
382 = returnRn (version, rule_bag)
385 mapRn (loadRule mod) rules `thenRn` \ new_rules ->
386 returnRn (version, rule_bag `unionBags` listToBag new_rules)
388 loadRule :: Module -> RdrNameRuleDecl -> RnM d GatedDecl
389 -- "Gate" the rule simply by whether the rule variable is
390 -- needed. We can refine this later.
391 loadRule mod decl@(IfaceRule _ _ var _ _ src_loc)
392 = lookupOrigName var `thenRn` \ var_name ->
393 returnRn (unitNameSet var_name, (mod, RuleD decl))
396 -----------------------------------------------------
397 -- Loading Deprecations
398 -----------------------------------------------------
400 loadDeprecs :: Module -> IfaceDeprecs -> RnM d Deprecations
401 loadDeprecs m Nothing = returnRn NoDeprecs
402 loadDeprecs m (Just (Left txt)) = returnRn (DeprecAll txt)
403 loadDeprecs m (Just (Right prs)) = setModuleRn m $
404 foldlRn loadDeprec emptyNameEnv prs `thenRn` \ env ->
405 returnRn (DeprecSome env)
406 loadDeprec deprec_env (n, txt)
407 = lookupOrigName n `thenRn` \ name ->
408 traceRn (text "Loaded deprecation(s) for" <+> ppr name <> colon <+> ppr txt) `thenRn_`
409 returnRn (extendNameEnv deprec_env name txt)
413 %*********************************************************
415 \subsection{Getting binders out of a declaration}
417 %*********************************************************
419 @getDeclBinders@ returns the names for a @RdrNameHsDecl@.
420 It's used for both source code (from @availsFromDecl@) and interface files
423 It doesn't deal with source-code specific things: @ValD@, @DefD@. They
424 are handled by the sourc-code specific stuff in @RnNames@.
427 getIfaceDeclBinders, getTyClDeclBinders
428 :: (RdrName -> SrcLoc -> RnM d Name) -- New-name function
432 getIfaceDeclBinders new_name tycl_decl
433 = getTyClDeclBinders new_name tycl_decl `thenRn` \ avail ->
434 getSysTyClDeclBinders new_name tycl_decl `thenRn` \ extras ->
435 returnRn (addSysAvails avail extras)
436 -- Add the sys-binders to avail. When we import the decl,
437 -- it's full_avail that will get added to the 'already-slurped' set (iSlurp)
438 -- If we miss out sys-binders, we'll read the decl multiple times!
440 getTyClDeclBinders new_name (IfaceSig var ty prags src_loc)
441 = new_name var src_loc `thenRn` \ var_name ->
442 returnRn (Avail var_name)
444 getTyClDeclBinders new_name tycl_decl
445 = mapRn do_one (tyClDeclNames tycl_decl) `thenRn` \ (main_name:sub_names) ->
446 returnRn (AvailTC main_name (main_name : sub_names))
448 do_one (name,loc) = new_name name loc
451 @getDeclSysBinders@ gets the implicit binders introduced by a decl.
452 A the moment that's just the tycon and datacon that come with a class decl.
453 They aren't returned by @getDeclBinders@ because they aren't in scope;
454 but they {\em should} be put into the @DeclsMap@ of this module.
456 Note that this excludes the default-method names of a class decl,
457 and the dict fun of an instance decl, because both of these have
458 bindings of their own elsewhere.
461 getSysTyClDeclBinders new_name (ClassDecl _ cname _ _ sigs _ names src_loc)
462 = sequenceRn [new_name n src_loc | n <- names]
464 getSysTyClDeclBinders new_name (TyData _ _ _ _ cons _ _ _ _ _)
465 = sequenceRn [new_name wkr_name src_loc | ConDecl _ wkr_name _ _ _ src_loc <- cons]
467 getSysTyClDeclBinders new_name other_decl
473 %*********************************************************
475 \subsection{Reading an interface file}
477 %*********************************************************
480 findAndReadIface :: SDoc -> ModuleName
481 -> IsBootInterface -- True <=> Look for a .hi-boot file
482 -- False <=> Look for .hi file
483 -> RnM d (Either Message (Module, ParsedIface))
484 -- Nothing <=> file not found, or unreadable, or illegible
485 -- Just x <=> successfully found and parsed
487 findAndReadIface doc_str mod_name hi_boot_file
488 = traceRn trace_msg `thenRn_`
490 getFinderRn `thenRn` \ finder ->
491 ioToRnM (finder mod_name) `thenRn` \ maybe_found ->
494 Right (Just (mod,locn))
495 | hi_boot_file -> readIface mod (hi_file locn ++ "-hi-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)