2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
4 \section[RnIfaces]{Cacheing and Renaming of Interfaces}
7 #include "HsVersions.h"
12 getSpecialInstModules,
13 getDecl, getWiredInDecl,
25 import HsSyn ( HsDecl(..), TyDecl(..), ClassDecl(..), HsTyVar, Bind, HsExpr, Sig(..),
26 HsBinds(..), MonoBinds, DefaultDecl, ConDecl(..), HsType, BangType, IfaceSig(..),
27 FixityDecl(..), Fixity, Fake, InPat, InstDecl(..), SYN_IE(Version), HsIdInfo
29 import HsPragmas ( noGenPragmas )
30 import RdrHsSyn ( SYN_IE(RdrNameHsDecl), SYN_IE(RdrNameInstDecl),
33 import RnEnv ( newGlobalName, lookupRn, addImplicitOccsRn, availNames )
34 import RnSource ( rnHsType )
36 import ParseIface ( parseIface )
38 import ErrUtils ( SYN_IE(Error), SYN_IE(Warning) )
39 import FiniteMap ( FiniteMap, emptyFM, unitFM, lookupFM, addToFM, addListToFM, fmToList )
40 import Name ( Name {-instance NamedThing-}, Provenance, OccName(..),
41 modAndOcc, occNameString, moduleString, pprModule,
42 NameSet(..), emptyNameSet, unionNameSets, nameSetToList,
43 minusNameSet, mkNameSet,
44 isWiredInName, maybeWiredInTyConName, maybeWiredInIdName
46 import Id ( GenId, Id(..), idType, dataConTyCon, isDataCon )
47 import TyCon ( TyCon, tyConDataCons, isSynTyCon, getSynTyConDefn )
48 import Type ( namesOfType )
49 import TyVar ( GenTyVar )
50 import SrcLoc ( mkIfaceSrcLoc )
51 import PrelMods ( gHC__ )
53 import Maybes ( MaybeErr(..), expectJust, maybeToBool )
54 import ListSetOps ( unionLists )
56 import PprStyle ( PprStyle(..) )
57 import Util ( pprPanic )
62 %*********************************************************
64 \subsection{Loading a new interface file}
66 %*********************************************************
69 loadInterface :: Pretty -> Module -> RnMG Ifaces
70 loadInterface doc_str load_mod
71 = getIfacesRn `thenRn` \ ifaces ->
73 Ifaces this_mod mod_vers_map export_env_map vers_map decls_map inst_map inst_mods = ifaces
75 -- CHECK WHETHER WE HAVE IT ALREADY
76 if maybeToBool (lookupFM export_env_map load_mod)
78 returnRn ifaces -- Already in the cache; don't re-read it
82 findAndReadIface doc_str load_mod `thenRn` \ read_result ->
84 -- Check for not found
85 Nothing -> -- Not found, so add an empty export env to the Ifaces map
86 -- so that we don't look again
88 new_export_env_map = addToFM export_env_map load_mod ([],[])
89 new_ifaces = Ifaces this_mod mod_vers_map
91 vers_map decls_map inst_map inst_mods
93 setIfacesRn new_ifaces `thenRn_`
94 failWithRn new_ifaces (noIfaceErr load_mod) ;
97 Just (ParsedIface _ mod_vers usages exports rd_inst_mods fixs decls insts) ->
99 -- LOAD IT INTO Ifaces
100 mapRn loadExport exports `thenRn` \ avails_s ->
101 foldlRn (loadDecl load_mod) (decls_map,vers_map) decls `thenRn` \ (new_decls_map, new_vers_map) ->
102 foldlRn (loadInstDecl load_mod) inst_map insts `thenRn` \ new_insts_map ->
104 export_env = (concat avails_s, fixs)
106 -- Exclude this module from the "special-inst" modules
107 new_inst_mods = inst_mods `unionLists` (filter (/= this_mod) rd_inst_mods)
109 new_ifaces = Ifaces this_mod
110 (addToFM mod_vers_map load_mod mod_vers)
111 (addToFM export_env_map load_mod export_env)
117 setIfacesRn new_ifaces `thenRn_`
121 loadExport :: ExportItem -> RnMG [AvailInfo]
122 loadExport (mod, entities)
123 = mapRn load_entity entities
125 new_name occ = newGlobalName mod occ
127 load_entity (occ, occs)
128 = new_name occ `thenRn` \ name ->
129 mapRn new_name occs `thenRn` \ names ->
130 returnRn (Avail name names)
132 loadVersion :: Module -> VersionMap -> (OccName,Version) -> RnMG VersionMap
133 loadVersion mod vers_map (occ, version)
134 = newGlobalName mod occ `thenRn` \ name ->
135 returnRn (addToFM vers_map name version)
138 loadDecl :: Module -> (DeclsMap, VersionMap)
139 -> (Version, RdrNameHsDecl)
140 -> RnMG (DeclsMap, VersionMap)
141 loadDecl mod (decls_map, vers_map) (version, decl)
142 = getDeclBinders new_implicit_name decl `thenRn` \ avail@(Avail name _) ->
143 returnRn (addListToFM decls_map
144 [(name,(avail,decl)) | name <- availNames avail],
145 addToFM vers_map name version
148 new_implicit_name rdr_name loc = newGlobalName mod (rdrNameOcc rdr_name)
150 loadInstDecl :: Module -> Bag IfaceInst -> RdrNameInstDecl -> RnMG (Bag IfaceInst)
151 loadInstDecl mod_name insts decl@(InstDecl inst_ty binds uprags dfun_name src_loc)
152 = initRnMS emptyRnEnv mod_name InterfaceMode $
154 -- Find out what type constructors and classes are mentioned in the
155 -- instance declaration. We have to be a bit clever.
157 -- We want to rename the type so that we can find what
158 -- (free) type constructors are inside it. But we must *not* thereby
159 -- put new occurrences into the global pool because otherwise we'll force
160 -- them all to be loaded. We kill two birds with ones stone by renaming
161 -- with a fresh occurrence pool.
162 findOccurrencesRn (rnHsType inst_ty) `thenRn` \ ty_names ->
164 returnRn ((ty_names, mod_name, decl) `consBag` insts)
168 %********************************************************
170 \subsection{Loading usage information}
172 %********************************************************
175 checkUpToDate :: Module -> RnMG Bool -- True <=> no need to recompile
176 checkUpToDate mod_name
177 = findAndReadIface doc_str mod_name `thenRn` \ read_result ->
179 Nothing -> -- Old interface file not found, so we'd better bale out
180 traceRn (ppSep [ppStr "Didnt find old iface", pprModule PprDebug mod_name]) `thenRn_`
183 Just (ParsedIface _ _ usages _ _ _ _ _)
184 -> -- Found it, so now check it
187 -- Only look in current directory, with suffix .hi
188 doc_str = ppSep [ppStr "Need usage info from", pprModule PprDebug mod_name]
191 checkModUsage [] = returnRn True -- Yes! Everything is up to date!
193 checkModUsage ((mod, old_mod_vers, old_local_vers) : rest)
194 = loadInterface doc_str mod `thenRn` \ ifaces ->
196 Ifaces _ mod_vers_map _ new_vers_map _ _ _ = ifaces
197 maybe_new_mod_vers = lookupFM mod_vers_map mod
198 Just new_mod_vers = maybe_new_mod_vers
200 -- If we can't find a version number for the old module then
201 -- bale out saying things aren't up to date
202 if not (maybeToBool maybe_new_mod_vers) then
206 -- If the module version hasn't changed, just move on
207 if new_mod_vers == old_mod_vers then
208 traceRn (ppSep [ppStr "Module version unchanged:", pprModule PprDebug mod]) `thenRn_`
211 traceRn (ppSep [ppStr "Module version has changed:", pprModule PprDebug mod]) `thenRn_`
213 -- New module version, so check entities inside
214 checkEntityUsage mod new_vers_map old_local_vers `thenRn` \ up_to_date ->
216 traceRn (ppStr "...but the bits I use havn't.") `thenRn_`
217 checkModUsage rest -- This one's ok, so check the rest
219 returnRn False -- This one failed, so just bail out now
221 doc_str = ppSep [ppStr "need version info for", pprModule PprDebug mod]
224 checkEntityUsage mod new_vers_map []
225 = returnRn True -- Yes! All up to date!
227 checkEntityUsage mod new_vers_map ((occ_name,old_vers) : rest)
228 = newGlobalName mod occ_name `thenRn` \ name ->
229 case lookupFM new_vers_map name of
231 Nothing -> -- We used it before, but it ain't there now
232 traceRn (ppSep [ppStr "...and this no longer exported:", ppr PprDebug name]) `thenRn_`
235 Just new_vers -> -- It's there, but is it up to date?
236 if new_vers == old_vers then
237 -- Up to date, so check the rest
238 checkEntityUsage mod new_vers_map rest
240 traceRn (ppSep [ppStr "...and this is out of date:", ppr PprDebug name]) `thenRn_`
241 returnRn False -- Out of date, so bale out
245 %*********************************************************
247 \subsection{Getting in a declaration}
249 %*********************************************************
252 getDecl :: Name -> RnMG (AvailInfo, RdrNameHsDecl)
254 = traceRn doc_str `thenRn_`
255 loadInterface doc_str mod `thenRn` \ (Ifaces _ _ _ _ decls_map _ _) ->
256 case lookupFM decls_map name of
258 Just avail_w_decl -> returnRn avail_w_decl
260 Nothing -> -- Can happen legitimately for "Optional" occurrences
261 returnRn (NotAvailable, ValD EmptyBinds)
263 (mod,_) = modAndOcc name
264 doc_str = ppSep [ppStr "Need decl for", ppr PprDebug name]
267 @getWiredInDecl@ maps a wired-in @Name@ to what it makes available.
268 It behaves exactly as if the wired in decl were actually in an interface file.
270 * if the wired-in name is a data type constructor or a data constructor,
271 it brings in the type constructor and all the data constructors; and
272 marks as "occurrences" any free vars of the data con.
274 * similarly for synonum type constructor
276 * if the wired-in name is another wired-in Id, it marks as "occurrences"
277 the free vars of the Id's type.
279 * it loads the interface file for the wired-in thing for the
280 sole purpose of making sure that its instance declarations are available
282 All this is necessary so that we know all types that are "in play", so
283 that we know just what instances to bring into scope.
286 getWiredInDecl :: Name -> RnMG AvailInfo
288 = -- Force in the home module in case it has instance decls for
289 -- the thing we are interested in
290 (if not is_tycon || mod == gHC__ then
291 returnRn () -- Mini hack 1: no point for non-tycons; and if we
292 -- do this we find PrelNum trying to import PackedString,
293 -- because PrelBase's .hi file mentions PackedString.unpackString
294 -- But PackedString.hi isn't built by that point!
296 -- Mini hack 2; GHC is guaranteed not to have
297 -- instance decls, so it's a waste of time
300 loadInterface doc_str mod `thenRn_`
305 get_wired_tycon the_tycon
306 else -- Must be a wired-in-Id
307 if (isDataCon the_id) then -- ... a wired-in data constructor
308 get_wired_tycon (dataConTyCon the_id)
309 else -- ... a wired-in non data-constructor
312 doc_str = ppSep [ppStr "Need home module for wired in thing", ppr PprDebug name]
313 (mod,_) = modAndOcc name
314 maybe_wired_in_tycon = maybeWiredInTyConName name
315 is_tycon = maybeToBool maybe_wired_in_tycon
316 maybe_wired_in_id = maybeWiredInIdName name
317 Just the_tycon = maybe_wired_in_tycon
318 Just the_id = maybe_wired_in_id
321 = addImplicitOccsRn (nameSetToList id_mentioned) `thenRn_`
322 returnRn (Avail (getName id) [])
324 id_mentioned = namesOfType (idType id)
326 get_wired_tycon tycon
328 = addImplicitOccsRn (nameSetToList mentioned) `thenRn_`
329 returnRn (Avail (getName tycon) [])
331 (tyvars,ty) = getSynTyConDefn tycon
332 mentioned = namesOfType ty `minusNameSet` mkNameSet (map getName tyvars)
334 get_wired_tycon tycon
335 | otherwise -- data or newtype
336 = addImplicitOccsRn (nameSetToList mentioned) `thenRn_`
337 returnRn (Avail (getName tycon) (map getName data_cons))
339 data_cons = tyConDataCons tycon
340 mentioned = foldr (unionNameSets . namesOfType . idType) emptyNameSet data_cons
344 %*********************************************************
346 \subsection{Getting other stuff}
348 %*********************************************************
351 getInterfaceExports :: Module -> RnMG (Avails, [(OccName,Fixity)])
352 getInterfaceExports mod
353 = loadInterface doc_str mod `thenRn` \ (Ifaces _ _ export_envs _ _ _ _) ->
354 case lookupFM export_envs mod of
355 Nothing -> -- Not there; it must be that the interface file wasn't found;
356 -- the error will have been reported already.
357 -- (Actually loadInterface should put the empty export env in there
358 -- anyway, but this does no harm.)
361 Just stuff -> returnRn stuff
363 doc_str = ppSep [pprModule PprDebug mod, ppStr "is directly imported"]
366 getImportedInstDecls :: RnMG [IfaceInst]
368 = -- First load any special-instance modules that aren't aready loaded
369 getSpecialInstModules `thenRn` \ inst_mods ->
370 mapRn load_it inst_mods `thenRn_`
372 -- Now we're ready to grab the instance declarations
373 getIfacesRn `thenRn` \ ifaces ->
375 Ifaces _ _ _ _ _ insts _ = ifaces
377 returnRn (bagToList insts)
379 load_it mod = loadInterface (doc_str mod) mod
380 doc_str mod = ppSep [pprModule PprDebug mod, ppStr "is a special-instance module"]
382 getSpecialInstModules :: RnMG [Module]
383 getSpecialInstModules
384 = getIfacesRn `thenRn` \ ifaces ->
386 Ifaces _ _ _ _ _ _ inst_mods = ifaces
392 getImportVersions :: [AvailInfo] -- Imported avails
393 -> RnMG (VersionInfo Name) -- Version info for these names
395 getImportVersions imported_avails
396 = getIfacesRn `thenRn` \ ifaces ->
398 Ifaces _ mod_versions_map _ version_map _ _ _ = ifaces
400 -- import_versions is harder: we have to group together all the things imported
401 -- from a particular module. We do this with yet another finite map
403 mv_map :: FiniteMap Module [LocalVersion Name]
404 mv_map = foldl add_mv emptyFM imported_avails
405 add_mv mv_map (Avail name _)
406 | isWiredInName name = mv_map -- Don't record versions for wired-in names
407 | otherwise = case lookupFM mv_map mod of
408 Just versions -> addToFM mv_map mod ((name,version):versions)
409 Nothing -> addToFM mv_map mod [(name,version)]
411 (mod,_) = modAndOcc name
412 version = case lookupFM version_map name of
414 Nothing -> pprPanic "getVersionInfo:" (ppr PprDebug name)
416 import_versions = [ (mod, expectJust "import_versions" (lookupFM mod_versions_map mod), local_versions)
417 | (mod, local_versions) <- fmToList mv_map
420 -- Question: should we filter the builtins out of import_versions?
422 returnRn import_versions
425 %*********************************************************
427 \subsection{Getting binders out of a declaration}
429 %*********************************************************
431 @getDeclBinders@ returns the names for a @RdrNameHsDecl@.
432 It's used for both source code (from @availsFromDecl@) and interface files
435 It doesn't deal with source-code specific things: ValD, DefD. They
436 are handled by the sourc-code specific stuff in RnNames.
439 getDeclBinders :: (RdrName -> SrcLoc -> RnMG Name) -- New-name function
443 getDeclBinders new_name (TyD (TyData _ tycon _ condecls _ _ src_loc))
444 = new_name tycon src_loc `thenRn` \ tycon_name ->
445 getConFieldNames new_name condecls `thenRn` \ sub_names ->
446 returnRn (Avail tycon_name sub_names)
448 getDeclBinders new_name (TyD (TyNew _ tycon _ (NewConDecl con _ con_loc) _ _ src_loc))
449 = new_name tycon src_loc `thenRn` \ tycon_name ->
450 new_name con src_loc `thenRn` \ con_name ->
451 returnRn (Avail tycon_name [con_name])
453 getDeclBinders new_name (TyD (TySynonym tycon _ _ src_loc))
454 = new_name tycon src_loc `thenRn` \ tycon_name ->
455 returnRn (Avail tycon_name [])
457 getDeclBinders new_name (ClD (ClassDecl _ cname _ sigs _ _ src_loc))
458 = new_name cname src_loc `thenRn` \ class_name ->
459 mapRn (getClassOpNames new_name) sigs `thenRn` \ sub_names ->
460 returnRn (Avail class_name sub_names)
462 getDeclBinders new_name (SigD (IfaceSig var ty prags src_loc))
463 = new_name var src_loc `thenRn` \ var_name ->
464 returnRn (Avail var_name [])
466 getDeclBinders new_name (DefD _) = returnRn NotAvailable
467 getDeclBinders new_name (InstD _) = returnRn NotAvailable
470 getConFieldNames new_name (ConDecl con _ src_loc : rest)
471 = new_name con src_loc `thenRn` \ n ->
472 getConFieldNames new_name rest `thenRn` \ ns ->
475 getConFieldNames new_name (NewConDecl con _ src_loc : rest)
476 = new_name con src_loc `thenRn` \ n ->
477 getConFieldNames new_name rest `thenRn` \ ns ->
480 getConFieldNames new_name (ConOpDecl _ con _ src_loc : rest)
481 = new_name con src_loc `thenRn` \ n ->
482 getConFieldNames new_name rest `thenRn` \ ns ->
485 getConFieldNames new_name (RecConDecl con fielddecls src_loc : rest)
486 = mapRn (\n -> new_name n src_loc) (con:fields) `thenRn` \ cfs ->
487 getConFieldNames new_name rest `thenRn` \ ns ->
490 fields = concat (map fst fielddecls)
492 getConFieldNames new_name [] = returnRn []
494 getClassOpNames new_name (ClassOpSig op _ _ src_loc) = new_name op src_loc
498 %*********************************************************
500 \subsection{Reading an interface file}
502 %*********************************************************
505 findAndReadIface :: Pretty -> Module -> RnMG (Maybe ParsedIface)
506 -- Nothing <=> file not found, or unreadable, or illegible
507 -- Just x <=> successfully found and parsed
508 findAndReadIface doc_str mod
509 = traceRn trace_msg `thenRn_`
510 getSearchPathRn `thenRn` \ dirs ->
513 trace_msg = ppHang (ppBesides [ppStr "Reading interface for ",
514 pprModule PprDebug mod, ppSemi])
515 4 (ppBesides [ppStr "reason: ", doc_str])
517 try all_dirs [] = traceRn (ppStr "...failed") `thenRn_`
520 try all_dirs (dir:dirs)
521 = readIface file_path `thenRn` \ read_result ->
523 Nothing -> try all_dirs dirs
524 Just iface -> traceRn (ppStr "...done") `thenRn_`
525 returnRn (Just iface)
527 file_path = dir ++ "/" ++ moduleString mod ++ ".hi"
530 @readIface@ trys just one file.
533 readIface :: String -> RnMG (Maybe ParsedIface)
534 -- Nothing <=> file not found, or unreadable, or illegible
535 -- Just x <=> successfully found and parsed
537 = ioToRnMG (readFile file_path) `thenRn` \ read_result ->
539 Right contents -> case parseIface contents of
540 Failed err -> failWithRn Nothing err
541 Succeeded iface -> returnRn (Just iface)
543 Left (NoSuchThing _) -> returnRn Nothing
545 Left err -> failWithRn Nothing
546 (cannaeReadFile file_path err)
550 mkSearchPath takes a string consisting of a colon-separated list of directories, and turns it into
551 a list of directories. For example:
553 mkSearchPath "foo:.:baz" = ["foo", ".", "baz"]
556 mkSearchPath :: Maybe String -> SearchPath
557 mkSearchPath Nothing = ["."]
558 mkSearchPath (Just s)
562 go s = first : go (drop 1 rest)
564 (first,rest) = span (/= ':') s
567 %*********************************************************
571 %*********************************************************
575 = ppBesides [ppStr "Could not find interface for ", ppQuote (pprModule sty mod)]
576 -- , ppStr " in"]) 4 (ppAboves (map ppStr dirs))
578 cannaeReadFile file err sty
579 = ppBesides [ppPStr SLIT("Failed in reading file: "), ppStr file, ppStr "; error=", ppStr (show err)]