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 ->
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 = (avails, 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, occ, occs)
123 = new_name occ `thenRn` \ name ->
124 mapRn new_name occs `thenRn` \ names ->
125 returnRn (Avail name names)
127 new_name occ = newGlobalName mod occ
129 loadVersion :: Module -> VersionMap -> (OccName,Version) -> RnMG VersionMap
130 loadVersion mod vers_map (occ, version)
131 = newGlobalName mod occ `thenRn` \ name ->
132 returnRn (addToFM vers_map name version)
135 loadDecl :: Module -> (DeclsMap, VersionMap)
136 -> (Version, RdrNameHsDecl)
137 -> RnMG (DeclsMap, VersionMap)
138 loadDecl mod (decls_map, vers_map) (version, decl)
139 = getDeclBinders new_implicit_name decl `thenRn` \ avail@(Avail name _) ->
140 returnRn (addListToFM decls_map
141 [(name,(avail,decl)) | name <- availNames avail],
142 addToFM vers_map name version
145 new_implicit_name rdr_name loc = newGlobalName mod (rdrNameOcc rdr_name)
147 loadInstDecl :: Module -> Bag IfaceInst -> RdrNameInstDecl -> RnMG (Bag IfaceInst)
148 loadInstDecl mod_name insts decl@(InstDecl inst_ty binds uprags dfun_name src_loc)
149 = initRnMS emptyRnEnv mod_name InterfaceMode $
151 -- Find out what type constructors and classes are mentioned in the
152 -- instance declaration. We have to be a bit clever.
154 -- We want to rename the type so that we can find what
155 -- (free) type constructors are inside it. But we must *not* thereby
156 -- put new occurrences into the global pool because otherwise we'll force
157 -- them all to be loaded. We kill two birds with ones stone by renaming
158 -- with a fresh occurrence pool.
159 findOccurrencesRn (rnHsType inst_ty) `thenRn` \ ty_names ->
161 returnRn ((ty_names, mod_name, decl) `consBag` insts)
165 %********************************************************
167 \subsection{Loading usage information}
169 %********************************************************
172 checkUpToDate :: Module -> RnMG Bool -- True <=> no need to recompile
173 checkUpToDate mod_name
174 = findAndReadIface doc_str mod_name `thenRn` \ read_result ->
176 Nothing -> -- Old interface file not found, so we'd better bale out
177 traceRn (ppSep [ppStr "Didnt find old iface", pprModule PprDebug mod_name]) `thenRn_`
180 Just (ParsedIface _ _ usages _ _ _ _ _)
181 -> -- Found it, so now check it
184 -- Only look in current directory, with suffix .hi
185 doc_str = ppSep [ppStr "Need usage info from", pprModule PprDebug mod_name]
188 checkModUsage [] = returnRn True -- Yes! Everything is up to date!
190 checkModUsage ((mod, old_mod_vers, old_local_vers) : rest)
191 = loadInterface doc_str mod `thenRn` \ ifaces ->
193 Ifaces _ mod_vers_map _ new_vers_map _ _ _ = ifaces
194 maybe_new_mod_vers = lookupFM mod_vers_map mod
195 Just new_mod_vers = maybe_new_mod_vers
197 -- If we can't find a version number for the old module then
198 -- bale out saying things aren't up to date
199 if not (maybeToBool maybe_new_mod_vers) then
203 -- If the module version hasn't changed, just move on
204 if new_mod_vers == old_mod_vers then
205 traceRn (ppSep [ppStr "Module version unchanged:", pprModule PprDebug mod]) `thenRn_`
208 traceRn (ppSep [ppStr "Module version has changed:", pprModule PprDebug mod]) `thenRn_`
210 -- New module version, so check entities inside
211 checkEntityUsage mod new_vers_map old_local_vers `thenRn` \ up_to_date ->
213 traceRn (ppStr "...but the bits I use havn't.") `thenRn_`
214 checkModUsage rest -- This one's ok, so check the rest
216 returnRn False -- This one failed, so just bail out now
218 doc_str = ppSep [ppStr "need version info for", pprModule PprDebug mod]
221 checkEntityUsage mod new_vers_map []
222 = returnRn True -- Yes! All up to date!
224 checkEntityUsage mod new_vers_map ((occ_name,old_vers) : rest)
225 = newGlobalName mod occ_name `thenRn` \ name ->
226 case lookupFM new_vers_map name of
228 Nothing -> -- We used it before, but it ain't there now
229 traceRn (ppSep [ppStr "...and this no longer exported:", ppr PprDebug name]) `thenRn_`
232 Just new_vers -> -- It's there, but is it up to date?
233 if new_vers == old_vers then
234 -- Up to date, so check the rest
235 checkEntityUsage mod new_vers_map rest
237 traceRn (ppSep [ppStr "...and this is out of date:", ppr PprDebug name]) `thenRn_`
238 returnRn False -- Out of date, so bale out
242 %*********************************************************
244 \subsection{Getting in a declaration}
246 %*********************************************************
249 getDecl :: Name -> RnMG (AvailInfo, RdrNameHsDecl)
251 = traceRn doc_str `thenRn_`
252 loadInterface doc_str mod `thenRn` \ (Ifaces _ _ _ _ decls_map _ _) ->
253 case lookupFM decls_map name of
255 Just avail_w_decl -> returnRn avail_w_decl
257 Nothing -> -- Can happen legitimately for "Optional" occurrences
258 returnRn (NotAvailable, ValD EmptyBinds)
260 (mod,_) = modAndOcc name
261 doc_str = ppSep [ppStr "Need decl for", ppr PprDebug name]
264 @getWiredInDecl@ maps a wired-in @Name@ to what it makes available.
265 It behaves exactly as if the wired in decl were actually in an interface file.
267 * if the wired-in name is a data type constructor or a data constructor,
268 it brings in the type constructor and all the data constructors; and
269 marks as "occurrences" any free vars of the data con.
271 * similarly for synonum type constructor
273 * if the wired-in name is another wired-in Id, it marks as "occurrences"
274 the free vars of the Id's type.
276 * it loads the interface file for the wired-in thing for the
277 sole purpose of making sure that its instance declarations are available
279 All this is necessary so that we know all types that are "in play", so
280 that we know just what instances to bring into scope.
283 getWiredInDecl :: Name -> RnMG AvailInfo
285 = -- Force in the home module in case it has instance decls for
286 -- the thing we are interested in
287 (if mod == gHC__ then
288 returnRn () -- Mini hack; GHC is guaranteed not to have
289 -- instance decls, so it's a waste of time
292 loadInterface doc_str mod `thenRn_`
296 if (maybeToBool maybe_wired_in_tycon) then
297 get_wired_tycon the_tycon
298 else -- Must be a wired-in-Id
299 if (isDataCon the_id) then -- ... a wired-in data constructor
300 get_wired_tycon (dataConTyCon the_id)
301 else -- ... a wired-in non data-constructor
304 doc_str = ppSep [ppStr "Need home module for wired in thing", ppr PprDebug name]
305 (mod,_) = modAndOcc name
306 maybe_wired_in_tycon = maybeWiredInTyConName name
307 maybe_wired_in_id = maybeWiredInIdName name
308 Just the_tycon = maybe_wired_in_tycon
309 Just the_id = maybe_wired_in_id
312 = addImplicitOccsRn (nameSetToList id_mentioned) `thenRn_`
313 returnRn (Avail (getName id) [])
315 id_mentioned = namesOfType (idType id)
317 get_wired_tycon tycon
319 = addImplicitOccsRn (nameSetToList mentioned) `thenRn_`
320 returnRn (Avail (getName tycon) [])
322 (tyvars,ty) = getSynTyConDefn tycon
323 mentioned = namesOfType ty `minusNameSet` mkNameSet (map getName tyvars)
325 get_wired_tycon tycon
326 | otherwise -- data or newtype
327 = addImplicitOccsRn (nameSetToList mentioned) `thenRn_`
328 returnRn (Avail (getName tycon) (map getName data_cons))
330 data_cons = tyConDataCons tycon
331 mentioned = foldr (unionNameSets . namesOfType . idType) emptyNameSet data_cons
335 %*********************************************************
337 \subsection{Getting other stuff}
339 %*********************************************************
342 getInterfaceExports :: Module -> RnMG (Avails, [(OccName,Fixity)])
343 getInterfaceExports mod
344 = loadInterface doc_str mod `thenRn` \ (Ifaces _ _ export_envs _ _ _ _) ->
345 case lookupFM export_envs mod of
346 Nothing -> -- Not there; it must be that the interface file wasn't found;
347 -- the error will have been reported already.
348 -- (Actually loadInterface should put the empty export env in there
349 -- anyway, but this does no harm.)
352 Just stuff -> returnRn stuff
354 doc_str = ppSep [pprModule PprDebug mod, ppStr "is directly imported"]
357 getImportedInstDecls :: RnMG [IfaceInst]
359 = -- First load any special-instance modules that aren't aready loaded
360 getSpecialInstModules `thenRn` \ inst_mods ->
361 mapRn load_it inst_mods `thenRn_`
363 -- Now we're ready to grab the instance declarations
364 getIfacesRn `thenRn` \ ifaces ->
366 Ifaces _ _ _ _ _ insts _ = ifaces
368 returnRn (bagToList insts)
370 load_it mod = loadInterface (doc_str mod) mod
371 doc_str mod = ppSep [pprModule PprDebug mod, ppStr "is a special-instance module"]
373 getSpecialInstModules :: RnMG [Module]
374 getSpecialInstModules
375 = getIfacesRn `thenRn` \ ifaces ->
377 Ifaces _ _ _ _ _ _ inst_mods = ifaces
383 getImportVersions :: [AvailInfo] -- Imported avails
384 -> RnMG (VersionInfo Name) -- Version info for these names
386 getImportVersions imported_avails
387 = getIfacesRn `thenRn` \ ifaces ->
389 Ifaces _ mod_versions_map _ version_map _ _ _ = ifaces
391 -- import_versions is harder: we have to group together all the things imported
392 -- from a particular module. We do this with yet another finite map
394 mv_map :: FiniteMap Module [LocalVersion Name]
395 mv_map = foldl add_mv emptyFM imported_avails
396 add_mv mv_map (Avail name _)
397 | isWiredInName name = mv_map -- Don't record versions for wired-in names
398 | otherwise = case lookupFM mv_map mod of
399 Just versions -> addToFM mv_map mod ((name,version):versions)
400 Nothing -> addToFM mv_map mod [(name,version)]
402 (mod,_) = modAndOcc name
403 version = case lookupFM version_map name of
405 Nothing -> pprPanic "getVersionInfo:" (ppr PprDebug name)
407 import_versions = [ (mod, expectJust "import_versions" (lookupFM mod_versions_map mod), local_versions)
408 | (mod, local_versions) <- fmToList mv_map
411 -- Question: should we filter the builtins out of import_versions?
413 returnRn import_versions
416 %*********************************************************
418 \subsection{Getting binders out of a declaration}
420 %*********************************************************
422 @getDeclBinders@ returns the names for a @RdrNameHsDecl@.
423 It's used for both source code (from @availsFromDecl@) and interface files
426 It doesn't deal with source-code specific things: ValD, DefD. They
427 are handled by the sourc-code specific stuff in RnNames.
430 getDeclBinders :: (RdrName -> SrcLoc -> RnMG Name) -- New-name function
434 getDeclBinders new_name (TyD (TyData _ tycon _ condecls _ _ src_loc))
435 = new_name tycon src_loc `thenRn` \ tycon_name ->
436 getConFieldNames new_name condecls `thenRn` \ sub_names ->
437 returnRn (Avail tycon_name sub_names)
439 getDeclBinders new_name (TyD (TyNew _ tycon _ (NewConDecl con _ con_loc) _ _ src_loc))
440 = new_name tycon src_loc `thenRn` \ tycon_name ->
441 new_name con src_loc `thenRn` \ con_name ->
442 returnRn (Avail tycon_name [con_name])
444 getDeclBinders new_name (TyD (TySynonym tycon _ _ src_loc))
445 = new_name tycon src_loc `thenRn` \ tycon_name ->
446 returnRn (Avail tycon_name [])
448 getDeclBinders new_name (ClD (ClassDecl _ cname _ sigs _ _ src_loc))
449 = new_name cname src_loc `thenRn` \ class_name ->
450 mapRn (getClassOpNames new_name) sigs `thenRn` \ sub_names ->
451 returnRn (Avail class_name sub_names)
453 getDeclBinders new_name (SigD (IfaceSig var ty prags src_loc))
454 = new_name var src_loc `thenRn` \ var_name ->
455 returnRn (Avail var_name [])
457 getDeclBinders new_name (DefD _) = returnRn NotAvailable
458 getDeclBinders new_name (InstD _) = returnRn NotAvailable
461 getConFieldNames new_name (ConDecl con _ src_loc : rest)
462 = new_name con src_loc `thenRn` \ n ->
463 getConFieldNames new_name rest `thenRn` \ ns ->
466 getConFieldNames new_name (NewConDecl con _ src_loc : rest)
467 = new_name con src_loc `thenRn` \ n ->
468 getConFieldNames new_name rest `thenRn` \ ns ->
471 getConFieldNames new_name (ConOpDecl _ con _ src_loc : rest)
472 = new_name con src_loc `thenRn` \ n ->
473 getConFieldNames new_name rest `thenRn` \ ns ->
476 getConFieldNames new_name (RecConDecl con fielddecls src_loc : rest)
477 = mapRn (\n -> new_name n src_loc) (con:fields) `thenRn` \ cfs ->
478 getConFieldNames new_name rest `thenRn` \ ns ->
481 fields = concat (map fst fielddecls)
483 getConFieldNames new_name [] = returnRn []
485 getClassOpNames new_name (ClassOpSig op _ _ src_loc) = new_name op src_loc
489 %*********************************************************
491 \subsection{Reading an interface file}
493 %*********************************************************
496 findAndReadIface :: Pretty -> Module -> RnMG (Maybe ParsedIface)
497 -- Nothing <=> file not found, or unreadable, or illegible
498 -- Just x <=> successfully found and parsed
499 findAndReadIface doc_str mod
500 = traceRn trace_msg `thenRn_`
501 getSearchPathRn `thenRn` \ dirs ->
504 trace_msg = ppHang (ppBesides [ppStr "Reading interface for ",
505 pprModule PprDebug mod, ppSemi])
506 4 (ppBesides [ppStr "reason: ", doc_str])
508 try all_dirs [] = traceRn (ppStr "...failed") `thenRn_`
511 try all_dirs (dir:dirs)
512 = readIface file_path `thenRn` \ read_result ->
514 Nothing -> try all_dirs dirs
515 Just iface -> traceRn (ppStr "...done") `thenRn_`
516 returnRn (Just iface)
518 file_path = dir ++ "/" ++ moduleString mod ++ ".hi"
521 @readIface@ trys just one file.
524 readIface :: String -> RnMG (Maybe ParsedIface)
525 -- Nothing <=> file not found, or unreadable, or illegible
526 -- Just x <=> successfully found and parsed
528 = ioToRnMG (readFile file_path) `thenRn` \ read_result ->
530 Right contents -> case parseIface contents of
531 Failed err -> failWithRn Nothing err
532 Succeeded iface -> returnRn (Just iface)
534 Left (NoSuchThing _) -> returnRn Nothing
536 Left err -> failWithRn Nothing
537 (cannaeReadFile file_path err)
541 mkSearchPath takes a string consisting of a colon-separated list of directories, and turns it into
542 a list of directories. For example:
544 mkSearchPath "foo:.:baz" = ["foo", ".", "baz"]
547 mkSearchPath :: Maybe String -> SearchPath
548 mkSearchPath Nothing = ["."]
549 mkSearchPath (Just s)
553 go s = first : go (drop 1 rest)
555 (first,rest) = span (/= ':') s
558 %*********************************************************
562 %*********************************************************
566 = ppBesides [ppStr "Could not find interface for ", ppQuote (pprModule sty mod)]
567 -- , ppStr " in"]) 4 (ppAboves (map ppStr dirs))
569 cannaeReadFile file err sty
570 = ppBesides [ppPStr SLIT("Failed in reading file: "), ppStr file, ppStr "; error=", ppStr (show err)]