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 CmdLineOpts ( opt_HiSuffix )
26 import HsSyn ( HsDecl(..), TyDecl(..), ClassDecl(..), HsTyVar, Bind, HsExpr, Sig(..),
27 HsBinds(..), MonoBinds, DefaultDecl, ConDecl(..), HsType, BangType, IfaceSig(..),
28 FixityDecl(..), Fixity, Fake, InPat, InstDecl(..), SYN_IE(Version), HsIdInfo
30 import HsPragmas ( noGenPragmas )
31 import RdrHsSyn ( SYN_IE(RdrNameHsDecl), SYN_IE(RdrNameInstDecl),
34 import RnEnv ( newGlobalName, lookupRn, addImplicitOccsRn, availNames )
35 import RnSource ( rnHsType )
37 import ParseIface ( parseIface )
39 import ErrUtils ( SYN_IE(Error), SYN_IE(Warning) )
40 import FiniteMap ( FiniteMap, emptyFM, unitFM, lookupFM, addToFM, addListToFM, fmToList )
41 import Name ( Name {-instance NamedThing-}, Provenance, OccName(..),
42 modAndOcc, occNameString, moduleString, pprModule,
43 NameSet(..), emptyNameSet, unionNameSets, nameSetToList,
44 minusNameSet, mkNameSet,
45 isWiredInName, maybeWiredInTyConName, maybeWiredInIdName
47 import Id ( GenId, Id(..), idType, dataConTyCon, isDataCon )
48 import TyCon ( TyCon, tyConDataCons, isSynTyCon, getSynTyConDefn )
49 import Type ( namesOfType )
50 import TyVar ( GenTyVar )
51 import SrcLoc ( mkIfaceSrcLoc )
52 import PrelMods ( gHC__ )
54 import Maybes ( MaybeErr(..), expectJust, maybeToBool )
55 import ListSetOps ( unionLists )
57 import PprStyle ( PprStyle(..) )
58 import Util ( pprPanic )
63 %*********************************************************
65 \subsection{Loading a new interface file}
67 %*********************************************************
70 loadInterface :: Pretty -> Module -> RnMG Ifaces
71 loadInterface doc_str load_mod
72 = getIfacesRn `thenRn` \ ifaces ->
74 Ifaces this_mod mod_vers_map export_env_map vers_map decls_map inst_map inst_mods = ifaces
76 -- CHECK WHETHER WE HAVE IT ALREADY
77 if maybeToBool (lookupFM export_env_map load_mod)
79 returnRn ifaces -- Already in the cache; don't re-read it
83 findAndReadIface doc_str load_mod `thenRn` \ read_result ->
85 -- Check for not found
86 Nothing -> -- Not found, so add an empty export env to the Ifaces map
87 -- so that we don't look again
89 new_export_env_map = addToFM export_env_map load_mod ([],[])
90 new_ifaces = Ifaces this_mod mod_vers_map
92 vers_map decls_map inst_map inst_mods
94 setIfacesRn new_ifaces `thenRn_`
95 failWithRn new_ifaces (noIfaceErr load_mod) ;
98 Just (ParsedIface _ mod_vers usages exports rd_inst_mods fixs decls insts) ->
100 -- LOAD IT INTO Ifaces
101 mapRn loadExport exports `thenRn` \ avails_s ->
102 foldlRn (loadDecl load_mod) (decls_map,vers_map) decls `thenRn` \ (new_decls_map, new_vers_map) ->
103 foldlRn (loadInstDecl load_mod) inst_map insts `thenRn` \ new_insts_map ->
105 export_env = (concat avails_s, fixs)
107 -- Exclude this module from the "special-inst" modules
108 new_inst_mods = inst_mods `unionLists` (filter (/= this_mod) rd_inst_mods)
110 new_ifaces = Ifaces this_mod
111 (addToFM mod_vers_map load_mod mod_vers)
112 (addToFM export_env_map load_mod export_env)
118 setIfacesRn new_ifaces `thenRn_`
122 loadExport :: ExportItem -> RnMG [AvailInfo]
123 loadExport (mod, entities)
124 = mapRn load_entity entities
126 new_name occ = newGlobalName mod occ
128 load_entity (occ, occs)
129 = new_name occ `thenRn` \ name ->
130 mapRn new_name occs `thenRn` \ names ->
131 returnRn (Avail name names)
133 loadVersion :: Module -> VersionMap -> (OccName,Version) -> RnMG VersionMap
134 loadVersion mod vers_map (occ, version)
135 = newGlobalName mod occ `thenRn` \ name ->
136 returnRn (addToFM vers_map name version)
139 loadDecl :: Module -> (DeclsMap, VersionMap)
140 -> (Version, RdrNameHsDecl)
141 -> RnMG (DeclsMap, VersionMap)
142 loadDecl mod (decls_map, vers_map) (version, decl)
143 = getDeclBinders new_implicit_name decl `thenRn` \ avail@(Avail name _) ->
144 returnRn (addListToFM decls_map
145 [(name,(avail,decl)) | name <- availNames avail],
146 addToFM vers_map name version
149 new_implicit_name rdr_name loc = newGlobalName mod (rdrNameOcc rdr_name)
151 loadInstDecl :: Module -> Bag IfaceInst -> RdrNameInstDecl -> RnMG (Bag IfaceInst)
152 loadInstDecl mod_name insts decl@(InstDecl inst_ty binds uprags dfun_name src_loc)
153 = initRnMS emptyRnEnv mod_name InterfaceMode $
155 -- Find out what type constructors and classes are mentioned in the
156 -- instance declaration. We have to be a bit clever.
158 -- We want to rename the type so that we can find what
159 -- (free) type constructors are inside it. But we must *not* thereby
160 -- put new occurrences into the global pool because otherwise we'll force
161 -- them all to be loaded. We kill two birds with ones stone by renaming
162 -- with a fresh occurrence pool.
163 findOccurrencesRn (rnHsType inst_ty) `thenRn` \ ty_names ->
165 returnRn ((ty_names, mod_name, decl) `consBag` insts)
169 %********************************************************
171 \subsection{Loading usage information}
173 %********************************************************
176 checkUpToDate :: Module -> RnMG Bool -- True <=> no need to recompile
177 checkUpToDate mod_name
178 = findAndReadIface doc_str mod_name `thenRn` \ read_result ->
180 Nothing -> -- Old interface file not found, so we'd better bale out
181 traceRn (ppSep [ppStr "Didnt find old iface", pprModule PprDebug mod_name]) `thenRn_`
184 Just (ParsedIface _ _ usages _ _ _ _ _)
185 -> -- Found it, so now check it
188 -- Only look in current directory, with suffix .hi
189 doc_str = ppSep [ppStr "Need usage info from", pprModule PprDebug mod_name]
192 checkModUsage [] = returnRn True -- Yes! Everything is up to date!
194 checkModUsage ((mod, old_mod_vers, old_local_vers) : rest)
195 = loadInterface doc_str mod `thenRn` \ ifaces ->
197 Ifaces _ mod_vers_map _ new_vers_map _ _ _ = ifaces
198 maybe_new_mod_vers = lookupFM mod_vers_map mod
199 Just new_mod_vers = maybe_new_mod_vers
201 -- If we can't find a version number for the old module then
202 -- bale out saying things aren't up to date
203 if not (maybeToBool maybe_new_mod_vers) then
207 -- If the module version hasn't changed, just move on
208 if new_mod_vers == old_mod_vers then
209 traceRn (ppSep [ppStr "Module version unchanged:", pprModule PprDebug mod]) `thenRn_`
212 traceRn (ppSep [ppStr "Module version has changed:", pprModule PprDebug mod]) `thenRn_`
214 -- New module version, so check entities inside
215 checkEntityUsage mod new_vers_map old_local_vers `thenRn` \ up_to_date ->
217 traceRn (ppStr "...but the bits I use havn't.") `thenRn_`
218 checkModUsage rest -- This one's ok, so check the rest
220 returnRn False -- This one failed, so just bail out now
222 doc_str = ppSep [ppStr "need version info for", pprModule PprDebug mod]
225 checkEntityUsage mod new_vers_map []
226 = returnRn True -- Yes! All up to date!
228 checkEntityUsage mod new_vers_map ((occ_name,old_vers) : rest)
229 = newGlobalName mod occ_name `thenRn` \ name ->
230 case lookupFM new_vers_map name of
232 Nothing -> -- We used it before, but it ain't there now
233 traceRn (ppSep [ppStr "...and this no longer exported:", ppr PprDebug name]) `thenRn_`
236 Just new_vers -> -- It's there, but is it up to date?
237 if new_vers == old_vers then
238 -- Up to date, so check the rest
239 checkEntityUsage mod new_vers_map rest
241 traceRn (ppSep [ppStr "...and this is out of date:", ppr PprDebug name]) `thenRn_`
242 returnRn False -- Out of date, so bale out
246 %*********************************************************
248 \subsection{Getting in a declaration}
250 %*********************************************************
253 getDecl :: Name -> RnMG (AvailInfo, RdrNameHsDecl)
255 = traceRn doc_str `thenRn_`
256 loadInterface doc_str mod `thenRn` \ (Ifaces _ _ _ _ decls_map _ _) ->
257 case lookupFM decls_map name of
259 Just avail_w_decl -> returnRn avail_w_decl
261 Nothing -> -- Can happen legitimately for "Optional" occurrences
262 returnRn (NotAvailable, ValD EmptyBinds)
264 (mod,_) = modAndOcc name
265 doc_str = ppSep [ppStr "Need decl for", ppr PprDebug name]
268 @getWiredInDecl@ maps a wired-in @Name@ to what it makes available.
269 It behaves exactly as if the wired in decl were actually in an interface file.
271 * if the wired-in name is a data type constructor or a data constructor,
272 it brings in the type constructor and all the data constructors; and
273 marks as "occurrences" any free vars of the data con.
275 * similarly for synonum type constructor
277 * if the wired-in name is another wired-in Id, it marks as "occurrences"
278 the free vars of the Id's type.
280 * it loads the interface file for the wired-in thing for the
281 sole purpose of making sure that its instance declarations are available
283 All this is necessary so that we know all types that are "in play", so
284 that we know just what instances to bring into scope.
287 getWiredInDecl :: Name -> RnMG AvailInfo
289 = -- Force in the home module in case it has instance decls for
290 -- the thing we are interested in
291 (if not is_tycon || mod == gHC__ then
292 returnRn () -- Mini hack 1: no point for non-tycons; and if we
293 -- do this we find PrelNum trying to import PackedString,
294 -- because PrelBase's .hi file mentions PackedString.unpackString
295 -- But PackedString.hi isn't built by that point!
297 -- Mini hack 2; GHC is guaranteed not to have
298 -- instance decls, so it's a waste of time
301 loadInterface doc_str mod `thenRn_`
306 get_wired_tycon the_tycon
307 else -- Must be a wired-in-Id
308 if (isDataCon the_id) then -- ... a wired-in data constructor
309 get_wired_tycon (dataConTyCon the_id)
310 else -- ... a wired-in non data-constructor
313 doc_str = ppSep [ppStr "Need home module for wired in thing", ppr PprDebug name]
314 (mod,_) = modAndOcc name
315 maybe_wired_in_tycon = maybeWiredInTyConName name
316 is_tycon = maybeToBool maybe_wired_in_tycon
317 maybe_wired_in_id = maybeWiredInIdName name
318 Just the_tycon = maybe_wired_in_tycon
319 Just the_id = maybe_wired_in_id
322 = addImplicitOccsRn (nameSetToList id_mentioned) `thenRn_`
323 returnRn (Avail (getName id) [])
325 id_mentioned = namesOfType (idType id)
327 get_wired_tycon tycon
329 = addImplicitOccsRn (nameSetToList mentioned) `thenRn_`
330 returnRn (Avail (getName tycon) [])
332 (tyvars,ty) = getSynTyConDefn tycon
333 mentioned = namesOfType ty `minusNameSet` mkNameSet (map getName tyvars)
335 get_wired_tycon tycon
336 | otherwise -- data or newtype
337 = addImplicitOccsRn (nameSetToList mentioned) `thenRn_`
338 returnRn (Avail (getName tycon) (map getName data_cons))
340 data_cons = tyConDataCons tycon
341 mentioned = foldr (unionNameSets . namesOfType . idType) emptyNameSet data_cons
345 %*********************************************************
347 \subsection{Getting other stuff}
349 %*********************************************************
352 getInterfaceExports :: Module -> RnMG (Avails, [(OccName,Fixity)])
353 getInterfaceExports mod
354 = loadInterface doc_str mod `thenRn` \ (Ifaces _ _ export_envs _ _ _ _) ->
355 case lookupFM export_envs mod of
356 Nothing -> -- Not there; it must be that the interface file wasn't found;
357 -- the error will have been reported already.
358 -- (Actually loadInterface should put the empty export env in there
359 -- anyway, but this does no harm.)
362 Just stuff -> returnRn stuff
364 doc_str = ppSep [pprModule PprDebug mod, ppStr "is directly imported"]
367 getImportedInstDecls :: RnMG [IfaceInst]
369 = -- First load any special-instance modules that aren't aready loaded
370 getSpecialInstModules `thenRn` \ inst_mods ->
371 mapRn load_it inst_mods `thenRn_`
373 -- Now we're ready to grab the instance declarations
374 getIfacesRn `thenRn` \ ifaces ->
376 Ifaces _ _ _ _ _ insts _ = ifaces
378 returnRn (bagToList insts)
380 load_it mod = loadInterface (doc_str mod) mod
381 doc_str mod = ppSep [pprModule PprDebug mod, ppStr "is a special-instance module"]
383 getSpecialInstModules :: RnMG [Module]
384 getSpecialInstModules
385 = getIfacesRn `thenRn` \ ifaces ->
387 Ifaces _ _ _ _ _ _ inst_mods = ifaces
393 getImportVersions :: [AvailInfo] -- Imported avails
394 -> RnMG (VersionInfo Name) -- Version info for these names
396 getImportVersions imported_avails
397 = getIfacesRn `thenRn` \ ifaces ->
399 Ifaces _ mod_versions_map _ version_map _ _ _ = ifaces
401 -- import_versions is harder: we have to group together all the things imported
402 -- from a particular module. We do this with yet another finite map
404 mv_map :: FiniteMap Module [LocalVersion Name]
405 mv_map = foldl add_mv emptyFM imported_avails
406 add_mv mv_map (Avail name _)
407 | isWiredInName name = mv_map -- Don't record versions for wired-in names
408 | otherwise = case lookupFM mv_map mod of
409 Just versions -> addToFM mv_map mod ((name,version):versions)
410 Nothing -> addToFM mv_map mod [(name,version)]
412 (mod,_) = modAndOcc name
413 version = case lookupFM version_map name of
415 Nothing -> pprPanic "getVersionInfo:" (ppr PprDebug name)
417 import_versions = [ (mod, expectJust "import_versions" (lookupFM mod_versions_map mod), local_versions)
418 | (mod, local_versions) <- fmToList mv_map
421 -- Question: should we filter the builtins out of import_versions?
423 returnRn import_versions
426 %*********************************************************
428 \subsection{Getting binders out of a declaration}
430 %*********************************************************
432 @getDeclBinders@ returns the names for a @RdrNameHsDecl@.
433 It's used for both source code (from @availsFromDecl@) and interface files
436 It doesn't deal with source-code specific things: ValD, DefD. They
437 are handled by the sourc-code specific stuff in RnNames.
440 getDeclBinders :: (RdrName -> SrcLoc -> RnMG Name) -- New-name function
444 getDeclBinders new_name (TyD (TyData _ tycon _ condecls _ _ src_loc))
445 = new_name tycon src_loc `thenRn` \ tycon_name ->
446 getConFieldNames new_name condecls `thenRn` \ sub_names ->
447 returnRn (Avail tycon_name sub_names)
449 getDeclBinders new_name (TyD (TyNew _ tycon _ (NewConDecl con _ con_loc) _ _ src_loc))
450 = new_name tycon src_loc `thenRn` \ tycon_name ->
451 new_name con src_loc `thenRn` \ con_name ->
452 returnRn (Avail tycon_name [con_name])
454 getDeclBinders new_name (TyD (TySynonym tycon _ _ src_loc))
455 = new_name tycon src_loc `thenRn` \ tycon_name ->
456 returnRn (Avail tycon_name [])
458 getDeclBinders new_name (ClD (ClassDecl _ cname _ sigs _ _ src_loc))
459 = new_name cname src_loc `thenRn` \ class_name ->
460 mapRn (getClassOpNames new_name) sigs `thenRn` \ sub_names ->
461 returnRn (Avail class_name sub_names)
463 getDeclBinders new_name (SigD (IfaceSig var ty prags src_loc))
464 = new_name var src_loc `thenRn` \ var_name ->
465 returnRn (Avail var_name [])
467 getDeclBinders new_name (DefD _) = returnRn NotAvailable
468 getDeclBinders new_name (InstD _) = returnRn NotAvailable
471 getConFieldNames new_name (ConDecl con _ src_loc : rest)
472 = new_name con src_loc `thenRn` \ n ->
473 getConFieldNames new_name rest `thenRn` \ ns ->
476 getConFieldNames new_name (NewConDecl con _ src_loc : rest)
477 = new_name con src_loc `thenRn` \ n ->
478 getConFieldNames new_name rest `thenRn` \ ns ->
481 getConFieldNames new_name (ConOpDecl _ con _ src_loc : rest)
482 = new_name con src_loc `thenRn` \ n ->
483 getConFieldNames new_name rest `thenRn` \ ns ->
486 getConFieldNames new_name (RecConDecl con fielddecls src_loc : rest)
487 = mapRn (\n -> new_name n src_loc) (con:fields) `thenRn` \ cfs ->
488 getConFieldNames new_name rest `thenRn` \ ns ->
491 fields = concat (map fst fielddecls)
493 getConFieldNames new_name [] = returnRn []
495 getClassOpNames new_name (ClassOpSig op _ _ src_loc) = new_name op src_loc
499 %*********************************************************
501 \subsection{Reading an interface file}
503 %*********************************************************
506 findAndReadIface :: Pretty -> Module -> RnMG (Maybe ParsedIface)
507 -- Nothing <=> file not found, or unreadable, or illegible
508 -- Just x <=> successfully found and parsed
509 findAndReadIface doc_str mod
510 = traceRn trace_msg `thenRn_`
511 getSearchPathRn `thenRn` \ dirs ->
514 trace_msg = ppHang (ppBesides [ppStr "Reading interface for ",
515 pprModule PprDebug mod, ppSemi])
516 4 (ppBesides [ppStr "reason: ", doc_str])
518 try all_dirs [] = traceRn (ppStr "...failed") `thenRn_`
521 try all_dirs (dir:dirs)
522 = readIface file_path `thenRn` \ read_result ->
524 Nothing -> try all_dirs dirs
525 Just iface -> traceRn (ppStr "...done") `thenRn_`
526 returnRn (Just iface)
528 file_path = dir ++ "/" ++ moduleString mod ++ ".hi"
531 @readIface@ trys just one file.
534 readIface :: String -> RnMG (Maybe ParsedIface)
535 -- Nothing <=> file not found, or unreadable, or illegible
536 -- Just x <=> successfully found and parsed
538 = ioToRnMG (readFile file_path) `thenRn` \ read_result ->
540 Right contents -> case parseIface contents of
541 Failed err -> failWithRn Nothing err
542 Succeeded iface -> returnRn (Just iface)
544 Left (NoSuchThing _) -> returnRn Nothing
546 Left err -> failWithRn Nothing
547 (cannaeReadFile file_path err)
551 mkSearchPath takes a string consisting of a colon-separated list of directories, and turns it into
552 a list of directories. For example:
554 mkSearchPath "foo:.:baz" = ["foo", ".", "baz"]
557 mkSearchPath :: Maybe String -> SearchPath
558 mkSearchPath Nothing = ["."]
559 mkSearchPath (Just s)
563 go s = first : go (drop 1 rest)
565 (first,rest) = span (/= ':') s
568 %*********************************************************
572 %*********************************************************
576 = ppBesides [ppStr "Could not find valid interface file for ", ppQuote (pprModule sty mod)]
577 -- , ppStr " in"]) 4 (ppAboves (map ppStr dirs))
579 cannaeReadFile file err sty
580 = ppBesides [ppPStr SLIT("Failed in reading file: "), ppStr file, ppStr "; error=", ppStr (show err)]