%
-% (c) The GRASP Project, Glasgow University, 1992-1996
+% (c) The GRASP Project, Glasgow University, 1992-1998
%
\section[Rename]{Renaming and dependency analysis passes}
\begin{code}
-#include "HsVersions.h"
-
module Rename ( renameModule ) where
-import PreludeGlaST ( thenPrimIO )
-
-IMP_Ubiq()
-IMPORT_1_3(List(partition))
+#include "HsVersions.h"
import HsSyn
-import RdrHsSyn ( SYN_IE(RdrNameHsModule), SYN_IE(RdrNameImportDecl) )
-import RnHsSyn ( RnName(..){-.. is for Ix hack only-}, SYN_IE(RenamedHsModule), isRnTyConOrClass, isRnWired )
-
---ToDo:rm: all for debugging only
---import Maybes
---import Name
---import Outputable
---import RnIfaces
---import PprStyle
---import Pretty
---import FiniteMap
---import Util (pprPanic, pprTrace)
-
-import ParseUtils ( ParsedIface(..), RdrIfaceDecl(..), RdrIfaceInst(..),
- UsagesMap(..), VersionsMap(..)
- )
+import RdrHsSyn ( RdrName(..), RdrNameHsModule )
+import RnHsSyn ( RenamedHsModule, RenamedHsDecl, extractHsTyNames )
+
+import CmdLineOpts ( opt_HiMap, opt_D_show_rn_trace,
+ opt_D_dump_rn, opt_D_show_rn_stats,
+ opt_WarnUnusedBinds, opt_WarnUnusedImports
+ )
import RnMonad
-import RnNames ( getGlobalNames, SYN_IE(GlobalNameInfo) )
-import RnSource ( rnSource )
-import RnIfaces ( rnIfaces, initIfaceCache, IfaceCache )
-import RnUtils ( SYN_IE(RnEnv), extendGlobalRnEnv, emptyRnEnv )
-
-import Bag ( isEmptyBag, unionBags, unionManyBags, bagToList, listToBag )
-import CmdLineOpts ( opt_HiMap, opt_NoImplicitPrelude )
-import ErrUtils ( SYN_IE(Error), SYN_IE(Warning) )
-import FiniteMap ( emptyFM, eltsFM, fmToList, addToFM, FiniteMap )
-import Maybes ( catMaybes )
-import Name ( isLocallyDefined, mkWiredInName, getLocalName, isLocalName,
- origName,
- Name, RdrName(..), ExportFlag(..)
+import RnNames ( getGlobalNames )
+import RnSource ( rnIfaceDecl, rnSourceDecls )
+import RnIfaces ( getImportedInstDecls, importDecl, getImportVersions, getSpecialInstModules,
+ getDeferredDataDecls,
+ mkSearchPath, getSlurpedNames, getRnStats
)
---import PprStyle -- ToDo:rm
-import PrelInfo ( builtinNameMaps, builtinKeysMap, SYN_IE(BuiltinNames), SYN_IE(BuiltinKeys) )
-import Pretty
-import Unique ( ixClassKey )
-import UniqFM ( emptyUFM, lookupUFM, addListToUFM_C, eltsUFM )
-import UniqSupply ( splitUniqSupply )
-import Util ( panic, assertPanic{-, pprTrace ToDo:rm-} )
+import RnEnv ( addImplicitOccsRn, availName, availNames, availsToNameSet, warnUnusedTopNames )
+import Name ( Name, isLocallyDefined,
+ NamedThing(..), ImportReason(..), Provenance(..),
+ nameModule, pprModule, pprOccName, nameOccName,
+ getNameProvenance
+ )
+import NameSet
+import TyCon ( TyCon )
+import PrelMods ( mAIN, pREL_MAIN )
+import TysWiredIn ( unitTyCon, intTyCon, doubleTyCon )
+import PrelInfo ( ioTyCon_NAME, thinAirIdNames )
+import ErrUtils ( pprBagOfErrors, pprBagOfWarnings,
+ doIfSet, dumpIfSet, ghcExit
+ )
+import Bag ( isEmptyBag )
+import FiniteMap ( fmToList, delListFromFM )
+import UniqSupply ( UniqSupply )
+import Util ( equivClasses )
+import Maybes ( maybeToBool )
+import Outputable
\end{code}
+
+
\begin{code}
renameModule :: UniqSupply
-> RdrNameHsModule
+ -> IO (Maybe
+ ( RenamedHsModule -- Output, after renaming
+ , InterfaceDetails -- Interface; for interface file generatino
+ , RnNameSupply -- Final env; for renaming derivings
+ , [Module] -- Imported modules; for profiling
+ ))
+
+renameModule us this_mod@(HsModule mod_name vers exports imports local_decls loc)
+ = -- Initialise the renamer monad
+ initRn mod_name us (mkSearchPath opt_HiMap) loc
+ (rename this_mod) >>=
+ \ (maybe_rn_stuff, rn_errs_bag, rn_warns_bag) ->
+
+ -- Check for warnings
+ doIfSet (not (isEmptyBag rn_warns_bag))
+ (printErrs (pprBagOfWarnings rn_warns_bag)) >>
+
+ -- Check for errors; exit if so
+ doIfSet (not (isEmptyBag rn_errs_bag))
+ (printErrs (pprBagOfErrors rn_errs_bag) >>
+ ghcExit 1
+ ) >>
+
+ -- Dump output, if any
+ (case maybe_rn_stuff of
+ Nothing -> return ()
+ Just results@(rn_mod, _, _, _)
+ -> dumpIfSet opt_D_dump_rn "Renamer:"
+ (ppr rn_mod)
+ ) >>
+
+ -- Return results
+ return maybe_rn_stuff
+\end{code}
- -> IO (RenamedHsModule, -- output, after renaming
- RnEnv, -- final env (for renaming derivings)
- [Module], -- imported modules; for profiling
-
- (Name -> ExportFlag, -- export info
- ([(Name,ExportFlag)],
- [(Name,ExportFlag)])),
- (UsagesMap,
- VersionsMap, -- version info; for usage
- [Module]), -- instance modules; for iface
+\begin{code}
+rename this_mod@(HsModule mod_name vers exports imports local_decls loc)
+ = -- FIND THE GLOBAL NAME ENVIRONMENT
+ getGlobalNames this_mod `thenRn` \ maybe_stuff ->
+
+ -- CHECK FOR EARLY EXIT
+ if not (maybeToBool maybe_stuff) then
+ -- Everything is up to date; no need to recompile further
+ rnStats [] `thenRn_`
+ returnRn Nothing
+ else
+ let
+ Just (export_env, rn_env, global_avail_env) = maybe_stuff
+ in
- Bag Error,
- Bag Warning)
-\end{code}
+ -- RENAME THE SOURCE
+ initRnMS rn_env mod_name SourceMode (
+ addImplicits mod_name `thenRn_`
+ rnSourceDecls local_decls
+ ) `thenRn` \ (rn_local_decls, fvs) ->
+
+ -- SLURP IN ALL THE NEEDED DECLARATIONS
+ slurpDecls rn_local_decls `thenRn` \ rn_all_decls ->
+
+ -- EXIT IF ERRORS FOUND
+ checkErrsRn `thenRn` \ no_errs_so_far ->
+ if not no_errs_so_far then
+ -- Found errors already, so exit now
+ rnStats [] `thenRn_`
+ returnRn Nothing
+ else
-ToDo: May want to arrange to return old interface for this module!
-ToDo: Deal with instances (instance version, this module on instance list ???)
+ -- GENERATE THE VERSION/USAGE INFO
+ getImportVersions mod_name exports `thenRn` \ import_versions ->
+ getNameSupplyRn `thenRn` \ name_supply ->
-\begin{code}
-renameModule us input@(HsModule modname _ _ imports _ _ _ _ _ _ _ _ _ _)
+ -- REPORT UNUSED NAMES
+ reportUnusedNames rn_env global_avail_env
+ export_env
+ fvs `thenRn_`
- = {-
+ -- GENERATE THE SPECIAL-INSTANCE MODULE LIST
+ -- The "special instance" modules are those modules that contain instance
+ -- declarations that contain no type constructor or class that was declared
+ -- in that module.
+ getSpecialInstModules `thenRn` \ imported_special_inst_mods ->
let
- pp_pair (n,m) = ppBesides [ppPStr m,ppChar '.',ppPStr n]
+ special_inst_decls = [d | InstD d@(InstDecl inst_ty _ _ _ _) <- rn_local_decls,
+ all (not.isLocallyDefined) (nameSetToList (extractHsTyNames inst_ty))
+ ]
+ special_inst_mods | null special_inst_decls = imported_special_inst_mods
+ | otherwise = mod_name : imported_special_inst_mods
in
- pprTrace "builtins:\n" (case builtinNameMaps of { (builtin_ids, builtin_tcs) ->
- ppAboves [ ppCat (map pp_pair (keysFM builtin_ids))
- , ppCat (map pp_pair (keysFM builtin_tcs))
- , ppCat (map pp_pair (keysFM builtinKeysMap))
- ]}) $
- -}
- -- _scc_ "rnGlobalNames"
- makeHiMap opt_HiMap >>= \ hi_files ->
--- pprTrace "HiMap:\n" (ppAboves [ ppCat [ppPStr m, ppStr p] | (m,p) <- fmToList hi_files])
- initIfaceCache modname hi_files >>= \ iface_cache ->
-
- fixIO ( \ ~(_, _, _, _, rec_occ_fm, ~(rec_export_fn,_)) ->
+
+
+ -- RETURN THE RENAMED MODULE
let
- rec_occ_fn :: Name -> [RdrName]
- rec_occ_fn n = case lookupUFM rec_occ_fm n of
- Nothing -> []
- Just (rn,occs) -> occs
+ import_mods = [mod | ImportDecl mod _ _ _ _ _ <- imports]
- global_name_info = (builtinNameMaps, builtinKeysMap, rec_export_fn, rec_occ_fn)
+ renamed_module = HsModule mod_name vers
+ trashed_exports trashed_imports
+ rn_all_decls
+ loc
in
- getGlobalNames iface_cache global_name_info us1 input >>=
- \ (occ_env, imp_mods, unqual_imps, imp_fixes, top_errs, top_warns) ->
-
- if not (isEmptyBag top_errs) then
- return (rn_panic, rn_panic, top_errs, top_warns, emptyUFM, rn_panic)
- else
-
- -- No top-level name errors so rename source ...
- -- _scc_ "rnSource"
- case initRn True modname occ_env us2
- (rnSource imp_mods unqual_imps imp_fixes input) of {
- ((rn_module, export_fn, module_dotdots, src_occs), src_errs, src_warns) ->
-
- --pprTrace "renameModule:" (ppCat (map (ppr PprDebug . fst) (bagToList src_occs))) $
- let
- occ_fm :: UniqFM (RnName, [RdrName])
+ rnStats rn_all_decls `thenRn_`
+ returnRn (Just (renamed_module,
+ (import_versions, export_env, special_inst_mods),
+ name_supply,
+ import_mods))
+ where
+ trashed_exports = {-trace "rnSource:trashed_exports"-} Nothing
+ trashed_imports = {-trace "rnSource:trashed_imports"-} []
+\end{code}
- occ_list = [ (rn,(rn,[occ])) | (rn,occ) <- bagToList src_occs]
- occ_fm = addListToUFM_C insert_occ emptyUFM occ_list
+@addImplicits@ forces the renamer to slurp in some things which aren't
+mentioned explicitly, but which might be needed by the type checker.
- insert_occ (rn,olds) (rn',[new]) = (rn, insert new olds)
+\begin{code}
+addImplicits mod_name
+ = addImplicitOccsRn (implicit_main ++ default_tys ++ thinAirIdNames)
+ where
+ -- Add occurrences for Int, Double, and (), because they
+ -- are the types to which ambigious type variables may be defaulted by
+ -- the type checker; so they won't always appear explicitly.
+ -- [The () one is a GHC extension for defaulting CCall results.]
+ default_tys = [getName intTyCon, getName doubleTyCon, getName unitTyCon ]
+
+ -- Add occurrences for IO or PrimIO
+ implicit_main | mod_name == mAIN
+ || mod_name == pREL_MAIN = [ioTyCon_NAME]
+ | otherwise = []
+\end{code}
- insert new [] = [new]
- insert new xxs@(x:xs) = case cmp new x of LT_ -> new : xxs
- EQ_ -> xxs
- GT__ -> x : insert new xs
- occ_warns = map multipleOccWarn (filter multiple_occs (eltsUFM occ_fm))
+\begin{code}
+slurpDecls decls
+ = -- First of all, get all the compulsory decls
+ slurp_compulsories decls `thenRn` \ decls1 ->
- multiple_occs (rn, (o1:o2:_)) = getLocalName o1 /= SLIT("negate")
- -- the user is rarely responsible if
- -- "negate" is mentioned in multiple ways
- multiple_occs _ = False
- in
- return (rn_module, imp_mods,
- top_errs `unionBags` src_errs,
- top_warns `unionBags` src_warns `unionBags` listToBag occ_warns,
- occ_fm, (export_fn, module_dotdots))
+ -- Next get the optional ones
+ closeDecls optional_mode decls1 `thenRn` \ decls2 ->
- }) >>= \ (rn_module, imp_mods, errs_so_far, warns_so_far, occ_fm, export_stuff) ->
+ -- Finally get those deferred data type declarations
+ getDeferredDataDecls `thenRn` \ data_decls ->
+ mapRn (rn_data_decl compulsory_mode) data_decls `thenRn` \ rn_data_decls ->
- if not (isEmptyBag errs_so_far) then
- return (rn_panic, rn_panic, rn_panic, rn_panic, rn_panic, errs_so_far, warns_so_far)
- else
+ -- Done
+ returnRn (rn_data_decls ++ decls2)
- -- No errors renaming source so rename the interfaces ...
- -- _scc_ "preRnIfaces"
- let
- -- split up all names that occurred in the source; between
- -- those that are defined therein and those merely mentioned.
- -- We also divide by tycon/class and value names (as usual).
-
- occ_rns = [ rn | (rn,_) <- eltsUFM occ_fm ]
- -- all occurrence names, from this module and imported
-
- (defined_here, defined_elsewhere)
- = partition isLocallyDefined occ_rns
-
- (_, imports_used)
- = partition isRnWired defined_elsewhere
-
- (def_tcs, def_vals) = partition isRnTyConOrClass defined_here
- (occ_tcs, occ_vals) = partition isRnTyConOrClass occ_rns
- -- the occ stuff includes *all* occurrences,
- -- including those for which we have definitions
-
- (orig_def_env, orig_def_dups)
- = extendGlobalRnEnv emptyRnEnv (map pairify_rn def_vals)
- (map pairify_rn def_tcs)
- (orig_occ_env, orig_occ_dups)
- = extendGlobalRnEnv emptyRnEnv (map pairify_rn occ_vals)
- (map pairify_rn occ_tcs)
-
- -- This stuff is pretty dodgy right now: I think original
- -- names and occurrence names may be getting entangled
- -- when they shouldn't be... WDP 96/06
-
- pairify_rn rn -- ToDo: move to Name?
- = let
- name = getName rn
- in
- (if isLocalName name
- then Unqual (getLocalName name)
- else case (origName "pairify_rn" name) of { OrigName m n ->
- Qual m n }
- , rn)
- in
--- ASSERT (isEmptyBag orig_occ_dups)
--- (if (isEmptyBag orig_occ_dups) then \x->x
--- else pprTrace "orig_occ_dups:" (ppAboves [ ppCat [ppr PprDebug m, ppr PprDebug n, ppr PprDebug o] | (m,n,o) <- bagToList orig_occ_dups])) $
- ASSERT (isEmptyBag orig_def_dups)
-
- -- _scc_ "rnIfaces"
- rnIfaces iface_cache imp_mods us3 orig_def_env orig_occ_env
- rn_module (initMustHaves ++ imports_used) >>=
- \ (rn_module_with_imports, final_env,
- (implicit_val_fm, implicit_tc_fm),
- usage_stuff,
- (iface_errs, iface_warns)) ->
-
- return (rn_module_with_imports,
- final_env,
- imp_mods,
- export_stuff,
- usage_stuff,
- errs_so_far `unionBags` iface_errs,
- warns_so_far `unionBags` iface_warns)
where
- rn_panic = panic "renameModule: aborted with errors"
-
- (us1, us') = splitUniqSupply us
- (us2, us3) = splitUniqSupply us'
-
-initMustHaves :: [RnName]
- -- things we *must* find declarations for, because the
- -- compiler may eventually make reference to them (e.g.,
- -- class Eq)
-initMustHaves
- | opt_NoImplicitPrelude
- = [{-no Prelude.hi, no point looking-}]
- | otherwise
- = [ name_fn (mkWiredInName u orig ExportAll)
- | (orig@(OrigName mod str), (u, name_fn)) <- fmToList builtinKeysMap ]
+ compulsory_mode = InterfaceMode Compulsory
+ optional_mode = InterfaceMode Optional
+
+ -- The "slurp_compulsories" function is a loop that alternates
+ -- between slurping compulsory decls and slurping the instance
+ -- decls thus made relavant.
+ -- We *must* loop again here. Why? Two reasons:
+ -- (a) an instance decl will give rise to an unresolved dfun, whose
+ -- decl we must slurp to get its version number; that's the version
+ -- number for the whole instance decl. (And its unfolding might mention new
+ -- unresolved names.)
+ -- (b) an instance decl might give rise to a new unresolved class,
+ -- whose decl we must slurp, which might let in some new instance decls,
+ -- and so on. Example: instance Foo a => Baz [a] where ...
+ slurp_compulsories decls
+ = closeDecls compulsory_mode decls `thenRn` \ decls1 ->
+
+ -- Instance decls still pending?
+ getImportedInstDecls `thenRn` \ inst_decls ->
+ if null inst_decls then
+ -- No, none
+ returnRn decls1
+ else
+ -- Yes, there are some, so rename them and loop
+ traceRn (sep [ptext SLIT("Slurped"), int (length inst_decls), ptext SLIT("instance decls")])
+ `thenRn_`
+ mapRn (rn_inst_decl compulsory_mode) inst_decls `thenRn` \ new_inst_decls ->
+ slurp_compulsories (new_inst_decls ++ decls1)
\end{code}
\begin{code}
-makeHiMap :: Maybe String -> IO (FiniteMap Module FilePath)
-
-makeHiMap Nothing = error "Rename.makeHiMap:no .hi map given by the GHC driver (?)"
-makeHiMap (Just f)
- = readFile f >>= \ cts ->
- return (snag_mod emptyFM cts [])
- where
- -- we alternate between "snag"ging mod(ule names) and path(names),
- -- accumulating names (reversed) and the final resulting map
- -- as we move along.
-
- snag_mod map [] [] = map
- snag_mod map (' ':cs) rmod = snag_path map (_PK_ (reverse rmod)) cs []
- snag_mod map (c:cs) rmod = snag_mod map cs (c:rmod)
-
- snag_path map mod [] rpath = addToFM map mod (reverse rpath)
- snag_path map mod ('\n':cs) rpath = snag_mod (addToFM map mod (reverse rpath)) cs []
- snag_path map mod (c:cs) rpath = snag_path map mod cs (c:rpath)
+closeDecls :: RnSMode
+ -> [RenamedHsDecl] -- Declarations got so far
+ -> RnMG [RenamedHsDecl] -- input + extra decls slurped
+ -- The monad includes a list of possibly-unresolved Names
+ -- This list is empty when closeDecls returns
+
+closeDecls mode decls
+ = popOccurrenceName mode `thenRn` \ maybe_unresolved ->
+ case maybe_unresolved of
+
+ -- No more unresolved names
+ Nothing -> returnRn decls
+
+ -- An unresolved name
+ Just name_w_loc
+ -> -- Slurp its declaration, if any
+-- traceRn (sep [ptext SLIT("Considering"), ppr name_w_loc]) `thenRn_`
+ importDecl name_w_loc mode `thenRn` \ maybe_decl ->
+ case maybe_decl of
+
+ -- No declaration... (wired in thing or optional)
+ Nothing -> closeDecls mode decls
+
+ -- Found a declaration... rename it
+ Just decl -> rn_iface_decl mod_name mode decl `thenRn` \ new_decl ->
+ closeDecls mode (new_decl : decls)
+ where
+ mod_name = nameModule (fst name_w_loc)
+
+rn_iface_decl mod_name mode decl
+ = initRnMS emptyRnEnv mod_name mode (rnIfaceDecl decl)
+
+rn_inst_decl mode (mod_name,decl) = rn_iface_decl mod_name mode (InstD decl)
+rn_data_decl mode (mod_name,ty_decl) = rn_iface_decl mod_name mode (TyClD ty_decl)
\end{code}
-Warning message used herein:
\begin{code}
-multipleOccWarn (name, occs) sty
- = ppBesides [ppStr "warning:multiple names used to refer to `", ppr sty name, ppStr "': ",
- ppInterleave ppComma (map (ppr sty) occs)]
+reportUnusedNames (RnEnv gbl_env _) avail_env (ExportEnv export_avails _) mentioned_names
+ | not (opt_WarnUnusedBinds || opt_WarnUnusedImports)
+ = returnRn ()
+
+ | otherwise
+ = let
+ used_names = mentioned_names `unionNameSets` availsToNameSet export_avails
+
+ -- Now, a use of C implies a use of T,
+ -- if C was brought into scope by T(..) or T(C)
+ really_used_names = used_names `unionNameSets`
+ mkNameSet [ availName avail
+ | sub_name <- nameSetToList used_names,
+ let avail = case lookupNameEnv avail_env sub_name of
+ Just avail -> avail
+ Nothing -> pprTrace "r.u.n" (ppr sub_name) $
+ Avail sub_name
+ ]
+
+ defined_names = mkNameSet (concat (rdrEnvElts gbl_env))
+ defined_but_not_used = defined_names `minusNameSet` really_used_names
+
+ -- Filter out the ones only defined implicitly or whose OccNames
+ -- start with an '_', which we won't report.
+ bad_guys = filter is_explicit (nameSetToList defined_but_not_used)
+ is_explicit n = case getNameProvenance n of
+ LocalDef _ _ -> True
+ NonLocalDef (UserImport _ _ explicit) _ _ -> explicit
+ other -> False
+
+ -- Now group by whether locally defined or imported;
+ -- one group is the locally-defined ones, one group per import module
+ groups = equivClasses cmp bad_guys
+ where
+ name1 `cmp` name2 = getNameProvenance name1 `cmph` getNameProvenance name2
+
+ cmph (LocalDef _ _) (NonLocalDef _ _ _) = LT
+ cmph (LocalDef _ _) (LocalDef _ _) = EQ
+ cmph (NonLocalDef (UserImport m1 _ _) _ _)
+ (NonLocalDef (UserImport m2 _ _) _ _)
+ = m1 `compare` m2
+ cmph (NonLocalDef _ _ _) (LocalDef _ _) = GT
+ -- In-scope NonLocalDefs must have UserImport info on them
+
+ -- ToDo: report somehow on T(..) things where no constructors
+ -- are imported
+ in
+ mapRn warnUnusedTopNames groups `thenRn_`
+ returnRn ()
+
+rnStats :: [RenamedHsDecl] -> RnMG ()
+rnStats all_decls
+ | opt_D_show_rn_trace ||
+ opt_D_show_rn_stats ||
+ opt_D_dump_rn
+ = getRnStats all_decls `thenRn` \ msg ->
+ ioToRnMG (printErrs msg) `thenRn_`
+ returnRn ()
+
+ | otherwise = returnRn ()
\end{code}
+