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,
13 removeContext -- removeContext probably belongs somewhere else
16 #include "HsVersions.h"
18 import CmdLineOpts ( opt_IgnoreIfacePragmas )
20 import HsSyn ( HsDecl(..), TyClDecl(..), InstDecl(..),
21 HsType(..), ConDecl(..),
22 FixitySig(..), RuleDecl(..),
25 import RdrHsSyn ( RdrNameTyClDecl, RdrNameInstDecl, RdrNameRuleDecl,
28 import BasicTypes ( Version )
31 import ParseIface ( parseIface, IfaceStuff(..) )
33 import Name ( Name {-instance NamedThing-}, nameOccName,
36 mkNameEnv, extendNameEnv
38 import Module ( Module,
39 moduleName, isModuleInThisPackage,
40 ModuleName, WhereFrom(..),
41 extendModuleEnv, lookupModuleEnvByName,
43 import RdrName ( RdrName, rdrNameOcc )
45 import SrcLoc ( mkSrcLoc, SrcLoc )
46 import Maybes ( maybeToBool )
47 import StringBuffer ( hGetStringBuffer )
48 import FastString ( mkFastString )
49 import ErrUtils ( Message )
57 %*********************************************************
59 \subsection{Loading a new interface file}
61 %*********************************************************
64 loadHomeInterface :: SDoc -> Name -> RnM d Ifaces
65 loadHomeInterface doc_str name
66 = loadInterface doc_str (moduleName (nameModule name)) ImportBySystem
68 loadOrphanModules :: [ModuleName] -> RnM d ()
69 loadOrphanModules mods
70 | null mods = returnRn ()
71 | otherwise = traceRn (text "Loading orphan modules:" <+>
72 fsep (map ppr mods)) `thenRn_`
73 mapRn_ load mods `thenRn_`
76 load mod = loadInterface (mk_doc mod) mod ImportBySystem
77 mk_doc mod = ppr mod <+> ptext SLIT("is a orphan-instance module")
79 loadInterface :: SDoc -> ModuleName -> WhereFrom -> RnM d Ifaces
80 loadInterface doc mod from
81 = tryLoadInterface doc mod from `thenRn` \ (ifaces, maybe_err) ->
83 Nothing -> returnRn ifaces
84 Just err -> failWithRn ifaces err
86 tryLoadInterface :: SDoc -> ModuleName -> WhereFrom -> RnM d (Ifaces, Maybe Message)
87 -- Returns (Just err) if an error happened
88 -- Guarantees to return with iImpModInfo m --> (..., True)
89 -- (If the load fails, we plug in a vanilla placeholder)
90 tryLoadInterface doc_str mod_name from
91 = getHomeIfaceTableRn `thenRn` \ hit ->
92 getIfacesRn `thenRn` \ ifaces ->
94 -- Check whether we have it already in the home package
95 case lookupModuleEnvByName hit mod_name of {
96 Just _ -> returnRn (ifaces, Nothing) ; -- In the home package
100 mod_map = iImpModInfo ifaces
101 mod_info = lookupFM mod_map mod_name
104 = case (from, mod_info) of
105 (ImportByUser, _) -> False -- Not hi-boot
106 (ImportByUserSource, _) -> True -- hi-boot
107 (ImportBySystem, Just (_, is_boot, _)) -> is_boot --
108 (ImportBySystem, Nothing) -> False
109 -- We're importing a module we know absolutely
110 -- nothing about, so we assume it's from
111 -- another package, where we aren't doing
112 -- dependency tracking. So it won't be a hi-boot file.
114 redundant_source_import
115 = case (from, mod_info) of
116 (ImportByUserSource, Just (_,False,_)) -> True
119 -- CHECK WHETHER WE HAVE IT ALREADY
122 -> -- We're read it already so don't re-read it
123 returnRn (ifaces, Nothing) ;
127 -- Issue a warning for a redundant {- SOURCE -} import
128 -- NB that we arrange to read all the ordinary imports before
129 -- any of the {- SOURCE -} imports
130 warnCheckRn (not redundant_source_import)
131 (warnRedundantSourceImport mod_name) `thenRn_`
133 -- READ THE MODULE IN
134 findAndReadIface doc_str mod_name hi_boot_file `thenRn` \ read_result ->
135 case read_result of {
136 Left err -> -- Not found, so add an empty export env to the Ifaces map
137 -- so that we don't look again
139 new_mod_map = addToFM mod_map mod_name (False, False, True)
140 new_ifaces = ifaces { iImpModInfo = new_mod_map }
142 setIfacesRn new_ifaces `thenRn_`
143 returnRn (new_ifaces, Just err) ;
146 Right (mod, iface) ->
148 -- LOAD IT INTO Ifaces
150 -- NB: *first* we do loadDecl, so that the provenance of all the locally-defined
151 --- names is done correctly (notably, whether this is an .hi file or .hi-boot file).
152 -- If we do loadExport first the wrong info gets into the cache (unless we
153 -- explicitly tag each export which seems a bit of a bore)
156 -- Sanity check. If we're system-importing a module we know nothing at all
157 -- about, it should be from a different package to this one
158 WARN( not (maybeToBool mod_info) &&
159 case from of { ImportBySystem -> True; other -> False } &&
160 isModuleInThisPackage mod,
163 loadDecls mod (iDecls ifaces) (pi_decls iface) `thenRn` \ (decls_vers, new_decls) ->
164 loadRules mod (iRules ifaces) (pi_rules iface) `thenRn` \ (rule_vers, new_rules) ->
165 foldlRn (loadInstDecl mod) (iInsts ifaces) (pi_insts iface) `thenRn` \ new_insts ->
166 loadExports (pi_exports iface) `thenRn` \ (export_vers, avails) ->
167 loadFixDecls mod (pi_fixity iface) `thenRn` \ fix_env ->
168 loadDeprecs mod (pi_deprecs iface) `thenRn` \ deprec_env ->
170 version = VersionInfo { vers_module = pi_vers iface,
171 vers_exports = export_vers,
172 vers_rules = rule_vers,
173 vers_decls = decls_vers }
175 -- For an explicit user import, add to mod_map info about
176 -- the things the imported module depends on, extracted
177 -- from its usage info.
178 mod_map1 = case from of
179 ImportByUser -> addModDeps mod (pi_usages iface) mod_map
181 mod_map2 = addToFM mod_map1 mod_name (has_orphans, hi_boot_file, True)
183 -- Now add info about this module to the PIT
184 has_orphans = pi_orphan iface
185 new_pit = extendModuleEnv (iPIT ifaces) mod mod_iface
186 mod_iface = ModIface { mi_module = mod, mi_version = version,
187 mi_exports = avails, mi_orphan = has_orphans,
188 mi_fixities = fix_env, mi_deprecs = deprec_env,
189 mi_usages = [], -- Will be filled in later
190 mi_decls = panic "No mi_decls in PIT",
191 mi_globals = panic "No mi_globals in PIT"
194 new_ifaces = ifaces { iPIT = new_pit,
198 iImpModInfo = mod_map2 }
200 setIfacesRn new_ifaces `thenRn_`
201 returnRn (new_ifaces, Nothing)
204 -----------------------------------------------------
205 -- Adding module dependencies from the
206 -- import decls in the interface file
207 -----------------------------------------------------
209 addModDeps :: Module -> [ImportVersion a]
210 -> ImportedModuleInfo -> ImportedModuleInfo
211 -- (addModDeps M ivs deps)
212 -- We are importing module M, and M.hi contains 'import' decls given by ivs
213 addModDeps mod new_deps mod_deps
214 = foldr add mod_deps filtered_new_deps
216 -- Don't record dependencies when importing a module from another package
217 -- Except for its descendents which contain orphans,
218 -- and in that case, forget about the boot indicator
219 filtered_new_deps :: [(ModuleName, (WhetherHasOrphans, IsBootInterface, IsLoaded))]
221 | isModuleInThisPackage mod
222 = [ (imp_mod, (has_orphans, is_boot, False))
223 | (imp_mod, has_orphans, is_boot, _) <- new_deps
225 | otherwise = [ (imp_mod, (True, False, False))
226 | (imp_mod, has_orphans, _, _) <- new_deps,
229 add (imp_mod, dep) deps = addToFM_C combine deps imp_mod dep
231 combine old@(_, old_is_boot, old_is_loaded) new
232 | old_is_loaded || not old_is_boot = old -- Keep the old info if it's already loaded
233 -- or if it's a non-boot pending load
234 | otherwise = new -- Otherwise pick new info
237 -----------------------------------------------------
238 -- Loading the export list
239 -----------------------------------------------------
241 loadExports :: (Version, [ExportItem]) -> RnM d (Version, Avails)
242 loadExports (vers, items)
243 = getModuleRn `thenRn` \ this_mod ->
244 mapRn (loadExport this_mod) items `thenRn` \ avails_s ->
245 returnRn (vers, concat avails_s)
248 loadExport :: Module -> ExportItem -> RnM d [AvailInfo]
249 loadExport this_mod (mod, entities)
250 | mod == moduleName this_mod = returnRn []
251 -- If the module exports anything defined in this module, just ignore it.
252 -- Reason: otherwise it looks as if there are two local definition sites
253 -- for the thing, and an error gets reported. Easiest thing is just to
254 -- filter them out up front. This situation only arises if a module
255 -- imports itself, or another module that imported it. (Necessarily,
256 -- this invoves a loop.) Consequence: if you say
261 -- module B( AType ) where
262 -- import {-# SOURCE #-} A( AType )
264 -- then you'll get a 'B does not export AType' message. A bit bogus
265 -- but it's a bogus thing to do!
268 = mapRn (load_entity mod) entities
270 new_name mod occ = newGlobalName mod occ
272 load_entity mod (Avail occ)
273 = new_name mod occ `thenRn` \ name ->
274 returnRn (Avail name)
275 load_entity mod (AvailTC occ occs)
276 = new_name mod occ `thenRn` \ name ->
277 mapRn (new_name mod) occs `thenRn` \ names ->
278 returnRn (AvailTC name names)
281 -----------------------------------------------------
282 -- Loading type/class/value decls
283 -----------------------------------------------------
287 -> [(Version, RdrNameTyClDecl)]
288 -> RnM d (NameEnv Version, DeclsMap)
289 loadDecls mod decls_map decls
290 = foldlRn (loadDecl mod) (emptyNameEnv, decls_map) decls
293 -> (NameEnv Version, DeclsMap)
294 -> (Version, RdrNameTyClDecl)
295 -> RnM d (NameEnv Version, DeclsMap)
296 loadDecl mod (version_map, decls_map) (version, decl)
297 = getIfaceDeclBinders new_name 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 -- newTopBinder puts into the cache the binder with the
309 -- module information set correctly. When the decl is later renamed,
310 -- the binding site will thereby get the correct module.
311 -- There maybe occurrences that don't have the correct Module, but
312 -- by the typechecker will propagate the binding definition to all
313 -- the occurrences, so that doesn't matter
314 new_name rdr_name loc = newTopBinder mod rdr_name loc
317 -----------------------------------------------------
318 -- Loading fixity decls
319 -----------------------------------------------------
321 loadFixDecls mod decls
322 = mapRn (loadFixDecl mod_name) decls `thenRn` \ to_add ->
323 returnRn (mkNameEnv to_add)
325 mod_name = moduleName mod
327 loadFixDecl mod_name sig@(FixitySig rdr_name fixity loc)
328 = newGlobalName mod_name (rdrNameOcc rdr_name) `thenRn` \ name ->
329 returnRn (name, fixity)
332 -----------------------------------------------------
333 -- Loading instance decls
334 -----------------------------------------------------
336 loadInstDecl :: Module
340 loadInstDecl mod insts decl@(InstDecl inst_ty binds uprags dfun_name src_loc)
342 -- Find out what type constructors and classes are "gates" for the
343 -- instance declaration. If all these "gates" are slurped in then
344 -- we should slurp the instance decl too.
346 -- We *don't* want to count names in the context part as gates, though.
348 -- instance Foo a => Baz (T a) where ...
350 -- Here the gates are Baz and T, but *not* Foo.
352 munged_inst_ty = removeContext inst_ty
353 free_names = extractHsTyRdrNames munged_inst_ty
356 mapRn lookupOrigName free_names `thenRn` \ gate_names ->
357 returnRn ((mkNameSet gate_names, (mod, InstD decl)) `consBag` insts)
360 -- In interface files, the instance decls now look like
361 -- forall a. Foo a -> Baz (T a)
362 -- so we have to strip off function argument types as well
363 -- as the bit before the '=>' (which is always empty in interface files)
364 removeContext (HsForAllTy tvs cxt ty) = HsForAllTy tvs [] (removeFuns ty)
365 removeContext ty = removeFuns ty
367 removeFuns (HsFunTy _ ty) = removeFuns ty
371 -----------------------------------------------------
373 -----------------------------------------------------
375 loadRules :: Module -> IfaceRules
376 -> (Version, [RdrNameRuleDecl])
377 -> RnM d (Version, IfaceRules)
378 loadRules mod rule_bag (version, rules)
379 | null rules || opt_IgnoreIfacePragmas
380 = returnRn (version, rule_bag)
383 mapRn (loadRule mod) rules `thenRn` \ new_rules ->
384 returnRn (version, rule_bag `unionBags` listToBag new_rules)
386 loadRule :: Module -> RdrNameRuleDecl -> RnM d GatedDecl
387 -- "Gate" the rule simply by whether the rule variable is
388 -- needed. We can refine this later.
389 loadRule mod decl@(IfaceRule _ _ var _ _ src_loc)
390 = lookupOrigName var `thenRn` \ var_name ->
391 returnRn (unitNameSet var_name, (mod, RuleD decl))
394 -----------------------------------------------------
395 -- Loading Deprecations
396 -----------------------------------------------------
398 loadDeprecs :: Module -> IfaceDeprecs -> RnM d Deprecations
399 loadDeprecs m Nothing = returnRn NoDeprecs
400 loadDeprecs m (Just (Left txt)) = returnRn (DeprecAll txt)
401 loadDeprecs m (Just (Right prs)) = setModuleRn m $
402 foldlRn loadDeprec emptyNameEnv prs `thenRn` \ env ->
403 returnRn (DeprecSome env)
404 loadDeprec deprec_env (n, txt)
405 = lookupOrigName n `thenRn` \ name ->
406 traceRn (text "Loaded deprecation(s) for" <+> ppr name <> colon <+> ppr txt) `thenRn_`
407 returnRn (extendNameEnv deprec_env name txt)
411 %*********************************************************
413 \subsection{Getting binders out of a declaration}
415 %*********************************************************
417 @getDeclBinders@ returns the names for a @RdrNameHsDecl@.
418 It's used for both source code (from @availsFromDecl@) and interface files
421 It doesn't deal with source-code specific things: @ValD@, @DefD@. They
422 are handled by the sourc-code specific stuff in @RnNames@.
425 getIfaceDeclBinders, getTyClDeclBinders
426 :: (RdrName -> SrcLoc -> RnM d Name) -- New-name function
430 getIfaceDeclBinders new_name tycl_decl
431 = getTyClDeclBinders new_name tycl_decl `thenRn` \ avail ->
432 getSysTyClDeclBinders new_name tycl_decl `thenRn` \ extras ->
433 returnRn (addSysAvails avail extras)
434 -- Add the sys-binders to avail. When we import the decl,
435 -- it's full_avail that will get added to the 'already-slurped' set (iSlurp)
436 -- If we miss out sys-binders, we'll read the decl multiple times!
438 getTyClDeclBinders new_name (IfaceSig var ty prags src_loc)
439 = new_name var src_loc `thenRn` \ var_name ->
440 returnRn (Avail var_name)
442 getTyClDeclBinders new_name tycl_decl
443 = mapRn do_one (tyClDeclNames tycl_decl) `thenRn` \ (main_name:sub_names) ->
444 returnRn (AvailTC main_name (main_name : sub_names))
446 do_one (name,loc) = new_name name loc
449 @getDeclSysBinders@ gets the implicit binders introduced by a decl.
450 A the moment that's just the tycon and datacon that come with a class decl.
451 They aren't returned by @getDeclBinders@ because they aren't in scope;
452 but they {\em should} be put into the @DeclsMap@ of this module.
454 Note that this excludes the default-method names of a class decl,
455 and the dict fun of an instance decl, because both of these have
456 bindings of their own elsewhere.
459 getSysTyClDeclBinders new_name (ClassDecl _ cname _ _ sigs _ names src_loc)
460 = sequenceRn [new_name n src_loc | n <- names]
462 getSysTyClDeclBinders new_name (TyData _ _ _ _ cons _ _ _ _ _)
463 = sequenceRn [new_name wkr_name src_loc | ConDecl _ wkr_name _ _ _ src_loc <- cons]
465 getSysTyClDeclBinders new_name other_decl
471 %*********************************************************
473 \subsection{Reading an interface file}
475 %*********************************************************
478 findAndReadIface :: SDoc -> ModuleName
479 -> IsBootInterface -- True <=> Look for a .hi-boot file
480 -- False <=> Look for .hi file
481 -> RnM d (Either Message (Module, ParsedIface))
482 -- Nothing <=> file not found, or unreadable, or illegible
483 -- Just x <=> successfully found and parsed
485 findAndReadIface doc_str mod_name hi_boot_file
486 = traceRn trace_msg `thenRn_`
488 getFinderRn `thenRn` \ finder ->
489 ioToRnM (finder mod_name) `thenRn` \ maybe_found ->
492 Right (Just (mod,locn))
493 | hi_boot_file -> readIface mod (hi_file locn ++ "-hi-boot")
494 | otherwise -> readIface mod (hi_file locn)
497 other -> traceRn (ptext SLIT("...not found")) `thenRn_`
498 returnRn (Left (noIfaceErr mod_name hi_boot_file))
501 trace_msg = sep [hsep [ptext SLIT("Reading"),
502 if hi_boot_file then ptext SLIT("[boot]") else empty,
503 ptext SLIT("interface for"),
504 ppr mod_name <> semi],
505 nest 4 (ptext SLIT("reason:") <+> doc_str)]
508 @readIface@ tries just the one file.
511 readIface :: Module -> String -> RnM d (Either Message (Module, ParsedIface))
512 -- Nothing <=> file not found, or unreadable, or illegible
513 -- Just x <=> successfully found and parsed
514 readIface wanted_mod file_path
515 = traceRn (ptext SLIT("...reading from") <+> text file_path) `thenRn_`
516 ioToRnM (hGetStringBuffer False file_path) `thenRn` \ read_result ->
519 case parseIface contents
520 PState{ bol = 0#, atbol = 1#,
523 loc = mkSrcLoc (mkFastString file_path) 1 } of
524 POk _ (PIface iface) ->
525 warnCheckRn (wanted_mod == read_mod)
526 (hiModuleNameMismatchWarn wanted_mod read_mod) `thenRn_`
527 returnRn (Right (wanted_mod, iface))
529 read_mod = pi_mod iface
531 PFailed err -> bale_out err
532 parse_result -> bale_out empty
533 -- This last case can happen if the interface file is (say) empty
534 -- in which case the parser thinks it looks like an IdInfo or
535 -- something like that. Just an artefact of the fact that the
536 -- parser is used for several purposes at once.
538 Left io_err -> bale_out (text (show io_err))
540 bale_out err = returnRn (Left (badIfaceFile file_path err))
544 %*********************************************************
548 %*********************************************************
551 noIfaceErr mod_name boot_file
552 = ptext SLIT("Could not find interface file for") <+> quotes (ppr mod_name)
553 -- We used to print the search path, but we can't do that
554 -- now, because it's hidden inside the finder.
555 -- Maybe the finder should expose more functions.
557 badIfaceFile file err
558 = vcat [ptext SLIT("Bad interface file:") <+> text file,
561 hiModuleNameMismatchWarn :: Module -> Module -> Message
562 hiModuleNameMismatchWarn requested_mod read_mod =
563 hsep [ ptext SLIT("Something is amiss; requested module name")
564 , ppr (moduleName requested_mod)
565 , ptext SLIT("differs from name found in the interface file")
569 warnRedundantSourceImport mod_name
570 = ptext SLIT("Unnecessary {- SOURCE -} in the import of module")
571 <+> quotes (ppr mod_name)