[project @ 1999-05-28 08:07:52 by simonpj]
authorsimonpj <unknown>
Fri, 28 May 1999 08:07:54 +0000 (08:07 +0000)
committersimonpj <unknown>
Fri, 28 May 1999 08:07:54 +0000 (08:07 +0000)
Make the renamer so that the class ops on the LEFT HAND SIDE
of the bindings of an instance decl count as free variables
of that declaration.  E.g.

instance Foo [a] where
  op x  = ...
  bop y = ...

Here, 'op' and 'bop' are now counted as free variables of
the decl.

This is vital, because the class decl for Foo might be imported,
and look like this:

class Foo a where
  op  :: a -> S
  bop :: T -> a

and these might happen to be the only mentions of S and T
in the program.  Then we need to treat S and T as instance
gates for the purpose of hauling in further instance decls,
and the Right Way to do that is to announce that 'op' and
'bop' have been mentioned.

I also removed the (now obselete) rn_omit field in the
monad.

ghc/compiler/rename/Rename.lhs
ghc/compiler/rename/RnBinds.lhs
ghc/compiler/rename/RnMonad.lhs
ghc/compiler/rename/RnNames.lhs

index c0b52db..377e4ba 100644 (file)
-%
-% (c) The GRASP Project, Glasgow University, 1992-1998
-%
-\section[Rename]{Renaming and dependency analysis passes}
-
-\begin{code}
-module Rename ( renameModule ) where
-
-#include "HsVersions.h"
-
-import HsSyn
-import RdrHsSyn                ( RdrNameHsModule )
-import RnHsSyn         ( RenamedHsModule, RenamedHsDecl, 
-                         extractHsTyNames, extractHsCtxtTyNames
-                       )
-
-import CmdLineOpts     ( opt_HiMap, opt_D_dump_rn_trace,
-                         opt_D_dump_rn, opt_D_dump_rn_stats,
-                         opt_WarnUnusedBinds, opt_WarnUnusedImports
-                       )
-import RnMonad
-import RnNames         ( getGlobalNames )
-import RnSource                ( rnSourceDecls, rnDecl )
-import RnIfaces                ( getImportedInstDecls, importDecl, getImportVersions,
-                         getImportedRules, loadHomeInterface, getSlurped
-                       )
-import RnEnv           ( availName, availNames, availsToNameSet, 
-                         warnUnusedTopNames, mapFvRn,
-                         FreeVars, plusFVs, plusFV, unitFV, emptyFVs, isEmptyFVs
-                       )
-import Module           ( Module, ModuleName, pprModule, mkSearchPath, mkThisModule )
-import Name            ( Name, isLocallyDefined,
-                         NamedThing(..), ImportReason(..), Provenance(..),
-                         pprOccName, nameOccName,
-                         getNameProvenance, occNameUserString, 
-                         maybeWiredInTyConName, maybeWiredInIdName, isWiredInName
-                       )
-import Id              ( idType )
-import DataCon         ( dataConTyCon, dataConType )
-import TyCon           ( TyCon, tyConDataCons, isSynTyCon, getSynTyConDefn )
-import RdrName         ( RdrName )
-import NameSet
-import PrelMods                ( mAIN_Name, pREL_MAIN_Name )
-import TysWiredIn      ( unitTyCon, intTyCon, doubleTyCon, boolTyCon )
-import PrelInfo                ( ioTyCon_NAME, thinAirIdNames )
-import Type            ( namesOfType, funTyCon )
-import ErrUtils                ( pprBagOfErrors, pprBagOfWarnings,
-                         doIfSet, dumpIfSet, ghcExit
-                       )
-import BasicTypes      ( NewOrData(..) )
-import Bag             ( isEmptyBag, bagToList )
-import FiniteMap       ( fmToList, delListFromFM, addToFM, sizeFM, eltsFM )
-import UniqSupply      ( UniqSupply )
-import Util            ( equivClasses )
-import Maybes          ( maybeToBool )
-import Outputable
-\end{code}
-
-
-
-\begin{code}
-renameModule :: UniqSupply
-            -> RdrNameHsModule
-            -> IO (Maybe 
-                     ( Module
-                     , RenamedHsModule   -- Output, after renaming
-                     , InterfaceDetails  -- Interface; for interface file generation
-                     , RnNameSupply      -- Final env; for renaming derivings
-                     , [ModuleName]      -- 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}
-
-
-\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, gbl_env, fixity_env, global_avail_env) = maybe_stuff
-    in
-
-       -- RENAME THE SOURCE
-    initRnMS gbl_env fixity_env SourceMode (
-       rnSourceDecls local_decls
-    )                                  `thenRn` \ (rn_local_decls, source_fvs) ->
-
-       -- SLURP IN ALL THE NEEDED DECLARATIONS
-    let
-       real_source_fvs = implicitFVs mod_name `plusFV` source_fvs
-               -- It's important to do the "plus" this way round, so that
-               -- when compiling the prelude, locally-defined (), Bool, etc
-               -- override the implicit ones. 
-    in
-    slurpImpDecls real_source_fvs      `thenRn` \ rn_imp_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
-
-       -- GENERATE THE VERSION/USAGE INFO
-    getImportVersions mod_name exports                 `thenRn` \ my_usages ->
-    getNameSupplyRn                                    `thenRn` \ name_supply ->
-
-       -- REPORT UNUSED NAMES
-    reportUnusedNames gbl_env global_avail_env
-                     export_env
-                     source_fvs                        `thenRn_`
-
-       -- RETURN THE RENAMED MODULE
-    let
-       has_orphans        = any isOrphanDecl rn_local_decls
-       direct_import_mods = [mod | ImportDecl mod _ _ _ _ _ <- imports]
-       rn_all_decls       = rn_imp_decls ++ rn_local_decls 
-       renamed_module = HsModule mod_name vers 
-                                 trashed_exports trashed_imports
-                                 rn_all_decls
-                                 loc
-    in
-    rnStats rn_imp_decls       `thenRn_`
-    returnRn (Just (mkThisModule mod_name,
-                   renamed_module, 
-                   (has_orphans, my_usages, export_env),
-                   name_supply,
-                   direct_import_mods))
-  where
-    trashed_exports  = {-trace "rnSource:trashed_exports"-} Nothing
-    trashed_imports  = {-trace "rnSource:trashed_imports"-} []
-\end{code}
-
-@implicitFVs@ forces the renamer to slurp in some things which aren't
-mentioned explicitly, but which might be needed by the type checker.
-
-\begin{code}
-implicitFVs mod_name
-  = implicit_main              `plusFV` 
-    mkNameSet default_tys      `plusFV`
-    mkNameSet 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.]
-       -- ALSO: funTyCon, since it occurs implicitly everywhere!
-       --       (we don't want to be bothered with making funTyCon a
-       --        free var at every function application!)
-    default_tys = [getName intTyCon, getName doubleTyCon,
-                  getName unitTyCon, getName funTyCon, getName boolTyCon]
-
-       -- Add occurrences for IO or PrimIO
-    implicit_main |  mod_name == mAIN_Name
-                 || mod_name == pREL_MAIN_Name = unitFV ioTyCon_NAME
-                 |  otherwise                  = emptyFVs
-\end{code}
-
-\begin{code}
-isOrphanDecl (InstD (InstDecl inst_ty _ _ _ _))
-  = not (foldNameSet ((||) . isLocallyDefined) False (extractHsTyNames inst_ty))
-isOrphanDecl (RuleD (RuleDecl _ _ _ lhs _ _))
-  = check lhs
-  where
-    check (HsVar v)   = not (isLocallyDefined v)
-    check (HsApp f a) = check f && check a
-    check other              = True
-isOrphanDecl other = False
-\end{code}
-
-
-%*********************************************************
-%*                                                      *
-\subsection{Slurping declarations}
-%*                                                      *
-%*********************************************************
-
-\begin{code}
--------------------------------------------------------
-slurpImpDecls source_fvs
-  = traceRn (text "slurpImp" <+> fsep (map ppr (nameSetToList source_fvs))) `thenRn_`
-
-       -- The current slurped-set records all local things
-    getSlurped                                 `thenRn` \ source_binders ->
-    slurpSourceRefs source_binders source_fvs  `thenRn` \ (decls1, needed1, inst_gates) ->
-
-       -- Now we can get the instance decls
-    slurpInstDecls decls1 needed1 inst_gates   `thenRn` \ (decls2, needed2) ->
-
-       -- And finally get everything else
-    closeDecls  decls2 needed2
-
--------------------------------------------------------
-slurpSourceRefs :: NameSet                     -- Variables defined in source
-               -> FreeVars                     -- Variables referenced in source
-               -> RnMG ([RenamedHsDecl],
-                        FreeVars,              -- Un-satisfied needs
-                        FreeVars)              -- "Gates"
--- The declaration (and hence home module) of each gate has
--- already been loaded
-
-slurpSourceRefs source_binders source_fvs
-  = go []                              -- Accumulating decls
-       emptyFVs                        -- Unsatisfied needs
-       source_fvs                      -- Accumulating gates
-       (nameSetToList source_fvs)      -- Gates whose defn hasn't been loaded yet
-  where
-    go decls fvs gates []
-       = returnRn (decls, fvs, gates)
-
-    go decls fvs gates (wanted_name:refs) 
-       | isWiredInName wanted_name
-       = load_home wanted_name         `thenRn_`
-         go decls fvs (gates `plusFV` getWiredInGates wanted_name) refs
-
-       | otherwise
-       = importDecl wanted_name                `thenRn` \ maybe_decl ->
-         case maybe_decl of
-               -- No declaration... (already slurped, or local)
-           Nothing   -> go decls fvs gates refs
-           Just decl -> rnIfaceDecl decl               `thenRn` \ (new_decl, fvs1) ->
-                        let
-                           new_gates = getGates source_fvs new_decl
-                        in
-                        go (new_decl : decls)
-                           (fvs1 `plusFV` fvs)
-                           (gates `plusFV` new_gates)
-                           (nameSetToList new_gates ++ refs)
-
-       -- When we find a wired-in name we must load its
-       -- home module so that we find any instance decls therein
-    load_home name 
-       | name `elemNameSet` source_binders = returnRn ()
-               -- When compiling the prelude, a wired-in thing may
-               -- be defined in this module, in which case we don't
-               -- want to load its home module!
-               -- Using 'isLocallyDefined' doesn't work because some of
-               -- the free variables returned are simply 'listTyCon_Name',
-               -- with a system provenance.  We could look them up every time
-               -- but that seems a waste.
-       | otherwise                           = loadHomeInterface doc name      `thenRn_`
-                                               returnRn ()
-        where
-         doc = ptext SLIT("need home module for wired in thing") <+> ppr name
-
--------------------------------------------------------
--- slurpInstDecls imports appropriate instance decls.
--- It has to incorporate a loop, because consider
---     instance Foo a => Baz (Maybe a) where ...
--- It may be that Baz and Maybe are used in the source module,
--- but not Foo; so we need to chase Foo too.
-
-slurpInstDecls decls needed gates
-  | isEmptyFVs gates
-  = returnRn (decls, needed)
-
-  | otherwise
-  = getImportedInstDecls gates                         `thenRn` \ inst_decls ->
-    rnInstDecls decls needed emptyFVs inst_decls       `thenRn` \ (decls1, needed1, gates1) ->
-    slurpInstDecls decls1 needed1 gates1
-  where
-    rnInstDecls decls fvs gates []
-       = returnRn (decls, fvs, gates)
-    rnInstDecls decls fvs gates (d:ds) 
-       = rnIfaceDecl d         `thenRn` \ (new_decl, fvs1) ->
-         rnInstDecls (new_decl:decls) 
-                     (fvs1 `plusFV` fvs)
-                     (gates `plusFV` getInstDeclGates new_decl)
-                     ds
-    
-
--------------------------------------------------------
--- closeDecls keeps going until the free-var set is empty
-closeDecls decls needed
-  | not (isEmptyFVs needed)
-  = slurpDecls decls needed    `thenRn` \ (decls1, needed1) ->
-    closeDecls decls1 needed1
-
-  | otherwise
-  = getImportedRules                   `thenRn` \ rule_decls ->
-    case rule_decls of
-       []    -> returnRn decls -- No new rules, so we are done
-       other -> rnIfaceDecls decls emptyFVs rule_decls         `thenRn` \ (decls1, needed1) ->
-                closeDecls decls1 needed1
-                
-
--------------------------------------------------------
-rnIfaceDecls :: [RenamedHsDecl] -> FreeVars
-            -> [(Module, RdrNameHsDecl)]
-            -> RnM d ([RenamedHsDecl], FreeVars)
-rnIfaceDecls decls fvs []     = returnRn (decls, fvs)
-rnIfaceDecls decls fvs (d:ds) = rnIfaceDecl d          `thenRn` \ (new_decl, fvs1) ->
-                               rnIfaceDecls (new_decl:decls) (fvs1 `plusFV` fvs) ds
-
-rnIfaceDecl (mod, decl) = initIfaceRnMS mod (rnDecl decl)      
-                       
-
--------------------------------------------------------
--- Augment decls with any decls needed by needed.
--- Return also free vars of the new decls (only)
-slurpDecls decls needed
-  = go decls emptyFVs (nameSetToList needed) 
-  where
-    go decls fvs []         = returnRn (decls, fvs)
-    go decls fvs (ref:refs) = slurpDecl decls fvs ref  `thenRn` \ (decls1, fvs1) ->
-                             go decls1 fvs1 refs
-
--------------------------------------------------------
-slurpDecl decls fvs wanted_name
-  = importDecl wanted_name             `thenRn` \ maybe_decl ->
-    case maybe_decl of
-       -- No declaration... (wired in thing)
-       Nothing -> returnRn (decls, fvs)
-
-       -- Found a declaration... rename it
-       Just decl -> rnIfaceDecl decl           `thenRn` \ (new_decl, fvs1) ->
-                    returnRn (new_decl:decls, fvs1 `plusFV` fvs)
-\end{code}
-
-
-%*********************************************************
-%*                                                      *
-\subsection{Extracting the 'gates'}
-%*                                                      *
-%*********************************************************
-
-When we import a declaration like
-
-       data T = T1 Wibble | T2 Wobble
-
-we don't want to treat Wibble and Wobble as gates *unless* T1, T2
-respectively are mentioned by the user program.  If only T is mentioned
-we want only T to be a gate; that way we don't suck in useless instance
-decls for (say) Eq Wibble, when they can't possibly be useful.
-
-@getGates@ takes a newly imported (and renamed) decl, and the free
-vars of the source program, and extracts from the decl the gate names.
-
-\begin{code}
-getGates source_fvs (SigD (IfaceSig _ ty _ _))
-  = extractHsTyNames ty
-
-getGates source_fvs (TyClD (ClassDecl ctxt cls tvs sigs _ _ _ _ _ _))
-  = delListFromNameSet (foldr (plusFV . get) (extractHsCtxtTyNames ctxt) sigs)
-                      (map getTyVarName tvs)
-    `addOneToNameSet` cls
-  where
-    get (ClassOpSig n _ ty _) 
-       | n `elemNameSet` source_fvs = extractHsTyNames ty
-       | otherwise                  = emptyFVs
-
-getGates source_fvs (TyClD (TySynonym tycon tvs ty _))
-  = delListFromNameSet (extractHsTyNames ty)
-                      (map getTyVarName tvs)
-       -- A type synonym type constructor isn't a "gate" for instance decls
-
-getGates source_fvs (TyClD (TyData _ ctxt tycon tvs cons _ _ _))
-  = delListFromNameSet (foldr (plusFV . get) (extractHsCtxtTyNames ctxt) cons)
-                      (map getTyVarName tvs)
-    `addOneToNameSet` tycon
-  where
-    get (ConDecl n tvs ctxt details _)
-       | n `elemNameSet` source_fvs
-               -- If the constructor is method, get fvs from all its fields
-       = delListFromNameSet (get_details details `plusFV` 
-                             extractHsCtxtTyNames ctxt)
-                            (map getTyVarName tvs)
-    get (ConDecl n tvs ctxt (RecCon fields) _)
-               -- Even if the constructor isn't mentioned, the fields
-               -- might be, as selectors.  They can't mention existentially
-               -- bound tyvars (typechecker checks for that) so no need for 
-               -- the deleteListFromNameSet part
-       = foldr (plusFV . get_field) emptyFVs fields
-       
-    get other_con = emptyFVs
-
-    get_details (VanillaCon tys) = plusFVs (map get_bang tys)
-    get_details (InfixCon t1 t2) = get_bang t1 `plusFV` get_bang t2
-    get_details (RecCon fields)  = plusFVs [get_bang t | (_, t) <- fields]
-    get_details (NewCon t _)    = extractHsTyNames t
-
-    get_field (fs,t) | any (`elemNameSet` source_fvs) fs = get_bang t
-                    | otherwise                         = emptyFVs
-
-    get_bang (Banged   t) = extractHsTyNames t
-    get_bang (Unbanged t) = extractHsTyNames t
-    get_bang (Unpacked t) = extractHsTyNames t
-
-getGates source_fvs other_decl = emptyFVs
-\end{code}
-
-getWiredInGates is just like getGates, but it sees a wired-in Name
-rather than a declaration.
-
-\begin{code}
-getWiredInGates :: Name -> FreeVars
-getWiredInGates name   -- No classes are wired in
-  | is_id               = getWiredInGates_s (namesOfType (idType the_id))
-  | isSynTyCon the_tycon = getWiredInGates_s (delListFromNameSet (namesOfType ty) (map getName tyvars))
-  | otherwise           = unitFV name
-  where
-    maybe_wired_in_id    = maybeWiredInIdName name
-    is_id               = maybeToBool maybe_wired_in_id
-    maybe_wired_in_tycon = maybeWiredInTyConName name
-    Just the_id         = maybe_wired_in_id
-    Just the_tycon      = maybe_wired_in_tycon
-    (tyvars,ty)         = getSynTyConDefn the_tycon
-
-getWiredInGates_s names = foldr (plusFV . getWiredInGates) emptyFVs (nameSetToList names)
-\end{code}
-
-\begin{code}
-getInstDeclGates (InstD (InstDecl inst_ty _ _ _ _)) = extractHsTyNames inst_ty
-getInstDeclGates other                             = emptyFVs
-\end{code}
-
-
-%*********************************************************
-%*                                                      *
-\subsection{Unused names}
-%*                                                      *
-%*********************************************************
-
-\begin{code}
-reportUnusedNames 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 = nameSetToList (defined_names `minusNameSet` really_used_names)
-
-       -- Filter out the ones only defined implicitly
-       bad_guys = filter reportableUnusedName defined_but_not_used
-    in
-    warnUnusedTopNames bad_guys        `thenRn_`
-    returnRn ()
-
-reportableUnusedName :: Name -> Bool
-reportableUnusedName name
-  = explicitlyImported (getNameProvenance name) &&
-    not (startsWithUnderscore (occNameUserString (nameOccName name)))
-  where
-    explicitlyImported (LocalDef _ _)                       = True     -- Report unused defns of local vars
-    explicitlyImported (NonLocalDef (UserImport _ _ expl) _) = expl    -- Report unused explicit imports
-    explicitlyImported other                                = False    -- Don't report others
-   
-       -- Haskell 98 encourages compilers to suppress warnings about
-       -- unused names in a pattern if they start with "_".
-    startsWithUnderscore ('_' : _) = True      -- Suppress warnings for names starting
-    startsWithUnderscore other     = False     -- with an underscore
-
-rnStats :: [RenamedHsDecl] -> RnMG ()
-rnStats imp_decls
-        | opt_D_dump_rn_trace || 
-         opt_D_dump_rn_stats ||
-         opt_D_dump_rn 
-       = getRnStats imp_decls          `thenRn` \ msg ->
-         ioToRnM (printErrs msg)       `thenRn_`
-         returnRn ()
-
-       | otherwise = returnRn ()
-\end{code}
-
-
-
-%*********************************************************
-%*                                                     *
-\subsection{Statistics}
-%*                                                     *
-%*********************************************************
-
-\begin{code}
-getRnStats :: [RenamedHsDecl] -> RnMG SDoc
-getRnStats imported_decls
-  = getIfacesRn                `thenRn` \ ifaces ->
-    let
-       n_mods = length [() | (_, _, Just _) <- eltsFM (iImpModInfo ifaces)]
-
-       decls_read     = [decl | (_, avail, True, (_,decl)) <- nameEnvElts (iDecls ifaces),
-                                       -- Data, newtype, and class decls are in the decls_fm
-                                       -- under multiple names; the tycon/class, and each
-                                       -- constructor/class op too.
-                                       -- The 'True' selects just the 'main' decl
-                                not (isLocallyDefined (availName avail))
-                            ]
-
-       (cd_rd, dd_rd, nd_rd, sd_rd, vd_rd,     _) = count_decls decls_read
-       (cd_sp, dd_sp, nd_sp, sd_sp, vd_sp, id_sp) = count_decls imported_decls
-
-       unslurped_insts       = iInsts ifaces
-       inst_decls_unslurped  = length (bagToList unslurped_insts)
-       inst_decls_read       = id_sp + inst_decls_unslurped
-
-       stats = vcat 
-               [int n_mods <+> text "interfaces read",
-                hsep [ int cd_sp, text "class decls imported, out of", 
-                       int cd_rd, text "read"],
-                hsep [ int dd_sp, text "data decls imported, out of",  
-                       int dd_rd, text "read"],
-                hsep [ int nd_sp, text "newtype decls imported, out of",  
-                       int nd_rd, text "read"],
-                hsep [int sd_sp, text "type synonym decls imported, out of",  
-                       int sd_rd, text "read"],
-                hsep [int vd_sp, text "value signatures imported, out of",  
-                       int vd_rd, text "read"],
-                hsep [int id_sp, text "instance decls imported, out of",  
-                       int inst_decls_read, text "read"],
-                text "cls dcls slurp" <+> fsep (map (ppr . tyClDeclName) 
-                                          [d | TyClD d <- imported_decls, isClassDecl d]),
-                text "cls dcls read"  <+> fsep (map (ppr . tyClDeclName) 
-                                          [d | TyClD d <- decls_read, isClassDecl d])]
-    in
-    returnRn (hcat [text "Renamer stats: ", stats])
-
-count_decls decls
-  = (class_decls, 
-     data_decls, 
-     newtype_decls,
-     syn_decls, 
-     val_decls, 
-     inst_decls)
-  where
-    tycl_decls = [d | TyClD d <- decls]
-    (class_decls, data_decls, newtype_decls, syn_decls) = countTyClDecls tycl_decls
-
-    val_decls     = length [() | SigD _          <- decls]
-    inst_decls    = length [() | InstD _  <- decls]
-\end{code}    
-
+%\r
+% (c) The GRASP Project, Glasgow University, 1992-1998\r
+%\r
+\section[Rename]{Renaming and dependency analysis passes}\r
+\r
+\begin{code}\r
+module Rename ( renameModule ) where\r
+\r
+#include "HsVersions.h"\r
+\r
+import HsSyn\r
+import RdrHsSyn                ( RdrNameHsModule )\r
+import RnHsSyn         ( RenamedHsModule, RenamedHsDecl, \r
+                         extractHsTyNames, extractHsCtxtTyNames\r
+                       )\r
+\r
+import CmdLineOpts     ( opt_HiMap, opt_D_dump_rn_trace,\r
+                         opt_D_dump_rn, opt_D_dump_rn_stats,\r
+                         opt_WarnUnusedBinds, opt_WarnUnusedImports\r
+                       )\r
+import RnMonad\r
+import RnNames         ( getGlobalNames )\r
+import RnSource                ( rnSourceDecls, rnDecl )\r
+import RnIfaces                ( getImportedInstDecls, importDecl, getImportVersions,\r
+                         getImportedRules, loadHomeInterface, getSlurped\r
+                       )\r
+import RnEnv           ( availName, availNames, availsToNameSet, \r
+                         warnUnusedTopNames, mapFvRn,\r
+                         FreeVars, plusFVs, plusFV, unitFV, emptyFVs, isEmptyFVs\r
+                       )\r
+import Module           ( Module, ModuleName, pprModule, mkSearchPath, mkThisModule )\r
+import Name            ( Name, isLocallyDefined,\r
+                         NamedThing(..), ImportReason(..), Provenance(..),\r
+                         pprOccName, nameOccName,\r
+                         getNameProvenance, occNameUserString, \r
+                         maybeWiredInTyConName, maybeWiredInIdName, isWiredInName\r
+                       )\r
+import Id              ( idType )\r
+import DataCon         ( dataConTyCon, dataConType )\r
+import TyCon           ( TyCon, tyConDataCons, isSynTyCon, getSynTyConDefn )\r
+import RdrName         ( RdrName )\r
+import NameSet\r
+import PrelMods                ( mAIN_Name, pREL_MAIN_Name )\r
+import TysWiredIn      ( unitTyCon, intTyCon, doubleTyCon, boolTyCon )\r
+import PrelInfo                ( ioTyCon_NAME, thinAirIdNames )\r
+import Type            ( namesOfType, funTyCon )\r
+import ErrUtils                ( pprBagOfErrors, pprBagOfWarnings,\r
+                         doIfSet, dumpIfSet, ghcExit\r
+                       )\r
+import BasicTypes      ( NewOrData(..) )\r
+import Bag             ( isEmptyBag, bagToList )\r
+import FiniteMap       ( fmToList, delListFromFM, addToFM, sizeFM, eltsFM )\r
+import UniqSupply      ( UniqSupply )\r
+import Util            ( equivClasses )\r
+import Maybes          ( maybeToBool )\r
+import Outputable\r
+\end{code}\r
+\r
+\r
+\r
+\begin{code}\r
+renameModule :: UniqSupply\r
+            -> RdrNameHsModule\r
+            -> IO (Maybe \r
+                     ( Module\r
+                     , RenamedHsModule   -- Output, after renaming\r
+                     , InterfaceDetails  -- Interface; for interface file generation\r
+                     , RnNameSupply      -- Final env; for renaming derivings\r
+                     , [ModuleName]      -- Imported modules; for profiling\r
+                     ))\r
+\r
+renameModule us this_mod@(HsModule mod_name vers exports imports local_decls loc)\r
+  =    -- Initialise the renamer monad\r
+    initRn mod_name us (mkSearchPath opt_HiMap) loc\r
+          (rename this_mod)                            >>=\r
+       \ (maybe_rn_stuff, rn_errs_bag, rn_warns_bag) ->\r
+\r
+       -- Check for warnings\r
+    doIfSet (not (isEmptyBag rn_warns_bag))\r
+           (printErrs (pprBagOfWarnings rn_warns_bag)) >>\r
+\r
+       -- Check for errors; exit if so\r
+    doIfSet (not (isEmptyBag rn_errs_bag))\r
+           (printErrs (pprBagOfErrors rn_errs_bag)      >>\r
+            ghcExit 1\r
+           )                                            >>\r
+\r
+       -- Dump output, if any\r
+    (case maybe_rn_stuff of\r
+       Nothing  -> return ()\r
+       Just results@(_, rn_mod, _, _, _)\r
+                -> dumpIfSet opt_D_dump_rn "Renamer:"\r
+                             (ppr rn_mod)\r
+    )                                                  >>\r
+\r
+       -- Return results\r
+    return maybe_rn_stuff\r
+\end{code}\r
+\r
+\r
+\begin{code}\r
+rename this_mod@(HsModule mod_name vers exports imports local_decls loc)\r
+  =    -- FIND THE GLOBAL NAME ENVIRONMENT\r
+    getGlobalNames this_mod                    `thenRn` \ maybe_stuff ->\r
+\r
+       -- CHECK FOR EARLY EXIT\r
+    if not (maybeToBool maybe_stuff) then\r
+       -- Everything is up to date; no need to recompile further\r
+       rnStats []              `thenRn_`\r
+       returnRn Nothing\r
+    else\r
+    let\r
+       Just (export_env, gbl_env, fixity_env, global_avail_env) = maybe_stuff\r
+    in\r
+\r
+       -- RENAME THE SOURCE\r
+    initRnMS gbl_env fixity_env SourceMode (\r
+       rnSourceDecls local_decls\r
+    )                                  `thenRn` \ (rn_local_decls, source_fvs) ->\r
+\r
+       -- SLURP IN ALL THE NEEDED DECLARATIONS\r
+    let\r
+       real_source_fvs = implicitFVs mod_name `plusFV` source_fvs\r
+               -- It's important to do the "plus" this way round, so that\r
+               -- when compiling the prelude, locally-defined (), Bool, etc\r
+               -- override the implicit ones. \r
+    in\r
+    slurpImpDecls real_source_fvs      `thenRn` \ rn_imp_decls ->\r
+\r
+       -- EXIT IF ERRORS FOUND\r
+    checkErrsRn                                `thenRn` \ no_errs_so_far ->\r
+    if not no_errs_so_far then\r
+       -- Found errors already, so exit now\r
+       rnStats []              `thenRn_`\r
+       returnRn Nothing\r
+    else\r
+\r
+       -- GENERATE THE VERSION/USAGE INFO\r
+    getImportVersions mod_name exports                 `thenRn` \ my_usages ->\r
+    getNameSupplyRn                                    `thenRn` \ name_supply ->\r
+\r
+       -- REPORT UNUSED NAMES\r
+    reportUnusedNames gbl_env global_avail_env\r
+                     export_env\r
+                     source_fvs                        `thenRn_`\r
+\r
+       -- RETURN THE RENAMED MODULE\r
+    let\r
+       has_orphans        = any isOrphanDecl rn_local_decls\r
+       direct_import_mods = [mod | ImportDecl mod _ _ _ _ _ <- imports]\r
+       rn_all_decls       = rn_imp_decls ++ rn_local_decls \r
+       renamed_module = HsModule mod_name vers \r
+                                 trashed_exports trashed_imports\r
+                                 rn_all_decls\r
+                                 loc\r
+    in\r
+    rnStats rn_imp_decls       `thenRn_`\r
+    returnRn (Just (mkThisModule mod_name,\r
+                   renamed_module, \r
+                   (has_orphans, my_usages, export_env),\r
+                   name_supply,\r
+                   direct_import_mods))\r
+  where\r
+    trashed_exports  = {-trace "rnSource:trashed_exports"-} Nothing\r
+    trashed_imports  = {-trace "rnSource:trashed_imports"-} []\r
+\end{code}\r
+\r
+@implicitFVs@ forces the renamer to slurp in some things which aren't\r
+mentioned explicitly, but which might be needed by the type checker.\r
+\r
+\begin{code}\r
+implicitFVs mod_name\r
+  = implicit_main              `plusFV` \r
+    mkNameSet default_tys      `plusFV`\r
+    mkNameSet thinAirIdNames\r
+  where\r
+       -- Add occurrences for Int, Double, and (), because they\r
+       -- are the types to which ambigious type variables may be defaulted by\r
+       -- the type checker; so they won't always appear explicitly.\r
+       -- [The () one is a GHC extension for defaulting CCall results.]\r
+       -- ALSO: funTyCon, since it occurs implicitly everywhere!\r
+       --       (we don't want to be bothered with making funTyCon a\r
+       --        free var at every function application!)\r
+    default_tys = [getName intTyCon, getName doubleTyCon,\r
+                  getName unitTyCon, getName funTyCon, getName boolTyCon]\r
+\r
+       -- Add occurrences for IO or PrimIO\r
+    implicit_main |  mod_name == mAIN_Name\r
+                 || mod_name == pREL_MAIN_Name = unitFV ioTyCon_NAME\r
+                 |  otherwise                  = emptyFVs\r
+\end{code}\r
+\r
+\begin{code}\r
+isOrphanDecl (InstD (InstDecl inst_ty _ _ _ _))\r
+  = not (foldNameSet ((||) . isLocallyDefined) False (extractHsTyNames inst_ty))\r
+isOrphanDecl (RuleD (RuleDecl _ _ _ lhs _ _))\r
+  = check lhs\r
+  where\r
+    check (HsVar v)   = not (isLocallyDefined v)\r
+    check (HsApp f a) = check f && check a\r
+    check other              = True\r
+isOrphanDecl other = False\r
+\end{code}\r
+\r
+\r
+%*********************************************************\r
+%*                                                      *\r
+\subsection{Slurping declarations}\r
+%*                                                      *\r
+%*********************************************************\r
+\r
+\begin{code}\r
+-------------------------------------------------------\r
+slurpImpDecls source_fvs\r
+  = traceRn (text "slurpImp" <+> fsep (map ppr (nameSetToList source_fvs))) `thenRn_`\r
+\r
+       -- The current slurped-set records all local things\r
+    getSlurped                                 `thenRn` \ source_binders ->\r
+    slurpSourceRefs source_binders source_fvs  `thenRn` \ (decls1, needed1, inst_gates) ->\r
+\r
+       -- Now we can get the instance decls\r
+    slurpInstDecls decls1 needed1 inst_gates   `thenRn` \ (decls2, needed2) ->\r
+\r
+       -- And finally get everything else\r
+    closeDecls  decls2 needed2\r
+\r
+-------------------------------------------------------\r
+slurpSourceRefs :: NameSet                     -- Variables defined in source\r
+               -> FreeVars                     -- Variables referenced in source\r
+               -> RnMG ([RenamedHsDecl],\r
+                        FreeVars,              -- Un-satisfied needs\r
+                        FreeVars)              -- "Gates"\r
+-- The declaration (and hence home module) of each gate has\r
+-- already been loaded\r
+\r
+slurpSourceRefs source_binders source_fvs\r
+  = go []                              -- Accumulating decls\r
+       emptyFVs                        -- Unsatisfied needs\r
+       source_fvs                      -- Accumulating gates\r
+       (nameSetToList source_fvs)      -- Gates whose defn hasn't been loaded yet\r
+  where\r
+    go decls fvs gates []\r
+       = returnRn (decls, fvs, gates)\r
+\r
+    go decls fvs gates (wanted_name:refs) \r
+       | isWiredInName wanted_name\r
+       = load_home wanted_name         `thenRn_`\r
+         go decls fvs (gates `plusFV` getWiredInGates wanted_name) refs\r
+\r
+       | otherwise\r
+       = importDecl wanted_name                `thenRn` \ maybe_decl ->\r
+         case maybe_decl of\r
+               -- No declaration... (already slurped, or local)\r
+           Nothing   -> go decls fvs gates refs\r
+           Just decl -> rnIfaceDecl decl               `thenRn` \ (new_decl, fvs1) ->\r
+                        let\r
+                           new_gates = getGates source_fvs new_decl\r
+                        in\r
+                        go (new_decl : decls)\r
+                           (fvs1 `plusFV` fvs)\r
+                           (gates `plusFV` new_gates)\r
+                           (nameSetToList new_gates ++ refs)\r
+\r
+       -- When we find a wired-in name we must load its\r
+       -- home module so that we find any instance decls therein\r
+    load_home name \r
+       | name `elemNameSet` source_binders = returnRn ()\r
+               -- When compiling the prelude, a wired-in thing may\r
+               -- be defined in this module, in which case we don't\r
+               -- want to load its home module!\r
+               -- Using 'isLocallyDefined' doesn't work because some of\r
+               -- the free variables returned are simply 'listTyCon_Name',\r
+               -- with a system provenance.  We could look them up every time\r
+               -- but that seems a waste.\r
+       | otherwise                           = loadHomeInterface doc name      `thenRn_`\r
+                                               returnRn ()\r
+        where\r
+         doc = ptext SLIT("need home module for wired in thing") <+> ppr name\r
+\r
+-------------------------------------------------------\r
+-- slurpInstDecls imports appropriate instance decls.\r
+-- It has to incorporate a loop, because consider\r
+--     instance Foo a => Baz (Maybe a) where ...\r
+-- It may be that Baz and Maybe are used in the source module,\r
+-- but not Foo; so we need to chase Foo too.\r
+\r
+slurpInstDecls decls needed gates\r
+  | isEmptyFVs gates\r
+  = returnRn (decls, needed)\r
+\r
+  | otherwise\r
+  = getImportedInstDecls gates                         `thenRn` \ inst_decls ->\r
+    rnInstDecls decls needed emptyFVs inst_decls       `thenRn` \ (decls1, needed1, gates1) ->\r
+    slurpInstDecls decls1 needed1 gates1\r
+  where\r
+    rnInstDecls decls fvs gates []\r
+       = returnRn (decls, fvs, gates)\r
+    rnInstDecls decls fvs gates (d:ds) \r
+       = rnIfaceDecl d         `thenRn` \ (new_decl, fvs1) ->\r
+         rnInstDecls (new_decl:decls) \r
+                     (fvs1 `plusFV` fvs)\r
+                     (gates `plusFV` getInstDeclGates new_decl)\r
+                     ds\r
+    \r
+\r
+-------------------------------------------------------\r
+-- closeDecls keeps going until the free-var set is empty\r
+closeDecls decls needed\r
+  | not (isEmptyFVs needed)\r
+  = slurpDecls decls needed    `thenRn` \ (decls1, needed1) ->\r
+    closeDecls decls1 needed1\r
+\r
+  | otherwise\r
+  = getImportedRules                   `thenRn` \ rule_decls ->\r
+    case rule_decls of\r
+       []    -> returnRn decls -- No new rules, so we are done\r
+       other -> rnIfaceDecls decls emptyFVs rule_decls         `thenRn` \ (decls1, needed1) ->\r
+                closeDecls decls1 needed1\r
+                \r
+\r
+-------------------------------------------------------\r
+rnIfaceDecls :: [RenamedHsDecl] -> FreeVars\r
+            -> [(Module, RdrNameHsDecl)]\r
+            -> RnM d ([RenamedHsDecl], FreeVars)\r
+rnIfaceDecls decls fvs []     = returnRn (decls, fvs)\r
+rnIfaceDecls decls fvs (d:ds) = rnIfaceDecl d          `thenRn` \ (new_decl, fvs1) ->\r
+                               rnIfaceDecls (new_decl:decls) (fvs1 `plusFV` fvs) ds\r
+\r
+rnIfaceDecl (mod, decl) = initIfaceRnMS mod (rnDecl decl)      \r
+                       \r
+\r
+-------------------------------------------------------\r
+-- Augment decls with any decls needed by needed.\r
+-- Return also free vars of the new decls (only)\r
+slurpDecls decls needed\r
+  = go decls emptyFVs (nameSetToList needed) \r
+  where\r
+    go decls fvs []         = returnRn (decls, fvs)\r
+    go decls fvs (ref:refs) = slurpDecl decls fvs ref  `thenRn` \ (decls1, fvs1) ->\r
+                             go decls1 fvs1 refs\r
+\r
+-------------------------------------------------------\r
+slurpDecl decls fvs wanted_name\r
+  = importDecl wanted_name             `thenRn` \ maybe_decl ->\r
+    case maybe_decl of\r
+       -- No declaration... (wired in thing)\r
+       Nothing -> returnRn (decls, fvs)\r
+\r
+       -- Found a declaration... rename it\r
+       Just decl -> rnIfaceDecl decl           `thenRn` \ (new_decl, fvs1) ->\r
+                    returnRn (new_decl:decls, fvs1 `plusFV` fvs)\r
+\end{code}\r
+\r
+\r
+%*********************************************************\r
+%*                                                      *\r
+\subsection{Extracting the 'gates'}\r
+%*                                                      *\r
+%*********************************************************\r
+\r
+When we import a declaration like\r
+\r
+       data T = T1 Wibble | T2 Wobble\r
+\r
+we don't want to treat Wibble and Wobble as gates *unless* T1, T2\r
+respectively are mentioned by the user program.  If only T is mentioned\r
+we want only T to be a gate; that way we don't suck in useless instance\r
+decls for (say) Eq Wibble, when they can't possibly be useful.\r
+\r
+@getGates@ takes a newly imported (and renamed) decl, and the free\r
+vars of the source program, and extracts from the decl the gate names.\r
+\r
+\begin{code}\r
+getGates source_fvs (SigD (IfaceSig _ ty _ _))\r
+  = extractHsTyNames ty\r
+\r
+getGates source_fvs (TyClD (ClassDecl ctxt cls tvs sigs _ _ _ _ _ _))\r
+  = delListFromNameSet (foldr (plusFV . get) (extractHsCtxtTyNames ctxt) sigs)\r
+                      (map getTyVarName tvs)\r
+    `addOneToNameSet` cls\r
+  where\r
+    get (ClassOpSig n _ ty _) \r
+       | n `elemNameSet` source_fvs = extractHsTyNames ty\r
+       | otherwise                  = emptyFVs\r
+\r
+getGates source_fvs (TyClD (TySynonym tycon tvs ty _))\r
+  = delListFromNameSet (extractHsTyNames ty)\r
+                      (map getTyVarName tvs)\r
+       -- A type synonym type constructor isn't a "gate" for instance decls\r
+\r
+getGates source_fvs (TyClD (TyData _ ctxt tycon tvs cons _ _ _))\r
+  = delListFromNameSet (foldr (plusFV . get) (extractHsCtxtTyNames ctxt) cons)\r
+                      (map getTyVarName tvs)\r
+    `addOneToNameSet` tycon\r
+  where\r
+    get (ConDecl n tvs ctxt details _)\r
+       | n `elemNameSet` source_fvs\r
+               -- If the constructor is method, get fvs from all its fields\r
+       = delListFromNameSet (get_details details `plusFV` \r
+                             extractHsCtxtTyNames ctxt)\r
+                            (map getTyVarName tvs)\r
+    get (ConDecl n tvs ctxt (RecCon fields) _)\r
+               -- Even if the constructor isn't mentioned, the fields\r
+               -- might be, as selectors.  They can't mention existentially\r
+               -- bound tyvars (typechecker checks for that) so no need for \r
+               -- the deleteListFromNameSet part\r
+       = foldr (plusFV . get_field) emptyFVs fields\r
+       \r
+    get other_con = emptyFVs\r
+\r
+    get_details (VanillaCon tys) = plusFVs (map get_bang tys)\r
+    get_details (InfixCon t1 t2) = get_bang t1 `plusFV` get_bang t2\r
+    get_details (RecCon fields)  = plusFVs [get_bang t | (_, t) <- fields]\r
+    get_details (NewCon t _)    = extractHsTyNames t\r
+\r
+    get_field (fs,t) | any (`elemNameSet` source_fvs) fs = get_bang t\r
+                    | otherwise                         = emptyFVs\r
+\r
+    get_bang (Banged   t) = extractHsTyNames t\r
+    get_bang (Unbanged t) = extractHsTyNames t\r
+    get_bang (Unpacked t) = extractHsTyNames t\r
+\r
+getGates source_fvs other_decl = emptyFVs\r
+\end{code}\r
+\r
+getWiredInGates is just like getGates, but it sees a wired-in Name\r
+rather than a declaration.\r
+\r
+\begin{code}\r
+getWiredInGates :: Name -> FreeVars\r
+getWiredInGates name   -- No classes are wired in\r
+  | is_id               = getWiredInGates_s (namesOfType (idType the_id))\r
+  | isSynTyCon the_tycon = getWiredInGates_s (delListFromNameSet (namesOfType ty) (map getName tyvars))\r
+  | otherwise           = unitFV name\r
+  where\r
+    maybe_wired_in_id    = maybeWiredInIdName name\r
+    is_id               = maybeToBool maybe_wired_in_id\r
+    maybe_wired_in_tycon = maybeWiredInTyConName name\r
+    Just the_id         = maybe_wired_in_id\r
+    Just the_tycon      = maybe_wired_in_tycon\r
+    (tyvars,ty)         = getSynTyConDefn the_tycon\r
+\r
+getWiredInGates_s names = foldr (plusFV . getWiredInGates) emptyFVs (nameSetToList names)\r
+\end{code}\r
+\r
+\begin{code}\r
+getInstDeclGates (InstD (InstDecl inst_ty _ _ _ _)) = extractHsTyNames inst_ty\r
+getInstDeclGates other                             = emptyFVs\r
+\end{code}\r
+\r
+\r
+%*********************************************************\r
+%*                                                      *\r
+\subsection{Unused names}\r
+%*                                                      *\r
+%*********************************************************\r
+\r
+\begin{code}\r
+reportUnusedNames gbl_env avail_env (ExportEnv export_avails _) mentioned_names\r
+  | not (opt_WarnUnusedBinds || opt_WarnUnusedImports)\r
+  = returnRn ()\r
+\r
+  | otherwise\r
+  = let\r
+       used_names = mentioned_names `unionNameSets` availsToNameSet export_avails\r
+\r
+       -- Now, a use of C implies a use of T,\r
+       -- if C was brought into scope by T(..) or T(C)\r
+       really_used_names = used_names `unionNameSets`\r
+                           mkNameSet [ availName avail \r
+                                     | sub_name <- nameSetToList used_names,\r
+                                       let avail = case lookupNameEnv avail_env sub_name of\r
+                                                       Just avail -> avail\r
+                                                       Nothing -> pprTrace "r.u.n" (ppr sub_name) $\r
+                                                                  Avail sub_name\r
+                                     ]\r
+\r
+       defined_names = mkNameSet (concat (rdrEnvElts gbl_env))\r
+       defined_but_not_used = nameSetToList (defined_names `minusNameSet` really_used_names)\r
+\r
+       -- Filter out the ones only defined implicitly\r
+       bad_guys = filter reportableUnusedName defined_but_not_used\r
+    in\r
+    warnUnusedTopNames bad_guys        `thenRn_`\r
+    returnRn ()\r
+\r
+reportableUnusedName :: Name -> Bool\r
+reportableUnusedName name\r
+  = explicitlyImported (getNameProvenance name) &&\r
+    not (startsWithUnderscore (occNameUserString (nameOccName name)))\r
+  where\r
+    explicitlyImported (LocalDef _ _)                       = True     -- Report unused defns of local vars\r
+    explicitlyImported (NonLocalDef (UserImport _ _ expl) _) = expl    -- Report unused explicit imports\r
+    explicitlyImported other                                = False    -- Don't report others\r
+   \r
+       -- Haskell 98 encourages compilers to suppress warnings about\r
+       -- unused names in a pattern if they start with "_".\r
+    startsWithUnderscore ('_' : _) = True      -- Suppress warnings for names starting\r
+    startsWithUnderscore other     = False     -- with an underscore\r
+\r
+rnStats :: [RenamedHsDecl] -> RnMG ()\r
+rnStats imp_decls\r
+        | opt_D_dump_rn_trace || \r
+         opt_D_dump_rn_stats ||\r
+         opt_D_dump_rn \r
+       = getRnStats imp_decls          `thenRn` \ msg ->\r
+         ioToRnM (printErrs msg)       `thenRn_`\r
+         returnRn ()\r
+\r
+       | otherwise = returnRn ()\r
+\end{code}\r
+\r
+\r
+\r
+%*********************************************************\r
+%*                                                     *\r
+\subsection{Statistics}\r
+%*                                                     *\r
+%*********************************************************\r
+\r
+\begin{code}\r
+getRnStats :: [RenamedHsDecl] -> RnMG SDoc\r
+getRnStats imported_decls\r
+  = getIfacesRn                `thenRn` \ ifaces ->\r
+    let\r
+       n_mods = length [() | (_, _, Just _) <- eltsFM (iImpModInfo ifaces)]\r
+\r
+       decls_read     = [decl | (_, avail, True, (_,decl)) <- nameEnvElts (iDecls ifaces),\r
+                                       -- Data, newtype, and class decls are in the decls_fm\r
+                                       -- under multiple names; the tycon/class, and each\r
+                                       -- constructor/class op too.\r
+                                       -- The 'True' selects just the 'main' decl\r
+                                not (isLocallyDefined (availName avail))\r
+                            ]\r
+\r
+       (cd_rd, dd_rd, nd_rd, sd_rd, vd_rd,     _) = count_decls decls_read\r
+       (cd_sp, dd_sp, nd_sp, sd_sp, vd_sp, id_sp) = count_decls imported_decls\r
+\r
+       unslurped_insts       = iInsts ifaces\r
+       inst_decls_unslurped  = length (bagToList unslurped_insts)\r
+       inst_decls_read       = id_sp + inst_decls_unslurped\r
+\r
+       stats = vcat \r
+               [int n_mods <+> text "interfaces read",\r
+                hsep [ int cd_sp, text "class decls imported, out of", \r
+                       int cd_rd, text "read"],\r
+                hsep [ int dd_sp, text "data decls imported, out of",  \r
+                       int dd_rd, text "read"],\r
+                hsep [ int nd_sp, text "newtype decls imported, out of",  \r
+                       int nd_rd, text "read"],\r
+                hsep [int sd_sp, text "type synonym decls imported, out of",  \r
+                       int sd_rd, text "read"],\r
+                hsep [int vd_sp, text "value signatures imported, out of",  \r
+                       int vd_rd, text "read"],\r
+                hsep [int id_sp, text "instance decls imported, out of",  \r
+                       int inst_decls_read, text "read"],\r
+                text "cls dcls slurp" <+> fsep (map (ppr . tyClDeclName) \r
+                                          [d | TyClD d <- imported_decls, isClassDecl d]),\r
+                text "cls dcls read"  <+> fsep (map (ppr . tyClDeclName) \r
+                                          [d | TyClD d <- decls_read, isClassDecl d])]\r
+    in\r
+    returnRn (hcat [text "Renamer stats: ", stats])\r
+\r
+count_decls decls\r
+  = (class_decls, \r
+     data_decls, \r
+     newtype_decls,\r
+     syn_decls, \r
+     val_decls, \r
+     inst_decls)\r
+  where\r
+    tycl_decls = [d | TyClD d <- decls]\r
+    (class_decls, data_decls, newtype_decls, syn_decls) = countTyClDecls tycl_decls\r
+\r
+    val_decls     = length [() | SigD _          <- decls]\r
+    inst_decls    = length [() | InstD _  <- decls]\r
+\end{code}    \r
+\r
index b6f6d2c..b55f6fe 100644 (file)
-%
-% (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
-%
-\section[RnBinds]{Renaming and dependency analysis of bindings}
-
-This module does renaming and dependency analysis on value bindings in
-the abstract syntax.  It does {\em not} do cycle-checks on class or
-type-synonym declarations; those cannot be done at this stage because
-they may be affected by renaming (which isn't fully worked out yet).
-
-\begin{code}
-module RnBinds (
-       rnTopBinds, rnTopMonoBinds,
-       rnMethodBinds, renameSigs,
-       rnBinds,
-       unknownSigErr
-   ) where
-
-#include "HsVersions.h"
-
-import {-# SOURCE #-} RnSource ( rnHsSigType )
-
-import HsSyn
-import HsBinds         ( sigsForMe )
-import RdrHsSyn
-import RnHsSyn
-import RnMonad
-import RnExpr          ( rnMatch, rnGRHSs, rnPat, checkPrecMatch )
-import RnEnv           ( bindLocatedLocalsRn, lookupBndrRn, lookupGlobalOccRn,
-                         warnUnusedLocalBinds, mapFvRn, 
-                         FreeVars, emptyFVs, plusFV, plusFVs, unitFV, addOneFV,
-                         unknownNameErr
-                       )
-import CmdLineOpts     ( opt_WarnMissingSigs )
-import Digraph         ( stronglyConnComp, SCC(..) )
-import Name            ( OccName, Name, nameOccName )
-import NameSet
-import RdrName         ( RdrName, rdrNameOcc  )
-import BasicTypes      ( RecFlag(..), TopLevelFlag(..) )
-import Util            ( thenCmp, removeDups )
-import List            ( partition )
-import ListSetOps      ( minusList )
-import Bag             ( bagToList )
-import FiniteMap       ( lookupFM, listToFM )
-import Maybe           ( isJust )
-import Outputable
-\end{code}
-
--- ToDo: Put the annotations into the monad, so that they arrive in the proper
--- place and can be used when complaining.
-
-The code tree received by the function @rnBinds@ contains definitions
-in where-clauses which are all apparently mutually recursive, but which may
-not really depend upon each other. For example, in the top level program
-\begin{verbatim}
-f x = y where a = x
-             y = x
-\end{verbatim}
-the definitions of @a@ and @y@ do not depend on each other at all.
-Unfortunately, the typechecker cannot always check such definitions.
-\footnote{Mycroft, A. 1984. Polymorphic type schemes and recursive
-definitions. In Proceedings of the International Symposium on Programming,
-Toulouse, pp. 217-39. LNCS 167. Springer Verlag.}
-However, the typechecker usually can check definitions in which only the
-strongly connected components have been collected into recursive bindings.
-This is precisely what the function @rnBinds@ does.
-
-ToDo: deal with case where a single monobinds binds the same variable
-twice.
-
-The vertag tag is a unique @Int@; the tags only need to be unique
-within one @MonoBinds@, so that unique-Int plumbing is done explicitly
-(heavy monad machinery not needed).
-
-\begin{code}
-type VertexTag = Int
-type Cycle     = [VertexTag]
-type Edge      = (VertexTag, VertexTag)
-\end{code}
-
-%************************************************************************
-%*                                                                     *
-%* naming conventions                                                  *
-%*                                                                     *
-%************************************************************************
-
-\subsection[name-conventions]{Name conventions}
-
-The basic algorithm involves walking over the tree and returning a tuple
-containing the new tree plus its free variables. Some functions, such
-as those walking polymorphic bindings (HsBinds) and qualifier lists in
-list comprehensions (@Quals@), return the variables bound in local
-environments. These are then used to calculate the free variables of the
-expression evaluated in these environments.
-
-Conventions for variable names are as follows:
-\begin{itemize}
-\item
-new code is given a prime to distinguish it from the old.
-
-\item
-a set of variables defined in @Exp@ is written @dvExp@
-
-\item
-a set of variables free in @Exp@ is written @fvExp@
-\end{itemize}
-
-%************************************************************************
-%*                                                                     *
-%* analysing polymorphic bindings (HsBinds, Bind, MonoBinds)           *
-%*                                                                     *
-%************************************************************************
-
-\subsubsection[dep-HsBinds]{Polymorphic bindings}
-
-Non-recursive expressions are reconstructed without any changes at top
-level, although their component expressions may have to be altered.
-However, non-recursive expressions are currently not expected as
-\Haskell{} programs, and this code should not be executed.
-
-Monomorphic bindings contain information that is returned in a tuple
-(a @FlatMonoBindsInfo@) containing:
-
-\begin{enumerate}
-\item
-a unique @Int@ that serves as the ``vertex tag'' for this binding.
-
-\item
-the name of a function or the names in a pattern. These are a set
-referred to as @dvLhs@, the defined variables of the left hand side.
-
-\item
-the free variables of the body. These are referred to as @fvBody@.
-
-\item
-the definition's actual code. This is referred to as just @code@.
-\end{enumerate}
-
-The function @nonRecDvFv@ returns two sets of variables. The first is
-the set of variables defined in the set of monomorphic bindings, while the
-second is the set of free variables in those bindings.
-
-The set of variables defined in a non-recursive binding is just the
-union of all of them, as @union@ removes duplicates. However, the
-free variables in each successive set of cumulative bindings is the
-union of those in the previous set plus those of the newest binding after
-the defined variables of the previous set have been removed.
-
-@rnMethodBinds@ deals only with the declarations in class and
-instance declarations. It expects only to see @FunMonoBind@s, and
-it expects the global environment to contain bindings for the binders
-(which are all class operations).
-
-%************************************************************************
-%*                                                                     *
-%*             Top-level bindings
-%*                                                                     *
-%************************************************************************
-
-@rnTopBinds@ assumes that the environment already
-contains bindings for the binders of this particular binding.
-
-\begin{code}
-rnTopBinds    :: RdrNameHsBinds -> RnMS (RenamedHsBinds, FreeVars)
-
-rnTopBinds EmptyBinds                    = returnRn (EmptyBinds, emptyFVs)
-rnTopBinds (MonoBind bind sigs _)        = rnTopMonoBinds bind sigs
-  -- The parser doesn't produce other forms
-
-
-rnTopMonoBinds EmptyMonoBinds sigs 
-  = returnRn (EmptyBinds, emptyFVs)
-
-rnTopMonoBinds mbinds sigs
- =  mapRn lookupBndrRn binder_rdr_names        `thenRn` \ binder_names ->
-    let
-       binder_set    = mkNameSet binder_names
-       binder_occ_fm = listToFM [(nameOccName x,x) | x <- binder_names]
-    in
-    renameSigs opt_WarnMissingSigs binder_set
-              (lookupSigOccRn binder_occ_fm) sigs      `thenRn` \ (siglist, sig_fvs) ->
-    rn_mono_binds siglist mbinds                       `thenRn` \ (final_binds, bind_fvs) ->
-    returnRn (final_binds, bind_fvs `plusFV` sig_fvs)
-  where
-    binder_rdr_names = map fst (bagToList (collectMonoBinders mbinds))
-
--- the names appearing in the sigs have to be bound by 
--- this group's binders.
-lookupSigOccRn binder_occ_fm rdr_name
-  = case lookupFM binder_occ_fm (rdrNameOcc rdr_name) of
-       Nothing -> failWithRn (mkUnboundName rdr_name)
-                             (unknownNameErr rdr_name)
-       Just x  -> returnRn x
-\end{code}
-
-%************************************************************************
-%*                                                                     *
-%*             Nested binds
-%*                                                                     *
-%************************************************************************
-
-@rnMonoBinds@
-       - collects up the binders for this declaration group,
-       - checks that they form a set
-       - extends the environment to bind them to new local names
-       - calls @rnMonoBinds@ to do the real work
-
-\begin{code}
-rnBinds              :: RdrNameHsBinds 
-             -> (RenamedHsBinds -> RnMS (result, FreeVars))
-             -> RnMS (result, FreeVars)
-
-rnBinds EmptyBinds            thing_inside = thing_inside EmptyBinds
-rnBinds (MonoBind bind sigs _) thing_inside = rnMonoBinds bind sigs thing_inside
-  -- the parser doesn't produce other forms
-
-
-rnMonoBinds :: RdrNameMonoBinds 
-            -> [RdrNameSig]
-           -> (RenamedHsBinds -> RnMS (result, FreeVars))
-           -> RnMS (result, FreeVars)
-
-rnMonoBinds EmptyMonoBinds sigs thing_inside = thing_inside EmptyBinds
-
-rnMonoBinds mbinds sigs        thing_inside -- Non-empty monobinds
-  =    -- Extract all the binders in this group,
-       -- and extend current scope, inventing new names for the new binders
-       -- This also checks that the names form a set
-    bindLocatedLocalsRn (text "a binding group") mbinders_w_srclocs            $ \ new_mbinders ->
-    let
-       binder_set  = mkNameSet new_mbinders
-
-          -- Weed out the fixity declarations that do not
-          -- apply to any of the binders in this group.
-       (sigs_for_me, fixes_not_for_me) = partition forLocalBind sigs
-
-       forLocalBind (FixSig sig@(FixitySig name _ _ )) =
-           isJust (lookupFM binder_occ_fm (rdrNameOcc name))
-       forLocalBind _ = True
-
-       binder_occ_fm = listToFM [(nameOccName x,x) | x <- new_mbinders]
-
-    in
-       -- Report the fixity declarations in this group that 
-       -- don't refer to any of the group's binders.
-       --
-    mapRn_ (unknownSigErr) fixes_not_for_me     `thenRn_`
-    renameSigs False binder_set
-              (lookupSigOccRn binder_occ_fm) sigs_for_me   `thenRn` \ (siglist, sig_fvs) ->
-    let
-       fixity_sigs = [(name,sig) | FixSig sig@(FixitySig name _ _) <- siglist ]
-    in
-       -- Install the fixity declarations that do apply here and go.
-    extendFixityEnv fixity_sigs (
-      rn_mono_binds siglist mbinds
-    )                                     `thenRn` \ (binds, bind_fvs) ->
-
-       -- Now do the "thing inside", and deal with the free-variable calculations
-    thing_inside binds                                 `thenRn` \ (result,result_fvs) ->
-    let
-       all_fvs        = result_fvs `plusFV` bind_fvs `plusFV` sig_fvs
-       unused_binders = nameSetToList (binder_set `minusNameSet` all_fvs)
-    in
-    warnUnusedLocalBinds unused_binders        `thenRn_`
-    returnRn (result, delListFromNameSet all_fvs new_mbinders)
-  where
-    mbinders_w_srclocs = bagToList (collectMonoBinders mbinds)
-\end{code}
-
-
-%************************************************************************
-%*                                                                     *
-%*             MonoBinds -- the main work is done here
-%*                                                                     *
-%************************************************************************
-
-@rn_mono_binds@ is used by *both* top-level and nested bindings.  It
-assumes that all variables bound in this group are already in scope.
-This is done *either* by pass 3 (for the top-level bindings), *or* by
-@rnMonoBinds@ (for the nested ones).
-
-\begin{code}
-rn_mono_binds :: [RenamedSig]          -- Signatures attached to this group
-             -> RdrNameMonoBinds       
-             -> RnMS (RenamedHsBinds,  -- 
-                        FreeVars)      -- Free variables
-
-rn_mono_binds siglist mbinds
-  =
-        -- Rename the bindings, returning a MonoBindsInfo
-        -- which is a list of indivisible vertices so far as
-        -- the strongly-connected-components (SCC) analysis is concerned
-    flattenMonoBinds siglist mbinds            `thenRn` \ mbinds_info ->
-
-        -- Do the SCC analysis
-    let 
-        edges      = mkEdges (mbinds_info `zip` [(0::Int)..])
-       scc_result  = stronglyConnComp edges
-       final_binds = foldr1 ThenBinds (map reconstructCycle scc_result)
-
-        -- Deal with bound and free-var calculation
-       rhs_fvs = plusFVs [fvs | (_,fvs,_,_) <- mbinds_info]
-    in
-    returnRn (final_binds, rhs_fvs)
-\end{code}
-
-@flattenMonoBinds@ is ever-so-slightly magical in that it sticks
-unique ``vertex tags'' on its output; minor plumbing required.
-
-Sigh - need to pass along the signatures for the group of bindings,
-in case any of them 
-
-\begin{code}
-flattenMonoBinds :: [RenamedSig]               -- Signatures
-                -> RdrNameMonoBinds
-                -> RnMS [FlatMonoBindsInfo]
-
-flattenMonoBinds sigs EmptyMonoBinds = returnRn []
-
-flattenMonoBinds sigs (AndMonoBinds bs1 bs2)
-  = flattenMonoBinds sigs bs1  `thenRn` \ flat1 ->
-    flattenMonoBinds sigs bs2  `thenRn` \ flat2 ->
-    returnRn (flat1 ++ flat2)
-
-flattenMonoBinds sigs (PatMonoBind pat grhss locn)
-  = pushSrcLocRn locn                  $
-    rnPat pat                          `thenRn` \ (pat', pat_fvs) ->
-
-        -- Find which things are bound in this group
-    let
-       names_bound_here = mkNameSet (collectPatBinders pat')
-       sigs_for_me      = sigsForMe (`elemNameSet` names_bound_here) sigs
-    in
-    rnGRHSs grhss                      `thenRn` \ (grhss', fvs) ->
-    returnRn 
-       [(names_bound_here,
-         fvs `plusFV` pat_fvs,
-         PatMonoBind pat' grhss' locn,
-         sigs_for_me
-        )]
-
-flattenMonoBinds sigs (FunMonoBind name inf matches locn)
-  = pushSrcLocRn locn                                  $
-    lookupBndrRn name                                  `thenRn` \ new_name ->
-    let
-       sigs_for_me = sigsForMe (new_name ==) sigs
-    in
-    mapFvRn rnMatch matches                            `thenRn` \ (new_matches, fvs) ->
-    mapRn_ (checkPrecMatch inf new_name) new_matches   `thenRn_`
-    returnRn
-      [(unitNameSet new_name,
-       fvs,
-       FunMonoBind new_name inf new_matches locn,
-       sigs_for_me
-       )]
-\end{code}
-
-
-@rnMethodBinds@ is used for the method bindings of a class and an instance
-declaration.   like @rnMonoBinds@ but without dependency analysis.
-
-\begin{code}
-rnMethodBinds :: RdrNameMonoBinds -> RnMS (RenamedMonoBinds, FreeVars)
-
-rnMethodBinds EmptyMonoBinds = returnRn (EmptyMonoBinds, emptyFVs)
-
-rnMethodBinds (AndMonoBinds mb1 mb2)
-  = rnMethodBinds mb1  `thenRn` \ (mb1', fvs1) ->
-    rnMethodBinds mb2  `thenRn` \ (mb2', fvs2) ->
-    returnRn (mb1' `AndMonoBinds` mb2', fvs1 `plusFV` fvs2)
-
-rnMethodBinds (FunMonoBind name inf matches locn)
-  = pushSrcLocRn locn                                  $
-
-    lookupGlobalOccRn name                             `thenRn` \ sel_name -> 
-       -- We use the selector name as the binder
-
-    mapFvRn rnMatch matches                            `thenRn` \ (new_matches, fvs) ->
-    mapRn_ (checkPrecMatch inf sel_name) new_matches   `thenRn_`
-    returnRn (FunMonoBind sel_name inf new_matches locn, fvs)
-
-rnMethodBinds (PatMonoBind (VarPatIn name) grhss locn)
-  = pushSrcLocRn locn                  $
-    lookupGlobalOccRn name             `thenRn` \ sel_name -> 
-    rnGRHSs grhss                      `thenRn` \ (grhss', fvs) ->
-    returnRn (PatMonoBind (VarPatIn sel_name) grhss' locn, fvs)
-
--- Can't handle method pattern-bindings which bind multiple methods.
-rnMethodBinds mbind@(PatMonoBind other_pat _ locn)
-  = pushSrcLocRn locn  $
-    failWithRn (EmptyMonoBinds, emptyFVs) (methodBindErr mbind)
-\end{code}
-
-
-%************************************************************************
-%*                                                                     *
-\subsection[reconstruct-deps]{Reconstructing dependencies}
-%*                                                                     *
-%************************************************************************
-
-This @MonoBinds@- and @ClassDecls@-specific code is segregated here,
-as the two cases are similar.
-
-\begin{code}
-reconstructCycle :: SCC FlatMonoBindsInfo
-                -> RenamedHsBinds
-
-reconstructCycle (AcyclicSCC (_, _, binds, sigs))
-  = MonoBind binds sigs NonRecursive
-
-reconstructCycle (CyclicSCC cycle)
-  = MonoBind this_gp_binds this_gp_sigs Recursive
-  where
-    this_gp_binds      = foldr1 AndMonoBinds [binds | (_, _, binds, _) <- cycle]
-    this_gp_sigs       = foldr1 (++)        [sigs  | (_, _, _, sigs) <- cycle]
-\end{code}
-
-%************************************************************************
-%*                                                                     *
-%*     Manipulating FlatMonoBindInfo                                   *
-%*                                                                     *
-%************************************************************************
-
-During analysis a @MonoBinds@ is flattened to a @FlatMonoBindsInfo@.
-The @RenamedMonoBinds@ is always an empty bind, a pattern binding or
-a function binding, and has itself been dependency-analysed and
-renamed.
-
-\begin{code}
-type FlatMonoBindsInfo
-  = (NameSet,                  -- Set of names defined in this vertex
-     NameSet,                  -- Set of names used in this vertex
-     RenamedMonoBinds,
-     [RenamedSig])             -- Signatures, if any, for this vertex
-
-mkEdges :: [(FlatMonoBindsInfo, VertexTag)] -> [(FlatMonoBindsInfo, VertexTag, [VertexTag])]
-
-mkEdges flat_info
-  = [ (info, tag, dest_vertices (nameSetToList names_used))
-    | (info@(names_defined, names_used, mbind, sigs), tag) <- flat_info
-    ]
-  where
-        -- An edge (v,v') indicates that v depends on v'
-    dest_vertices src_mentions = [ target_vertex
-                                | ((names_defined, _, _, _), target_vertex) <- flat_info,
-                                  mentioned_name <- src_mentions,
-                                  mentioned_name `elemNameSet` names_defined
-                                ]
-\end{code}
-
-
-%************************************************************************
-%*                                                                     *
-\subsubsection[dep-Sigs]{Signatures (and user-pragmas for values)}
-%*                                                                     *
-%************************************************************************
-
-@renameSigs@ checks for: (a)~more than one sig for one thing;
-(b)~signatures given for things not bound here; (c)~with suitably
-flaggery, that all top-level things have type signatures.
-
-At the moment we don't gather free-var info from the types in
-signatures.  We'd only need this if we wanted to report unused tyvars.
-
-\begin{code}
-renameSigs ::  Bool                    -- True => warn if (required) type signatures are missing.
-           -> NameSet                  -- Set of names bound in this group
-           -> (RdrName -> RnMS Name)
-           -> [RdrNameSig]
-           -> RnMS ([RenamedSig], FreeVars)             -- List of Sig constructors
-
-renameSigs sigs_required binders lookup_occ_nm sigs
-  =     -- Rename the signatures
-    mapFvRn (renameSig lookup_occ_nm) sigs     `thenRn` \ (sigs', fvs) ->
-
-       -- Check for (a) duplicate signatures
-       --           (b) signatures for things not in this group
-       --           (c) optionally, bindings with no signature
-    let
-       (goodies, dups) = removeDups cmp_sig (sigsForMe (not . isUnboundName) sigs')
-       not_this_group  = sigsForMe (not . (`elemNameSet` binders)) goodies
-       type_sig_vars   = [n | Sig n _ _     <- goodies]
-       un_sigd_binders | sigs_required = nameSetToList binders `minusList` type_sig_vars
-                       | otherwise     = []
-    in
-    mapRn_ dupSigDeclErr dups                          `thenRn_`
-    mapRn_ unknownSigErr not_this_group                        `thenRn_`
-    mapRn_ (addWarnRn.missingSigWarn) un_sigd_binders  `thenRn_`
-    returnRn (sigs', fvs)      
-               -- bad ones and all:
-               -- we need bindings of *some* sort for every name
-
--- We use lookupOccRn in the signatures, which is a little bit unsatisfactory
--- because this won't work for:
---     instance Foo T where
---       {-# INLINE op #-}
---       Baz.op = ...
--- We'll just rename the INLINE prag to refer to whatever other 'op'
--- is in scope.  (I'm assuming that Baz.op isn't in scope unqualified.)
--- Doesn't seem worth much trouble to sort this.
-
-renameSig lookup_occ_nm (Sig v ty src_loc)
-  = pushSrcLocRn src_loc $
-    lookup_occ_nm v                            `thenRn` \ new_v ->
-    rnHsSigType (quotes (ppr v)) ty            `thenRn` \ (new_ty,fvs) ->
-    returnRn (Sig new_v new_ty src_loc, fvs `addOneFV` new_v)
-
-renameSig _ (SpecInstSig ty src_loc)
-  = pushSrcLocRn src_loc $
-    rnHsSigType (text "A SPECIALISE instance pragma") ty       `thenRn` \ (new_ty, fvs) ->
-    returnRn (SpecInstSig new_ty src_loc, fvs)
-
-renameSig lookup_occ_nm (SpecSig v ty src_loc)
-  = pushSrcLocRn src_loc $
-    lookup_occ_nm v                    `thenRn` \ new_v ->
-    rnHsSigType (quotes (ppr v)) ty    `thenRn` \ (new_ty,fvs) ->
-    returnRn (SpecSig new_v new_ty src_loc, fvs `addOneFV` new_v)
-
-renameSig lookup_occ_nm (InlineSig v src_loc)
-  = pushSrcLocRn src_loc $
-    lookup_occ_nm v            `thenRn` \ new_v ->
-    returnRn (InlineSig new_v src_loc, unitFV new_v)
-
-renameSig lookup_occ_nm (FixSig (FixitySig v fix src_loc))
-  = pushSrcLocRn src_loc $
-    lookup_occ_nm v            `thenRn` \ new_v ->
-    returnRn (FixSig (FixitySig new_v fix src_loc), unitFV new_v)
-
-renameSig lookup_occ_nm (NoInlineSig v src_loc)
-  = pushSrcLocRn src_loc $
-    lookup_occ_nm v            `thenRn` \ new_v ->
-    returnRn (NoInlineSig new_v src_loc, unitFV new_v)
-\end{code}
-
-Checking for distinct signatures; oh, so boring
-
-\begin{code}
-cmp_sig :: RenamedSig -> RenamedSig -> Ordering
-cmp_sig (Sig n1 _ _)        (Sig n2 _ _)         = n1 `compare` n2
-cmp_sig (InlineSig n1 _)     (InlineSig n2 _)    = n1 `compare` n2
-cmp_sig (NoInlineSig n1 _)   (NoInlineSig n2 _)          = n1 `compare` n2
-cmp_sig (SpecInstSig ty1 _)  (SpecInstSig ty2 _)  = cmpHsType compare ty1 ty2
-cmp_sig (SpecSig n1 ty1 _)   (SpecSig n2 ty2 _) 
-  = -- may have many specialisations for one value;
-    -- but not ones that are exactly the same...
-       thenCmp (n1 `compare` n2) (cmpHsType compare ty1 ty2)
-
-cmp_sig other_1 other_2                                        -- Tags *must* be different
-  | (sig_tag other_1) _LT_ (sig_tag other_2) = LT 
-  | otherwise                               = GT
-
-sig_tag (Sig n1 _ _)              = (ILIT(1) :: FAST_INT)
-sig_tag (SpecSig n1 _ _)          = ILIT(2)
-sig_tag (InlineSig n1 _)          = ILIT(3)
-sig_tag (NoInlineSig n1 _)        = ILIT(4)
-sig_tag (SpecInstSig _ _)         = ILIT(5)
-sig_tag (FixSig _)                = ILIT(6)
-sig_tag _                         = panic# "tag(RnBinds)"
-\end{code}
-
-%************************************************************************
-%*                                                                     *
-\subsection{Error messages}
-%*                                                                     *
-%************************************************************************
-
-\begin{code}
-dupSigDeclErr (sig:sigs)
-  = pushSrcLocRn loc $
-    addErrRn (sep [ptext SLIT("Duplicate") <+> ptext what_it_is <> colon,
-                  ppr sig])
-  where
-    (what_it_is, loc) = sig_doc sig
-
-unknownSigErr sig
-  = pushSrcLocRn loc $
-    addErrRn (sep [ptext SLIT("Misplaced"),
-                  ptext what_it_is <> colon,
-                  ppr sig])
-  where
-    (what_it_is, loc) = sig_doc sig
-
-sig_doc (Sig        _ _ loc)        = (SLIT("type signature"),loc)
-sig_doc (ClassOpSig _ _ _ loc)              = (SLIT("class-method type signature"), loc)
-sig_doc (SpecSig    _ _ loc)        = (SLIT("SPECIALISE pragma"),loc)
-sig_doc (InlineSig  _     loc)              = (SLIT("INLINE pragma"),loc)
-sig_doc (NoInlineSig  _   loc)              = (SLIT("NOINLINE pragma"),loc)
-sig_doc (SpecInstSig _ loc)         = (SLIT("SPECIALISE instance pragma"),loc)
-sig_doc (FixSig (FixitySig _ _ loc)) = (SLIT("fixity declaration"), loc)
-
-missingSigWarn var
-  = sep [ptext SLIT("definition but no type signature for"), quotes (ppr var)]
-
-methodBindErr mbind
- =  hang (ptext SLIT("Can't handle multiple methods defined by one pattern binding"))
-       4 (ppr mbind)
-\end{code}
+%\r
+% (c) The GRASP/AQUA Project, Glasgow University, 1992-1998\r
+%\r
+\section[RnBinds]{Renaming and dependency analysis of bindings}\r
+\r
+This module does renaming and dependency analysis on value bindings in\r
+the abstract syntax.  It does {\em not} do cycle-checks on class or\r
+type-synonym declarations; those cannot be done at this stage because\r
+they may be affected by renaming (which isn't fully worked out yet).\r
+\r
+\begin{code}\r
+module RnBinds (\r
+       rnTopBinds, rnTopMonoBinds,\r
+       rnMethodBinds, renameSigs,\r
+       rnBinds,\r
+       unknownSigErr\r
+   ) where\r
+\r
+#include "HsVersions.h"\r
+\r
+import {-# SOURCE #-} RnSource ( rnHsSigType )\r
+\r
+import HsSyn\r
+import HsBinds         ( sigsForMe )\r
+import RdrHsSyn\r
+import RnHsSyn\r
+import RnMonad\r
+import RnExpr          ( rnMatch, rnGRHSs, rnPat, checkPrecMatch )\r
+import RnEnv           ( bindLocatedLocalsRn, lookupBndrRn, lookupGlobalOccRn,\r
+                         warnUnusedLocalBinds, mapFvRn, \r
+                         FreeVars, emptyFVs, plusFV, plusFVs, unitFV, addOneFV,\r
+                         unknownNameErr\r
+                       )\r
+import CmdLineOpts     ( opt_WarnMissingSigs )\r
+import Digraph         ( stronglyConnComp, SCC(..) )\r
+import Name            ( OccName, Name, nameOccName )\r
+import NameSet\r
+import RdrName         ( RdrName, rdrNameOcc  )\r
+import BasicTypes      ( RecFlag(..), TopLevelFlag(..) )\r
+import Util            ( thenCmp, removeDups )\r
+import List            ( partition )\r
+import ListSetOps      ( minusList )\r
+import Bag             ( bagToList )\r
+import FiniteMap       ( lookupFM, listToFM )\r
+import Maybe           ( isJust )\r
+import Outputable\r
+\end{code}\r
+\r
+-- ToDo: Put the annotations into the monad, so that they arrive in the proper\r
+-- place and can be used when complaining.\r
+\r
+The code tree received by the function @rnBinds@ contains definitions\r
+in where-clauses which are all apparently mutually recursive, but which may\r
+not really depend upon each other. For example, in the top level program\r
+\begin{verbatim}\r
+f x = y where a = x\r
+             y = x\r
+\end{verbatim}\r
+the definitions of @a@ and @y@ do not depend on each other at all.\r
+Unfortunately, the typechecker cannot always check such definitions.\r
+\footnote{Mycroft, A. 1984. Polymorphic type schemes and recursive\r
+definitions. In Proceedings of the International Symposium on Programming,\r
+Toulouse, pp. 217-39. LNCS 167. Springer Verlag.}\r
+However, the typechecker usually can check definitions in which only the\r
+strongly connected components have been collected into recursive bindings.\r
+This is precisely what the function @rnBinds@ does.\r
+\r
+ToDo: deal with case where a single monobinds binds the same variable\r
+twice.\r
+\r
+The vertag tag is a unique @Int@; the tags only need to be unique\r
+within one @MonoBinds@, so that unique-Int plumbing is done explicitly\r
+(heavy monad machinery not needed).\r
+\r
+\begin{code}\r
+type VertexTag = Int\r
+type Cycle     = [VertexTag]\r
+type Edge      = (VertexTag, VertexTag)\r
+\end{code}\r
+\r
+%************************************************************************\r
+%*                                                                     *\r
+%* naming conventions                                                  *\r
+%*                                                                     *\r
+%************************************************************************\r
+\r
+\subsection[name-conventions]{Name conventions}\r
+\r
+The basic algorithm involves walking over the tree and returning a tuple\r
+containing the new tree plus its free variables. Some functions, such\r
+as those walking polymorphic bindings (HsBinds) and qualifier lists in\r
+list comprehensions (@Quals@), return the variables bound in local\r
+environments. These are then used to calculate the free variables of the\r
+expression evaluated in these environments.\r
+\r
+Conventions for variable names are as follows:\r
+\begin{itemize}\r
+\item\r
+new code is given a prime to distinguish it from the old.\r
+\r
+\item\r
+a set of variables defined in @Exp@ is written @dvExp@\r
+\r
+\item\r
+a set of variables free in @Exp@ is written @fvExp@\r
+\end{itemize}\r
+\r
+%************************************************************************\r
+%*                                                                     *\r
+%* analysing polymorphic bindings (HsBinds, Bind, MonoBinds)           *\r
+%*                                                                     *\r
+%************************************************************************\r
+\r
+\subsubsection[dep-HsBinds]{Polymorphic bindings}\r
+\r
+Non-recursive expressions are reconstructed without any changes at top\r
+level, although their component expressions may have to be altered.\r
+However, non-recursive expressions are currently not expected as\r
+\Haskell{} programs, and this code should not be executed.\r
+\r
+Monomorphic bindings contain information that is returned in a tuple\r
+(a @FlatMonoBindsInfo@) containing:\r
+\r
+\begin{enumerate}\r
+\item\r
+a unique @Int@ that serves as the ``vertex tag'' for this binding.\r
+\r
+\item\r
+the name of a function or the names in a pattern. These are a set\r
+referred to as @dvLhs@, the defined variables of the left hand side.\r
+\r
+\item\r
+the free variables of the body. These are referred to as @fvBody@.\r
+\r
+\item\r
+the definition's actual code. This is referred to as just @code@.\r
+\end{enumerate}\r
+\r
+The function @nonRecDvFv@ returns two sets of variables. The first is\r
+the set of variables defined in the set of monomorphic bindings, while the\r
+second is the set of free variables in those bindings.\r
+\r
+The set of variables defined in a non-recursive binding is just the\r
+union of all of them, as @union@ removes duplicates. However, the\r
+free variables in each successive set of cumulative bindings is the\r
+union of those in the previous set plus those of the newest binding after\r
+the defined variables of the previous set have been removed.\r
+\r
+@rnMethodBinds@ deals only with the declarations in class and\r
+instance declarations. It expects only to see @FunMonoBind@s, and\r
+it expects the global environment to contain bindings for the binders\r
+(which are all class operations).\r
+\r
+%************************************************************************\r
+%*                                                                     *\r
+%*             Top-level bindings\r
+%*                                                                     *\r
+%************************************************************************\r
+\r
+@rnTopBinds@ assumes that the environment already\r
+contains bindings for the binders of this particular binding.\r
+\r
+\begin{code}\r
+rnTopBinds    :: RdrNameHsBinds -> RnMS (RenamedHsBinds, FreeVars)\r
+\r
+rnTopBinds EmptyBinds                    = returnRn (EmptyBinds, emptyFVs)\r
+rnTopBinds (MonoBind bind sigs _)        = rnTopMonoBinds bind sigs\r
+  -- The parser doesn't produce other forms\r
+\r
+\r
+rnTopMonoBinds EmptyMonoBinds sigs \r
+  = returnRn (EmptyBinds, emptyFVs)\r
+\r
+rnTopMonoBinds mbinds sigs\r
+ =  mapRn lookupBndrRn binder_rdr_names        `thenRn` \ binder_names ->\r
+    let\r
+       binder_set    = mkNameSet binder_names\r
+       binder_occ_fm = listToFM [(nameOccName x,x) | x <- binder_names]\r
+    in\r
+    renameSigs opt_WarnMissingSigs binder_set\r
+              (lookupSigOccRn binder_occ_fm) sigs      `thenRn` \ (siglist, sig_fvs) ->\r
+    rn_mono_binds siglist mbinds                       `thenRn` \ (final_binds, bind_fvs) ->\r
+    returnRn (final_binds, bind_fvs `plusFV` sig_fvs)\r
+  where\r
+    binder_rdr_names = map fst (bagToList (collectMonoBinders mbinds))\r
+\r
+-- the names appearing in the sigs have to be bound by \r
+-- this group's binders.\r
+lookupSigOccRn binder_occ_fm rdr_name\r
+  = case lookupFM binder_occ_fm (rdrNameOcc rdr_name) of\r
+       Nothing -> failWithRn (mkUnboundName rdr_name)\r
+                             (unknownNameErr rdr_name)\r
+       Just x  -> returnRn x\r
+\end{code}\r
+\r
+%************************************************************************\r
+%*                                                                     *\r
+%*             Nested binds\r
+%*                                                                     *\r
+%************************************************************************\r
+\r
+@rnMonoBinds@\r
+       - collects up the binders for this declaration group,\r
+       - checks that they form a set\r
+       - extends the environment to bind them to new local names\r
+       - calls @rnMonoBinds@ to do the real work\r
+\r
+\begin{code}\r
+rnBinds              :: RdrNameHsBinds \r
+             -> (RenamedHsBinds -> RnMS (result, FreeVars))\r
+             -> RnMS (result, FreeVars)\r
+\r
+rnBinds EmptyBinds            thing_inside = thing_inside EmptyBinds\r
+rnBinds (MonoBind bind sigs _) thing_inside = rnMonoBinds bind sigs thing_inside\r
+  -- the parser doesn't produce other forms\r
+\r
+\r
+rnMonoBinds :: RdrNameMonoBinds \r
+            -> [RdrNameSig]\r
+           -> (RenamedHsBinds -> RnMS (result, FreeVars))\r
+           -> RnMS (result, FreeVars)\r
+\r
+rnMonoBinds EmptyMonoBinds sigs thing_inside = thing_inside EmptyBinds\r
+\r
+rnMonoBinds mbinds sigs        thing_inside -- Non-empty monobinds\r
+  =    -- Extract all the binders in this group,\r
+       -- and extend current scope, inventing new names for the new binders\r
+       -- This also checks that the names form a set\r
+    bindLocatedLocalsRn (text "a binding group") mbinders_w_srclocs            $ \ new_mbinders ->\r
+    let\r
+       binder_set  = mkNameSet new_mbinders\r
+\r
+          -- Weed out the fixity declarations that do not\r
+          -- apply to any of the binders in this group.\r
+       (sigs_for_me, fixes_not_for_me) = partition forLocalBind sigs\r
+\r
+       forLocalBind (FixSig sig@(FixitySig name _ _ )) =\r
+           isJust (lookupFM binder_occ_fm (rdrNameOcc name))\r
+       forLocalBind _ = True\r
+\r
+       binder_occ_fm = listToFM [(nameOccName x,x) | x <- new_mbinders]\r
+\r
+    in\r
+       -- Report the fixity declarations in this group that \r
+       -- don't refer to any of the group's binders.\r
+       --\r
+    mapRn_ (unknownSigErr) fixes_not_for_me     `thenRn_`\r
+    renameSigs False binder_set\r
+              (lookupSigOccRn binder_occ_fm) sigs_for_me   `thenRn` \ (siglist, sig_fvs) ->\r
+    let\r
+       fixity_sigs = [(name,sig) | FixSig sig@(FixitySig name _ _) <- siglist ]\r
+    in\r
+       -- Install the fixity declarations that do apply here and go.\r
+    extendFixityEnv fixity_sigs (\r
+      rn_mono_binds siglist mbinds\r
+    )                                     `thenRn` \ (binds, bind_fvs) ->\r
+\r
+       -- Now do the "thing inside", and deal with the free-variable calculations\r
+    thing_inside binds                                 `thenRn` \ (result,result_fvs) ->\r
+    let\r
+       all_fvs        = result_fvs `plusFV` bind_fvs `plusFV` sig_fvs\r
+       unused_binders = nameSetToList (binder_set `minusNameSet` all_fvs)\r
+    in\r
+    warnUnusedLocalBinds unused_binders        `thenRn_`\r
+    returnRn (result, delListFromNameSet all_fvs new_mbinders)\r
+  where\r
+    mbinders_w_srclocs = bagToList (collectMonoBinders mbinds)\r
+\end{code}\r
+\r
+\r
+%************************************************************************\r
+%*                                                                     *\r
+%*             MonoBinds -- the main work is done here\r
+%*                                                                     *\r
+%************************************************************************\r
+\r
+@rn_mono_binds@ is used by *both* top-level and nested bindings.  It\r
+assumes that all variables bound in this group are already in scope.\r
+This is done *either* by pass 3 (for the top-level bindings), *or* by\r
+@rnMonoBinds@ (for the nested ones).\r
+\r
+\begin{code}\r
+rn_mono_binds :: [RenamedSig]          -- Signatures attached to this group\r
+             -> RdrNameMonoBinds       \r
+             -> RnMS (RenamedHsBinds,  -- \r
+                        FreeVars)      -- Free variables\r
+\r
+rn_mono_binds siglist mbinds\r
+  =\r
+        -- Rename the bindings, returning a MonoBindsInfo\r
+        -- which is a list of indivisible vertices so far as\r
+        -- the strongly-connected-components (SCC) analysis is concerned\r
+    flattenMonoBinds siglist mbinds            `thenRn` \ mbinds_info ->\r
+\r
+        -- Do the SCC analysis\r
+    let \r
+        edges      = mkEdges (mbinds_info `zip` [(0::Int)..])\r
+       scc_result  = stronglyConnComp edges\r
+       final_binds = foldr1 ThenBinds (map reconstructCycle scc_result)\r
+\r
+        -- Deal with bound and free-var calculation\r
+       rhs_fvs = plusFVs [fvs | (_,fvs,_,_) <- mbinds_info]\r
+    in\r
+    returnRn (final_binds, rhs_fvs)\r
+\end{code}\r
+\r
+@flattenMonoBinds@ is ever-so-slightly magical in that it sticks\r
+unique ``vertex tags'' on its output; minor plumbing required.\r
+\r
+Sigh - need to pass along the signatures for the group of bindings,\r
+in case any of them \r
+\r
+\begin{code}\r
+flattenMonoBinds :: [RenamedSig]               -- Signatures\r
+                -> RdrNameMonoBinds\r
+                -> RnMS [FlatMonoBindsInfo]\r
+\r
+flattenMonoBinds sigs EmptyMonoBinds = returnRn []\r
+\r
+flattenMonoBinds sigs (AndMonoBinds bs1 bs2)\r
+  = flattenMonoBinds sigs bs1  `thenRn` \ flat1 ->\r
+    flattenMonoBinds sigs bs2  `thenRn` \ flat2 ->\r
+    returnRn (flat1 ++ flat2)\r
+\r
+flattenMonoBinds sigs (PatMonoBind pat grhss locn)\r
+  = pushSrcLocRn locn                  $\r
+    rnPat pat                          `thenRn` \ (pat', pat_fvs) ->\r
+\r
+        -- Find which things are bound in this group\r
+    let\r
+       names_bound_here = mkNameSet (collectPatBinders pat')\r
+       sigs_for_me      = sigsForMe (`elemNameSet` names_bound_here) sigs\r
+    in\r
+    rnGRHSs grhss                      `thenRn` \ (grhss', fvs) ->\r
+    returnRn \r
+       [(names_bound_here,\r
+         fvs `plusFV` pat_fvs,\r
+         PatMonoBind pat' grhss' locn,\r
+         sigs_for_me\r
+        )]\r
+\r
+flattenMonoBinds sigs (FunMonoBind name inf matches locn)\r
+  = pushSrcLocRn locn                                  $\r
+    lookupBndrRn name                                  `thenRn` \ new_name ->\r
+    let\r
+       sigs_for_me = sigsForMe (new_name ==) sigs\r
+    in\r
+    mapFvRn rnMatch matches                            `thenRn` \ (new_matches, fvs) ->\r
+    mapRn_ (checkPrecMatch inf new_name) new_matches   `thenRn_`\r
+    returnRn\r
+      [(unitNameSet new_name,\r
+       fvs,\r
+       FunMonoBind new_name inf new_matches locn,\r
+       sigs_for_me\r
+       )]\r
+\end{code}\r
+\r
+\r
+@rnMethodBinds@ is used for the method bindings of a class and an instance\r
+declaration.   like @rnMonoBinds@ but without dependency analysis.\r
+\r
+NOTA BENE: we record each *binder* of a method-bind group as a free variable.\r
+That's crucial when dealing with an instance decl:\r
+       instance Foo (T a) where\r
+          op x = ...\r
+This might be the *sole* occurrence of 'op' for an imported class Foo,\r
+and unless op occurs we won't treat the type signature of op in the class\r
+decl for Foo as a source of instance-decl gates.  But we should!  Indeed,\r
+in many ways the op in an instance decl is just like an occurrence, not\r
+a binder.\r
+\r
+\begin{code}\r
+rnMethodBinds :: RdrNameMonoBinds -> RnMS (RenamedMonoBinds, FreeVars)\r
+\r
+rnMethodBinds EmptyMonoBinds = returnRn (EmptyMonoBinds, emptyFVs)\r
+\r
+rnMethodBinds (AndMonoBinds mb1 mb2)\r
+  = rnMethodBinds mb1  `thenRn` \ (mb1', fvs1) ->\r
+    rnMethodBinds mb2  `thenRn` \ (mb2', fvs2) ->\r
+    returnRn (mb1' `AndMonoBinds` mb2', fvs1 `plusFV` fvs2)\r
+\r
+rnMethodBinds (FunMonoBind name inf matches locn)\r
+  = pushSrcLocRn locn                                  $\r
+\r
+    lookupGlobalOccRn name                             `thenRn` \ sel_name -> \r
+       -- We use the selector name as the binder\r
+\r
+    mapFvRn rnMatch matches                            `thenRn` \ (new_matches, fvs) ->\r
+    mapRn_ (checkPrecMatch inf sel_name) new_matches   `thenRn_`\r
+    returnRn (FunMonoBind sel_name inf new_matches locn, fvs `addOneFV` sel_name)\r
+\r
+rnMethodBinds (PatMonoBind (VarPatIn name) grhss locn)\r
+  = pushSrcLocRn locn                  $\r
+    lookupGlobalOccRn name             `thenRn` \ sel_name -> \r
+    rnGRHSs grhss                      `thenRn` \ (grhss', fvs) ->\r
+    returnRn (PatMonoBind (VarPatIn sel_name) grhss' locn, fvs `addOneFV` sel_name)\r
+\r
+-- Can't handle method pattern-bindings which bind multiple methods.\r
+rnMethodBinds mbind@(PatMonoBind other_pat _ locn)\r
+  = pushSrcLocRn locn  $\r
+    failWithRn (EmptyMonoBinds, emptyFVs) (methodBindErr mbind)\r
+\end{code}\r
+\r
+\r
+%************************************************************************\r
+%*                                                                     *\r
+\subsection[reconstruct-deps]{Reconstructing dependencies}\r
+%*                                                                     *\r
+%************************************************************************\r
+\r
+This @MonoBinds@- and @ClassDecls@-specific code is segregated here,\r
+as the two cases are similar.\r
+\r
+\begin{code}\r
+reconstructCycle :: SCC FlatMonoBindsInfo\r
+                -> RenamedHsBinds\r
+\r
+reconstructCycle (AcyclicSCC (_, _, binds, sigs))\r
+  = MonoBind binds sigs NonRecursive\r
+\r
+reconstructCycle (CyclicSCC cycle)\r
+  = MonoBind this_gp_binds this_gp_sigs Recursive\r
+  where\r
+    this_gp_binds      = foldr1 AndMonoBinds [binds | (_, _, binds, _) <- cycle]\r
+    this_gp_sigs       = foldr1 (++)        [sigs  | (_, _, _, sigs) <- cycle]\r
+\end{code}\r
+\r
+%************************************************************************\r
+%*                                                                     *\r
+%*     Manipulating FlatMonoBindInfo                                   *\r
+%*                                                                     *\r
+%************************************************************************\r
+\r
+During analysis a @MonoBinds@ is flattened to a @FlatMonoBindsInfo@.\r
+The @RenamedMonoBinds@ is always an empty bind, a pattern binding or\r
+a function binding, and has itself been dependency-analysed and\r
+renamed.\r
+\r
+\begin{code}\r
+type FlatMonoBindsInfo\r
+  = (NameSet,                  -- Set of names defined in this vertex\r
+     NameSet,                  -- Set of names used in this vertex\r
+     RenamedMonoBinds,\r
+     [RenamedSig])             -- Signatures, if any, for this vertex\r
+\r
+mkEdges :: [(FlatMonoBindsInfo, VertexTag)] -> [(FlatMonoBindsInfo, VertexTag, [VertexTag])]\r
+\r
+mkEdges flat_info\r
+  = [ (info, tag, dest_vertices (nameSetToList names_used))\r
+    | (info@(names_defined, names_used, mbind, sigs), tag) <- flat_info\r
+    ]\r
+  where\r
+        -- An edge (v,v') indicates that v depends on v'\r
+    dest_vertices src_mentions = [ target_vertex\r
+                                | ((names_defined, _, _, _), target_vertex) <- flat_info,\r
+                                  mentioned_name <- src_mentions,\r
+                                  mentioned_name `elemNameSet` names_defined\r
+                                ]\r
+\end{code}\r
+\r
+\r
+%************************************************************************\r
+%*                                                                     *\r
+\subsubsection[dep-Sigs]{Signatures (and user-pragmas for values)}\r
+%*                                                                     *\r
+%************************************************************************\r
+\r
+@renameSigs@ checks for: (a)~more than one sig for one thing;\r
+(b)~signatures given for things not bound here; (c)~with suitably\r
+flaggery, that all top-level things have type signatures.\r
+\r
+At the moment we don't gather free-var info from the types in\r
+signatures.  We'd only need this if we wanted to report unused tyvars.\r
+\r
+\begin{code}\r
+renameSigs ::  Bool                    -- True => warn if (required) type signatures are missing.\r
+           -> NameSet                  -- Set of names bound in this group\r
+           -> (RdrName -> RnMS Name)\r
+           -> [RdrNameSig]\r
+           -> RnMS ([RenamedSig], FreeVars)             -- List of Sig constructors\r
+\r
+renameSigs sigs_required binders lookup_occ_nm sigs\r
+  =     -- Rename the signatures\r
+    mapFvRn (renameSig lookup_occ_nm) sigs     `thenRn` \ (sigs', fvs) ->\r
+\r
+       -- Check for (a) duplicate signatures\r
+       --           (b) signatures for things not in this group\r
+       --           (c) optionally, bindings with no signature\r
+    let\r
+       (goodies, dups) = removeDups cmp_sig (sigsForMe (not . isUnboundName) sigs')\r
+       not_this_group  = sigsForMe (not . (`elemNameSet` binders)) goodies\r
+       type_sig_vars   = [n | Sig n _ _     <- goodies]\r
+       un_sigd_binders | sigs_required = nameSetToList binders `minusList` type_sig_vars\r
+                       | otherwise     = []\r
+    in\r
+    mapRn_ dupSigDeclErr dups                          `thenRn_`\r
+    mapRn_ unknownSigErr not_this_group                        `thenRn_`\r
+    mapRn_ (addWarnRn.missingSigWarn) un_sigd_binders  `thenRn_`\r
+    returnRn (sigs', fvs)      \r
+               -- bad ones and all:\r
+               -- we need bindings of *some* sort for every name\r
+\r
+-- We use lookupOccRn in the signatures, which is a little bit unsatisfactory\r
+-- because this won't work for:\r
+--     instance Foo T where\r
+--       {-# INLINE op #-}\r
+--       Baz.op = ...\r
+-- We'll just rename the INLINE prag to refer to whatever other 'op'\r
+-- is in scope.  (I'm assuming that Baz.op isn't in scope unqualified.)\r
+-- Doesn't seem worth much trouble to sort this.\r
+\r
+renameSig lookup_occ_nm (Sig v ty src_loc)\r
+  = pushSrcLocRn src_loc $\r
+    lookup_occ_nm v                            `thenRn` \ new_v ->\r
+    rnHsSigType (quotes (ppr v)) ty            `thenRn` \ (new_ty,fvs) ->\r
+    returnRn (Sig new_v new_ty src_loc, fvs `addOneFV` new_v)\r
+\r
+renameSig _ (SpecInstSig ty src_loc)\r
+  = pushSrcLocRn src_loc $\r
+    rnHsSigType (text "A SPECIALISE instance pragma") ty       `thenRn` \ (new_ty, fvs) ->\r
+    returnRn (SpecInstSig new_ty src_loc, fvs)\r
+\r
+renameSig lookup_occ_nm (SpecSig v ty src_loc)\r
+  = pushSrcLocRn src_loc $\r
+    lookup_occ_nm v                    `thenRn` \ new_v ->\r
+    rnHsSigType (quotes (ppr v)) ty    `thenRn` \ (new_ty,fvs) ->\r
+    returnRn (SpecSig new_v new_ty src_loc, fvs `addOneFV` new_v)\r
+\r
+renameSig lookup_occ_nm (InlineSig v src_loc)\r
+  = pushSrcLocRn src_loc $\r
+    lookup_occ_nm v            `thenRn` \ new_v ->\r
+    returnRn (InlineSig new_v src_loc, unitFV new_v)\r
+\r
+renameSig lookup_occ_nm (FixSig (FixitySig v fix src_loc))\r
+  = pushSrcLocRn src_loc $\r
+    lookup_occ_nm v            `thenRn` \ new_v ->\r
+    returnRn (FixSig (FixitySig new_v fix src_loc), unitFV new_v)\r
+\r
+renameSig lookup_occ_nm (NoInlineSig v src_loc)\r
+  = pushSrcLocRn src_loc $\r
+    lookup_occ_nm v            `thenRn` \ new_v ->\r
+    returnRn (NoInlineSig new_v src_loc, unitFV new_v)\r
+\end{code}\r
+\r
+Checking for distinct signatures; oh, so boring\r
+\r
+\begin{code}\r
+cmp_sig :: RenamedSig -> RenamedSig -> Ordering\r
+cmp_sig (Sig n1 _ _)        (Sig n2 _ _)         = n1 `compare` n2\r
+cmp_sig (InlineSig n1 _)     (InlineSig n2 _)    = n1 `compare` n2\r
+cmp_sig (NoInlineSig n1 _)   (NoInlineSig n2 _)          = n1 `compare` n2\r
+cmp_sig (SpecInstSig ty1 _)  (SpecInstSig ty2 _)  = cmpHsType compare ty1 ty2\r
+cmp_sig (SpecSig n1 ty1 _)   (SpecSig n2 ty2 _) \r
+  = -- may have many specialisations for one value;\r
+    -- but not ones that are exactly the same...\r
+       thenCmp (n1 `compare` n2) (cmpHsType compare ty1 ty2)\r
+\r
+cmp_sig other_1 other_2                                        -- Tags *must* be different\r
+  | (sig_tag other_1) _LT_ (sig_tag other_2) = LT \r
+  | otherwise                               = GT\r
+\r
+sig_tag (Sig n1 _ _)              = (ILIT(1) :: FAST_INT)\r
+sig_tag (SpecSig n1 _ _)          = ILIT(2)\r
+sig_tag (InlineSig n1 _)          = ILIT(3)\r
+sig_tag (NoInlineSig n1 _)        = ILIT(4)\r
+sig_tag (SpecInstSig _ _)         = ILIT(5)\r
+sig_tag (FixSig _)                = ILIT(6)\r
+sig_tag _                         = panic# "tag(RnBinds)"\r
+\end{code}\r
+\r
+%************************************************************************\r
+%*                                                                     *\r
+\subsection{Error messages}\r
+%*                                                                     *\r
+%************************************************************************\r
+\r
+\begin{code}\r
+dupSigDeclErr (sig:sigs)\r
+  = pushSrcLocRn loc $\r
+    addErrRn (sep [ptext SLIT("Duplicate") <+> ptext what_it_is <> colon,\r
+                  ppr sig])\r
+  where\r
+    (what_it_is, loc) = sig_doc sig\r
+\r
+unknownSigErr sig\r
+  = pushSrcLocRn loc $\r
+    addErrRn (sep [ptext SLIT("Misplaced"),\r
+                  ptext what_it_is <> colon,\r
+                  ppr sig])\r
+  where\r
+    (what_it_is, loc) = sig_doc sig\r
+\r
+sig_doc (Sig        _ _ loc)        = (SLIT("type signature"),loc)\r
+sig_doc (ClassOpSig _ _ _ loc)              = (SLIT("class-method type signature"), loc)\r
+sig_doc (SpecSig    _ _ loc)        = (SLIT("SPECIALISE pragma"),loc)\r
+sig_doc (InlineSig  _     loc)              = (SLIT("INLINE pragma"),loc)\r
+sig_doc (NoInlineSig  _   loc)              = (SLIT("NOINLINE pragma"),loc)\r
+sig_doc (SpecInstSig _ loc)         = (SLIT("SPECIALISE instance pragma"),loc)\r
+sig_doc (FixSig (FixitySig _ _ loc)) = (SLIT("fixity declaration"), loc)\r
+\r
+missingSigWarn var\r
+  = sep [ptext SLIT("definition but no type signature for"), quotes (ppr var)]\r
+\r
+methodBindErr mbind\r
+ =  hang (ptext SLIT("Can't handle multiple methods defined by one pattern binding"))\r
+       4 (ppr mbind)\r
+\end{code}\r
index 687451c..b303525 100644 (file)
-%
-% (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
-%
-\section[RnMonad]{The monad used by the renamer}
-
-\begin{code}
-module RnMonad(
-       module RnMonad,
-       Module,
-       FiniteMap,
-       Bag,
-       Name,
-       RdrNameHsDecl,
-       RdrNameInstDecl,
-       Version,
-       NameSet,
-       OccName,
-       Fixity
-    ) where
-
-#include "HsVersions.h"
-
-import PrelIOBase      ( fixIO )       -- Should be in GlaExts
-import IOExts          ( IORef, newIORef, readIORef, writeIORef, unsafePerformIO )
-       
-import HsSyn           
-import RdrHsSyn
-import RnHsSyn         ( RenamedFixitySig )
-import BasicTypes      ( Version )
-import SrcLoc          ( noSrcLoc )
-import ErrUtils                ( addShortErrLocLine, addShortWarnLocLine,
-                         pprBagOfErrors, ErrMsg, WarnMsg, Message
-                       )
-import Name            ( Name, OccName, NamedThing(..),
-                         isLocallyDefinedName, nameModule, nameOccName,
-                         decode, mkLocalName
-                       )
-import Module          ( Module, ModuleName, ModuleHiMap, SearchPath, WhereFrom,
-                         mkModuleHiMaps, moduleName
-                       )
-import NameSet         
-import RdrName         ( RdrName, dummyRdrVarName, rdrNameOcc )
-import CmdLineOpts     ( opt_D_dump_rn_trace, opt_IgnoreIfacePragmas )
-import PrelInfo                ( builtinNames )
-import TysWiredIn      ( boolTyCon )
-import SrcLoc          ( SrcLoc, mkGeneratedSrcLoc )
-import Unique          ( Unique, getUnique, unboundKey )
-import UniqFM          ( UniqFM )
-import FiniteMap       ( FiniteMap, emptyFM, bagToFM, lookupFM, addToFM, addListToFM, 
-                         addListToFM_C, addToFM_C, eltsFM, fmToList
-                       )
-import Bag             ( Bag, mapBag, emptyBag, isEmptyBag, snocBag )
-import Maybes          ( mapMaybe )
-import UniqSet
-import UniqFM
-import UniqSupply
-import Util
-import Outputable
-
-infixr 9 `thenRn`, `thenRn_`
-\end{code}
-
-
-%************************************************************************
-%*                                                                     *
-\subsection{Somewhat magical interface to other monads}
-%*                                                                     *
-%************************************************************************
-
-\begin{code}
-ioToRnM :: IO r -> RnM d (Either IOError r)
-ioToRnM io rn_down g_down = (io >>= \ ok -> return (Right ok)) 
-                           `catch` 
-                           (\ err -> return (Left err))
-           
-traceRn :: SDoc -> RnM d ()
-traceRn msg | opt_D_dump_rn_trace = putDocRn msg
-           | otherwise           = returnRn ()
-
-putDocRn :: SDoc -> RnM d ()
-putDocRn msg = ioToRnM (printErrs msg) `thenRn_`
-              returnRn ()
-\end{code}
-
-
-%************************************************************************
-%*                                                                     *
-\subsection{Data types}
-%*                                                                     *
-%************************************************************************
-
-===================================================
-               MONAD TYPES
-===================================================
-
-\begin{code}
-type RnM d r = RnDown -> d -> IO r
-type RnMS r  = RnM SDown r             -- Renaming source
-type RnMG r  = RnM ()    r             -- Getting global names etc
-
-       -- Common part
-data RnDown = RnDown {
-                 rn_mod     :: ModuleName,
-                 rn_loc     :: SrcLoc,
-                 rn_omit    :: Name -> Bool,                   -- True <=> omit qualifier when printing
-                 rn_ns      :: IORef RnNameSupply,
-                 rn_errs    :: IORef (Bag WarnMsg, Bag ErrMsg),
-                 rn_ifaces  :: IORef Ifaces,
-                 rn_hi_maps :: (ModuleHiMap,   -- for .hi files
-                                ModuleHiMap)   -- for .hi-boot files
-               }
-
-       -- For renaming source code
-data SDown = SDown {
-                 rn_mode :: RnMode,
-
-                 rn_genv :: GlobalRdrEnv,      -- Global envt; the fixity component gets extended
-                                               --   with local fixity decls
-
-                 rn_lenv :: LocalRdrEnv,       -- Local name envt
-                                       --   Does *not* includes global name envt; may shadow it
-                                       --   Includes both ordinary variables and type variables;
-                                       --   they are kept distinct because tyvar have a different
-                                       --   occurrence contructor (Name.TvOcc)
-                                       -- We still need the unsullied global name env so that
-                                       --   we can look up record field names
-
-                 rn_fixenv :: FixityEnv        -- Local fixities
-                                               -- The global ones are held in the
-                                               -- rn_ifaces field
-               }
-
-data RnMode    = SourceMode                    -- Renaming source code
-               | InterfaceMode                 -- Renaming interface declarations.  
-\end{code}
-
-===================================================
-               ENVIRONMENTS
-===================================================
-
-\begin{code}
---------------------------------
-type RdrNameEnv a = FiniteMap RdrName a
-type GlobalRdrEnv = RdrNameEnv [Name]  -- The list is because there may be name clashes
-                                       -- These only get reported on lookup,
-                                       -- not on construction
-type LocalRdrEnv  = RdrNameEnv Name
-
-emptyRdrEnv  :: RdrNameEnv a
-lookupRdrEnv :: RdrNameEnv a -> RdrName -> Maybe a
-addListToRdrEnv :: RdrNameEnv a -> [(RdrName,a)] -> RdrNameEnv a
-extendRdrEnv   :: RdrNameEnv a -> RdrName -> a -> RdrNameEnv a
-
-emptyRdrEnv  = emptyFM
-lookupRdrEnv = lookupFM
-addListToRdrEnv = addListToFM
-rdrEnvElts     = eltsFM
-extendRdrEnv    = addToFM
-rdrEnvToList    = fmToList
-
---------------------------------
-type NameEnv a = UniqFM a      -- Domain is Name
-
-emptyNameEnv   :: NameEnv a
-nameEnvElts    :: NameEnv a -> [a]
-addToNameEnv_C :: (a->a->a) -> NameEnv a -> Name -> a -> NameEnv a
-addToNameEnv   :: NameEnv a -> Name -> a -> NameEnv a
-plusNameEnv    :: NameEnv a -> NameEnv a -> NameEnv a
-extendNameEnv  :: NameEnv a -> [(Name,a)] -> NameEnv a
-lookupNameEnv  :: NameEnv a -> Name -> Maybe a
-delFromNameEnv :: NameEnv a -> Name -> NameEnv a
-elemNameEnv    :: Name -> NameEnv a -> Bool
-
-emptyNameEnv   = emptyUFM
-nameEnvElts    = eltsUFM
-addToNameEnv_C = addToUFM_C
-addToNameEnv   = addToUFM
-plusNameEnv    = plusUFM
-extendNameEnv  = addListToUFM
-lookupNameEnv  = lookupUFM
-delFromNameEnv = delFromUFM
-elemNameEnv    = elemUFM
-
---------------------------------
-type FixityEnv = NameEnv RenamedFixitySig
-       -- We keep the whole fixity sig so that we
-       -- can report line-number info when there is a duplicate
-       -- fixity declaration
-\end{code}
-
-\begin{code}
---------------------------------
-type RnNameSupply
- = ( UniqSupply
-
-   , FiniteMap (OccName, OccName) Int
-       -- This is used as a name supply for dictionary functions
-       -- From the inst decl we derive a (class, tycon) pair;
-       -- this map then gives a unique int for each inst decl with that
-       -- (class, tycon) pair.  (In Haskell 98 there can only be one,
-       -- but not so in more extended versions.)
-       --      
-       -- We could just use one Int for all the instance decls, but this
-       -- way the uniques change less when you add an instance decl,   
-       -- hence less recompilation
-
-   , FiniteMap (ModuleName, OccName) Name
-       -- Ensures that one (module,occname) pair gets one unique
-   )
-
-
---------------------------------
-data ExportEnv   = ExportEnv Avails Fixities
-type Avails      = [AvailInfo]
-type Fixities    = [(Name, Fixity)]
-
-type ExportAvails = (FiniteMap ModuleName Avails,      -- Used to figure out "module M" export specifiers
-                                                       -- Includes avails only from *unqualified* imports
-                                                       -- (see 1.4 Report Section 5.1.1)
-
-                    NameEnv AvailInfo)         -- Used to figure out all other export specifiers.
-                                               -- Maps a Name to the AvailInfo that contains it
-
-
-data GenAvailInfo name = Avail name            -- An ordinary identifier
-                       | AvailTC name          -- The name of the type or class
-                                 [name]        -- The available pieces of type/class. NB: If the type or
-                                               -- class is itself to be in scope, it must be in this list.
-                                               -- Thus, typically: AvailTC Eq [Eq, ==, /=]
-type AvailInfo    = GenAvailInfo Name
-type RdrAvailInfo = GenAvailInfo OccName
-\end{code}
-
-===================================================
-               INTERFACE FILE STUFF
-===================================================
-
-\begin{code}
-type ExportItem                 = (ModuleName, [RdrAvailInfo])
-type VersionInfo name    = [ImportVersion name]
-
-type ImportVersion name  = (ModuleName, Version, WhetherHasOrphans, WhatsImported name)
-
-type WhetherHasOrphans   = Bool
-       -- An "orphan" is 
-       --      * an instance decl in a module other than the defn module for 
-       --              one of the tycons or classes in the instance head
-       --      * a transformation rule in a module other than the one defining
-       --              the function in the head of the rule.
-
-data WhatsImported name  = Everything 
-                        | Specifically [LocalVersion name]     -- List guaranteed non-empty
-
-    -- ("M", hif, ver, Everything) means there was a "module M" in 
-    -- this module's export list, so we just have to go by M's version, "ver",
-    -- not the list of LocalVersions.
-
-
-type LocalVersion name   = (name, Version)
-
-data ParsedIface
-  = ParsedIface {
-      pi_mod      :: Version,                          -- Module version number
-      pi_orphan    :: WhetherHasOrphans,               -- Whether this module has orphans
-      pi_usages           :: [ImportVersion OccName],          -- Usages
-      pi_exports   :: [ExportItem],                    -- Exports
-      pi_decls    :: [(Version, RdrNameHsDecl)],       -- Local definitions
-      pi_insts    :: [RdrNameInstDecl],                -- Local instance declarations
-      pi_rules    :: [RdrNameRuleDecl]                 -- Rules
-    }
-
-type InterfaceDetails = (WhetherHasOrphans,
-                        VersionInfo Name,      -- Version information for what this module imports
-                        ExportEnv)             -- What modules this one depends on
-
-
--- needed by Main to fish out the fixities assoc list.
-getIfaceFixities :: InterfaceDetails -> Fixities
-getIfaceFixities (_, _, ExportEnv _ fs) = fs
-
-
-type RdrNamePragma = ()                                -- Fudge for now
--------------------
-
-data Ifaces = Ifaces {
-               iImpModInfo :: ImportedModuleInfo,
-                               -- Modules this one depends on: that is, the union 
-                               -- of the modules its direct imports depend on.
-
-               iDecls :: DeclsMap,     -- A single, global map of Names to decls
-
-               iFixes :: FixityEnv,    -- A single, global map of Names to fixities
-
-               iSlurp :: NameSet,      -- All the names (whether "big" or "small", whether wired-in or not,
-                                       -- whether locally defined or not) that have been slurped in so far.
-
-               iVSlurp :: [(Name,Version)],    -- All the (a) non-wired-in (b) "big" (c) non-locally-defined 
-                                               -- names that have been slurped in so far, with their versions. 
-                                               -- This is used to generate the "usage" information for this module.
-                                               -- Subset of the previous field.
-
-               iInsts :: Bag GatedDecl,
-                               -- The as-yet un-slurped instance decls; this bag is depleted when we
-                               -- slurp an instance decl so that we don't slurp the same one twice.
-                               -- Each is 'gated' by the names that must be available before
-                               -- this instance decl is needed.
-
-               iRules :: Bag GatedDecl
-                               -- Ditto transformation rules
-       }
-
-type GatedDecl = (NameSet, (Module, RdrNameHsDecl))
-
-type ImportedModuleInfo 
-     = FiniteMap ModuleName (Version, Bool, Maybe (Module, Bool, Avails))
-               -- Suppose the domain element is module 'A'
-               --
-               -- The first Bool is True if A contains 
-               -- 'orphan' rules or instance decls
-
-               -- The second Bool is true if the interface file actually
-               -- read was an .hi-boot file
-
-               -- Nothing => A's interface not yet read, but this module has
-               --            imported a module, B, that itself depends on A
-               --
-               -- Just xx => A's interface has been read.  The Module in 
-               --              the Just has the correct Dll flag
-
-               -- This set is used to decide whether to look for
-               -- A.hi or A.hi-boot when importing A.f.
-               -- Basically, we look for A.hi if A is in the map, and A.hi-boot
-               -- otherwise
-
-type DeclsMap = NameEnv (Version, AvailInfo, Bool, (Module, RdrNameHsDecl))
-               -- A DeclsMap contains a binding for each Name in the declaration
-               -- including the constructors of a type decl etc.
-               -- The Bool is True just for the 'main' Name.
-\end{code}
-
-
-%************************************************************************
-%*                                                                     *
-\subsection{Main monad code}
-%*                                                                     *
-%************************************************************************
-
-\begin{code}
-initRn :: ModuleName -> UniqSupply -> SearchPath -> SrcLoc
-       -> RnMG r
-       -> IO (r, Bag ErrMsg, Bag WarnMsg)
-
-initRn mod us dirs loc do_rn = do
-  himaps    <- mkModuleHiMaps dirs
-  names_var <- newIORef (us, emptyFM, builtins)
-  errs_var  <- newIORef (emptyBag,emptyBag)
-  iface_var <- newIORef emptyIfaces 
-  let
-        rn_down = RnDown { rn_loc = loc, rn_omit = \n -> False, rn_ns = names_var, 
-                          rn_errs = errs_var, 
-                          rn_hi_maps = himaps, 
-                          rn_ifaces = iface_var,
-                          rn_mod = mod }
-
-       -- do the business
-  res <- do_rn rn_down ()
-
-       -- grab errors and return
-  (warns, errs) <- readIORef errs_var
-
-  return (res, errs, warns)
-
-
-initRnMS :: GlobalRdrEnv -> FixityEnv -> RnMode -> RnMS r -> RnM d r
-initRnMS rn_env fixity_env mode thing_inside rn_down g_down
-  = let
-       s_down = SDown { rn_genv = rn_env, rn_lenv = emptyRdrEnv, 
-                        rn_fixenv = fixity_env, rn_mode = mode }
-    in
-    thing_inside rn_down s_down
-
-initIfaceRnMS :: Module -> RnMS r -> RnM d r
-initIfaceRnMS mod thing_inside 
-  = initRnMS emptyRdrEnv emptyNameEnv InterfaceMode $
-    setModuleRn (moduleName mod) thing_inside
-
-emptyIfaces :: Ifaces
-emptyIfaces = Ifaces { iImpModInfo = emptyFM,
-                      iDecls = emptyNameEnv,
-                      iFixes = emptyNameEnv,
-                      iSlurp = unitNameSet (mkUnboundName dummyRdrVarName),
-                       -- Pretend that the dummy unbound name has already been
-                       -- slurped.  This is what's returned for an out-of-scope name,
-                       -- and we don't want thereby to try to suck it in!
-                      iVSlurp = [],
-                      iInsts = emptyBag,
-                      iRules = emptyBag
-             }
-
--- mkUnboundName makes a place-holder Name; it shouldn't be looked at except possibly
--- during compiler debugging.
-mkUnboundName :: RdrName -> Name
-mkUnboundName rdr_name = mkLocalName unboundKey (rdrNameOcc rdr_name) noSrcLoc
-
-isUnboundName :: Name -> Bool
-isUnboundName name = getUnique name == unboundKey
-
-builtins :: FiniteMap (ModuleName,OccName) Name
-builtins = 
-   bagToFM (
-   mapBag (\ name ->  ((moduleName (nameModule name), nameOccName name), name))
-         builtinNames)
-\end{code}
-
-@renameSourceCode@ is used to rename stuff "out-of-line"; that is, not as part of
-the main renamer.  Sole examples: derived definitions, which are only generated
-in the type checker.
-
-The @RnNameSupply@ includes a @UniqueSupply@, so if you call it more than
-once you must either split it, or install a fresh unique supply.
-
-\begin{code}
-renameSourceCode :: ModuleName
-                -> RnNameSupply
-                -> RnMS r
-                -> r
-
-renameSourceCode mod_name name_supply m
-  = unsafePerformIO (
-       -- It's not really unsafe!  When renaming source code we
-       -- only do any I/O if we need to read in a fixity declaration;
-       -- and that doesn't happen in pragmas etc
-
-       newIORef name_supply            >>= \ names_var ->
-       newIORef (emptyBag,emptyBag)    >>= \ errs_var ->
-       let
-           rn_down = RnDown { rn_loc = mkGeneratedSrcLoc, rn_ns = names_var,
-                              rn_errs = errs_var,
-                              rn_mod = mod_name }
-           s_down = SDown { rn_mode = InterfaceMode,   -- So that we can refer to PrelBase.True etc
-                            rn_genv = emptyRdrEnv, rn_lenv = emptyRdrEnv,
-                            rn_fixenv = emptyNameEnv }
-       in
-       m rn_down s_down                        >>= \ result ->
-       
-       readIORef errs_var                      >>= \ (warns,errs) ->
-
-       (if not (isEmptyBag errs) then
-               pprTrace "Urk! renameSourceCode found errors" (display errs) 
-#ifdef DEBUG
-        else if not (isEmptyBag warns) then
-               pprTrace "Note: renameSourceCode found warnings" (display warns)
-#endif
-        else
-               id) $
-
-       return result
-    )
-  where
-    display errs = pprBagOfErrors errs
-
-{-# INLINE thenRn #-}
-{-# INLINE thenRn_ #-}
-{-# INLINE returnRn #-}
-{-# INLINE andRn #-}
-
-returnRn :: a -> RnM d a
-thenRn   :: RnM d a -> (a -> RnM d b) -> RnM d b
-thenRn_  :: RnM d a -> RnM d b -> RnM d b
-andRn    :: (a -> a -> a) -> RnM d a -> RnM d a -> RnM d a
-mapRn    :: (a -> RnM d b) -> [a] -> RnM d [b]
-mapRn_   :: (a -> RnM d b) -> [a] -> RnM d ()
-mapMaybeRn :: (a -> RnM d (Maybe b)) -> [a] -> RnM d [b]
-sequenceRn :: [RnM d a] -> RnM d [a]
-foldlRn :: (b  -> a -> RnM d b) -> b -> [a] -> RnM d b
-mapAndUnzipRn :: (a -> RnM d (b,c)) -> [a] -> RnM d ([b],[c])
-fixRn    :: (a -> RnM d a) -> RnM d a
-
-returnRn v gdown ldown  = return v
-thenRn m k gdown ldown  = m gdown ldown >>= \ r -> k r gdown ldown
-thenRn_ m k gdown ldown = m gdown ldown >> k gdown ldown
-fixRn m gdown ldown = fixIO (\r -> m r gdown ldown)
-andRn combiner m1 m2 gdown ldown
-  = m1 gdown ldown >>= \ res1 ->
-    m2 gdown ldown >>= \ res2 ->
-    return (combiner res1 res2)
-
-sequenceRn []     = returnRn []
-sequenceRn (m:ms) =  m                 `thenRn` \ r ->
-                    sequenceRn ms      `thenRn` \ rs ->
-                    returnRn (r:rs)
-
-mapRn f []     = returnRn []
-mapRn f (x:xs)
-  = f x                `thenRn` \ r ->
-    mapRn f xs         `thenRn` \ rs ->
-    returnRn (r:rs)
-
-mapRn_ f []     = returnRn ()
-mapRn_ f (x:xs) = 
-    f x                `thenRn_`
-    mapRn_ f xs
-
-foldlRn k z [] = returnRn z
-foldlRn k z (x:xs) = k z x     `thenRn` \ z' ->
-                    foldlRn k z' xs
-
-mapAndUnzipRn f [] = returnRn ([],[])
-mapAndUnzipRn f (x:xs)
-  = f x                        `thenRn` \ (r1,  r2)  ->
-    mapAndUnzipRn f xs `thenRn` \ (rs1, rs2) ->
-    returnRn (r1:rs1, r2:rs2)
-
-mapAndUnzip3Rn f [] = returnRn ([],[],[])
-mapAndUnzip3Rn f (x:xs)
-  = f x                        `thenRn` \ (r1,  r2,  r3)  ->
-    mapAndUnzip3Rn f xs        `thenRn` \ (rs1, rs2, rs3) ->
-    returnRn (r1:rs1, r2:rs2, r3:rs3)
-
-mapMaybeRn f []     = returnRn []
-mapMaybeRn f (x:xs) = f x              `thenRn` \ maybe_r ->
-                     mapMaybeRn f xs   `thenRn` \ rs ->
-                     case maybe_r of
-                       Nothing -> returnRn rs
-                       Just r  -> returnRn (r:rs)
-\end{code}
-
-
-
-%************************************************************************
-%*                                                                     *
-\subsection{Boring plumbing for common part}
-%*                                                                     *
-%************************************************************************
-
-
-================  Errors and warnings =====================
-
-\begin{code}
-failWithRn :: a -> Message -> RnM d a
-failWithRn res msg (RnDown {rn_errs = errs_var, rn_loc = loc}) l_down
-  = readIORef  errs_var                                        >>=  \ (warns,errs) ->
-    writeIORef errs_var (warns, errs `snocBag` err)            >> 
-    return res
-  where
-    err = addShortErrLocLine loc msg
-
-warnWithRn :: a -> Message -> RnM d a
-warnWithRn res msg (RnDown {rn_errs = errs_var, rn_loc = loc}) l_down
-  = readIORef  errs_var                                        >>=  \ (warns,errs) ->
-    writeIORef errs_var (warns `snocBag` warn, errs)   >> 
-    return res
-  where
-    warn = addShortWarnLocLine loc msg
-
-addErrRn :: Message -> RnM d ()
-addErrRn err = failWithRn () err
-
-checkRn :: Bool -> Message -> RnM d () -- Check that a condition is true
-checkRn False err = addErrRn err
-checkRn True  err = returnRn ()
-
-warnCheckRn :: Bool -> Message -> RnM d ()     -- Check that a condition is true
-warnCheckRn False err = addWarnRn err
-warnCheckRn True  err = returnRn ()
-
-addWarnRn :: Message -> RnM d ()
-addWarnRn warn = warnWithRn () warn
-
-checkErrsRn :: RnM d Bool              -- True <=> no errors so far
-checkErrsRn (RnDown {rn_errs = errs_var}) l_down
-  = readIORef  errs_var                                        >>=  \ (warns,errs) ->
-    return (isEmptyBag errs)
-\end{code}
-
-
-================  Source location =====================
-
-\begin{code}
-pushSrcLocRn :: SrcLoc -> RnM d a -> RnM d a
-pushSrcLocRn loc' m down l_down
-  = m (down {rn_loc = loc'}) l_down
-
-getSrcLocRn :: RnM d SrcLoc
-getSrcLocRn down l_down
-  = return (rn_loc down)
-\end{code}
-
-================  Name supply =====================
-
-\begin{code}
-getNameSupplyRn :: RnM d RnNameSupply
-getNameSupplyRn rn_down l_down
-  = readIORef (rn_ns rn_down)
-
-setNameSupplyRn :: RnNameSupply -> RnM d ()
-setNameSupplyRn names' (RnDown {rn_ns = names_var}) l_down
-  = writeIORef names_var names'
-
--- See comments with RnNameSupply above.
-newInstUniq :: (OccName, OccName) -> RnM d Int
-newInstUniq key (RnDown {rn_ns = names_var}) l_down
-  = readIORef names_var                                >>= \ (us, mapInst, cache) ->
-    let
-       uniq = case lookupFM mapInst key of
-                  Just x  -> x+1
-                  Nothing -> 0
-       mapInst' = addToFM mapInst key uniq
-    in
-    writeIORef names_var (us, mapInst', cache) >>
-    return uniq
-
-getUniqRn :: RnM d Unique
-getUniqRn (RnDown {rn_ns = names_var}) l_down
- = readIORef names_var >>= \ (us, mapInst, cache) ->
-   let
-     (us1,us') = splitUniqSupply us
-   in
-   writeIORef names_var (us', mapInst, cache)  >>
-   return (uniqFromSupply us1)
-\end{code}
-
-================  Module =====================
-
-\begin{code}
-getModuleRn :: RnM d ModuleName
-getModuleRn (RnDown {rn_mod = mod_name}) l_down
-  = return mod_name
-
-setModuleRn :: ModuleName -> RnM d a -> RnM d a
-setModuleRn new_mod enclosed_thing rn_down l_down
-  = enclosed_thing (rn_down {rn_mod = new_mod}) l_down
-\end{code}
-
-\begin{code}
-setOmitQualFn :: (Name -> Bool) -> RnM d a -> RnM d a
-setOmitQualFn fn m g_down l_down = m (g_down { rn_omit = fn }) l_down
-
-getOmitQualFn :: RnM d (Name -> Bool)
-getOmitQualFn (RnDown {rn_omit = omit_fn}) l_down
-  = return omit_fn
-\end{code}
-
-%************************************************************************
-%*                                                                     *
-\subsection{Plumbing for rename-source part}
-%*                                                                     *
-%************************************************************************
-
-================  RnEnv  =====================
-
-\begin{code}
-getNameEnvs :: RnMS (GlobalRdrEnv, LocalRdrEnv)
-getNameEnvs rn_down (SDown {rn_genv = global_env, rn_lenv = local_env})
-  = return (global_env, local_env)
-
-getLocalNameEnv :: RnMS LocalRdrEnv
-getLocalNameEnv rn_down (SDown {rn_lenv = local_env})
-  = return local_env
-
-setLocalNameEnv :: LocalRdrEnv -> RnMS a -> RnMS a
-setLocalNameEnv local_env' m rn_down l_down
-  = m rn_down (l_down {rn_lenv = local_env'})
-
-getFixityEnv :: RnMS FixityEnv
-getFixityEnv rn_down (SDown {rn_fixenv = fixity_env})
-  = return fixity_env
-
-extendFixityEnv :: [(Name, RenamedFixitySig)] -> RnMS a -> RnMS a
-extendFixityEnv fixes enclosed_scope
-               rn_down l_down@(SDown {rn_fixenv = fixity_env})
-  = let
-       new_fixity_env = extendNameEnv fixity_env fixes
-    in
-    enclosed_scope rn_down (l_down {rn_fixenv = new_fixity_env})
-\end{code}
-
-================  Mode  =====================
-
-\begin{code}
-getModeRn :: RnMS RnMode
-getModeRn rn_down (SDown {rn_mode = mode})
-  = return mode
-
-setModeRn :: RnMode -> RnMS a -> RnMS a
-setModeRn new_mode thing_inside rn_down l_down
-  = thing_inside rn_down (l_down {rn_mode = new_mode})
-\end{code}
-
-
-%************************************************************************
-%*                                                                     *
-\subsection{Plumbing for rename-globals part}
-%*                                                                     *
-%************************************************************************
-
-\begin{code}
-getIfacesRn :: RnM d Ifaces
-getIfacesRn (RnDown {rn_ifaces = iface_var}) _
-  = readIORef iface_var
-
-setIfacesRn :: Ifaces -> RnM d ()
-setIfacesRn ifaces (RnDown {rn_ifaces = iface_var}) _
-  = writeIORef iface_var ifaces
-
-getHiMaps :: RnM d (ModuleHiMap, ModuleHiMap)
-getHiMaps (RnDown {rn_hi_maps = himaps}) _ 
-  = return himaps
-\end{code}
+%\r
+% (c) The GRASP/AQUA Project, Glasgow University, 1992-1998\r
+%\r
+\section[RnMonad]{The monad used by the renamer}\r
+\r
+\begin{code}\r
+module RnMonad(\r
+       module RnMonad,\r
+       Module,\r
+       FiniteMap,\r
+       Bag,\r
+       Name,\r
+       RdrNameHsDecl,\r
+       RdrNameInstDecl,\r
+       Version,\r
+       NameSet,\r
+       OccName,\r
+       Fixity\r
+    ) where\r
+\r
+#include "HsVersions.h"\r
+\r
+import PrelIOBase      ( fixIO )       -- Should be in GlaExts\r
+import IOExts          ( IORef, newIORef, readIORef, writeIORef, unsafePerformIO )\r
+       \r
+import HsSyn           \r
+import RdrHsSyn\r
+import RnHsSyn         ( RenamedFixitySig )\r
+import BasicTypes      ( Version )\r
+import SrcLoc          ( noSrcLoc )\r
+import ErrUtils                ( addShortErrLocLine, addShortWarnLocLine,\r
+                         pprBagOfErrors, ErrMsg, WarnMsg, Message\r
+                       )\r
+import Name            ( Name, OccName, NamedThing(..),\r
+                         isLocallyDefinedName, nameModule, nameOccName,\r
+                         decode, mkLocalName\r
+                       )\r
+import Module          ( Module, ModuleName, ModuleHiMap, SearchPath, WhereFrom,\r
+                         mkModuleHiMaps, moduleName\r
+                       )\r
+import NameSet         \r
+import RdrName         ( RdrName, dummyRdrVarName, rdrNameOcc )\r
+import CmdLineOpts     ( opt_D_dump_rn_trace, opt_IgnoreIfacePragmas )\r
+import PrelInfo                ( builtinNames )\r
+import TysWiredIn      ( boolTyCon )\r
+import SrcLoc          ( SrcLoc, mkGeneratedSrcLoc )\r
+import Unique          ( Unique, getUnique, unboundKey )\r
+import UniqFM          ( UniqFM )\r
+import FiniteMap       ( FiniteMap, emptyFM, bagToFM, lookupFM, addToFM, addListToFM, \r
+                         addListToFM_C, addToFM_C, eltsFM, fmToList\r
+                       )\r
+import Bag             ( Bag, mapBag, emptyBag, isEmptyBag, snocBag )\r
+import Maybes          ( mapMaybe )\r
+import UniqSet\r
+import UniqFM\r
+import UniqSupply\r
+import Util\r
+import Outputable\r
+\r
+infixr 9 `thenRn`, `thenRn_`\r
+\end{code}\r
+\r
+\r
+%************************************************************************\r
+%*                                                                     *\r
+\subsection{Somewhat magical interface to other monads}\r
+%*                                                                     *\r
+%************************************************************************\r
+\r
+\begin{code}\r
+ioToRnM :: IO r -> RnM d (Either IOError r)\r
+ioToRnM io rn_down g_down = (io >>= \ ok -> return (Right ok)) \r
+                           `catch` \r
+                           (\ err -> return (Left err))\r
+           \r
+traceRn :: SDoc -> RnM d ()\r
+traceRn msg | opt_D_dump_rn_trace = putDocRn msg\r
+           | otherwise           = returnRn ()\r
+\r
+putDocRn :: SDoc -> RnM d ()\r
+putDocRn msg = ioToRnM (printErrs msg) `thenRn_`\r
+              returnRn ()\r
+\end{code}\r
+\r
+\r
+%************************************************************************\r
+%*                                                                     *\r
+\subsection{Data types}\r
+%*                                                                     *\r
+%************************************************************************\r
+\r
+===================================================\r
+               MONAD TYPES\r
+===================================================\r
+\r
+\begin{code}\r
+type RnM d r = RnDown -> d -> IO r\r
+type RnMS r  = RnM SDown r             -- Renaming source\r
+type RnMG r  = RnM ()    r             -- Getting global names etc\r
+\r
+       -- Common part\r
+data RnDown = RnDown {\r
+                 rn_mod     :: ModuleName,\r
+                 rn_loc     :: SrcLoc,\r
+                 rn_ns      :: IORef RnNameSupply,\r
+                 rn_errs    :: IORef (Bag WarnMsg, Bag ErrMsg),\r
+                 rn_ifaces  :: IORef Ifaces,\r
+                 rn_hi_maps :: (ModuleHiMap,   -- for .hi files\r
+                                ModuleHiMap)   -- for .hi-boot files\r
+               }\r
+\r
+       -- For renaming source code\r
+data SDown = SDown {\r
+                 rn_mode :: RnMode,\r
+\r
+                 rn_genv :: GlobalRdrEnv,      -- Global envt; the fixity component gets extended\r
+                                               --   with local fixity decls\r
+\r
+                 rn_lenv :: LocalRdrEnv,       -- Local name envt\r
+                                       --   Does *not* includes global name envt; may shadow it\r
+                                       --   Includes both ordinary variables and type variables;\r
+                                       --   they are kept distinct because tyvar have a different\r
+                                       --   occurrence contructor (Name.TvOcc)\r
+                                       -- We still need the unsullied global name env so that\r
+                                       --   we can look up record field names\r
+\r
+                 rn_fixenv :: FixityEnv        -- Local fixities\r
+                                               -- The global ones are held in the\r
+                                               -- rn_ifaces field\r
+               }\r
+\r
+data RnMode    = SourceMode                    -- Renaming source code\r
+               | InterfaceMode                 -- Renaming interface declarations.  \r
+\end{code}\r
+\r
+===================================================\r
+               ENVIRONMENTS\r
+===================================================\r
+\r
+\begin{code}\r
+--------------------------------\r
+type RdrNameEnv a = FiniteMap RdrName a\r
+type GlobalRdrEnv = RdrNameEnv [Name]  -- The list is because there may be name clashes\r
+                                       -- These only get reported on lookup,\r
+                                       -- not on construction\r
+type LocalRdrEnv  = RdrNameEnv Name\r
+\r
+emptyRdrEnv  :: RdrNameEnv a\r
+lookupRdrEnv :: RdrNameEnv a -> RdrName -> Maybe a\r
+addListToRdrEnv :: RdrNameEnv a -> [(RdrName,a)] -> RdrNameEnv a\r
+extendRdrEnv   :: RdrNameEnv a -> RdrName -> a -> RdrNameEnv a\r
+\r
+emptyRdrEnv  = emptyFM\r
+lookupRdrEnv = lookupFM\r
+addListToRdrEnv = addListToFM\r
+rdrEnvElts     = eltsFM\r
+extendRdrEnv    = addToFM\r
+rdrEnvToList    = fmToList\r
+\r
+--------------------------------\r
+type NameEnv a = UniqFM a      -- Domain is Name\r
+\r
+emptyNameEnv   :: NameEnv a\r
+nameEnvElts    :: NameEnv a -> [a]\r
+addToNameEnv_C :: (a->a->a) -> NameEnv a -> Name -> a -> NameEnv a\r
+addToNameEnv   :: NameEnv a -> Name -> a -> NameEnv a\r
+plusNameEnv    :: NameEnv a -> NameEnv a -> NameEnv a\r
+extendNameEnv  :: NameEnv a -> [(Name,a)] -> NameEnv a\r
+lookupNameEnv  :: NameEnv a -> Name -> Maybe a\r
+delFromNameEnv :: NameEnv a -> Name -> NameEnv a\r
+elemNameEnv    :: Name -> NameEnv a -> Bool\r
+\r
+emptyNameEnv   = emptyUFM\r
+nameEnvElts    = eltsUFM\r
+addToNameEnv_C = addToUFM_C\r
+addToNameEnv   = addToUFM\r
+plusNameEnv    = plusUFM\r
+extendNameEnv  = addListToUFM\r
+lookupNameEnv  = lookupUFM\r
+delFromNameEnv = delFromUFM\r
+elemNameEnv    = elemUFM\r
+\r
+--------------------------------\r
+type FixityEnv = NameEnv RenamedFixitySig\r
+       -- We keep the whole fixity sig so that we\r
+       -- can report line-number info when there is a duplicate\r
+       -- fixity declaration\r
+\end{code}\r
+\r
+\begin{code}\r
+--------------------------------\r
+type RnNameSupply\r
+ = ( UniqSupply\r
+\r
+   , FiniteMap (OccName, OccName) Int\r
+       -- This is used as a name supply for dictionary functions\r
+       -- From the inst decl we derive a (class, tycon) pair;\r
+       -- this map then gives a unique int for each inst decl with that\r
+       -- (class, tycon) pair.  (In Haskell 98 there can only be one,\r
+       -- but not so in more extended versions.)\r
+       --      \r
+       -- We could just use one Int for all the instance decls, but this\r
+       -- way the uniques change less when you add an instance decl,   \r
+       -- hence less recompilation\r
+\r
+   , FiniteMap (ModuleName, OccName) Name\r
+       -- Ensures that one (module,occname) pair gets one unique\r
+   )\r
+\r
+\r
+--------------------------------\r
+data ExportEnv   = ExportEnv Avails Fixities\r
+type Avails      = [AvailInfo]\r
+type Fixities    = [(Name, Fixity)]\r
+\r
+type ExportAvails = (FiniteMap ModuleName Avails,      -- Used to figure out "module M" export specifiers\r
+                                                       -- Includes avails only from *unqualified* imports\r
+                                                       -- (see 1.4 Report Section 5.1.1)\r
+\r
+                    NameEnv AvailInfo)         -- Used to figure out all other export specifiers.\r
+                                               -- Maps a Name to the AvailInfo that contains it\r
+\r
+\r
+data GenAvailInfo name = Avail name            -- An ordinary identifier\r
+                       | AvailTC name          -- The name of the type or class\r
+                                 [name]        -- The available pieces of type/class. NB: If the type or\r
+                                               -- class is itself to be in scope, it must be in this list.\r
+                                               -- Thus, typically: AvailTC Eq [Eq, ==, /=]\r
+type AvailInfo    = GenAvailInfo Name\r
+type RdrAvailInfo = GenAvailInfo OccName\r
+\end{code}\r
+\r
+===================================================\r
+               INTERFACE FILE STUFF\r
+===================================================\r
+\r
+\begin{code}\r
+type ExportItem                 = (ModuleName, [RdrAvailInfo])\r
+type VersionInfo name    = [ImportVersion name]\r
+\r
+type ImportVersion name  = (ModuleName, Version, WhetherHasOrphans, WhatsImported name)\r
+\r
+type WhetherHasOrphans   = Bool\r
+       -- An "orphan" is \r
+       --      * an instance decl in a module other than the defn module for \r
+       --              one of the tycons or classes in the instance head\r
+       --      * a transformation rule in a module other than the one defining\r
+       --              the function in the head of the rule.\r
+\r
+data WhatsImported name  = Everything \r
+                        | Specifically [LocalVersion name]     -- List guaranteed non-empty\r
+\r
+    -- ("M", hif, ver, Everything) means there was a "module M" in \r
+    -- this module's export list, so we just have to go by M's version, "ver",\r
+    -- not the list of LocalVersions.\r
+\r
+\r
+type LocalVersion name   = (name, Version)\r
+\r
+data ParsedIface\r
+  = ParsedIface {\r
+      pi_mod      :: Version,                          -- Module version number\r
+      pi_orphan    :: WhetherHasOrphans,               -- Whether this module has orphans\r
+      pi_usages           :: [ImportVersion OccName],          -- Usages\r
+      pi_exports   :: [ExportItem],                    -- Exports\r
+      pi_decls    :: [(Version, RdrNameHsDecl)],       -- Local definitions\r
+      pi_insts    :: [RdrNameInstDecl],                -- Local instance declarations\r
+      pi_rules    :: [RdrNameRuleDecl]                 -- Rules\r
+    }\r
+\r
+type InterfaceDetails = (WhetherHasOrphans,\r
+                        VersionInfo Name,      -- Version information for what this module imports\r
+                        ExportEnv)             -- What modules this one depends on\r
+\r
+\r
+-- needed by Main to fish out the fixities assoc list.\r
+getIfaceFixities :: InterfaceDetails -> Fixities\r
+getIfaceFixities (_, _, ExportEnv _ fs) = fs\r
+\r
+\r
+type RdrNamePragma = ()                                -- Fudge for now\r
+-------------------\r
+\r
+data Ifaces = Ifaces {\r
+               iImpModInfo :: ImportedModuleInfo,\r
+                               -- Modules this one depends on: that is, the union \r
+                               -- of the modules its direct imports depend on.\r
+\r
+               iDecls :: DeclsMap,     -- A single, global map of Names to decls\r
+\r
+               iFixes :: FixityEnv,    -- A single, global map of Names to fixities\r
+\r
+               iSlurp :: NameSet,      -- All the names (whether "big" or "small", whether wired-in or not,\r
+                                       -- whether locally defined or not) that have been slurped in so far.\r
+\r
+               iVSlurp :: [(Name,Version)],    -- All the (a) non-wired-in (b) "big" (c) non-locally-defined \r
+                                               -- names that have been slurped in so far, with their versions. \r
+                                               -- This is used to generate the "usage" information for this module.\r
+                                               -- Subset of the previous field.\r
+\r
+               iInsts :: Bag GatedDecl,\r
+                               -- The as-yet un-slurped instance decls; this bag is depleted when we\r
+                               -- slurp an instance decl so that we don't slurp the same one twice.\r
+                               -- Each is 'gated' by the names that must be available before\r
+                               -- this instance decl is needed.\r
+\r
+               iRules :: Bag GatedDecl\r
+                               -- Ditto transformation rules\r
+       }\r
+\r
+type GatedDecl = (NameSet, (Module, RdrNameHsDecl))\r
+\r
+type ImportedModuleInfo \r
+     = FiniteMap ModuleName (Version, Bool, Maybe (Module, Bool, Avails))\r
+               -- Suppose the domain element is module 'A'\r
+               --\r
+               -- The first Bool is True if A contains \r
+               -- 'orphan' rules or instance decls\r
+\r
+               -- The second Bool is true if the interface file actually\r
+               -- read was an .hi-boot file\r
+\r
+               -- Nothing => A's interface not yet read, but this module has\r
+               --            imported a module, B, that itself depends on A\r
+               --\r
+               -- Just xx => A's interface has been read.  The Module in \r
+               --              the Just has the correct Dll flag\r
+\r
+               -- This set is used to decide whether to look for\r
+               -- A.hi or A.hi-boot when importing A.f.\r
+               -- Basically, we look for A.hi if A is in the map, and A.hi-boot\r
+               -- otherwise\r
+\r
+type DeclsMap = NameEnv (Version, AvailInfo, Bool, (Module, RdrNameHsDecl))\r
+               -- A DeclsMap contains a binding for each Name in the declaration\r
+               -- including the constructors of a type decl etc.\r
+               -- The Bool is True just for the 'main' Name.\r
+\end{code}\r
+\r
+\r
+%************************************************************************\r
+%*                                                                     *\r
+\subsection{Main monad code}\r
+%*                                                                     *\r
+%************************************************************************\r
+\r
+\begin{code}\r
+initRn :: ModuleName -> UniqSupply -> SearchPath -> SrcLoc\r
+       -> RnMG r\r
+       -> IO (r, Bag ErrMsg, Bag WarnMsg)\r
+\r
+initRn mod us dirs loc do_rn = do\r
+  himaps    <- mkModuleHiMaps dirs\r
+  names_var <- newIORef (us, emptyFM, builtins)\r
+  errs_var  <- newIORef (emptyBag,emptyBag)\r
+  iface_var <- newIORef emptyIfaces \r
+  let\r
+        rn_down = RnDown { rn_loc = loc, rn_ns = names_var, \r
+                          rn_errs = errs_var, \r
+                          rn_hi_maps = himaps, \r
+                          rn_ifaces = iface_var,\r
+                          rn_mod = mod }\r
+\r
+       -- do the business\r
+  res <- do_rn rn_down ()\r
+\r
+       -- grab errors and return\r
+  (warns, errs) <- readIORef errs_var\r
+\r
+  return (res, errs, warns)\r
+\r
+\r
+initRnMS :: GlobalRdrEnv -> FixityEnv -> RnMode -> RnMS r -> RnM d r\r
+initRnMS rn_env fixity_env mode thing_inside rn_down g_down\r
+  = let\r
+       s_down = SDown { rn_genv = rn_env, rn_lenv = emptyRdrEnv, \r
+                        rn_fixenv = fixity_env, rn_mode = mode }\r
+    in\r
+    thing_inside rn_down s_down\r
+\r
+initIfaceRnMS :: Module -> RnMS r -> RnM d r\r
+initIfaceRnMS mod thing_inside \r
+  = initRnMS emptyRdrEnv emptyNameEnv InterfaceMode $\r
+    setModuleRn (moduleName mod) thing_inside\r
+\r
+emptyIfaces :: Ifaces\r
+emptyIfaces = Ifaces { iImpModInfo = emptyFM,\r
+                      iDecls = emptyNameEnv,\r
+                      iFixes = emptyNameEnv,\r
+                      iSlurp = unitNameSet (mkUnboundName dummyRdrVarName),\r
+                       -- Pretend that the dummy unbound name has already been\r
+                       -- slurped.  This is what's returned for an out-of-scope name,\r
+                       -- and we don't want thereby to try to suck it in!\r
+                      iVSlurp = [],\r
+                      iInsts = emptyBag,\r
+                      iRules = emptyBag\r
+             }\r
+\r
+-- mkUnboundName makes a place-holder Name; it shouldn't be looked at except possibly\r
+-- during compiler debugging.\r
+mkUnboundName :: RdrName -> Name\r
+mkUnboundName rdr_name = mkLocalName unboundKey (rdrNameOcc rdr_name) noSrcLoc\r
+\r
+isUnboundName :: Name -> Bool\r
+isUnboundName name = getUnique name == unboundKey\r
+\r
+builtins :: FiniteMap (ModuleName,OccName) Name\r
+builtins = \r
+   bagToFM (\r
+   mapBag (\ name ->  ((moduleName (nameModule name), nameOccName name), name))\r
+         builtinNames)\r
+\end{code}\r
+\r
+@renameSourceCode@ is used to rename stuff "out-of-line"; that is, not as part of\r
+the main renamer.  Sole examples: derived definitions, which are only generated\r
+in the type checker.\r
+\r
+The @RnNameSupply@ includes a @UniqueSupply@, so if you call it more than\r
+once you must either split it, or install a fresh unique supply.\r
+\r
+\begin{code}\r
+renameSourceCode :: ModuleName\r
+                -> RnNameSupply\r
+                -> RnMS r\r
+                -> r\r
+\r
+renameSourceCode mod_name name_supply m\r
+  = unsafePerformIO (\r
+       -- It's not really unsafe!  When renaming source code we\r
+       -- only do any I/O if we need to read in a fixity declaration;\r
+       -- and that doesn't happen in pragmas etc\r
+\r
+       newIORef name_supply            >>= \ names_var ->\r
+       newIORef (emptyBag,emptyBag)    >>= \ errs_var ->\r
+       let\r
+           rn_down = RnDown { rn_loc = mkGeneratedSrcLoc, rn_ns = names_var,\r
+                              rn_errs = errs_var,\r
+                              rn_mod = mod_name }\r
+           s_down = SDown { rn_mode = InterfaceMode,   -- So that we can refer to PrelBase.True etc\r
+                            rn_genv = emptyRdrEnv, rn_lenv = emptyRdrEnv,\r
+                            rn_fixenv = emptyNameEnv }\r
+       in\r
+       m rn_down s_down                        >>= \ result ->\r
+       \r
+       readIORef errs_var                      >>= \ (warns,errs) ->\r
+\r
+       (if not (isEmptyBag errs) then\r
+               pprTrace "Urk! renameSourceCode found errors" (display errs) \r
+#ifdef DEBUG\r
+        else if not (isEmptyBag warns) then\r
+               pprTrace "Note: renameSourceCode found warnings" (display warns)\r
+#endif\r
+        else\r
+               id) $\r
+\r
+       return result\r
+    )\r
+  where\r
+    display errs = pprBagOfErrors errs\r
+\r
+{-# INLINE thenRn #-}\r
+{-# INLINE thenRn_ #-}\r
+{-# INLINE returnRn #-}\r
+{-# INLINE andRn #-}\r
+\r
+returnRn :: a -> RnM d a\r
+thenRn   :: RnM d a -> (a -> RnM d b) -> RnM d b\r
+thenRn_  :: RnM d a -> RnM d b -> RnM d b\r
+andRn    :: (a -> a -> a) -> RnM d a -> RnM d a -> RnM d a\r
+mapRn    :: (a -> RnM d b) -> [a] -> RnM d [b]\r
+mapRn_   :: (a -> RnM d b) -> [a] -> RnM d ()\r
+mapMaybeRn :: (a -> RnM d (Maybe b)) -> [a] -> RnM d [b]\r
+sequenceRn :: [RnM d a] -> RnM d [a]\r
+foldlRn :: (b  -> a -> RnM d b) -> b -> [a] -> RnM d b\r
+mapAndUnzipRn :: (a -> RnM d (b,c)) -> [a] -> RnM d ([b],[c])\r
+fixRn    :: (a -> RnM d a) -> RnM d a\r
+\r
+returnRn v gdown ldown  = return v\r
+thenRn m k gdown ldown  = m gdown ldown >>= \ r -> k r gdown ldown\r
+thenRn_ m k gdown ldown = m gdown ldown >> k gdown ldown\r
+fixRn m gdown ldown = fixIO (\r -> m r gdown ldown)\r
+andRn combiner m1 m2 gdown ldown\r
+  = m1 gdown ldown >>= \ res1 ->\r
+    m2 gdown ldown >>= \ res2 ->\r
+    return (combiner res1 res2)\r
+\r
+sequenceRn []     = returnRn []\r
+sequenceRn (m:ms) =  m                 `thenRn` \ r ->\r
+                    sequenceRn ms      `thenRn` \ rs ->\r
+                    returnRn (r:rs)\r
+\r
+mapRn f []     = returnRn []\r
+mapRn f (x:xs)\r
+  = f x                `thenRn` \ r ->\r
+    mapRn f xs         `thenRn` \ rs ->\r
+    returnRn (r:rs)\r
+\r
+mapRn_ f []     = returnRn ()\r
+mapRn_ f (x:xs) = \r
+    f x                `thenRn_`\r
+    mapRn_ f xs\r
+\r
+foldlRn k z [] = returnRn z\r
+foldlRn k z (x:xs) = k z x     `thenRn` \ z' ->\r
+                    foldlRn k z' xs\r
+\r
+mapAndUnzipRn f [] = returnRn ([],[])\r
+mapAndUnzipRn f (x:xs)\r
+  = f x                        `thenRn` \ (r1,  r2)  ->\r
+    mapAndUnzipRn f xs `thenRn` \ (rs1, rs2) ->\r
+    returnRn (r1:rs1, r2:rs2)\r
+\r
+mapAndUnzip3Rn f [] = returnRn ([],[],[])\r
+mapAndUnzip3Rn f (x:xs)\r
+  = f x                        `thenRn` \ (r1,  r2,  r3)  ->\r
+    mapAndUnzip3Rn f xs        `thenRn` \ (rs1, rs2, rs3) ->\r
+    returnRn (r1:rs1, r2:rs2, r3:rs3)\r
+\r
+mapMaybeRn f []     = returnRn []\r
+mapMaybeRn f (x:xs) = f x              `thenRn` \ maybe_r ->\r
+                     mapMaybeRn f xs   `thenRn` \ rs ->\r
+                     case maybe_r of\r
+                       Nothing -> returnRn rs\r
+                       Just r  -> returnRn (r:rs)\r
+\end{code}\r
+\r
+\r
+\r
+%************************************************************************\r
+%*                                                                     *\r
+\subsection{Boring plumbing for common part}\r
+%*                                                                     *\r
+%************************************************************************\r
+\r
+\r
+================  Errors and warnings =====================\r
+\r
+\begin{code}\r
+failWithRn :: a -> Message -> RnM d a\r
+failWithRn res msg (RnDown {rn_errs = errs_var, rn_loc = loc}) l_down\r
+  = readIORef  errs_var                                        >>=  \ (warns,errs) ->\r
+    writeIORef errs_var (warns, errs `snocBag` err)            >> \r
+    return res\r
+  where\r
+    err = addShortErrLocLine loc msg\r
+\r
+warnWithRn :: a -> Message -> RnM d a\r
+warnWithRn res msg (RnDown {rn_errs = errs_var, rn_loc = loc}) l_down\r
+  = readIORef  errs_var                                        >>=  \ (warns,errs) ->\r
+    writeIORef errs_var (warns `snocBag` warn, errs)   >> \r
+    return res\r
+  where\r
+    warn = addShortWarnLocLine loc msg\r
+\r
+addErrRn :: Message -> RnM d ()\r
+addErrRn err = failWithRn () err\r
+\r
+checkRn :: Bool -> Message -> RnM d () -- Check that a condition is true\r
+checkRn False err = addErrRn err\r
+checkRn True  err = returnRn ()\r
+\r
+warnCheckRn :: Bool -> Message -> RnM d ()     -- Check that a condition is true\r
+warnCheckRn False err = addWarnRn err\r
+warnCheckRn True  err = returnRn ()\r
+\r
+addWarnRn :: Message -> RnM d ()\r
+addWarnRn warn = warnWithRn () warn\r
+\r
+checkErrsRn :: RnM d Bool              -- True <=> no errors so far\r
+checkErrsRn (RnDown {rn_errs = errs_var}) l_down\r
+  = readIORef  errs_var                                        >>=  \ (warns,errs) ->\r
+    return (isEmptyBag errs)\r
+\end{code}\r
+\r
+\r
+================  Source location =====================\r
+\r
+\begin{code}\r
+pushSrcLocRn :: SrcLoc -> RnM d a -> RnM d a\r
+pushSrcLocRn loc' m down l_down\r
+  = m (down {rn_loc = loc'}) l_down\r
+\r
+getSrcLocRn :: RnM d SrcLoc\r
+getSrcLocRn down l_down\r
+  = return (rn_loc down)\r
+\end{code}\r
+\r
+================  Name supply =====================\r
+\r
+\begin{code}\r
+getNameSupplyRn :: RnM d RnNameSupply\r
+getNameSupplyRn rn_down l_down\r
+  = readIORef (rn_ns rn_down)\r
+\r
+setNameSupplyRn :: RnNameSupply -> RnM d ()\r
+setNameSupplyRn names' (RnDown {rn_ns = names_var}) l_down\r
+  = writeIORef names_var names'\r
+\r
+-- See comments with RnNameSupply above.\r
+newInstUniq :: (OccName, OccName) -> RnM d Int\r
+newInstUniq key (RnDown {rn_ns = names_var}) l_down\r
+  = readIORef names_var                                >>= \ (us, mapInst, cache) ->\r
+    let\r
+       uniq = case lookupFM mapInst key of\r
+                  Just x  -> x+1\r
+                  Nothing -> 0\r
+       mapInst' = addToFM mapInst key uniq\r
+    in\r
+    writeIORef names_var (us, mapInst', cache) >>\r
+    return uniq\r
+\r
+getUniqRn :: RnM d Unique\r
+getUniqRn (RnDown {rn_ns = names_var}) l_down\r
+ = readIORef names_var >>= \ (us, mapInst, cache) ->\r
+   let\r
+     (us1,us') = splitUniqSupply us\r
+   in\r
+   writeIORef names_var (us', mapInst, cache)  >>\r
+   return (uniqFromSupply us1)\r
+\end{code}\r
+\r
+================  Module =====================\r
+\r
+\begin{code}\r
+getModuleRn :: RnM d ModuleName\r
+getModuleRn (RnDown {rn_mod = mod_name}) l_down\r
+  = return mod_name\r
+\r
+setModuleRn :: ModuleName -> RnM d a -> RnM d a\r
+setModuleRn new_mod enclosed_thing rn_down l_down\r
+  = enclosed_thing (rn_down {rn_mod = new_mod}) l_down\r
+\end{code}\r
+\r
+\r
+%************************************************************************\r
+%*                                                                     *\r
+\subsection{Plumbing for rename-source part}\r
+%*                                                                     *\r
+%************************************************************************\r
+\r
+================  RnEnv  =====================\r
+\r
+\begin{code}\r
+getNameEnvs :: RnMS (GlobalRdrEnv, LocalRdrEnv)\r
+getNameEnvs rn_down (SDown {rn_genv = global_env, rn_lenv = local_env})\r
+  = return (global_env, local_env)\r
+\r
+getLocalNameEnv :: RnMS LocalRdrEnv\r
+getLocalNameEnv rn_down (SDown {rn_lenv = local_env})\r
+  = return local_env\r
+\r
+setLocalNameEnv :: LocalRdrEnv -> RnMS a -> RnMS a\r
+setLocalNameEnv local_env' m rn_down l_down\r
+  = m rn_down (l_down {rn_lenv = local_env'})\r
+\r
+getFixityEnv :: RnMS FixityEnv\r
+getFixityEnv rn_down (SDown {rn_fixenv = fixity_env})\r
+  = return fixity_env\r
+\r
+extendFixityEnv :: [(Name, RenamedFixitySig)] -> RnMS a -> RnMS a\r
+extendFixityEnv fixes enclosed_scope\r
+               rn_down l_down@(SDown {rn_fixenv = fixity_env})\r
+  = let\r
+       new_fixity_env = extendNameEnv fixity_env fixes\r
+    in\r
+    enclosed_scope rn_down (l_down {rn_fixenv = new_fixity_env})\r
+\end{code}\r
+\r
+================  Mode  =====================\r
+\r
+\begin{code}\r
+getModeRn :: RnMS RnMode\r
+getModeRn rn_down (SDown {rn_mode = mode})\r
+  = return mode\r
+\r
+setModeRn :: RnMode -> RnMS a -> RnMS a\r
+setModeRn new_mode thing_inside rn_down l_down\r
+  = thing_inside rn_down (l_down {rn_mode = new_mode})\r
+\end{code}\r
+\r
+\r
+%************************************************************************\r
+%*                                                                     *\r
+\subsection{Plumbing for rename-globals part}\r
+%*                                                                     *\r
+%************************************************************************\r
+\r
+\begin{code}\r
+getIfacesRn :: RnM d Ifaces\r
+getIfacesRn (RnDown {rn_ifaces = iface_var}) _\r
+  = readIORef iface_var\r
+\r
+setIfacesRn :: Ifaces -> RnM d ()\r
+setIfacesRn ifaces (RnDown {rn_ifaces = iface_var}) _\r
+  = writeIORef iface_var ifaces\r
+\r
+getHiMaps :: RnM d (ModuleHiMap, ModuleHiMap)\r
+getHiMaps (RnDown {rn_hi_maps = himaps}) _ \r
+  = return himaps\r
+\end{code}\r
index 0b7691f..633735b 100644 (file)
-%
-% (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
-%
-\section[RnNames]{Extracting imported and top-level names in scope}
-
-\begin{code}
-module RnNames (
-       getGlobalNames
-    ) where
-
-#include "HsVersions.h"
-
-import CmdLineOpts    ( opt_NoImplicitPrelude, opt_WarnDuplicateExports, 
-                       opt_SourceUnchanged, opt_WarnUnusedBinds
-                     )
-
-import HsSyn   ( HsModule(..), HsDecl(..), TyClDecl(..),
-                 IE(..), ieName, 
-                 ForeignDecl(..), ForKind(..), isDynamic,
-                 FixitySig(..), Sig(..), ImportDecl(..),
-                 collectTopBinders
-               )
-import RdrHsSyn        ( RdrNameIE, RdrNameImportDecl,
-                 RdrNameHsModule, RdrNameHsDecl
-               )
-import RnIfaces        ( getInterfaceExports, getDeclBinders,
-                 recordSlurp, checkUpToDate
-               )
-import RnEnv
-import RnMonad
-
-import FiniteMap
-import PrelMods
-import PrelInfo ( main_RDR )
-import UniqFM  ( lookupUFM )
-import Bag     ( bagToList )
-import Maybes  ( maybeToBool )
-import Module  ( ModuleName, mkThisModule, pprModuleName, WhereFrom(..) )
-import NameSet
-import Name    ( Name, ExportFlag(..), ImportReason(..), Provenance(..),
-                 isLocallyDefined, setNameProvenance,
-                 nameOccName, getSrcLoc, pprProvenance, getNameProvenance
-               )
-import RdrName ( RdrName, rdrNameOcc, mkRdrQual, mkRdrUnqual, isQual )
-import SrcLoc  ( SrcLoc )
-import NameSet ( elemNameSet, emptyNameSet )
-import Outputable
-import Unique  ( getUnique )
-import Util    ( removeDups, equivClassesByUniq, sortLt )
-import List    ( partition )
-\end{code}
-
-
-
-%************************************************************************
-%*                                                                     *
-\subsection{Get global names}
-%*                                                                     *
-%************************************************************************
-
-\begin{code}
-getGlobalNames :: RdrNameHsModule
-              -> RnMG (Maybe (ExportEnv, 
-                              GlobalRdrEnv,
-                              FixityEnv,               -- Fixities for local decls only
-                              NameEnv AvailInfo        -- Maps a name to its parent AvailInfo
-                                                       -- Just for in-scope things only
-                              ))
-                       -- Nothing => no need to recompile
-
-getGlobalNames (HsModule this_mod _ exports imports decls mod_loc)
-  =    -- These two fix-loops are to get the right
-       -- provenance information into a Name
-    fixRn (\ ~(rec_gbl_env, rec_exported_avails, _) ->
-
---       fixRn (\ ~(rec_rn_env, _) ->
-       let
-          rec_unqual_fn :: Name -> Bool        -- Is this chap in scope unqualified?
-          rec_unqual_fn = unQualInScope rec_gbl_env
-
-          rec_exp_fn :: Name -> ExportFlag
-          rec_exp_fn = mk_export_fn (availsToNameSet rec_exported_avails)
-       in
---     setOmitQualFn rec_unqual_fn             $
-       setModuleRn this_mod                    $
-
-               -- PROCESS LOCAL DECLS
-               -- Do these *first* so that the correct provenance gets
-               -- into the global name cache.
-       importsFromLocalDecls this_mod rec_exp_fn decls `thenRn` \ (local_gbl_env, local_mod_avails) ->
-
-               -- PROCESS IMPORT DECLS
-               -- Do the non {- SOURCE -} ones first, so that we get a helpful
-               -- warning for {- SOURCE -} ones that are unnecessary
-       let
-         (source, ordinary) = partition is_source_import all_imports
-         is_source_import (ImportDecl _ ImportByUserSource _ _ _ _) = True
-         is_source_import other                                     = False
-       in
-       mapAndUnzipRn (importsFromImportDecl rec_unqual_fn) ordinary    `thenRn` \ (imp_gbl_envs1, imp_avails_s1) ->
-       mapAndUnzipRn (importsFromImportDecl rec_unqual_fn) source      `thenRn` \ (imp_gbl_envs2, imp_avails_s2) ->
-
-               -- COMBINE RESULTS
-               -- We put the local env second, so that a local provenance
-               -- "wins", even if a module imports itself.
-       let
-           gbl_env :: GlobalRdrEnv
-           imp_gbl_env = foldr plusGlobalRdrEnv emptyRdrEnv (imp_gbl_envs2 ++ imp_gbl_envs1)
-           gbl_env     = imp_gbl_env `plusGlobalRdrEnv` local_gbl_env
-
-           all_avails :: ExportAvails
-           all_avails = foldr plusExportAvails local_mod_avails (imp_avails_s2 ++ imp_avails_s1)
-       in
---     returnRn (gbl_env, all_avails)
---      )                                                      `thenRn` \ (gbl_env, all_avails) ->
-
-       -- TRY FOR EARLY EXIT
-       -- We can't go for an early exit before this because we have to check
-       -- for name clashes.  Consider:
-       --
-       --      module A where          module B where
-       --         import B                h = True
-       --         f = h
-       --
-       -- Suppose I've compiled everything up, and then I add a
-       -- new definition to module B, that defines "f".
-       --
-       -- Then I must detect the name clash in A before going for an early
-       -- exit.  The early-exit code checks what's actually needed from B
-       -- to compile A, and of course that doesn't include B.f.  That's
-       -- why we wait till after the plusEnv stuff to do the early-exit.
-      checkEarlyExit this_mod                  `thenRn` \ up_to_date ->
-      if up_to_date then
-       returnRn (gbl_env, junk_exp_fn, Nothing)
-      else
-       -- RECORD BETTER PROVENANCES IN THE CACHE
-       -- The names in the envirnoment have better provenances (e.g. imported on line x)
-       -- than the names in the name cache.  We update the latter now, so that we
-       -- we start renaming declarations we'll get the good names
-       -- The isQual is because the qualified name is always in scope
-      updateProvenances (concat [names | (rdr_name, names) <- rdrEnvToList imp_gbl_env, 
-                                         isQual rdr_name])     `thenRn_`
-
-       -- PROCESS EXPORT LISTS
-      exportsFromAvail this_mod exports all_avails gbl_env     `thenRn` \ exported_avails ->
-
-       -- DONE
-      returnRn (gbl_env, exported_avails, Just all_avails)
-    )          `thenRn` \ (gbl_env, exported_avails, maybe_stuff) ->
-
-    case maybe_stuff of {
-       Nothing -> returnRn Nothing ;
-       Just all_avails ->
-
-   traceRn (text "updateProv" <+> fsep (map ppr (rdrEnvElts gbl_env))) `thenRn_`
-    
-       -- DEAL WITH FIXITIES
-   fixitiesFromLocalDecls gbl_env decls                `thenRn` \ local_fixity_env ->
-   let
-       -- Export only those fixities that are for names that are
-       --      (a) defined in this module
-       --      (b) exported
-       exported_fixities :: [(Name,Fixity)]
-       exported_fixities = [(name,fixity) | FixitySig name fixity _ <- nameEnvElts local_fixity_env,
-                                            isLocallyDefined name
-                           ]
-   in
-   traceRn (text "fixity env" <+> vcat (map ppr (nameEnvElts local_fixity_env)))       `thenRn_`
-
-       --- TIDY UP 
-   let
-       export_env            = ExportEnv exported_avails exported_fixities
-       (_, global_avail_env) = all_avails
-   in
-   returnRn (Just (export_env, gbl_env, local_fixity_env, global_avail_env))
-   }
-  where
-    junk_exp_fn = error "RnNames:export_fn"
-
-    all_imports = prel_imports ++ imports
-
-       -- NB: opt_NoImplicitPrelude is slightly different to import Prelude ();
-       -- because the former doesn't even look at Prelude.hi for instance declarations,
-       -- whereas the latter does.
-    prel_imports | this_mod == pRELUDE_Name ||
-                  explicit_prelude_import ||
-                  opt_NoImplicitPrelude
-                = []
-
-                | otherwise               = [ImportDecl pRELUDE_Name
-                                                        ImportByUser
-                                                        False          {- Not qualified -}
-                                                        Nothing        {- No "as" -}
-                                                        Nothing        {- No import list -}
-                                                        mod_loc]
-    
-    explicit_prelude_import
-      = not (null [ () | (ImportDecl mod _ _ _ _ _) <- imports, mod == pRELUDE_Name ])
-\end{code}
-       
-\begin{code}
-checkEarlyExit mod
-  = checkErrsRn                                `thenRn` \ no_errs_so_far ->
-    if not no_errs_so_far then
-       -- Found errors already, so exit now
-       returnRn True
-    else
-
-    traceRn (text "Considering whether compilation is required...")    `thenRn_`
-    if not opt_SourceUnchanged then
-       -- Source code changed and no errors yet... carry on 
-       traceRn (nest 4 (text "source file changed or recompilation check turned off")) `thenRn_` 
-       returnRn False
-    else
-
-       -- Unchanged source, and no errors yet; see if usage info
-       -- up to date, and exit if so
-    checkUpToDate mod                                          `thenRn` \ up_to_date ->
-    putDocRn (text "Compilation" <+> 
-             text (if up_to_date then "IS NOT" else "IS") <+>
-             text "required")                                  `thenRn_`
-    returnRn up_to_date
-\end{code}
-       
-\begin{code}
-importsFromImportDecl :: (Name -> Bool)                -- OK to omit qualifier
-                     -> RdrNameImportDecl
-                     -> RnMG (GlobalRdrEnv, 
-                              ExportAvails) 
-
-importsFromImportDecl is_unqual (ImportDecl imp_mod_name from qual_only as_mod import_spec iloc)
-  = pushSrcLocRn iloc $
-    getInterfaceExports imp_mod_name from      `thenRn` \ (imp_mod, avails) ->
-
-    if null avails then
-       -- If there's an error in getInterfaceExports, (e.g. interface
-       -- file not found) we get lots of spurious errors from 'filterImports'
-       returnRn (emptyRdrEnv, mkEmptyExportAvails imp_mod_name)
-    else
-
-    filterImports imp_mod_name import_spec avails      `thenRn` \ (filtered_avails, hides, explicits) ->
-
-       -- We 'improve' the provenance by setting
-       --      (a) the import-reason field, so that the Name says how it came into scope
-       --              including whether it's explicitly imported
-       --      (b) the print-unqualified field
-       -- But don't fiddle with wired-in things or we get in a twist
-    let
-       improve_prov name = setNameProvenance name (NonLocalDef (UserImport imp_mod iloc (is_explicit name)) 
-                                                               (is_unqual name))
-       is_explicit name  = name `elemNameSet` explicits
-    in
-    qualifyImports imp_mod_name
-                  (not qual_only)      -- Maybe want unqualified names
-                  as_mod hides
-                  filtered_avails improve_prov         `thenRn` \ (rdr_name_env, mod_avails) ->
-
-    returnRn (rdr_name_env, mod_avails)
-\end{code}
-
-
-\begin{code}
-importsFromLocalDecls mod_name rec_exp_fn decls
-  = mapRn (getLocalDeclBinders newLocalName) decls     `thenRn` \ avails_s ->
-
-    let
-       avails = concat avails_s
-
-       all_names :: [Name]     -- All the defns; no dups eliminated
-       all_names = [name | avail <- avails, name <- availNames avail]
-
-       dups :: [[Name]]
-       dups = filter non_singleton (equivClassesByUniq getUnique all_names)
-            where
-               non_singleton (x1:x2:xs) = True
-               non_singleton other      = False
-    in
-       -- Check for duplicate definitions
-    mapRn_ (addErrRn . dupDeclErr) dups                `thenRn_` 
-
-       -- Record that locally-defined things are available
-    mapRn_ (recordSlurp Nothing) avails                `thenRn_`
-
-       -- Build the environment
-    qualifyImports mod_name 
-                  True         -- Want unqualified names
-                  Nothing      -- no 'as M'
-                  []           -- Hide nothing
-                  avails
-                  (\n -> n)
-
-  where
-    newLocalName rdr_name loc = newLocalTopBinder mod (rdrNameOcc rdr_name)
-                                                 rec_exp_fn loc
-    mod = mkThisModule mod_name
-
-getLocalDeclBinders :: (RdrName -> SrcLoc -> RnMG Name)        -- New-name function
-                   -> RdrNameHsDecl
-                   -> RnMG Avails
-getLocalDeclBinders new_name (ValD binds)
-  = mapRn do_one (bagToList (collectTopBinders binds))
-  where
-    do_one (rdr_name, loc) = new_name rdr_name loc     `thenRn` \ name ->
-                            returnRn (Avail name)
-
-    -- foreign declarations
-getLocalDeclBinders new_name (ForD (ForeignDecl nm kind _ dyn _ loc))
-  | binds_haskell_name kind dyn
-  = new_name nm loc                `thenRn` \ name ->
-    returnRn [Avail name]
-
-  | otherwise
-  = returnRn []
-
-getLocalDeclBinders new_name decl
-  = getDeclBinders new_name decl       `thenRn` \ maybe_avail ->
-    case maybe_avail of
-       Nothing    -> returnRn []               -- Instance decls and suchlike
-       Just avail -> returnRn [avail]
-
-binds_haskell_name (FoImport _) _   = True
-binds_haskell_name FoLabel      _   = True
-binds_haskell_name FoExport  ext_nm = isDynamic ext_nm
-
-fixitiesFromLocalDecls :: GlobalRdrEnv -> [RdrNameHsDecl] -> RnMG FixityEnv
-fixitiesFromLocalDecls gbl_env decls
-  = foldlRn getFixities emptyNameEnv decls
-  where
-    getFixities :: FixityEnv -> RdrNameHsDecl -> RnMG FixityEnv
-    getFixities acc (FixD fix)
-      = fix_decl acc fix
-
-    getFixities acc (TyClD (ClassDecl _ _ _ sigs _ _ _ _ _ _))
-      = foldlRn fix_decl acc [sig | FixSig sig <- sigs]
-               -- Get fixities from class decl sigs too.
-    getFixities acc other_decl
-      = returnRn acc
-
-    fix_decl acc sig@(FixitySig rdr_name fixity loc)
-       =       -- Check for fixity decl for something not declared
-         case lookupRdrEnv gbl_env rdr_name of {
-           Nothing | opt_WarnUnusedBinds 
-                   -> pushSrcLocRn loc (addWarnRn (unusedFixityDecl rdr_name fixity))  `thenRn_`
-                      returnRn acc 
-                   | otherwise -> returnRn acc ;
-       
-           Just (name:_) ->
-
-               -- Check for duplicate fixity decl
-         case lookupNameEnv acc name of {
-           Just (FixitySig _ _ loc') -> addErrRn (dupFixityDecl rdr_name loc loc')     `thenRn_`
-                                        returnRn acc ;
-
-           Nothing -> returnRn (addToNameEnv acc name (FixitySig name fixity loc))
-         }}
-\end{code}
-
-%************************************************************************
-%*                                                                     *
-\subsection{Filtering imports}
-%*                                                                     *
-%************************************************************************
-
-@filterImports@ takes the @ExportEnv@ telling what the imported module makes
-available, and filters it through the import spec (if any).
-
-\begin{code}
-filterImports :: ModuleName                    -- The module being imported
-             -> Maybe (Bool, [RdrNameIE])      -- Import spec; True => hiding
-             -> [AvailInfo]                    -- What's available
-             -> RnMG ([AvailInfo],             -- What's actually imported
-                      [AvailInfo],             -- What's to be hidden (the unqualified version, that is)
-                      NameSet)                 -- What was imported explicitly
-
-       -- Complains if import spec mentions things that the module doesn't export
-        -- Warns/informs if import spec contains duplicates.
-filterImports mod Nothing imports
-  = returnRn (imports, [], emptyNameSet)
-
-filterImports mod (Just (want_hiding, import_items)) avails
-  = mapMaybeRn check_item import_items         `thenRn` \ avails_w_explicits ->
-    let
-       (item_avails, explicits_s) = unzip avails_w_explicits
-       explicits                  = foldl addListToNameSet emptyNameSet explicits_s
-    in
-    if want_hiding 
-    then       
-       -- All imported; item_avails to be hidden
-       returnRn (avails, item_avails, emptyNameSet)
-    else
-       -- Just item_avails imported; nothing to be hidden
-       returnRn (item_avails, [], explicits)
-  where
-    import_fm :: FiniteMap OccName AvailInfo
-    import_fm = listToFM [ (nameOccName name, avail) 
-                        | avail <- avails,
-                          name  <- availNames avail]
-       -- Even though availNames returns data constructors too,
-       -- they won't make any difference because naked entities like T
-       -- in an import list map to TcOccs, not VarOccs.
-
-    check_item item@(IEModuleContents _)
-      = addErrRn (badImportItemErr mod item)   `thenRn_`
-       returnRn Nothing
-
-    check_item item
-      | not (maybeToBool maybe_in_import_avails) ||
-       not (maybeToBool maybe_filtered_avail)
-      = addErrRn (badImportItemErr mod item)   `thenRn_`
-       returnRn Nothing
-
-      | dodgy_import = addWarnRn (dodgyImportWarn mod item)    `thenRn_`
-                      returnRn (Just (filtered_avail, explicits))
-
-      | otherwise    = returnRn (Just (filtered_avail, explicits))
-               
-      where
-       wanted_occ             = rdrNameOcc (ieName item)
-       maybe_in_import_avails = lookupFM import_fm wanted_occ
-
-       Just avail             = maybe_in_import_avails
-       maybe_filtered_avail   = filterAvail item avail
-       Just filtered_avail    = maybe_filtered_avail
-       explicits              | dot_dot   = [availName filtered_avail]
-                              | otherwise = availNames filtered_avail
-
-       dot_dot = case item of 
-                   IEThingAll _    -> True
-                   other           -> False
-
-       dodgy_import = case (item, avail) of
-                         (IEThingAll _, AvailTC _ [n]) -> True
-                               -- This occurs when you import T(..), but
-                               -- only export T abstractly.  The single [n]
-                               -- in the AvailTC is the type or class itself
-                                       
-                         other -> False
-\end{code}
-
-
-
-%************************************************************************
-%*                                                                     *
-\subsection{Qualifiying imports}
-%*                                                                     *
-%************************************************************************
-
-@qualifyImports@ takes the @ExportEnv@ after filtering through the import spec
-of an import decl, and deals with producing an @RnEnv@ with the 
-right qualified names.  It also turns the @Names@ in the @ExportEnv@ into
-fully fledged @Names@.
-
-\begin{code}
-qualifyImports :: ModuleName           -- Imported module
-              -> Bool                  -- True <=> want unqualified import
-              -> Maybe ModuleName      -- Optional "as M" part 
-              -> [AvailInfo]           -- What's to be hidden
-              -> Avails                -- Whats imported and how
-              -> (Name -> Name)        -- Improves the provenance on imported things
-              -> RnMG (GlobalRdrEnv, ExportAvails)
-       -- NB: the Names in ExportAvails don't have the improve-provenance
-       --     function applied to them
-       -- We could fix that, but I don't think it matters
-
-qualifyImports this_mod unqual_imp as_mod hides
-              avails improve_prov
-  = 
-       -- Make the name environment.  We're talking about a 
-       -- single module here, so there must be no name clashes.
-       -- In practice there only ever will be if it's the module
-       -- being compiled.
-    let
-       -- Add the things that are available
-       name_env1 = foldl add_avail emptyRdrEnv avails
-
-       -- Delete things that are hidden
-       name_env2 = foldl del_avail name_env1 hides
-
-       -- Create the export-availability info
-       export_avails = mkExportAvails qual_mod unqual_imp name_env2 avails
-    in
-    returnRn (name_env2, export_avails)
-
-  where
-    qual_mod = case as_mod of
-                 Nothing           -> this_mod
-                 Just another_name -> another_name
-
-    add_avail :: GlobalRdrEnv -> AvailInfo -> GlobalRdrEnv
-    add_avail env avail = foldl add_name env (availNames avail)
-
-    add_name env name
-       | unqual_imp = env2
-       | otherwise  = env1
-       where
-         env1 = addOneToGlobalRdrEnv env  (mkRdrQual qual_mod occ) better_name
-         env2 = addOneToGlobalRdrEnv env1 (mkRdrUnqual occ)        better_name
-         occ         = nameOccName name
-         better_name = improve_prov name
-
-    del_avail env avail = foldl delOneFromGlobalRdrEnv env rdr_names
-                       where
-                         rdr_names = map (mkRdrUnqual . nameOccName) (availNames avail)
-\end{code}
-
-
-%************************************************************************
-%*                                                                     *
-\subsection{Export list processing
-%*                                                                     *
-%************************************************************************
-
-Processing the export list.
-
-You might think that we should record things that appear in the export list as
-``occurrences'' (using addOccurrenceName), but you'd be wrong.  We do check (here)
-that they are in scope, but there is no need to slurp in their actual declaration
-(which is what addOccurrenceName forces).  Indeed, doing so would big trouble when
-compiling PrelBase, because it re-exports GHC, which includes takeMVar#, whose type
-includes ConcBase.StateAndSynchVar#, and so on...
-
-\begin{code}
-type ExportAccum       -- The type of the accumulating parameter of
-                       -- the main worker function in exportsFromAvail
-     = ([ModuleName],          -- 'module M's seen so far
-       ExportOccMap,           -- Tracks exported occurrence names
-       NameEnv AvailInfo)      -- The accumulated exported stuff, kept in an env
-                               --   so we can common-up related AvailInfos
-
-type ExportOccMap = FiniteMap OccName (Name, RdrNameIE)
-       -- Tracks what a particular exported OccName
-       --   in an export list refers to, and which item
-       --   it came from.  It's illegal to export two distinct things
-       --   that have the same occurrence name
-
-
-exportsFromAvail :: ModuleName
-                -> Maybe [RdrNameIE]   -- Export spec
-                -> ExportAvails
-                -> GlobalRdrEnv 
-                -> RnMG Avails
-       -- Complains if two distinct exports have same OccName
-        -- Warns about identical exports.
-       -- Complains about exports items not in scope
-exportsFromAvail this_mod Nothing export_avails global_name_env
-  = exportsFromAvail this_mod true_exports export_avails global_name_env
-  where
-    true_exports = Just $ if this_mod == mAIN_Name
-                          then [IEVar main_RDR]
-                               -- export Main.main *only* unless otherwise specified,
-                          else [IEModuleContents this_mod]
-                               -- but for all other modules export everything.
-
-exportsFromAvail this_mod (Just export_items) 
-                (mod_avail_env, entity_avail_env)
-                global_name_env
-  = foldlRn exports_from_item
-           ([], emptyFM, emptyNameEnv) export_items    `thenRn` \ (_, _, export_avail_map) ->
-    let
-       export_avails :: [AvailInfo]
-       export_avails   = nameEnvElts export_avail_map
-    in
-    returnRn export_avails
-
-  where
-    exports_from_item :: ExportAccum -> RdrNameIE -> RnMG ExportAccum
-
-    exports_from_item acc@(mods, occs, avails) ie@(IEModuleContents mod)
-       | mod `elem` mods       -- Duplicate export of M
-       = warnCheckRn opt_WarnDuplicateExports
-                     (dupModuleExport mod)     `thenRn_`
-         returnRn acc
-
-       | otherwise
-       = case lookupFM mod_avail_env mod of
-               Nothing         -> failWithRn acc (modExportErr mod)
-               Just mod_avails -> foldlRn (check_occs ie) occs mod_avails      `thenRn` \ occs' ->
-                                  let
-                                       avails' = foldl add_avail avails mod_avails
-                                  in
-                                  returnRn (mod:mods, occs', avails')
-
-    exports_from_item acc@(mods, occs, avails) ie
-       | not (maybeToBool maybe_in_scope) 
-       = failWithRn acc (unknownNameErr (ieName ie))
-
-       | not (null dup_names)
-       = addNameClashErrRn rdr_name (name:dup_names)   `thenRn_`
-         returnRn acc
-
-#ifdef DEBUG
-       -- I can't see why this should ever happen; if the thing is in scope
-       -- at all it ought to have some availability
-       | not (maybeToBool maybe_avail)
-       = pprTrace "exportsFromAvail: curious Nothing:" (ppr name)
-         returnRn acc
-#endif
-
-       | not enough_avail
-       = failWithRn acc (exportItemErr ie)
-
-       | otherwise     -- Phew!  It's OK!  Now to check the occurrence stuff!
-       = check_occs ie occs export_avail       `thenRn` \ occs' ->
-         returnRn (mods, occs', add_avail avails export_avail)
-
-       where
-         rdr_name        = ieName ie
-          maybe_in_scope  = lookupFM global_name_env rdr_name
-         Just (name:dup_names) = maybe_in_scope
-         maybe_avail        = lookupUFM entity_avail_env name
-         Just avail         = maybe_avail
-         maybe_export_avail = filterAvail ie avail
-         enough_avail       = maybeToBool maybe_export_avail
-         Just export_avail  = maybe_export_avail
-
-add_avail avails avail = addToNameEnv_C plusAvail avails (availName avail) avail
-
-check_occs :: RdrNameIE -> ExportOccMap -> AvailInfo -> RnMG ExportOccMap
-check_occs ie occs avail 
-  = foldlRn check occs (availNames avail)
-  where
-    check occs name
-      = case lookupFM occs name_occ of
-         Nothing           -> returnRn (addToFM occs name_occ (name, ie))
-         Just (name', ie') 
-           | name == name' ->  -- Duplicate export
-                               warnCheckRn opt_WarnDuplicateExports
-                                           (dupExportWarn name_occ ie ie')     `thenRn_`
-                               returnRn occs
-
-           | otherwise     ->  -- Same occ name but different names: an error
-                               failWithRn occs (exportClashErr name_occ ie ie')
-      where
-       name_occ = nameOccName name
-       
-mk_export_fn :: NameSet -> (Name -> ExportFlag)
-mk_export_fn exported_names
-  = \name -> if name `elemNameSet` exported_names
-            then Exported
-            else NotExported
-\end{code}
-
-%************************************************************************
-%*                                                                     *
-\subsection{Errors}
-%*                                                                     *
-%************************************************************************
-
-\begin{code}
-badImportItemErr mod ie
-  = sep [ptext SLIT("Module"), quotes (pprModuleName mod), 
-        ptext SLIT("does not export"), quotes (ppr ie)]
-
-dodgyImportWarn mod (IEThingAll tc)
-  = sep [ptext SLIT("Module") <+> quotes (pprModuleName mod) <+> ptext SLIT("exports") <+> quotes (ppr tc), 
-        ptext SLIT("with no constructors/class operations;"),
-        ptext SLIT("yet it is imported with a (..)")]
-
-modExportErr mod
-  = hsep [ ptext SLIT("Unknown module in export list: module"), quotes (pprModuleName mod)]
-
-exportItemErr export_item
-  = sep [ ptext SLIT("Bad export item"), quotes (ppr export_item)]
-
-exportClashErr occ_name ie1 ie2
-  = hsep [ptext SLIT("The export items"), quotes (ppr ie1), ptext SLIT("and"), quotes (ppr ie2),
-         ptext SLIT("create conflicting exports for"), quotes (ppr occ_name)]
-
-dupDeclErr (n:ns)
-  = vcat [ptext SLIT("Multiple declarations of") <+> quotes (ppr n),
-         nest 4 (vcat (map pp sorted_ns))]
-  where
-    sorted_ns = sortLt occ'ed_before (n:ns)
-
-    occ'ed_before a b = LT == compare (getSrcLoc a) (getSrcLoc b)
-
-    pp n      = pprProvenance (getNameProvenance n)
-
-dupExportWarn occ_name ie1 ie2
-  = hsep [quotes (ppr occ_name), 
-          ptext SLIT("is exported by"), quotes (ppr ie1),
-          ptext SLIT("and"),            quotes (ppr ie2)]
-
-dupModuleExport mod
-  = hsep [ptext SLIT("Duplicate"),
-         quotes (ptext SLIT("Module") <+> pprModuleName mod), 
-          ptext SLIT("in export list")]
-
-unusedFixityDecl rdr_name fixity
-  = hsep [ptext SLIT("Unused fixity declaration for"), quotes (ppr rdr_name)]
-
-dupFixityDecl rdr_name loc1 loc2
-  = vcat [ptext SLIT("Multiple fixity declarations for") <+> quotes (ppr rdr_name),
-         ptext SLIT("at ") <+> ppr loc1,
-         ptext SLIT("and") <+> ppr loc2]
-
-\end{code}
+%\r
+% (c) The GRASP/AQUA Project, Glasgow University, 1992-1998\r
+%\r
+\section[RnNames]{Extracting imported and top-level names in scope}\r
+\r
+\begin{code}\r
+module RnNames (\r
+       getGlobalNames\r
+    ) where\r
+\r
+#include "HsVersions.h"\r
+\r
+import CmdLineOpts    ( opt_NoImplicitPrelude, opt_WarnDuplicateExports, \r
+                       opt_SourceUnchanged, opt_WarnUnusedBinds\r
+                     )\r
+\r
+import HsSyn   ( HsModule(..), HsDecl(..), TyClDecl(..),\r
+                 IE(..), ieName, \r
+                 ForeignDecl(..), ForKind(..), isDynamic,\r
+                 FixitySig(..), Sig(..), ImportDecl(..),\r
+                 collectTopBinders\r
+               )\r
+import RdrHsSyn        ( RdrNameIE, RdrNameImportDecl,\r
+                 RdrNameHsModule, RdrNameHsDecl\r
+               )\r
+import RnIfaces        ( getInterfaceExports, getDeclBinders,\r
+                 recordSlurp, checkUpToDate\r
+               )\r
+import RnEnv\r
+import RnMonad\r
+\r
+import FiniteMap\r
+import PrelMods\r
+import PrelInfo ( main_RDR )\r
+import UniqFM  ( lookupUFM )\r
+import Bag     ( bagToList )\r
+import Maybes  ( maybeToBool )\r
+import Module  ( ModuleName, mkThisModule, pprModuleName, WhereFrom(..) )\r
+import NameSet\r
+import Name    ( Name, ExportFlag(..), ImportReason(..), Provenance(..),\r
+                 isLocallyDefined, setNameProvenance,\r
+                 nameOccName, getSrcLoc, pprProvenance, getNameProvenance\r
+               )\r
+import RdrName ( RdrName, rdrNameOcc, mkRdrQual, mkRdrUnqual, isQual )\r
+import SrcLoc  ( SrcLoc )\r
+import NameSet ( elemNameSet, emptyNameSet )\r
+import Outputable\r
+import Unique  ( getUnique )\r
+import Util    ( removeDups, equivClassesByUniq, sortLt )\r
+import List    ( partition )\r
+\end{code}\r
+\r
+\r
+\r
+%************************************************************************\r
+%*                                                                     *\r
+\subsection{Get global names}\r
+%*                                                                     *\r
+%************************************************************************\r
+\r
+\begin{code}\r
+getGlobalNames :: RdrNameHsModule\r
+              -> RnMG (Maybe (ExportEnv, \r
+                              GlobalRdrEnv,\r
+                              FixityEnv,               -- Fixities for local decls only\r
+                              NameEnv AvailInfo        -- Maps a name to its parent AvailInfo\r
+                                                       -- Just for in-scope things only\r
+                              ))\r
+                       -- Nothing => no need to recompile\r
+\r
+getGlobalNames (HsModule this_mod _ exports imports decls mod_loc)\r
+  =    -- These two fix-loops are to get the right\r
+       -- provenance information into a Name\r
+    fixRn (\ ~(rec_gbl_env, rec_exported_avails, _) ->\r
+\r
+       let\r
+          rec_unqual_fn :: Name -> Bool        -- Is this chap in scope unqualified?\r
+          rec_unqual_fn = unQualInScope rec_gbl_env\r
+\r
+          rec_exp_fn :: Name -> ExportFlag\r
+          rec_exp_fn = mk_export_fn (availsToNameSet rec_exported_avails)\r
+       in\r
+       setModuleRn this_mod                    $\r
+\r
+               -- PROCESS LOCAL DECLS\r
+               -- Do these *first* so that the correct provenance gets\r
+               -- into the global name cache.\r
+       importsFromLocalDecls this_mod rec_exp_fn decls `thenRn` \ (local_gbl_env, local_mod_avails) ->\r
+\r
+               -- PROCESS IMPORT DECLS\r
+               -- Do the non {- SOURCE -} ones first, so that we get a helpful\r
+               -- warning for {- SOURCE -} ones that are unnecessary\r
+       let\r
+         (source, ordinary) = partition is_source_import all_imports\r
+         is_source_import (ImportDecl _ ImportByUserSource _ _ _ _) = True\r
+         is_source_import other                                     = False\r
+       in\r
+       mapAndUnzipRn (importsFromImportDecl rec_unqual_fn) ordinary    `thenRn` \ (imp_gbl_envs1, imp_avails_s1) ->\r
+       mapAndUnzipRn (importsFromImportDecl rec_unqual_fn) source      `thenRn` \ (imp_gbl_envs2, imp_avails_s2) ->\r
+\r
+               -- COMBINE RESULTS\r
+               -- We put the local env second, so that a local provenance\r
+               -- "wins", even if a module imports itself.\r
+       let\r
+           gbl_env :: GlobalRdrEnv\r
+           imp_gbl_env = foldr plusGlobalRdrEnv emptyRdrEnv (imp_gbl_envs2 ++ imp_gbl_envs1)\r
+           gbl_env     = imp_gbl_env `plusGlobalRdrEnv` local_gbl_env\r
+\r
+           all_avails :: ExportAvails\r
+           all_avails = foldr plusExportAvails local_mod_avails (imp_avails_s2 ++ imp_avails_s1)\r
+       in\r
+\r
+       -- TRY FOR EARLY EXIT\r
+       -- We can't go for an early exit before this because we have to check\r
+       -- for name clashes.  Consider:\r
+       --\r
+       --      module A where          module B where\r
+       --         import B                h = True\r
+       --         f = h\r
+       --\r
+       -- Suppose I've compiled everything up, and then I add a\r
+       -- new definition to module B, that defines "f".\r
+       --\r
+       -- Then I must detect the name clash in A before going for an early\r
+       -- exit.  The early-exit code checks what's actually needed from B\r
+       -- to compile A, and of course that doesn't include B.f.  That's\r
+       -- why we wait till after the plusEnv stuff to do the early-exit.\r
+      checkEarlyExit this_mod                  `thenRn` \ up_to_date ->\r
+      if up_to_date then\r
+       returnRn (gbl_env, junk_exp_fn, Nothing)\r
+      else\r
\r
+       -- RECORD BETTER PROVENANCES IN THE CACHE\r
+       -- The names in the envirnoment have better provenances (e.g. imported on line x)\r
+       -- than the names in the name cache.  We update the latter now, so that we\r
+       -- we start renaming declarations we'll get the good names\r
+       -- The isQual is because the qualified name is always in scope\r
+      updateProvenances (concat [names | (rdr_name, names) <- rdrEnvToList imp_gbl_env, \r
+                                         isQual rdr_name])     `thenRn_`\r
+\r
+       -- PROCESS EXPORT LISTS\r
+      exportsFromAvail this_mod exports all_avails gbl_env     `thenRn` \ exported_avails ->\r
+\r
+       -- DONE\r
+      returnRn (gbl_env, exported_avails, Just all_avails)\r
+    )          `thenRn` \ (gbl_env, exported_avails, maybe_stuff) ->\r
+\r
+    case maybe_stuff of {\r
+       Nothing -> returnRn Nothing ;\r
+       Just all_avails ->\r
+\r
+   traceRn (text "updateProv" <+> fsep (map ppr (rdrEnvElts gbl_env))) `thenRn_`\r
+    \r
+       -- DEAL WITH FIXITIES\r
+   fixitiesFromLocalDecls gbl_env decls                `thenRn` \ local_fixity_env ->\r
+   let\r
+       -- Export only those fixities that are for names that are\r
+       --      (a) defined in this module\r
+       --      (b) exported\r
+       exported_fixities :: [(Name,Fixity)]\r
+       exported_fixities = [(name,fixity) | FixitySig name fixity _ <- nameEnvElts local_fixity_env,\r
+                                            isLocallyDefined name\r
+                           ]\r
+   in\r
+   traceRn (text "fixity env" <+> vcat (map ppr (nameEnvElts local_fixity_env)))       `thenRn_`\r
+\r
+       --- TIDY UP \r
+   let\r
+       export_env            = ExportEnv exported_avails exported_fixities\r
+       (_, global_avail_env) = all_avails\r
+   in\r
+   returnRn (Just (export_env, gbl_env, local_fixity_env, global_avail_env))\r
+   }\r
+  where\r
+    junk_exp_fn = error "RnNames:export_fn"\r
+\r
+    all_imports = prel_imports ++ imports\r
+\r
+       -- NB: opt_NoImplicitPrelude is slightly different to import Prelude ();\r
+       -- because the former doesn't even look at Prelude.hi for instance declarations,\r
+       -- whereas the latter does.\r
+    prel_imports | this_mod == pRELUDE_Name ||\r
+                  explicit_prelude_import ||\r
+                  opt_NoImplicitPrelude\r
+                = []\r
+\r
+                | otherwise               = [ImportDecl pRELUDE_Name\r
+                                                        ImportByUser\r
+                                                        False          {- Not qualified -}\r
+                                                        Nothing        {- No "as" -}\r
+                                                        Nothing        {- No import list -}\r
+                                                        mod_loc]\r
+    \r
+    explicit_prelude_import\r
+      = not (null [ () | (ImportDecl mod _ _ _ _ _) <- imports, mod == pRELUDE_Name ])\r
+\end{code}\r
+       \r
+\begin{code}\r
+checkEarlyExit mod\r
+  = checkErrsRn                                `thenRn` \ no_errs_so_far ->\r
+    if not no_errs_so_far then\r
+       -- Found errors already, so exit now\r
+       returnRn True\r
+    else\r
+\r
+    traceRn (text "Considering whether compilation is required...")    `thenRn_`\r
+    if not opt_SourceUnchanged then\r
+       -- Source code changed and no errors yet... carry on \r
+       traceRn (nest 4 (text "source file changed or recompilation check turned off")) `thenRn_` \r
+       returnRn False\r
+    else\r
+\r
+       -- Unchanged source, and no errors yet; see if usage info\r
+       -- up to date, and exit if so\r
+    checkUpToDate mod                                          `thenRn` \ up_to_date ->\r
+    putDocRn (text "Compilation" <+> \r
+             text (if up_to_date then "IS NOT" else "IS") <+>\r
+             text "required")                                  `thenRn_`\r
+    returnRn up_to_date\r
+\end{code}\r
+       \r
+\begin{code}\r
+importsFromImportDecl :: (Name -> Bool)                -- OK to omit qualifier\r
+                     -> RdrNameImportDecl\r
+                     -> RnMG (GlobalRdrEnv, \r
+                              ExportAvails) \r
+\r
+importsFromImportDecl is_unqual (ImportDecl imp_mod_name from qual_only as_mod import_spec iloc)\r
+  = pushSrcLocRn iloc $\r
+    getInterfaceExports imp_mod_name from      `thenRn` \ (imp_mod, avails) ->\r
+\r
+    if null avails then\r
+       -- If there's an error in getInterfaceExports, (e.g. interface\r
+       -- file not found) we get lots of spurious errors from 'filterImports'\r
+       returnRn (emptyRdrEnv, mkEmptyExportAvails imp_mod_name)\r
+    else\r
+\r
+    filterImports imp_mod_name import_spec avails      `thenRn` \ (filtered_avails, hides, explicits) ->\r
+\r
+       -- We 'improve' the provenance by setting\r
+       --      (a) the import-reason field, so that the Name says how it came into scope\r
+       --              including whether it's explicitly imported\r
+       --      (b) the print-unqualified field\r
+       -- But don't fiddle with wired-in things or we get in a twist\r
+    let\r
+       improve_prov name = setNameProvenance name (NonLocalDef (UserImport imp_mod iloc (is_explicit name)) \r
+                                                               (is_unqual name))\r
+       is_explicit name  = name `elemNameSet` explicits\r
+    in\r
+    qualifyImports imp_mod_name\r
+                  (not qual_only)      -- Maybe want unqualified names\r
+                  as_mod hides\r
+                  filtered_avails improve_prov         `thenRn` \ (rdr_name_env, mod_avails) ->\r
+\r
+    returnRn (rdr_name_env, mod_avails)\r
+\end{code}\r
+\r
+\r
+\begin{code}\r
+importsFromLocalDecls mod_name rec_exp_fn decls\r
+  = mapRn (getLocalDeclBinders newLocalName) decls     `thenRn` \ avails_s ->\r
+\r
+    let\r
+       avails = concat avails_s\r
+\r
+       all_names :: [Name]     -- All the defns; no dups eliminated\r
+       all_names = [name | avail <- avails, name <- availNames avail]\r
+\r
+       dups :: [[Name]]\r
+       dups = filter non_singleton (equivClassesByUniq getUnique all_names)\r
+            where\r
+               non_singleton (x1:x2:xs) = True\r
+               non_singleton other      = False\r
+    in\r
+       -- Check for duplicate definitions\r
+    mapRn_ (addErrRn . dupDeclErr) dups                `thenRn_` \r
+\r
+       -- Record that locally-defined things are available\r
+    mapRn_ (recordSlurp Nothing) avails                `thenRn_`\r
+\r
+       -- Build the environment\r
+    qualifyImports mod_name \r
+                  True         -- Want unqualified names\r
+                  Nothing      -- no 'as M'\r
+                  []           -- Hide nothing\r
+                  avails\r
+                  (\n -> n)\r
+\r
+  where\r
+    newLocalName rdr_name loc = newLocalTopBinder mod (rdrNameOcc rdr_name)\r
+                                                 rec_exp_fn loc\r
+    mod = mkThisModule mod_name\r
+\r
+getLocalDeclBinders :: (RdrName -> SrcLoc -> RnMG Name)        -- New-name function\r
+                   -> RdrNameHsDecl\r
+                   -> RnMG Avails\r
+getLocalDeclBinders new_name (ValD binds)\r
+  = mapRn do_one (bagToList (collectTopBinders binds))\r
+  where\r
+    do_one (rdr_name, loc) = new_name rdr_name loc     `thenRn` \ name ->\r
+                            returnRn (Avail name)\r
+\r
+    -- foreign declarations\r
+getLocalDeclBinders new_name (ForD (ForeignDecl nm kind _ dyn _ loc))\r
+  | binds_haskell_name kind dyn\r
+  = new_name nm loc                `thenRn` \ name ->\r
+    returnRn [Avail name]\r
+\r
+  | otherwise\r
+  = returnRn []\r
+\r
+getLocalDeclBinders new_name decl\r
+  = getDeclBinders new_name decl       `thenRn` \ maybe_avail ->\r
+    case maybe_avail of\r
+       Nothing    -> returnRn []               -- Instance decls and suchlike\r
+       Just avail -> returnRn [avail]\r
+\r
+binds_haskell_name (FoImport _) _   = True\r
+binds_haskell_name FoLabel      _   = True\r
+binds_haskell_name FoExport  ext_nm = isDynamic ext_nm\r
+\r
+fixitiesFromLocalDecls :: GlobalRdrEnv -> [RdrNameHsDecl] -> RnMG FixityEnv\r
+fixitiesFromLocalDecls gbl_env decls\r
+  = foldlRn getFixities emptyNameEnv decls\r
+  where\r
+    getFixities :: FixityEnv -> RdrNameHsDecl -> RnMG FixityEnv\r
+    getFixities acc (FixD fix)\r
+      = fix_decl acc fix\r
+\r
+    getFixities acc (TyClD (ClassDecl _ _ _ sigs _ _ _ _ _ _))\r
+      = foldlRn fix_decl acc [sig | FixSig sig <- sigs]\r
+               -- Get fixities from class decl sigs too.\r
+    getFixities acc other_decl\r
+      = returnRn acc\r
+\r
+    fix_decl acc sig@(FixitySig rdr_name fixity loc)\r
+       =       -- Check for fixity decl for something not declared\r
+         case lookupRdrEnv gbl_env rdr_name of {\r
+           Nothing | opt_WarnUnusedBinds \r
+                   -> pushSrcLocRn loc (addWarnRn (unusedFixityDecl rdr_name fixity))  `thenRn_`\r
+                      returnRn acc \r
+                   | otherwise -> returnRn acc ;\r
+       \r
+           Just (name:_) ->\r
+\r
+               -- Check for duplicate fixity decl\r
+         case lookupNameEnv acc name of {\r
+           Just (FixitySig _ _ loc') -> addErrRn (dupFixityDecl rdr_name loc loc')     `thenRn_`\r
+                                        returnRn acc ;\r
+\r
+           Nothing -> returnRn (addToNameEnv acc name (FixitySig name fixity loc))\r
+         }}\r
+\end{code}\r
+\r
+%************************************************************************\r
+%*                                                                     *\r
+\subsection{Filtering imports}\r
+%*                                                                     *\r
+%************************************************************************\r
+\r
+@filterImports@ takes the @ExportEnv@ telling what the imported module makes\r
+available, and filters it through the import spec (if any).\r
+\r
+\begin{code}\r
+filterImports :: ModuleName                    -- The module being imported\r
+             -> Maybe (Bool, [RdrNameIE])      -- Import spec; True => hiding\r
+             -> [AvailInfo]                    -- What's available\r
+             -> RnMG ([AvailInfo],             -- What's actually imported\r
+                      [AvailInfo],             -- What's to be hidden (the unqualified version, that is)\r
+                      NameSet)                 -- What was imported explicitly\r
+\r
+       -- Complains if import spec mentions things that the module doesn't export\r
+        -- Warns/informs if import spec contains duplicates.\r
+filterImports mod Nothing imports\r
+  = returnRn (imports, [], emptyNameSet)\r
+\r
+filterImports mod (Just (want_hiding, import_items)) avails\r
+  = mapMaybeRn check_item import_items         `thenRn` \ avails_w_explicits ->\r
+    let\r
+       (item_avails, explicits_s) = unzip avails_w_explicits\r
+       explicits                  = foldl addListToNameSet emptyNameSet explicits_s\r
+    in\r
+    if want_hiding \r
+    then       \r
+       -- All imported; item_avails to be hidden\r
+       returnRn (avails, item_avails, emptyNameSet)\r
+    else\r
+       -- Just item_avails imported; nothing to be hidden\r
+       returnRn (item_avails, [], explicits)\r
+  where\r
+    import_fm :: FiniteMap OccName AvailInfo\r
+    import_fm = listToFM [ (nameOccName name, avail) \r
+                        | avail <- avails,\r
+                          name  <- availNames avail]\r
+       -- Even though availNames returns data constructors too,\r
+       -- they won't make any difference because naked entities like T\r
+       -- in an import list map to TcOccs, not VarOccs.\r
+\r
+    check_item item@(IEModuleContents _)\r
+      = addErrRn (badImportItemErr mod item)   `thenRn_`\r
+       returnRn Nothing\r
+\r
+    check_item item\r
+      | not (maybeToBool maybe_in_import_avails) ||\r
+       not (maybeToBool maybe_filtered_avail)\r
+      = addErrRn (badImportItemErr mod item)   `thenRn_`\r
+       returnRn Nothing\r
+\r
+      | dodgy_import = addWarnRn (dodgyImportWarn mod item)    `thenRn_`\r
+                      returnRn (Just (filtered_avail, explicits))\r
+\r
+      | otherwise    = returnRn (Just (filtered_avail, explicits))\r
+               \r
+      where\r
+       wanted_occ             = rdrNameOcc (ieName item)\r
+       maybe_in_import_avails = lookupFM import_fm wanted_occ\r
+\r
+       Just avail             = maybe_in_import_avails\r
+       maybe_filtered_avail   = filterAvail item avail\r
+       Just filtered_avail    = maybe_filtered_avail\r
+       explicits              | dot_dot   = [availName filtered_avail]\r
+                              | otherwise = availNames filtered_avail\r
+\r
+       dot_dot = case item of \r
+                   IEThingAll _    -> True\r
+                   other           -> False\r
+\r
+       dodgy_import = case (item, avail) of\r
+                         (IEThingAll _, AvailTC _ [n]) -> True\r
+                               -- This occurs when you import T(..), but\r
+                               -- only export T abstractly.  The single [n]\r
+                               -- in the AvailTC is the type or class itself\r
+                                       \r
+                         other -> False\r
+\end{code}\r
+\r
+\r
+\r
+%************************************************************************\r
+%*                                                                     *\r
+\subsection{Qualifiying imports}\r
+%*                                                                     *\r
+%************************************************************************\r
+\r
+@qualifyImports@ takes the @ExportEnv@ after filtering through the import spec\r
+of an import decl, and deals with producing an @RnEnv@ with the \r
+right qualified names.  It also turns the @Names@ in the @ExportEnv@ into\r
+fully fledged @Names@.\r
+\r
+\begin{code}\r
+qualifyImports :: ModuleName           -- Imported module\r
+              -> Bool                  -- True <=> want unqualified import\r
+              -> Maybe ModuleName      -- Optional "as M" part \r
+              -> [AvailInfo]           -- What's to be hidden\r
+              -> Avails                -- Whats imported and how\r
+              -> (Name -> Name)        -- Improves the provenance on imported things\r
+              -> RnMG (GlobalRdrEnv, ExportAvails)\r
+       -- NB: the Names in ExportAvails don't have the improve-provenance\r
+       --     function applied to them\r
+       -- We could fix that, but I don't think it matters\r
+\r
+qualifyImports this_mod unqual_imp as_mod hides\r
+              avails improve_prov\r
+  = \r
+       -- Make the name environment.  We're talking about a \r
+       -- single module here, so there must be no name clashes.\r
+       -- In practice there only ever will be if it's the module\r
+       -- being compiled.\r
+    let\r
+       -- Add the things that are available\r
+       name_env1 = foldl add_avail emptyRdrEnv avails\r
+\r
+       -- Delete things that are hidden\r
+       name_env2 = foldl del_avail name_env1 hides\r
+\r
+       -- Create the export-availability info\r
+       export_avails = mkExportAvails qual_mod unqual_imp name_env2 avails\r
+    in\r
+    returnRn (name_env2, export_avails)\r
+\r
+  where\r
+    qual_mod = case as_mod of\r
+                 Nothing           -> this_mod\r
+                 Just another_name -> another_name\r
+\r
+    add_avail :: GlobalRdrEnv -> AvailInfo -> GlobalRdrEnv\r
+    add_avail env avail = foldl add_name env (availNames avail)\r
+\r
+    add_name env name\r
+       | unqual_imp = env2\r
+       | otherwise  = env1\r
+       where\r
+         env1 = addOneToGlobalRdrEnv env  (mkRdrQual qual_mod occ) better_name\r
+         env2 = addOneToGlobalRdrEnv env1 (mkRdrUnqual occ)        better_name\r
+         occ         = nameOccName name\r
+         better_name = improve_prov name\r
+\r
+    del_avail env avail = foldl delOneFromGlobalRdrEnv env rdr_names\r
+                       where\r
+                         rdr_names = map (mkRdrUnqual . nameOccName) (availNames avail)\r
+\end{code}\r
+\r
+\r
+%************************************************************************\r
+%*                                                                     *\r
+\subsection{Export list processing\r
+%*                                                                     *\r
+%************************************************************************\r
+\r
+Processing the export list.\r
+\r
+You might think that we should record things that appear in the export list as\r
+``occurrences'' (using addOccurrenceName), but you'd be wrong.  We do check (here)\r
+that they are in scope, but there is no need to slurp in their actual declaration\r
+(which is what addOccurrenceName forces).  Indeed, doing so would big trouble when\r
+compiling PrelBase, because it re-exports GHC, which includes takeMVar#, whose type\r
+includes ConcBase.StateAndSynchVar#, and so on...\r
+\r
+\begin{code}\r
+type ExportAccum       -- The type of the accumulating parameter of\r
+                       -- the main worker function in exportsFromAvail\r
+     = ([ModuleName],          -- 'module M's seen so far\r
+       ExportOccMap,           -- Tracks exported occurrence names\r
+       NameEnv AvailInfo)      -- The accumulated exported stuff, kept in an env\r
+                               --   so we can common-up related AvailInfos\r
+\r
+type ExportOccMap = FiniteMap OccName (Name, RdrNameIE)\r
+       -- Tracks what a particular exported OccName\r
+       --   in an export list refers to, and which item\r
+       --   it came from.  It's illegal to export two distinct things\r
+       --   that have the same occurrence name\r
+\r
+\r
+exportsFromAvail :: ModuleName\r
+                -> Maybe [RdrNameIE]   -- Export spec\r
+                -> ExportAvails\r
+                -> GlobalRdrEnv \r
+                -> RnMG Avails\r
+       -- Complains if two distinct exports have same OccName\r
+        -- Warns about identical exports.\r
+       -- Complains about exports items not in scope\r
+exportsFromAvail this_mod Nothing export_avails global_name_env\r
+  = exportsFromAvail this_mod true_exports export_avails global_name_env\r
+  where\r
+    true_exports = Just $ if this_mod == mAIN_Name\r
+                          then [IEVar main_RDR]\r
+                               -- export Main.main *only* unless otherwise specified,\r
+                          else [IEModuleContents this_mod]\r
+                               -- but for all other modules export everything.\r
+\r
+exportsFromAvail this_mod (Just export_items) \r
+                (mod_avail_env, entity_avail_env)\r
+                global_name_env\r
+  = foldlRn exports_from_item\r
+           ([], emptyFM, emptyNameEnv) export_items    `thenRn` \ (_, _, export_avail_map) ->\r
+    let\r
+       export_avails :: [AvailInfo]\r
+       export_avails   = nameEnvElts export_avail_map\r
+    in\r
+    returnRn export_avails\r
+\r
+  where\r
+    exports_from_item :: ExportAccum -> RdrNameIE -> RnMG ExportAccum\r
+\r
+    exports_from_item acc@(mods, occs, avails) ie@(IEModuleContents mod)\r
+       | mod `elem` mods       -- Duplicate export of M\r
+       = warnCheckRn opt_WarnDuplicateExports\r
+                     (dupModuleExport mod)     `thenRn_`\r
+         returnRn acc\r
+\r
+       | otherwise\r
+       = case lookupFM mod_avail_env mod of\r
+               Nothing         -> failWithRn acc (modExportErr mod)\r
+               Just mod_avails -> foldlRn (check_occs ie) occs mod_avails      `thenRn` \ occs' ->\r
+                                  let\r
+                                       avails' = foldl add_avail avails mod_avails\r
+                                  in\r
+                                  returnRn (mod:mods, occs', avails')\r
+\r
+    exports_from_item acc@(mods, occs, avails) ie\r
+       | not (maybeToBool maybe_in_scope) \r
+       = failWithRn acc (unknownNameErr (ieName ie))\r
+\r
+       | not (null dup_names)\r
+       = addNameClashErrRn rdr_name (name:dup_names)   `thenRn_`\r
+         returnRn acc\r
+\r
+#ifdef DEBUG\r
+       -- I can't see why this should ever happen; if the thing is in scope\r
+       -- at all it ought to have some availability\r
+       | not (maybeToBool maybe_avail)\r
+       = pprTrace "exportsFromAvail: curious Nothing:" (ppr name)\r
+         returnRn acc\r
+#endif\r
+\r
+       | not enough_avail\r
+       = failWithRn acc (exportItemErr ie)\r
+\r
+       | otherwise     -- Phew!  It's OK!  Now to check the occurrence stuff!\r
+       = check_occs ie occs export_avail       `thenRn` \ occs' ->\r
+         returnRn (mods, occs', add_avail avails export_avail)\r
+\r
+       where\r
+         rdr_name        = ieName ie\r
+          maybe_in_scope  = lookupFM global_name_env rdr_name\r
+         Just (name:dup_names) = maybe_in_scope\r
+         maybe_avail        = lookupUFM entity_avail_env name\r
+         Just avail         = maybe_avail\r
+         maybe_export_avail = filterAvail ie avail\r
+         enough_avail       = maybeToBool maybe_export_avail\r
+         Just export_avail  = maybe_export_avail\r
+\r
+add_avail avails avail = addToNameEnv_C plusAvail avails (availName avail) avail\r
+\r
+check_occs :: RdrNameIE -> ExportOccMap -> AvailInfo -> RnMG ExportOccMap\r
+check_occs ie occs avail \r
+  = foldlRn check occs (availNames avail)\r
+  where\r
+    check occs name\r
+      = case lookupFM occs name_occ of\r
+         Nothing           -> returnRn (addToFM occs name_occ (name, ie))\r
+         Just (name', ie') \r
+           | name == name' ->  -- Duplicate export\r
+                               warnCheckRn opt_WarnDuplicateExports\r
+                                           (dupExportWarn name_occ ie ie')     `thenRn_`\r
+                               returnRn occs\r
+\r
+           | otherwise     ->  -- Same occ name but different names: an error\r
+                               failWithRn occs (exportClashErr name_occ ie ie')\r
+      where\r
+       name_occ = nameOccName name\r
+       \r
+mk_export_fn :: NameSet -> (Name -> ExportFlag)\r
+mk_export_fn exported_names\r
+  = \name -> if name `elemNameSet` exported_names\r
+            then Exported\r
+            else NotExported\r
+\end{code}\r
+\r
+%************************************************************************\r
+%*                                                                     *\r
+\subsection{Errors}\r
+%*                                                                     *\r
+%************************************************************************\r
+\r
+\begin{code}\r
+badImportItemErr mod ie\r
+  = sep [ptext SLIT("Module"), quotes (pprModuleName mod), \r
+        ptext SLIT("does not export"), quotes (ppr ie)]\r
+\r
+dodgyImportWarn mod (IEThingAll tc)\r
+  = sep [ptext SLIT("Module") <+> quotes (pprModuleName mod) <+> ptext SLIT("exports") <+> quotes (ppr tc), \r
+        ptext SLIT("with no constructors/class operations;"),\r
+        ptext SLIT("yet it is imported with a (..)")]\r
+\r
+modExportErr mod\r
+  = hsep [ ptext SLIT("Unknown module in export list: module"), quotes (pprModuleName mod)]\r
+\r
+exportItemErr export_item\r
+  = sep [ ptext SLIT("Bad export item"), quotes (ppr export_item)]\r
+\r
+exportClashErr occ_name ie1 ie2\r
+  = hsep [ptext SLIT("The export items"), quotes (ppr ie1), ptext SLIT("and"), quotes (ppr ie2),\r
+         ptext SLIT("create conflicting exports for"), quotes (ppr occ_name)]\r
+\r
+dupDeclErr (n:ns)\r
+  = vcat [ptext SLIT("Multiple declarations of") <+> quotes (ppr n),\r
+         nest 4 (vcat (map pp sorted_ns))]\r
+  where\r
+    sorted_ns = sortLt occ'ed_before (n:ns)\r
+\r
+    occ'ed_before a b = LT == compare (getSrcLoc a) (getSrcLoc b)\r
+\r
+    pp n      = pprProvenance (getNameProvenance n)\r
+\r
+dupExportWarn occ_name ie1 ie2\r
+  = hsep [quotes (ppr occ_name), \r
+          ptext SLIT("is exported by"), quotes (ppr ie1),\r
+          ptext SLIT("and"),            quotes (ppr ie2)]\r
+\r
+dupModuleExport mod\r
+  = hsep [ptext SLIT("Duplicate"),\r
+         quotes (ptext SLIT("Module") <+> pprModuleName mod), \r
+          ptext SLIT("in export list")]\r
+\r
+unusedFixityDecl rdr_name fixity\r
+  = hsep [ptext SLIT("Unused fixity declaration for"), quotes (ppr rdr_name)]\r
+\r
+dupFixityDecl rdr_name loc1 loc2\r
+  = vcat [ptext SLIT("Multiple fixity declarations for") <+> quotes (ppr rdr_name),\r
+         ptext SLIT("at ") <+> ppr loc1,\r
+         ptext SLIT("and") <+> ppr loc2]\r
+\r
+\end{code}\r