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, plusFM_C, eltsFM,
41 fmToList, delListFromFM, sizeFM, keysFM{-ToDo:rm-}
43 import Maybes ( maybeToBool )
44 import Name ( moduleNamePair, origName, isRdrLexCon, RdrName(..) )
45 import PprStyle -- ToDo:rm
46 import Outputable -- ToDo:rm
47 import PrelInfo ( builtinNameInfo )
49 import Maybes ( MaybeErr(..) )
50 import UniqFM ( emptyUFM )
51 import UniqSupply ( splitUniqSupply )
52 import Util ( sortLt, removeDups, cmpPString, startsWith,
53 panic, pprPanic, assertPanic, pprTrace{-ToDo:rm-} )
57 type ModuleToIfaceContents = FiniteMap Module ParsedIface
58 type ModuleToIfaceFilePath = FiniteMap Module FilePath
61 = MutableVar _RealWorld
62 (ModuleToIfaceContents, -- interfaces for individual interface files
63 ModuleToIfaceContents, -- merged interfaces based on module name
64 -- used for extracting info about original names
65 ModuleToIfaceFilePath)
68 *********************************************************
70 \subsection{Looking for interface files}
72 *********************************************************
74 Return a mapping from module-name to
75 absolute-filename-for-that-interface.
77 findHiFiles :: [FilePath] -> [FilePath] -> IO (FiniteMap Module FilePath)
79 findHiFiles dirs sysdirs
80 = hPutStr stderr " findHiFiles " >>
81 do_dirs emptyFM (dirs ++ sysdirs) >>= \ result ->
82 hPutStr stderr " done\n" >>
85 do_dirs env [] = return env
86 do_dirs env (dir:dirs)
87 = do_dir env dir >>= \ new_env ->
91 = hPutStr stderr "D" >>
92 getDirectoryContents dir >>= \ entries ->
93 do_entries env entries
95 do_entries env [] = return env
97 = do_entry env e >>= \ new_env ->
101 = case (acceptable_hi (reverse e)) of
102 Nothing -> --trace ("Deemed uncool:"++e) $
103 hPutStr stderr "." >>
109 case (lookupFM env pmod) of
110 Nothing -> --trace ("Adding "++mod++" -> "++e) $
111 hPutStr stderr "!" >>
112 return (addToFM env pmod (dir ++ '/':e))
113 -- ToDo: use DIR_SEP, not /
115 Just xx -> ( if de_dot xx /= e then trace ("Already mapped!! "++mod++" -> "++xx++"; ignoring:"++e) else id) $
116 hPutStr stderr "." >>
119 acceptable_hi rev_e -- looking at pathname *backwards*
120 = case (startsWith (reverse opt_HiSuffix) rev_e) of
122 Just xs -> plausible_modname xs{-reversed-}
125 de_dot ('.' : '/' : xs) = xs
129 plausible_modname rev_e
131 cand = reverse (takeWhile is_modname_char rev_e)
133 if null cand || not (isUpper (head cand))
137 is_modname_char c = isAlphanum c || c == '_'
140 *********************************************************
142 \subsection{Reading interface files}
144 *********************************************************
146 Return cached info about a Module's interface; otherwise,
147 read the interface (using our @ModuleToIfaceFilePath@ map
148 to decide where to look).
150 Note: we have two notions of interface
151 * the interface for a particular file name
152 * the (combined) interface for a particular module name
154 The idea is that two source files may declare a module
155 with the same name with the declarations being merged.
157 This allows us to have file PreludeList.hs producing
158 PreludeList.hi but defining part of module Prelude.
159 When PreludeList is imported its contents will be
160 added to Prelude. In this way all the original names
161 for a particular module will be available the imported
164 ToDo: Check duplicate definitons are the same.
165 ToDo: Check/Merge duplicate pragmas.
169 cachedIface :: Bool -- True => want merged interface for original name
170 -> IfaceCache -- False => want file interface only
172 -> IO (MaybeErr ParsedIface Error)
174 cachedIface want_orig_iface iface_cache mod
175 = readVar iface_cache `thenPrimIO` \ (iface_fm, orig_fm, file_fm) ->
177 case (lookupFM iface_fm mod) of
178 Just iface -> return (want_iface iface orig_fm)
180 case (lookupFM file_fm mod) of
181 Nothing -> return (Failed (noIfaceErr mod))
183 readIface file mod >>= \ read_iface ->
185 Failed err -> -- pprTrace "module-file map:\n" (ppAboves [ppCat [ppPStr m, ppStr f] | (m,f) <- fmToList file_fm]) $
189 iface_fm' = addToFM iface_fm mod iface
190 orig_fm' = addToFM_C mergeIfaces orig_fm (iface_mod iface) iface
192 writeVar iface_cache (iface_fm', orig_fm', file_fm) `seqPrimIO`
193 return (want_iface iface orig_fm')
195 want_iface iface orig_fm
197 = case lookupFM orig_fm of
198 Nothing -> Failed (noOrigIfaceErr mod)
199 Just orig_iface -> Succeeded orig_iface
203 iface_mod (ParsedIface mod _ _ _ _ _ _ _ _ _ _ _ _) = mod
206 mergeIfaces (ParsedIface mod1 (_, files1) _ _ _ _ _ _ fixes1 tdefs1 vdefs1 idefs1 prags1)
207 (ParsedIface mod2 (_, files2) _ _ _ _ _ _ fixes2 tdefs2 vdefs2 idefs2 prags2)
208 = pprTrace "mergeIfaces:" (ppCat [ppStr "import", ppCat (map ppPStr (bagToList files2)),
209 ppStr "merged with", ppPStr mod1]) $
212 (True, unionBags files1 files2)
213 (panic "mergeIface: module version numbers")
214 (panic "mergeIface: source version numbers") -- Version numbers etc must be extracted from
215 (panic "mergeIface: usage version numbers") -- the merged file interfaces named above
216 (panic "mergeIface: decl version numbers")
217 (panic "mergeIface: exports")
218 (panic "mergeIface: instance modules")
219 (plusFM_C (dup_merge "fixity" (ppr PprDebug . fixDeclName)) fixes1 fixes2)
220 (plusFM_C (dup_merge "tycon/class" (ppr PprDebug . idecl_nm)) tdefs1 tdefs2)
221 (plusFM_C (dup_merge "value" (ppr PprDebug . idecl_nm)) vdefs1 vdefs2)
222 (unionBags idefs1 idefs2)
223 (plusFM_C (dup_merge "pragma" ppStr) prags1 prags2)
225 dup_merge str ppr_dup dup1 dup2
226 = pprTrace "mergeIfaces:"
227 (ppCat [ppPStr mod, ppPStr mod1, ppStr ": dup", ppStr str, ppStr "decl",
228 ppr_dup dup1, ppr_dup dup2]) $
231 idecl_nm (TypeSig n _ _) = n
232 idecl_nm (NewTypeSig n _ _ _) = n
233 idecl_nm (DataSig n _ _ _ _) = n
234 idecl_nm (ClassSig n _ _ _) = n
235 idecl_nm (ValSig n _ _) = n
238 cachedDecl :: IfaceCache
239 -> Bool -- True <=> tycon or class name
241 -> IO (MaybeErr RdrIfaceDecl Error)
243 cachedDecl iface_cache class_or_tycon orig
244 = cachedIface True iface_cache mod >>= \ maybe_iface ->
246 Failed err -> return (Failed err)
247 Succeeded (ParsedIface _ _ _ _ _ _ exps _ _ tdefs vdefs _ _) ->
248 case (lookupFM (if class_or_tycon then tdefs else vdefs) str) of
249 Just decl -> return (Succeeded decl)
250 Nothing -> return (Failed (noDeclInIfaceErr mod str))
252 (mod, str) = moduleNamePair orig
255 cachedDeclByType :: IfaceCache
256 -> RnName{-NB: diff type than cachedDecl -}
257 -> IO (MaybeErr RdrIfaceDecl Error)
259 cachedDeclByType iface_cache rn
260 -- the idea is: check that, e.g., if we're given an
261 -- RnClass, then we really get back a ClassDecl from
262 -- the cache (not an RnData, or something silly)
263 = cachedDecl iface_cache (isRnTyConOrClass rn) (origName rn) >>= \ maybe_decl ->
265 return_maybe_decl = return maybe_decl
266 return_failed msg = return (Failed msg)
269 Failed _ -> return_maybe_decl
272 WiredInId _ -> return_failed (ifaceLookupWiredErr "value" rn)
273 WiredInTyCon _ -> return_failed (ifaceLookupWiredErr "type constructor" rn)
274 RnUnbound _ -> pprPanic "cachedDeclByType:" (ppr PprDebug rn)
276 RnSyn _ -> return_maybe_decl
277 RnData _ _ _ -> return_maybe_decl
278 RnImplicitTyCon _ -> if is_tycon_decl if_decl
279 then return_maybe_decl
280 else return_failed (badIfaceLookupErr "type constructor" rn if_decl)
282 RnClass _ _ -> return_maybe_decl
283 RnImplicitClass _ -> if is_class_decl if_decl
284 then return_maybe_decl
285 else return_failed (badIfaceLookupErr "class" rn if_decl)
287 RnName _ -> return_maybe_decl
288 RnConstr _ _ -> return_maybe_decl
289 RnField _ _ -> return_maybe_decl
290 RnClassOp _ _ -> return_maybe_decl
291 RnImplicit _ -> if is_val_decl if_decl
292 then return_maybe_decl
293 else return_failed (badIfaceLookupErr "value" rn if_decl)
295 is_tycon_decl (TypeSig _ _ _) = True
296 is_tycon_decl (NewTypeSig _ _ _ _) = True
297 is_tycon_decl (DataSig _ _ _ _ _) = True
298 is_tycon_decl _ = False
300 is_class_decl (ClassSig _ _ _ _) = True
301 is_class_decl _ = False
303 is_val_decl (ValSig _ _ _) = True
304 is_val_decl (DataSig _ _ _ _ _) = True -- may be a constr or field
305 is_val_decl (NewTypeSig _ _ _ _) = True -- may be a constr
306 is_val_decl (ClassSig _ _ _ _) = True -- may be a method
307 is_val_decl _ = False
311 readIface :: FilePath -> Module
312 -> IO (MaybeErr ParsedIface Error)
315 = hPutStr stderr (" reading "++file) >>
316 readFile file `thenPrimIO` \ read_result ->
318 Left err -> return (Failed (cannaeReadErr file err))
319 Right contents -> hPutStr stderr " parsing" >>
320 let parsed = parseIface contents in
321 hPutStr stderr " done\n" >>
322 return (Succeeded (init_merge mod parsed))
324 init_merge this (ParsedIface mod _ v sv us vs exps insts fixes tdefs vdefs idefs prags)
325 = ParsedIface mod (False, unitBag this) v sv us vs exps insts fixes tdefs vdefs idefs prags
330 rnIfaces :: IfaceCache -- iface cache (mutvar)
331 -> [Module] -- directly imported modules
333 -> RnEnv -- defined (in the source) name env
334 -> RnEnv -- mentioned (in the source) name env
335 -> RenamedHsModule -- module to extend with iface decls
336 -> [RnName] -- imported names required (really the
337 -- same info as in mentioned name env)
338 -- Also, all the things we may look up
339 -- later by key (Unique).
340 -> IO (RenamedHsModule, -- extended module
341 RnEnv, -- final env (for renaming derivings)
342 ImplicitEnv, -- implicit names used (for usage info)
343 (UsagesMap,VersionsMap,[Module]), -- usage info
344 (Bag Error, Bag Warning))
346 rnIfaces iface_cache imp_mods us
347 def_env@((dqual, dunqual, dtc_qual, dtc_unqual), dstack)
348 occ_env@((qual, unqual, tc_qual, tc_unqual), stack)
349 rn_module@(HsModule modname iface_version exports imports fixities
350 typedecls typesigs classdecls instdecls instsigs
351 defdecls binds sigs src_loc)
354 pprTrace "rnIfaces:going after:" (ppCat (map (ppr PprDebug) todo)) $
356 pprTrace "rnIfaces:qual:" (ppCat [ppBesides[ppPStr m,ppChar '.',ppPStr n] | (n,m) <- keysFM qual]) $
357 pprTrace "rnIfaces:unqual:" (ppCat (map ppPStr (keysFM unqual))) $
358 pprTrace "rnIfaces:tc_qual:" (ppCat [ppBesides[ppPStr m,ppChar '.',ppPStr n] | (n,m) <- keysFM tc_qual]) $
359 pprTrace "rnIfaces:tc_unqual:" (ppCat (map ppPStr (keysFM tc_unqual))) $
361 pprTrace "rnIfaces:dqual:" (ppCat [ppBesides[ppPStr m,ppChar '.',ppPStr n] | (n,m) <- keysFM dqual]) $
362 pprTrace "rnIfaces:dunqual:" (ppCat (map ppPStr (keysFM dunqual))) $
363 pprTrace "rnIfaces:dtc_qual:" (ppCat [ppBesides[ppPStr m,ppChar '.',ppPStr n] | (n,m) <- keysFM dtc_qual]) $
364 pprTrace "rnIfaces:dtc_unqual:"(ppCat (map ppPStr (keysFM dtc_unqual))) $
367 -- do transitive closure to bring in all needed names/defns and insts:
369 decls_and_insts todo def_env occ_env empty_return us
370 >>= \ (((if_typedecls, if_classdecls, if_instdecls, if_sigs),
375 -- finalize what we want to say we learned about the
377 finalIfaceInfo iface_cache if_final_env if_instdecls {-all_imports_used imp_mods-} >>=
378 \ usage_stuff@(usage_info, version_info, instance_mods) ->
380 return (HsModule modname iface_version exports imports fixities
381 (typedecls ++ if_typedecls)
383 (classdecls ++ if_classdecls)
384 (instdecls ++ if_instdecls)
385 instsigs defdecls binds
393 decls_and_insts todo def_env occ_env to_return us
394 = do_decls todo -- initial batch of names to process
395 (def_env, occ_env, us1) -- init stuff down
396 to_return -- acc results
401 cacheInstModules iface_cache imp_mods >>= \ errs ->
403 do_insts decls_def_env decls_occ_env emptyRnEnv emptyFM
404 (add_errs errs decls_return) us2
406 (us1,us2) = splitUniqSupply us
408 do_insts def_env occ_env prev_env done_insts to_return us
409 | size_tc_env occ_env == size_tc_env prev_env
410 = return (to_return, occ_env)
413 = rnIfaceInstStuff iface_cache modname us1 occ_env done_insts to_return
419 do_decls new_unknowns -- new batch of names to process
420 (def_env, insts_occ_env, us2) -- init stuff down
421 insts_return -- acc results
426 do_insts decls_def_env decls_occ_env occ_env new_insts decls_return us3
428 (us1,us') = splitUniqSupply us
429 (us2,us3) = splitUniqSupply us'
431 size_tc_env ((_, _, qual, unqual), _)
432 = sizeFM qual + sizeFM unqual
435 do_decls :: [RnName] -- Names we're looking for; we keep adding/deleting
436 -- from this list; we're done when empty (nothing
437 -- more needs to be looked for)
438 -> Go_Down -- see defn below
439 -> To_Return -- accumulated result
441 RnEnv, -- extended decl env
442 RnEnv) -- extended occ env
444 do_decls to_find@[] down to_return
445 = return (to_return, defenv down, occenv down)
447 do_decls to_find@(n:ns) down to_return
448 = case (lookup_defd down n) of
449 Just _ -> -- previous processing must've found the stuff for this name;
450 -- continue with the rest:
451 -- pprTrace "do_decls:done:" (ppr PprDebug n) $
452 do_decls ns down to_return
455 | fst (moduleNamePair n) == modname ->
456 -- avoid looking in interface for the module being compiled
457 -- pprTrace "do_decls:this module error:" (ppr PprDebug n) $
458 do_decls ns down (add_err (thisModImplicitErr modname n) to_return)
461 -- OK, see what the cache has for us...
463 cachedDeclByType iface_cache n >>= \ maybe_ans ->
465 Failed err -> -- add the error, but keep going:
466 -- pprTrace "do_decls:cache error:" (ppr PprDebug n) $
467 do_decls ns down (add_err err to_return)
469 Succeeded iface_decl -> -- something needing renaming!
471 (us1, us2) = splitUniqSupply (uniqsupply down)
473 case (initRn False{-iface-} modname (occenv down) us1 (
474 setExtraRn emptyUFM{-no fixities-} $
475 rnIfaceDecl iface_decl)) of {
476 ((if_decl, if_defd, if_implicits), if_errs, if_warns) ->
478 new_unknowns = eltsFM (fst if_implicits) ++ eltsFM (snd if_implicits)
481 pprTrace "do_decls:renamed:" (ppAboves [ppr PprDebug n
482 , ppCat [ppStr "new unknowns:", interpp'SP PprDebug new_unknowns]
483 , ppCat [ppStr "defd vals:", interpp'SP PprDebug [n | (_,n) <- fst if_defd] ]
484 , ppCat [ppStr "defd tcs:", interpp'SP PprDebug [n | (_,n) <- snd if_defd] ]
487 do_decls (new_unknowns ++ ns)
488 (add_occs if_defd if_implicits $
489 new_uniqsupply us2 down)
491 add_implicits if_implicits $
493 add_warns if_warns to_return)
497 type Go_Down = (RnEnv, -- stuff we already have defns for;
498 -- to check quickly if we've already
499 -- found something for the name under consideration,
500 -- due to previous processing.
501 -- It starts off just w/ the defns for
502 -- the things in this module.
503 RnEnv, -- occurrence env; this gets added to as
504 -- we process new iface decls. It includes
505 -- entries for *all* occurrences, including those
506 -- for which we have definitions.
507 UniqSupply -- the obvious
510 lookup_defd (def_env, _, _) n
512 = lookupTcRnEnv def_env (origName n)
514 = lookupRnEnv def_env (origName n)
516 defenv (def_env, _, _) = def_env
517 occenv (_, occ_env, _) = occ_env
518 uniqsupply (_, _, us) = us
520 new_uniqsupply us (def_env, occ_env, _) = (def_env, occ_env, us)
522 add_occs (val_defds, tc_defds) (val_imps, tc_imps) (def_env, occ_env, us)
523 = case (extendGlobalRnEnv def_env val_defds tc_defds) of { (new_def_env, def_dups) ->
524 ASSERT(isEmptyBag def_dups)
526 val_occs = val_defds ++ fmToList val_imps
527 tc_occs = tc_defds ++ fmToList tc_imps
529 case (extendGlobalRnEnv occ_env val_occs tc_occs) of { (new_occ_env, occ_dups) ->
531 -- ASSERT(isEmptyBag occ_dups)
532 -- False because we may get a dup on the name we just shoved in
534 (new_def_env, new_occ_env, us) }}
537 type To_Return = (([RenamedTyDecl], [RenamedClassDecl], [RenamedInstDecl], [RenamedSig]),
538 ImplicitEnv, -- new names used implicitly
539 (Bag Error, Bag Warning)
542 empty_return :: To_Return
543 empty_return = (([],[],[],[]), emptyImplicitEnv, (emptyBag,emptyBag))
545 add_decl decl ((tydecls, classdecls, instdecls, sigs), implicit, msgs)
547 AddedTy t -> ((t:tydecls, classdecls, instdecls, sigs), implicit, msgs)
548 AddedClass c -> ((tydecls, c:classdecls, instdecls, sigs), implicit, msgs)
549 AddedSig s -> ((tydecls, classdecls, instdecls, s:sigs), implicit, msgs)
551 add_insts is ((tydecls, classdecls, instdecls, sigs), implicit, msgs)
552 = ((tydecls, classdecls, is ++ instdecls, sigs), implicit, msgs)
554 add_implicits (val_imps, tc_imps) (decls, (val_fm, tc_fm), msgs)
555 = (decls, (val_fm `plusFM` val_imps, tc_fm `plusFM` tc_imps), msgs)
557 add_err err (decls,implicit,(errs,warns)) = (decls,implicit,(errs `snocBag` err,warns))
558 add_errs ers (decls,implicit,(errs,warns)) = (decls,implicit,(errs `unionBags` ers,warns))
559 add_warns ws (decls,implicit,(errs,warns)) = (decls,implicit,(errs, warns `unionBags` ws))
563 data AddedDecl -- purely local
564 = AddedTy RenamedTyDecl
565 | AddedClass RenamedClassDecl
566 | AddedSig RenamedSig
568 rnIfaceDecl :: RdrIfaceDecl
569 -> RnM_Fixes _RealWorld
570 (AddedDecl, -- the resulting decl to add to the pot
571 ([(RdrName,RnName)], [(RdrName,RnName)]),
572 -- new val/tycon-class names that have
573 -- *been defined* while processing this decl
574 ImplicitEnv -- new implicit val/tycon-class names that we
578 rnIfaceDecl (TypeSig tc _ decl)
579 = rnTyDecl decl `thenRn` \ rn_decl ->
580 lookupTyCon tc `thenRn` \ rn_tc ->
581 getImplicitUpRn `thenRn` \ mentioned ->
583 defds = ([], [(tc, rn_tc)])
584 implicits = mentioned `sub` defds
586 returnRn (AddedTy rn_decl, defds, implicits)
588 rnIfaceDecl (NewTypeSig tc dc _ decl)
589 = rnTyDecl decl `thenRn` \ rn_decl ->
590 lookupTyCon tc `thenRn` \ rn_tc ->
591 lookupValue dc `thenRn` \ rn_dc ->
592 getImplicitUpRn `thenRn` \ mentioned ->
594 defds = ([(dc, rn_dc)], [(tc, rn_tc)])
595 implicits = mentioned `sub` defds
597 returnRn (AddedTy rn_decl, defds, implicits)
599 rnIfaceDecl (DataSig tc dcs fcs _ decl)
600 = rnTyDecl decl `thenRn` \ rn_decl ->
601 lookupTyCon tc `thenRn` \ rn_tc ->
602 mapRn lookupValue dcs `thenRn` \ rn_dcs ->
603 mapRn lookupValue fcs `thenRn` \ rn_fcs ->
604 getImplicitUpRn `thenRn` \ mentioned ->
606 defds = (zip dcs rn_dcs ++ zip fcs rn_fcs , [(tc, rn_tc)])
607 implicits = mentioned `sub` defds
609 returnRn (AddedTy rn_decl, defds, implicits)
611 rnIfaceDecl (ClassSig clas ops _ decl)
612 = rnClassDecl decl `thenRn` \ rn_decl ->
613 lookupClass clas `thenRn` \ rn_clas ->
614 mapRn (lookupClassOp rn_clas) ops `thenRn` \ rn_ops ->
615 getImplicitUpRn `thenRn` \ mentioned ->
617 defds = (ops `zip` rn_ops, [(clas, rn_clas)])
618 implicits = mentioned `sub` defds
620 returnRn (AddedClass rn_decl, defds, implicits)
622 rnIfaceDecl (ValSig f src_loc ty)
623 -- should rename_sig in RnBinds be used here? ToDo
624 = lookupValue f `thenRn` \ rn_f ->
625 -- pprTrace "rnIfaceDecl:ValSig:" (ppr PprDebug ty) $
626 rnPolyType nullTyVarNamesEnv ty `thenRn` \ rn_ty ->
627 getImplicitUpRn `thenRn` \ mentioned ->
629 defds = ([(f, rn_f)], [])
630 implicits = mentioned `sub` defds
632 returnRn (AddedSig (Sig rn_f rn_ty noGenPragmas src_loc), defds, implicits)
635 sub :: ImplicitEnv -> ([(RdrName,RnName)], [(RdrName,RnName)]) -> ImplicitEnv
637 sub (val_ment, tc_ment) (val_defds, tc_defds)
638 = (delListFromFM val_ment (map fst val_defds),
639 delListFromFM tc_ment (map fst tc_defds))
642 % ------------------------------
644 @cacheInstModules@: cache instance modules specified in imports
647 cacheInstModules :: IfaceCache -> [Module] -> IO (Bag Error)
648 cacheInstModules iface_cache imp_mods
649 = readVar iface_cache `thenPrimIO` \ (iface_fm, _, _) ->
651 imp_ifaces = [ iface | Just iface <- map (lookupFM iface_fm) imp_mods ]
652 (imp_imods, _) = removeDups cmpPString (bagToList (unionManyBags (map get_ims imp_ifaces)))
653 get_ims (ParsedIface _ _ _ _ _ _ _ ims _ _ _ _ _) = ims
655 accumulate (map (cachedIface False iface_cache) imp_imods) >>= \ err_or_ifaces ->
658 -- Assert that instance modules given by direct imports contains
659 -- instance modules extracted from all visited modules
661 readVar iface_cache `thenPrimIO` \ (all_iface_fm, _, _) ->
663 all_ifaces = eltsFM all_iface_fm
664 (all_imods, _) = removeDups cmpPString (bagToList (unionManyBags (map get_ims (all_ifaces))))
666 ASSERT(sortLt (<) imp_imods == sortLt (<) all_imods)
668 return (bag_errs err_or_ifaces)
670 bag_errs [] = emptyBag
671 bag_errs (Failed err :rest) = err `consBag` bag_errs rest
672 bag_errs (Succeeded _:rest) = bag_errs rest
676 @rnIfaceInstStuff@: Deal with instance declarations from interface files.
679 type InstanceEnv = FiniteMap (RdrName, RdrName) Int
682 :: IfaceCache -- all about ifaces we've read
685 -> RnEnv -- current occ env
686 -> InstanceEnv -- instances for these tycon/class pairs done
689 InstanceEnv, -- extended instance env
690 RnEnv, -- final occ env
691 [RnName]) -- new unknown names
693 rnIfaceInstStuff iface_cache modname us occ_env done_inst_env to_return
694 = -- all the instance decls we might even want to consider
695 -- are in the ParsedIfaces that are in our cache
697 readVar iface_cache `thenPrimIO` \ (_, orig_iface_fm, _) ->
699 all_ifaces = eltsFM orig_iface_fm
700 all_insts = unionManyBags (map get_insts all_ifaces)
701 interesting_insts = filter want_inst (bagToList all_insts)
704 -- Assert that there are no more instances for the done instances
706 claim_done = filter is_done_inst (bagToList all_insts)
707 claim_done_env = foldr add_done_inst emptyFM claim_done
708 has_val fm (k,i) = case lookupFM fm k of { Nothing -> False; Just v -> i == v }
711 pprTrace "all_insts:\n" (ppr_insts (bagToList all_insts)) $
712 pprTrace "interesting_insts:\n" (ppr_insts interesting_insts) $
714 ASSERT(sizeFM done_inst_env == sizeFM claim_done_env)
715 ASSERT(all (has_val claim_done_env) (fmToList done_inst_env))
717 case (initRn False{-iface-} modname occ_env us (
718 setExtraRn emptyUFM{-no fixities-} $
719 mapRn rnIfaceInst interesting_insts `thenRn` \ insts ->
720 getImplicitUpRn `thenRn` \ implicits ->
721 returnRn (insts, implicits))) of {
722 ((if_insts, if_implicits), if_errs, if_warns) ->
724 return (add_insts if_insts $
725 add_implicits if_implicits $
727 add_warns if_warns to_return,
728 foldr add_done_inst done_inst_env interesting_insts,
729 add_imp_occs if_implicits occ_env,
730 eltsFM (fst if_implicits) ++ eltsFM (snd if_implicits))
733 get_insts (ParsedIface _ _ _ _ _ _ _ _ _ _ _ insts _) = insts
735 add_done_inst (InstSig clas tycon _ _) inst_env
736 = addToFM_C (+) inst_env (tycon,clas) 1
738 is_done_inst (InstSig clas tycon _ _)
739 = maybeToBool (lookupFM done_inst_env (tycon,clas))
741 add_imp_occs (val_imps, tc_imps) occ_env
742 = case extendGlobalRnEnv occ_env (fmToList val_imps) (fmToList tc_imps) of
743 (ext_occ_env, occ_dups) -> ASSERT(isEmptyBag occ_dups)
746 want_inst i@(InstSig clas tycon _ _)
747 = -- it's a "good instance" (one to hang onto) if we have a
748 -- chance of referring to *both* the class and tycon later on ...
750 mentionable tycon && mentionable clas && not (is_done_inst i)
753 = case lookupTcRnEnv occ_env nm of
755 Nothing -> -- maybe it's builtin
759 case (lookupFM b_tc_names n) of
761 Nothing -> maybeToBool (lookupFM b_keys n)
763 (b_tc_names, b_keys) -- pretty UGLY ...
764 = case builtinNameInfo of ((_,builtin_tcs),b_keys,_) -> (builtin_tcs,b_keys)
767 = ppAboves (map ppr_inst insts)
769 ppr_inst (InstSig c t _ inst_decl)
770 = ppCat [ppr PprDebug c, ppr PprDebug t, ppr PprDebug inst_decl]
774 rnIfaceInst :: RdrIfaceInst -> RnM_Fixes _RealWorld RenamedInstDecl
776 rnIfaceInst (InstSig _ _ _ inst_decl) = rnInstDecl inst_decl
781 IfaceCache -- iface cache
784 -- -> [RnName] -- all imported names required
785 -- -> [Module] -- directly imported modules
787 VersionsMap, -- info about version numbers
788 [Module]) -- special instance modules
790 finalIfaceInfo iface_cache if_final_env@((qual, unqual, tc_qual, tc_unqual), stack) if_instdecls
792 pprTrace "usageIf:qual:" (ppCat [ppBesides[ppPStr m,ppChar '.',ppPStr n] | (n,m) <- keysFM qual]) $
793 -- pprTrace "usageIf:unqual:" (ppCat (map ppPStr (keysFM unqual))) $
794 pprTrace "usageIf:tc_qual:" (ppCat [ppBesides[ppPStr m,ppChar '.',ppPStr n] | (n,m) <- keysFM tc_qual]) $
795 -- pprTrace "usageIf:tc_unqual:" (ppCat (map ppPStr (keysFM tc_unqual))) $
797 return (emptyFM, emptyFM, [])
802 thisModImplicitErr mod n sty
803 = ppCat [ppPStr SLIT("Implicit import of"), ppr sty n, ppPStr SLIT("when compiling"), ppPStr mod]
806 = ppCat [ppPStr SLIT("Could not find interface for:"), ppPStr mod]
808 noOrigIfaceErr mod sty
809 = ppCat [ppPStr SLIT("Could not find original interface for:"), ppPStr mod]
811 noDeclInIfaceErr mod str sty
812 = ppBesides [ppPStr SLIT("Could not find interface declaration of: "),
813 ppPStr mod, ppStr ".", ppPStr str]
815 cannaeReadErr file err sty
816 = ppBesides [ppPStr SLIT("Failed in reading file: "), ppStr file, ppStr "; error=", ppStr (show err)]
818 ifaceLookupWiredErr msg n sty
819 = ppBesides [ppPStr SLIT("Why am I looking up a wired-in "), ppStr msg, ppChar ':', ppr sty n]
821 badIfaceLookupErr msg name decl sty
822 = ppBesides [ppPStr SLIT("Expected a "), ppStr msg, ppPStr SLIT(" declaration, but got this: ???")]