2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
4 \section[RnIfaces]{Cacheing and Renaming of Interfaces}
7 #include "HsVersions.h"
21 import PreludeGlaST ( thenPrimIO, seqPrimIO, readVar, writeVar, MutableVar(..) )
24 import HsPragmas ( noGenPragmas )
29 import RnSource ( rnTyDecl, rnClassDecl, rnInstDecl, rnPolyType )
30 import RnUtils ( RnEnv(..), emptyRnEnv, lookupRnEnv, lookupTcRnEnv, extendGlobalRnEnv )
31 import ParseIface ( parseIface )
32 import ParseUtils ( ParsedIface(..), RdrIfaceDecl(..), RdrIfaceInst(..),
33 VersionsMap(..), UsagesMap(..)
36 import Bag ( emptyBag, unitBag, consBag, snocBag,
37 unionBags, unionManyBags, isEmptyBag, bagToList )
38 import CmdLineOpts ( opt_HiSuffix, opt_SysHiSuffix )
39 import ErrUtils ( Error(..), Warning(..) )
40 import FiniteMap ( emptyFM, lookupFM, addToFM, addToFM_C, plusFM, eltsFM,
41 fmToList, delListFromFM, sizeFM, foldFM, unitFM,
42 plusFM_C, keysFM{-ToDo:rm-}
44 import Maybes ( maybeToBool )
45 import Name ( moduleNamePair, origName, isRdrLexCon, RdrName(..) )
46 import PprStyle -- ToDo:rm
47 import Outputable -- ToDo:rm
48 import PrelInfo ( builtinNameInfo )
50 import Maybes ( MaybeErr(..) )
51 import UniqFM ( emptyUFM )
52 import UniqSupply ( splitUniqSupply )
53 import Util ( sortLt, removeDups, cmpPString, startsWith,
54 panic, pprPanic, assertPanic, pprTrace{-ToDo:rm-} )
58 type ModuleToIfaceContents = FiniteMap Module ParsedIface
59 type ModuleToIfaceFilePath = FiniteMap Module FilePath
62 = MutableVar _RealWorld
63 (ModuleToIfaceContents, -- interfaces for individual interface files
64 ModuleToIfaceContents, -- merged interfaces based on module name
65 -- used for extracting info about original names
66 ModuleToIfaceFilePath)
69 *********************************************************
71 \subsection{Looking for interface files}
73 *********************************************************
75 Return a mapping from module-name to
76 absolute-filename-for-that-interface.
78 findHiFiles :: [FilePath] -> [FilePath] -> IO (FiniteMap Module FilePath)
80 findHiFiles dirs sysdirs
81 = --hPutStr stderr " findHiFiles " >>
82 do_dirs emptyFM (dirs ++ sysdirs) >>= \ result ->
83 --hPutStr stderr " done\n" >>
86 do_dirs env [] = return env
87 do_dirs env (dir:dirs)
88 = do_dir env dir >>= \ new_env ->
92 = --hPutStr stderr "D" >>
93 getDirectoryContents dir >>= \ entries ->
94 do_entries env entries
96 do_entries env [] = return env
98 = do_entry env e >>= \ new_env ->
102 = case (acceptable_hi (reverse e)) of
103 Nothing -> --trace ("Deemed uncool:"++e) $
104 --hPutStr stderr "." >>
110 case (lookupFM env pmod) of
111 Nothing -> --trace ("Adding "++mod++" -> "++e) $
112 --hPutStr stderr "!" >>
113 return (addToFM env pmod (dir ++ '/':e))
114 -- ToDo: use DIR_SEP, not /
116 Just xx -> ( if de_dot xx /= e then trace ("Already mapped!! "++mod++" -> "++xx++"; ignoring:"++e) else id) $
117 --hPutStr stderr "." >>
120 acceptable_hi rev_e -- looking at pathname *backwards*
121 = case (startsWith (reverse opt_HiSuffix) rev_e) of
123 Just xs -> plausible_modname xs{-reversed-}
126 de_dot ('.' : '/' : xs) = xs
130 plausible_modname rev_e
132 cand = reverse (takeWhile is_modname_char rev_e)
134 if null cand || not (isUpper (head cand))
138 is_modname_char c = isAlphanum c || c == '_'
141 *********************************************************
143 \subsection{Reading interface files}
145 *********************************************************
147 Return cached info about a Module's interface; otherwise,
148 read the interface (using our @ModuleToIfaceFilePath@ map
149 to decide where to look).
151 Note: we have two notions of interface
152 * the interface for a particular file name
153 * the (combined) interface for a particular module name
155 The idea is that two source files may declare a module
156 with the same name with the declarations being merged.
158 This allows us to have file PreludeList.hs producing
159 PreludeList.hi but defining part of module Prelude.
160 When PreludeList is imported its contents will be
161 added to Prelude. In this way all the original names
162 for a particular module will be available the imported
165 ToDo: Check duplicate definitons are the same.
166 ToDo: Check/Merge duplicate pragmas.
170 cachedIface :: Bool -- True => want merged interface for original name
171 -> IfaceCache -- False => want file interface only
173 -> IO (MaybeErr ParsedIface Error)
175 cachedIface want_orig_iface iface_cache mod
176 = readVar iface_cache `thenPrimIO` \ (iface_fm, orig_fm, file_fm) ->
178 case (lookupFM iface_fm mod) of
179 Just iface -> return (want_iface iface orig_fm)
181 case (lookupFM file_fm mod) of
182 Nothing -> return (Failed (noIfaceErr mod))
184 readIface file mod >>= \ read_iface ->
186 Failed err -> -- pprTrace "module-file map:\n" (ppAboves [ppCat [ppPStr m, ppStr f] | (m,f) <- fmToList file_fm]) $
190 iface_fm' = addToFM iface_fm mod iface
191 orig_fm' = addToFM_C mergeIfaces orig_fm (iface_mod iface) iface
193 writeVar iface_cache (iface_fm', orig_fm', file_fm) `seqPrimIO`
194 return (want_iface iface orig_fm')
196 want_iface iface orig_fm
198 = case lookupFM orig_fm mod of
199 Nothing -> Failed (noOrigIfaceErr mod)
200 Just orig_iface -> Succeeded orig_iface
204 iface_mod (ParsedIface mod _ _ _ _ _ _ _ _ _ _ _ _) = mod
207 mergeIfaces (ParsedIface mod1 (_, files1) _ _ _ _ _ _ fixes1 tdefs1 vdefs1 idefs1 prags1)
208 (ParsedIface mod2 (_, files2) _ _ _ _ _ _ fixes2 tdefs2 vdefs2 idefs2 prags2)
209 = pprTrace "mergeIfaces:" (ppCat [ppStr "import", ppCat (map ppPStr (bagToList files2)),
210 ppStr "merged with", ppPStr mod1]) $
213 (True, unionBags files1 files2)
214 (panic "mergeIface: module version numbers")
215 (panic "mergeIface: source version numbers") -- Version numbers etc must be extracted from
216 (panic "mergeIface: usage version numbers") -- the merged file interfaces named above
217 (panic "mergeIface: decl version numbers")
218 (panic "mergeIface: exports")
219 (panic "mergeIface: instance modules")
220 (plusFM_C (dup_merge "fixity" (ppr PprDebug . fixDeclName)) fixes1 fixes2)
221 (plusFM_C (dup_merge "tycon/class" (ppr PprDebug . idecl_nm)) tdefs1 tdefs2)
222 (plusFM_C (dup_merge "value" (ppr PprDebug . idecl_nm)) vdefs1 vdefs2)
223 (unionBags idefs1 idefs2)
224 (plusFM_C (dup_merge "pragma" ppStr) prags1 prags2)
226 dup_merge str ppr_dup dup1 dup2
227 = pprTrace "mergeIfaces:"
228 (ppCat [ppPStr mod1, ppPStr mod2, ppStr ": dup", ppStr str, ppStr "decl",
229 ppr_dup dup1, ppr_dup dup2]) $
232 idecl_nm (TypeSig n _ _) = n
233 idecl_nm (NewTypeSig n _ _ _) = n
234 idecl_nm (DataSig n _ _ _ _) = n
235 idecl_nm (ClassSig n _ _ _) = n
236 idecl_nm (ValSig n _ _) = n
239 cachedDecl :: IfaceCache
240 -> Bool -- True <=> tycon or class name
242 -> IO (MaybeErr RdrIfaceDecl Error)
244 cachedDecl iface_cache class_or_tycon orig
245 = cachedIface True iface_cache mod >>= \ maybe_iface ->
247 Failed err -> return (Failed err)
248 Succeeded (ParsedIface _ _ _ _ _ _ exps _ _ tdefs vdefs _ _) ->
249 case (lookupFM (if class_or_tycon then tdefs else vdefs) str) of
250 Just decl -> return (Succeeded decl)
251 Nothing -> return (Failed (noDeclInIfaceErr mod str))
253 (mod, str) = moduleNamePair orig
256 cachedDeclByType :: IfaceCache
257 -> RnName{-NB: diff type than cachedDecl -}
258 -> IO (MaybeErr RdrIfaceDecl Error)
260 cachedDeclByType iface_cache rn
261 -- the idea is: check that, e.g., if we're given an
262 -- RnClass, then we really get back a ClassDecl from
263 -- the cache (not an RnData, or something silly)
264 = cachedDecl iface_cache (isRnTyConOrClass rn) (origName rn) >>= \ maybe_decl ->
266 return_maybe_decl = return maybe_decl
267 return_failed msg = return (Failed msg)
270 Failed _ -> return_maybe_decl
273 WiredInId _ -> return_failed (ifaceLookupWiredErr "value" rn)
274 WiredInTyCon _ -> return_failed (ifaceLookupWiredErr "type constructor" rn)
275 RnUnbound _ -> pprPanic "cachedDeclByType:" (ppr PprDebug rn)
277 RnSyn _ -> return_maybe_decl
278 RnData _ _ _ -> return_maybe_decl
279 RnImplicitTyCon _ -> if is_tycon_decl if_decl
280 then return_maybe_decl
281 else return_failed (badIfaceLookupErr "type constructor" rn if_decl)
283 RnClass _ _ -> return_maybe_decl
284 RnImplicitClass _ -> if is_class_decl if_decl
285 then return_maybe_decl
286 else return_failed (badIfaceLookupErr "class" rn if_decl)
288 RnName _ -> return_maybe_decl
289 RnConstr _ _ -> return_maybe_decl
290 RnField _ _ -> return_maybe_decl
291 RnClassOp _ _ -> return_maybe_decl
292 RnImplicit _ -> if is_val_decl if_decl
293 then return_maybe_decl
294 else return_failed (badIfaceLookupErr "value" rn if_decl)
296 is_tycon_decl (TypeSig _ _ _) = True
297 is_tycon_decl (NewTypeSig _ _ _ _) = True
298 is_tycon_decl (DataSig _ _ _ _ _) = True
299 is_tycon_decl _ = False
301 is_class_decl (ClassSig _ _ _ _) = True
302 is_class_decl _ = False
304 is_val_decl (ValSig _ _ _) = True
305 is_val_decl (DataSig _ _ _ _ _) = True -- may be a constr or field
306 is_val_decl (NewTypeSig _ _ _ _) = True -- may be a constr
307 is_val_decl (ClassSig _ _ _ _) = True -- may be a method
308 is_val_decl _ = False
312 readIface :: FilePath -> Module
313 -> IO (MaybeErr ParsedIface Error)
316 = --hPutStr stderr (" reading "++file) >>
317 readFile file `thenPrimIO` \ read_result ->
319 Left err -> return (Failed (cannaeReadErr file err))
320 Right contents -> --hPutStr stderr " parsing" >>
321 let parsed = parseIface contents in
322 --hPutStr stderr " done\n" >>
326 Succeeded p -> Succeeded (init_merge mod p)
329 init_merge this (ParsedIface mod _ v sv us vs exps insts fixes tdefs vdefs idefs prags)
330 = ParsedIface mod (False, unitBag this) v sv us vs exps insts fixes tdefs vdefs idefs prags
335 rnIfaces :: IfaceCache -- iface cache (mutvar)
336 -> [Module] -- directly imported modules
338 -> RnEnv -- defined (in the source) name env
339 -> RnEnv -- mentioned (in the source) name env
340 -> RenamedHsModule -- module to extend with iface decls
341 -> [RnName] -- imported names required (really the
342 -- same info as in mentioned name env)
343 -- Also, all the things we may look up
344 -- later by key (Unique).
345 -> IO (RenamedHsModule, -- extended module
346 RnEnv, -- final env (for renaming derivings)
347 ImplicitEnv, -- implicit names used (for usage info)
348 (UsagesMap,VersionsMap,[Module]), -- usage info
349 (Bag Error, Bag Warning))
351 rnIfaces iface_cache imp_mods us
352 def_env@((dqual, dunqual, dtc_qual, dtc_unqual), dstack)
353 occ_env@((qual, unqual, tc_qual, tc_unqual), stack)
354 rn_module@(HsModule modname iface_version exports imports fixities
355 typedecls typesigs classdecls instdecls instsigs
356 defdecls binds sigs src_loc)
359 pprTrace "rnIfaces:going after:" (ppCat (map (ppr PprDebug) todo)) $
361 pprTrace "rnIfaces:qual:" (ppCat [ppBesides[ppPStr m,ppChar '.',ppPStr n] | (n,m) <- keysFM qual]) $
362 pprTrace "rnIfaces:unqual:" (ppCat (map ppPStr (keysFM unqual))) $
363 pprTrace "rnIfaces:tc_qual:" (ppCat [ppBesides[ppPStr m,ppChar '.',ppPStr n] | (n,m) <- keysFM tc_qual]) $
364 pprTrace "rnIfaces:tc_unqual:" (ppCat (map ppPStr (keysFM tc_unqual))) $
366 pprTrace "rnIfaces:dqual:" (ppCat [ppBesides[ppPStr m,ppChar '.',ppPStr n] | (n,m) <- keysFM dqual]) $
367 pprTrace "rnIfaces:dunqual:" (ppCat (map ppPStr (keysFM dunqual))) $
368 pprTrace "rnIfaces:dtc_qual:" (ppCat [ppBesides[ppPStr m,ppChar '.',ppPStr n] | (n,m) <- keysFM dtc_qual]) $
369 pprTrace "rnIfaces:dtc_unqual:"(ppCat (map ppPStr (keysFM dtc_unqual))) $
372 -- do transitive closure to bring in all needed names/defns and insts:
374 decls_and_insts todo def_env occ_env empty_return us
375 >>= \ (((if_typedecls, if_classdecls, if_instdecls, if_sigs),
380 -- finalize what we want to say we learned about the
382 finalIfaceInfo iface_cache modname if_final_env if_instdecls {-all_imports_used imp_mods-} >>=
383 \ usage_stuff@(usage_info, version_info, instance_mods) ->
385 return (HsModule modname iface_version exports imports fixities
386 (typedecls ++ if_typedecls)
388 (classdecls ++ if_classdecls)
389 (instdecls ++ if_instdecls)
390 instsigs defdecls binds
398 decls_and_insts todo def_env occ_env to_return us
399 = do_decls todo -- initial batch of names to process
400 (def_env, occ_env, us1) -- init stuff down
401 to_return -- acc results
406 cacheInstModules iface_cache imp_mods >>= \ errs ->
408 do_insts decls_def_env decls_occ_env emptyRnEnv emptyFM
409 (add_errs errs decls_return) us2
411 (us1,us2) = splitUniqSupply us
413 do_insts def_env occ_env prev_env done_insts to_return us
414 | size_tc_env occ_env == size_tc_env prev_env
415 = return (to_return, occ_env)
418 = rnIfaceInstStuff iface_cache modname us1 occ_env done_insts to_return
424 do_decls new_unknowns -- new batch of names to process
425 (def_env, insts_occ_env, us2) -- init stuff down
426 insts_return -- acc results
431 do_insts decls_def_env decls_occ_env occ_env new_insts decls_return us3
433 (us1,us') = splitUniqSupply us
434 (us2,us3) = splitUniqSupply us'
436 size_tc_env ((_, _, qual, unqual), _)
437 = sizeFM qual + sizeFM unqual
440 do_decls :: [RnName] -- Names we're looking for; we keep adding/deleting
441 -- from this list; we're done when empty (nothing
442 -- more needs to be looked for)
443 -> Go_Down -- see defn below
444 -> To_Return -- accumulated result
446 RnEnv, -- extended decl env
447 RnEnv) -- extended occ env
449 do_decls to_find@[] down to_return
450 = return (to_return, defenv down, occenv down)
452 do_decls to_find@(n:ns) down to_return
453 = case (lookup_defd down n) of
454 Just _ -> -- previous processing must've found the stuff for this name;
455 -- continue with the rest:
456 -- pprTrace "do_decls:done:" (ppr PprDebug n) $
457 do_decls ns down to_return
460 | fst (moduleNamePair n) == modname ->
461 -- avoid looking in interface for the module being compiled
462 -- pprTrace "do_decls:this module error:" (ppr PprDebug n) $
463 do_decls ns down (add_err (thisModImplicitErr modname n) to_return)
466 -- OK, see what the cache has for us...
468 cachedDeclByType iface_cache n >>= \ maybe_ans ->
470 Failed err -> -- add the error, but keep going:
471 -- pprTrace "do_decls:cache error:" (ppr PprDebug n) $
472 do_decls ns down (add_err err to_return)
474 Succeeded iface_decl -> -- something needing renaming!
476 (us1, us2) = splitUniqSupply (uniqsupply down)
478 case (initRn False{-iface-} modname (occenv down) us1 (
479 setExtraRn emptyUFM{-no fixities-} $
480 rnIfaceDecl iface_decl)) of {
481 ((if_decl, if_defd, if_implicits), if_errs, if_warns) ->
483 new_unknowns = eltsFM (fst if_implicits) ++ eltsFM (snd if_implicits)
486 pprTrace "do_decls:renamed:" (ppAboves [ppr PprDebug n
487 , ppCat [ppStr "new unknowns:", interpp'SP PprDebug new_unknowns]
488 , ppCat [ppStr "defd vals:", interpp'SP PprDebug [n | (_,n) <- fst if_defd] ]
489 , ppCat [ppStr "defd tcs:", interpp'SP PprDebug [n | (_,n) <- snd if_defd] ]
492 do_decls (new_unknowns ++ ns)
493 (add_occs if_defd if_implicits $
494 new_uniqsupply us2 down)
496 add_implicits if_implicits $
498 add_warns if_warns to_return)
502 type Go_Down = (RnEnv, -- stuff we already have defns for;
503 -- to check quickly if we've already
504 -- found something for the name under consideration,
505 -- due to previous processing.
506 -- It starts off just w/ the defns for
507 -- the things in this module.
508 RnEnv, -- occurrence env; this gets added to as
509 -- we process new iface decls. It includes
510 -- entries for *all* occurrences, including those
511 -- for which we have definitions.
512 UniqSupply -- the obvious
515 lookup_defd (def_env, _, _) n
517 = lookupTcRnEnv def_env (origName n)
519 = lookupRnEnv def_env (origName n)
521 defenv (def_env, _, _) = def_env
522 occenv (_, occ_env, _) = occ_env
523 uniqsupply (_, _, us) = us
525 new_uniqsupply us (def_env, occ_env, _) = (def_env, occ_env, us)
527 add_occs (val_defds, tc_defds) (val_imps, tc_imps) (def_env, occ_env, us)
528 = case (extendGlobalRnEnv def_env val_defds tc_defds) of { (new_def_env, def_dups) ->
529 ASSERT(isEmptyBag def_dups)
531 val_occs = val_defds ++ fmToList val_imps
532 tc_occs = tc_defds ++ fmToList tc_imps
534 case (extendGlobalRnEnv occ_env val_occs tc_occs) of { (new_occ_env, occ_dups) ->
536 -- ASSERT(isEmptyBag occ_dups)
537 -- False because we may get a dup on the name we just shoved in
539 (new_def_env, new_occ_env, us) }}
542 type To_Return = (([RenamedTyDecl], [RenamedClassDecl], [RenamedInstDecl], [RenamedSig]),
543 ImplicitEnv, -- new names used implicitly
544 (Bag Error, Bag Warning)
547 empty_return :: To_Return
548 empty_return = (([],[],[],[]), emptyImplicitEnv, (emptyBag,emptyBag))
550 add_decl decl ((tydecls, classdecls, instdecls, sigs), implicit, msgs)
552 AddedTy t -> ((t:tydecls, classdecls, instdecls, sigs), implicit, msgs)
553 AddedClass c -> ((tydecls, c:classdecls, instdecls, sigs), implicit, msgs)
554 AddedSig s -> ((tydecls, classdecls, instdecls, s:sigs), implicit, msgs)
556 add_insts is ((tydecls, classdecls, instdecls, sigs), implicit, msgs)
557 = ((tydecls, classdecls, is ++ instdecls, sigs), implicit, msgs)
559 add_implicits (val_imps, tc_imps) (decls, (val_fm, tc_fm), msgs)
560 = (decls, (val_fm `plusFM` val_imps, tc_fm `plusFM` tc_imps), msgs)
562 add_err err (decls,implicit,(errs,warns)) = (decls,implicit,(errs `snocBag` err,warns))
563 add_errs ers (decls,implicit,(errs,warns)) = (decls,implicit,(errs `unionBags` ers,warns))
564 add_warns ws (decls,implicit,(errs,warns)) = (decls,implicit,(errs, warns `unionBags` ws))
568 data AddedDecl -- purely local
569 = AddedTy RenamedTyDecl
570 | AddedClass RenamedClassDecl
571 | AddedSig RenamedSig
573 rnIfaceDecl :: RdrIfaceDecl
574 -> RnM_Fixes _RealWorld
575 (AddedDecl, -- the resulting decl to add to the pot
576 ([(RdrName,RnName)], [(RdrName,RnName)]),
577 -- new val/tycon-class names that have
578 -- *been defined* while processing this decl
579 ImplicitEnv -- new implicit val/tycon-class names that we
583 rnIfaceDecl (TypeSig tc _ decl)
584 = rnTyDecl decl `thenRn` \ rn_decl ->
585 lookupTyCon tc `thenRn` \ rn_tc ->
586 getImplicitUpRn `thenRn` \ mentioned ->
588 defds = ([], [(tc, rn_tc)])
589 implicits = mentioned `sub` defds
591 returnRn (AddedTy rn_decl, defds, implicits)
593 rnIfaceDecl (NewTypeSig tc dc _ decl)
594 = rnTyDecl decl `thenRn` \ rn_decl ->
595 lookupTyCon tc `thenRn` \ rn_tc ->
596 lookupValue dc `thenRn` \ rn_dc ->
597 getImplicitUpRn `thenRn` \ mentioned ->
599 defds = ([(dc, rn_dc)], [(tc, rn_tc)])
600 implicits = mentioned `sub` defds
602 returnRn (AddedTy rn_decl, defds, implicits)
604 rnIfaceDecl (DataSig tc dcs fcs _ decl)
605 = rnTyDecl decl `thenRn` \ rn_decl ->
606 lookupTyCon tc `thenRn` \ rn_tc ->
607 mapRn lookupValue dcs `thenRn` \ rn_dcs ->
608 mapRn lookupValue fcs `thenRn` \ rn_fcs ->
609 getImplicitUpRn `thenRn` \ mentioned ->
611 defds = (zip dcs rn_dcs ++ zip fcs rn_fcs , [(tc, rn_tc)])
612 implicits = mentioned `sub` defds
614 returnRn (AddedTy rn_decl, defds, implicits)
616 rnIfaceDecl (ClassSig clas ops _ decl)
617 = rnClassDecl decl `thenRn` \ rn_decl ->
618 lookupClass clas `thenRn` \ rn_clas ->
619 mapRn (lookupClassOp rn_clas) ops `thenRn` \ rn_ops ->
620 getImplicitUpRn `thenRn` \ mentioned ->
622 defds = (ops `zip` rn_ops, [(clas, rn_clas)])
623 implicits = mentioned `sub` defds
625 returnRn (AddedClass rn_decl, defds, implicits)
627 rnIfaceDecl (ValSig f src_loc ty)
628 -- should rename_sig in RnBinds be used here? ToDo
629 = lookupValue f `thenRn` \ rn_f ->
630 -- pprTrace "rnIfaceDecl:ValSig:" (ppr PprDebug ty) $
631 rnPolyType nullTyVarNamesEnv ty `thenRn` \ rn_ty ->
632 getImplicitUpRn `thenRn` \ mentioned ->
634 defds = ([(f, rn_f)], [])
635 implicits = mentioned `sub` defds
637 returnRn (AddedSig (Sig rn_f rn_ty noGenPragmas src_loc), defds, implicits)
640 sub :: ImplicitEnv -> ([(RdrName,RnName)], [(RdrName,RnName)]) -> ImplicitEnv
642 sub (val_ment, tc_ment) (val_defds, tc_defds)
643 = (delListFromFM val_ment (map fst val_defds),
644 delListFromFM tc_ment (map fst tc_defds))
647 % ------------------------------
649 @cacheInstModules@: cache instance modules specified in imports
652 cacheInstModules :: IfaceCache -> [Module] -> IO (Bag Error)
653 cacheInstModules iface_cache imp_mods
654 = readVar iface_cache `thenPrimIO` \ (iface_fm, _, _) ->
656 imp_ifaces = [ iface | Just iface <- map (lookupFM iface_fm) imp_mods ]
657 (imp_imods, _) = removeDups cmpPString (bagToList (unionManyBags (map get_ims imp_ifaces)))
658 get_ims (ParsedIface _ _ _ _ _ _ _ ims _ _ _ _ _) = ims
660 accumulate (map (cachedIface False iface_cache) imp_imods) >>= \ err_or_ifaces ->
663 -- Assert that instance modules given by direct imports contains
664 -- instance modules extracted from all visited modules
666 readVar iface_cache `thenPrimIO` \ (all_iface_fm, _, _) ->
668 all_ifaces = eltsFM all_iface_fm
669 (all_imods, _) = removeDups cmpPString (bagToList (unionManyBags (map get_ims (all_ifaces))))
671 ASSERT(sortLt (<) imp_imods == sortLt (<) all_imods)
673 return (bag_errs err_or_ifaces)
675 bag_errs [] = emptyBag
676 bag_errs (Failed err :rest) = err `consBag` bag_errs rest
677 bag_errs (Succeeded _:rest) = bag_errs rest
681 @rnIfaceInstStuff@: Deal with instance declarations from interface files.
684 type InstanceEnv = FiniteMap (RdrName, RdrName) Int
687 :: IfaceCache -- all about ifaces we've read
690 -> RnEnv -- current occ env
691 -> InstanceEnv -- instances for these tycon/class pairs done
694 InstanceEnv, -- extended instance env
695 RnEnv, -- final occ env
696 [RnName]) -- new unknown names
698 rnIfaceInstStuff iface_cache modname us occ_env done_inst_env to_return
699 = -- all the instance decls we might even want to consider
700 -- are in the ParsedIfaces that are in our cache
702 readVar iface_cache `thenPrimIO` \ (_, orig_iface_fm, _) ->
704 all_ifaces = eltsFM orig_iface_fm
705 all_insts = unionManyBags (map get_insts all_ifaces)
706 interesting_insts = filter want_inst (bagToList all_insts)
709 -- Assert that there are no more instances for the done instances
711 claim_done = filter is_done_inst (bagToList all_insts)
712 claim_done_env = foldr add_done_inst emptyFM claim_done
713 has_val fm (k,i) = case lookupFM fm k of { Nothing -> False; Just v -> i == v }
716 pprTrace "all_insts:\n" (ppr_insts (bagToList all_insts)) $
717 pprTrace "interesting_insts:\n" (ppr_insts interesting_insts) $
719 ASSERT(sizeFM done_inst_env == sizeFM claim_done_env)
720 ASSERT(all (has_val claim_done_env) (fmToList done_inst_env))
722 case (initRn False{-iface-} modname occ_env us (
723 setExtraRn emptyUFM{-no fixities-} $
724 mapRn rnIfaceInst interesting_insts `thenRn` \ insts ->
725 getImplicitUpRn `thenRn` \ implicits ->
726 returnRn (insts, implicits))) of {
727 ((if_insts, if_implicits), if_errs, if_warns) ->
729 return (add_insts if_insts $
730 add_implicits if_implicits $
732 add_warns if_warns to_return,
733 foldr add_done_inst done_inst_env interesting_insts,
734 add_imp_occs if_implicits occ_env,
735 eltsFM (fst if_implicits) ++ eltsFM (snd if_implicits))
738 get_insts (ParsedIface _ _ _ _ _ _ _ _ _ _ _ insts _) = insts
740 add_done_inst (InstSig clas tycon _ _) inst_env
741 = addToFM_C (+) inst_env (tycon,clas) 1
743 is_done_inst (InstSig clas tycon _ _)
744 = maybeToBool (lookupFM done_inst_env (tycon,clas))
746 add_imp_occs (val_imps, tc_imps) occ_env
747 = case extendGlobalRnEnv occ_env (fmToList val_imps) (fmToList tc_imps) of
748 (ext_occ_env, occ_dups) -> ASSERT(isEmptyBag occ_dups)
751 want_inst i@(InstSig clas tycon _ _)
752 = -- it's a "good instance" (one to hang onto) if we have a
753 -- chance of referring to *both* the class and tycon later on ...
755 mentionable tycon && mentionable clas && not (is_done_inst i)
758 = case lookupTcRnEnv occ_env nm of
760 Nothing -> -- maybe it's builtin
764 case (lookupFM b_tc_names n) of
766 Nothing -> maybeToBool (lookupFM b_keys n)
768 (b_tc_names, b_keys) -- pretty UGLY ...
769 = case builtinNameInfo of ((_,builtin_tcs),b_keys,_) -> (builtin_tcs,b_keys)
772 = ppAboves (map ppr_inst insts)
774 ppr_inst (InstSig c t _ inst_decl)
775 = ppCat [ppr PprDebug c, ppr PprDebug t, ppr PprDebug inst_decl]
779 rnIfaceInst :: RdrIfaceInst -> RnM_Fixes _RealWorld RenamedInstDecl
781 rnIfaceInst (InstSig _ _ _ inst_decl) = rnInstDecl inst_decl
786 IfaceCache -- iface cache
787 -> Module -- this module's name
790 -- -> [RnName] -- all imported names required
791 -- -> [Module] -- directly imported modules
793 VersionsMap, -- info about version numbers
794 [Module]) -- special instance modules
796 finalIfaceInfo iface_cache modname if_final_env@((qual, unqual, tc_qual, tc_unqual), stack) if_instdecls
798 pprTrace "usageIf:qual:" (ppCat [ppBesides[ppPStr m,ppChar '.',ppPStr n] | (n,m) <- keysFM qual]) $
799 -- pprTrace "usageIf:unqual:" (ppCat (map ppPStr (keysFM unqual))) $
800 pprTrace "usageIf:tc_qual:" (ppCat [ppBesides[ppPStr m,ppChar '.',ppPStr n] | (n,m) <- keysFM tc_qual]) $
801 -- pprTrace "usageIf:tc_unqual:" (ppCat (map ppPStr (keysFM tc_unqual))) $
803 val_stuff@(val_usages, val_versions)
804 = foldFM process_item (emptyFM, emptyFM){-init-} qual
806 (all_usages, all_versions)
807 = foldFM process_item val_stuff{-keep going-} tc_qual
809 return (all_usages, all_versions, [])
811 process_item :: (FAST_STRING,Module) -> RnName -- RnEnv (QualNames) components
812 -> (UsagesMap, VersionsMap) -- input
813 -> (UsagesMap, VersionsMap) -- output
815 process_item (n,m) rn as_before@(usages, versions)
818 | m == modname -- this module => add to "versions"
819 = (usages, addToFM versions n 1{-stub-})
820 | otherwise -- from another module => add to "usages"
821 = (add_to_usages usages m n 1{-stub-}, versions)
823 irrelevant (RnConstr _ _) = True -- We don't report these in their
824 irrelevant (RnField _ _) = True -- own right in usages/etc.
825 irrelevant (RnClassOp _ _) = True
828 add_to_usages usages m n version
830 case (lookupFM usages m) of
831 Nothing -> -- nothing for this module yet...
832 (1{-stub-}, unitFM n version)
834 Just (mversion, mstuff) -> -- the "new" stuff will shadow the old
835 (mversion, addToFM mstuff n version)
841 thisModImplicitErr mod n sty
842 = ppCat [ppPStr SLIT("Implicit import of"), ppr sty n, ppPStr SLIT("when compiling"), ppPStr mod]
845 = ppCat [ppPStr SLIT("Could not find interface for:"), ppPStr mod]
847 noOrigIfaceErr mod sty
848 = ppCat [ppPStr SLIT("Could not find original interface for:"), ppPStr mod]
850 noDeclInIfaceErr mod str sty
851 = ppBesides [ppPStr SLIT("Could not find interface declaration of: "),
852 ppPStr mod, ppStr ".", ppPStr str]
854 cannaeReadErr file err sty
855 = ppBesides [ppPStr SLIT("Failed in reading file: "), ppStr file, ppStr "; error=", ppStr (show err)]
857 ifaceLookupWiredErr msg n sty
858 = ppBesides [ppPStr SLIT("Why am I looking up a wired-in "), ppStr msg, ppChar ':', ppr sty n]
860 badIfaceLookupErr msg name decl sty
861 = ppBesides [ppPStr SLIT("Expected a "), ppStr msg, ppPStr SLIT(" declaration, but got this: ???")]