[project @ 2000-10-30 09:52:14 by simonpj]
[ghc-hetmet.git] / ghc / compiler / rename / RnEnv.lhs
index 8ed2072..023e10c 100644 (file)
@@ -11,38 +11,36 @@ module RnEnv where          -- Export everything
 import HsSyn
 import RdrHsSyn                ( RdrNameIE )
 import RdrName         ( RdrName, rdrNameModule, rdrNameOcc, isQual, isUnqual,
-                         mkRdrUnqual, qualifyRdrName
+                         mkRdrUnqual, qualifyRdrName, lookupRdrEnv
                        )
-import HsTypes         ( hsTyVarName, hsTyVarNames, replaceTyVarName )
+import HsTypes         ( hsTyVarName, replaceTyVarName )
 import HscTypes                ( Provenance(..), pprNameProvenance, hasBetterProv,
-                         ImportReason(..), GlobalRdrEnv, Avails, AvailEnv,
-                         AvailInfo, GenAvailInfo(..), RdrAvailInfo )
+                         ImportReason(..), GlobalRdrEnv, AvailEnv,
+                         AvailInfo, Avails, GenAvailInfo(..), RdrAvailInfo )
 import RnMonad
 import Name            ( Name, NamedThing(..),
                          getSrcLoc, 
                          mkLocalName, mkImportedLocalName, mkGlobalName,
-                         mkIPName, isLocallyDefined, 
-                         nameOccName, nameModule,
+                         mkIPName, nameOccName, nameModule_maybe,
                          extendNameEnv_C, plusNameEnv_C, nameEnvElts,
                          setNameModuleAndLoc
                        )
 import NameSet
 import OccName         ( OccName, occNameUserString, occNameFlavour )
-import Module          ( ModuleName, moduleName, mkVanillaModule )
+import Module          ( ModuleName, moduleName, mkVanillaModule, mkSysModuleNameFS, moduleNameFS )
 import FiniteMap
 import Unique          ( Unique )
 import UniqSupply
 import SrcLoc          ( SrcLoc, noSrcLoc )
 import Outputable
 import ListSetOps      ( removeDups, equivClasses )
-import Util            ( thenCmp, sortLt )
+import Util            ( sortLt )
 import List            ( nub )
 import PrelNames       ( mkUnboundName )
 import CmdLineOpts
+import FastString      ( FastString )
 \end{code}
 
-
-
 %*********************************************************
 %*                                                     *
 \subsection{Making new names}
@@ -50,13 +48,26 @@ import CmdLineOpts
 %*********************************************************
 
 \begin{code}
-implicitImportProvenance = NonLocalDef ImplicitImport False
-
 newTopBinder :: Module -> RdrName -> SrcLoc -> RnM d Name
+       -- newTopBinder puts into the cache the binder with the
+       -- module information set correctly.  When the decl is later renamed,
+       -- the binding site will thereby get the correct module.
+       -- There maybe occurrences that don't have the correct Module, but
+       -- by the typechecker will propagate the binding definition to all 
+       -- the occurrences, so that doesn't matter
+
 newTopBinder mod rdr_name loc
   =    -- First check the cache
     traceRn (text "newTopBinder" <+> ppr mod <+> ppr loc) `thenRn_`
 
+       -- There should never be a qualified name in a binding position (except in instance decls)
+       -- The parser doesn't check this because the same parser parses instance decls
+    (if isQual rdr_name then
+       qualNameErr (text "its declaration") (rdr_name,loc)
+     else
+       returnRn ()
+    )                          `thenRn_`
+
     getNameSupplyRn            `thenRn` \ (us, cache, ipcache) ->
     let 
        occ = rdrNameOcc rdr_name
@@ -173,8 +184,8 @@ lookupTopBndrRn rdr_name
                getModuleRn             `thenRn` \ mod ->
                getGlobalNameEnv        `thenRn` \ global_env ->
                case lookupRdrEnv global_env (qualifyRdrName (moduleName mod) rdr_name) of
-                 Just (name:rest) -> ASSERT( null rest )
-                                     returnRn name 
+                 Just ((name,_):rest) -> ASSERT( null rest )
+                                         returnRn name 
                  Nothing          ->   -- Almost always this case is a compiler bug.
                                        -- But consider a type signature that doesn't have 
                                        -- a corresponding binder: 
@@ -221,12 +232,22 @@ lookupGlobalOccRn rdr_name
     getGlobalNameEnv   `thenRn` \ global_env ->
     case lookupRdrEnv global_env rdr_name of
        Just [(name,_)]  -> returnRn name
-       Just stuff@(_:_) -> addNameClashErrRn rdr_name stuff    `thenRn_`
-                           returnRn rdr_name
+       Just stuff@((name,_):_) 
+               -> addNameClashErrRn rdr_name stuff     `thenRn_`
+                          returnRn name
        Nothing ->      -- Not found when processing source code; so fail
                        failWithRn (mkUnboundName rdr_name)
                                   (unknownNameErr rdr_name)
     }
+
+lookupGlobalRn :: GlobalRdrEnv -> RdrName -> RnM d (Maybe Name)
+  -- Checks that there is exactly one
+lookupGlobalRn global_env rdr_name
+  = case lookupRdrEnv global_env rdr_name of
+       Just [(name,_)]         -> returnRn (Just name)
+       Just stuff@((name,_):_) -> addNameClashErrRn rdr_name stuff     `thenRn_`
+                                  returnRn (Just name)
+       Nothing                 -> returnRn Nothing
 \end{code}
 %
 
@@ -346,15 +367,14 @@ bindLocatedLocalsRn doc_str rdr_names_w_loc enclosed_scope
                Just name -> pushSrcLocRn loc $
                             addWarnRn (shadowedNameWarn rdr_name)
 
-bindCoreLocalFVRn :: RdrName -> (Name -> RnMS (a, FreeVars))
-                 -> RnMS (a, FreeVars)
+bindCoreLocalRn :: RdrName -> (Name -> RnMS a) -> RnMS a
   -- A specialised variant when renaming stuff from interface
   -- files (of which there is a lot)
   --   * one at a time
   --   * no checks for shadowing
   --   * always imported
   --   * deal with free vars
-bindCoreLocalFVRn rdr_name enclosed_scope
+bindCoreLocalRn rdr_name enclosed_scope
   = getSrcLocRn                `thenRn` \ loc ->
     getLocalNameEnv            `thenRn` \ name_env ->
     getNameSupplyRn            `thenRn` \ (us, cache, ipcache) ->
@@ -367,13 +387,12 @@ bindCoreLocalFVRn rdr_name enclosed_scope
     let
        new_name_env = extendRdrEnv name_env rdr_name name
     in
-    setLocalNameEnv new_name_env (enclosed_scope name) `thenRn` \ (result, fvs) ->
-    returnRn (result, delFromNameSet fvs name)
+    setLocalNameEnv new_name_env (enclosed_scope name)
 
-bindCoreLocalsFVRn []     thing_inside = thing_inside []
-bindCoreLocalsFVRn (b:bs) thing_inside = bindCoreLocalFVRn b   $ \ name' ->
-                                        bindCoreLocalsFVRn bs  $ \ names' ->
-                                        thing_inside (name':names')
+bindCoreLocalsRn []     thing_inside = thing_inside []
+bindCoreLocalsRn (b:bs) thing_inside = bindCoreLocalRn b       $ \ name' ->
+                                      bindCoreLocalsRn bs      $ \ names' ->
+                                      thing_inside (name':names')
 
 bindLocalNames names enclosed_scope
   = getLocalNameEnv            `thenRn` \ name_env ->
@@ -403,8 +422,8 @@ bindLocalsFVRn doc rdr_names enclosed_scope
     returnRn (thing, delListFromNameSet fvs names)
 
 -------------------------------------
-bindUVarRn :: SDoc -> RdrName -> (Name -> RnMS (a, FreeVars)) -> RnMS (a, FreeVars)
-bindUVarRn = bindLocalRn
+bindUVarRn :: RdrName -> (Name -> RnMS a) -> RnMS a
+bindUVarRn = bindCoreLocalRn
 
 -------------------------------------
 extendTyVarEnvFVRn :: [Name] -> RnMS (a, FreeVars) -> RnMS (a, FreeVars)
@@ -512,9 +531,9 @@ combine_globals ns_old ns_new       -- ns_new is often short
 
     (n,pn) `beats` (m,pm) = n==m && pn `hasBetterProv` pm
 
-    is_duplicate :: Provenance -> (Name,Provenance) -> Bool
-    is_duplicate (n1,LocalDef _) (n2,LocalDef _) = False
-    is_duplicate n1             n2              = n1 == n2
+    is_duplicate :: (Name,Provenance) -> (Name,Provenance) -> Bool
+    is_duplicate (n1,LocalDef) (n2,LocalDef) = False
+    is_duplicate (n1,_)        (n2,_)       = n1 == n2
 \end{code}
 
 We treat two bindings of a locally-defined name as a duplicate,
@@ -586,16 +605,19 @@ availNames :: GenAvailInfo name -> [name]
 availNames (Avail n)      = [n]
 availNames (AvailTC n ns) = ns
 
+-------------------------------------
 addSysAvails :: AvailInfo -> [Name] -> AvailInfo
 addSysAvails avail          []  = avail
 addSysAvails (AvailTC n ns) sys = AvailTC n (sys ++ ns)
 
+-------------------------------------
 rdrAvailInfo :: AvailInfo -> RdrAvailInfo
 -- Used when building the avails we are going to put in an interface file
 -- We sort the components to reduce needless wobbling of interfaces
 rdrAvailInfo (Avail n)     = Avail   (nameOccName n)
 rdrAvailInfo (AvailTC n ns) = AvailTC (nameOccName n) (sortLt (<) (map nameOccName ns))
 
+-------------------------------------
 filterAvail :: RdrNameIE       -- Wanted
            -> AvailInfo        -- Available
            -> Maybe AvailInfo  -- Resulting available; 
@@ -631,6 +653,34 @@ filterAvail (IEThingAll _) avail@(AvailTC _ _)   = Just avail
 
 filterAvail ie avail = Nothing
 
+-------------------------------------
+groupAvails :: Module -> Avails -> [(ModuleName, Avails)]
+  -- Group by module and sort by occurrence
+  -- This keeps the list in canonical order
+groupAvails this_mod avails 
+  = [ (mkSysModuleNameFS fs, sortLt lt avails)
+    | (fs,avails) <- fmToList groupFM
+    ]
+  where
+    groupFM :: FiniteMap FastString Avails
+       -- Deliberatey use the FastString so we
+       -- get a canonical ordering
+    groupFM = foldl add emptyFM avails
+
+    add env avail = addToFM_C combine env mod_fs [avail]
+                 where
+                   mod_fs = moduleNameFS (moduleName avail_mod)
+                   avail_mod = case nameModule_maybe (availName avail) of
+                                         Just m  -> m
+                                         Nothing -> this_mod
+                   combine old _ = avail:old
+
+    a1 `lt` a2 = occ1 < occ2
+              where
+                occ1  = nameOccName (availName a1)
+                occ2  = nameOccName (availName a2)
+                               
+-------------------------------------
 pprAvail :: AvailInfo -> SDoc
 pprAvail (AvailTC n ns) = ppr n <> case filter (/= n) ns of
                                        []  -> empty
@@ -647,25 +697,6 @@ pprAvail (Avail n) = ppr n
 %************************************************************************
 
 \begin{code}
-type FreeVars  = NameSet
-
-plusFV   :: FreeVars -> FreeVars -> FreeVars
-addOneFV :: FreeVars -> Name -> FreeVars
-unitFV   :: Name -> FreeVars
-emptyFVs :: FreeVars
-plusFVs  :: [FreeVars] -> FreeVars
-mkFVs   :: [Name] -> FreeVars
-
-isEmptyFVs = isEmptyNameSet
-emptyFVs   = emptyNameSet
-plusFVs    = unionManyNameSets
-plusFV     = unionNameSets
-mkFVs     = mkNameSet
-
--- No point in adding implicitly imported names to the free-var set
-addOneFV s n = addOneToNameSet s n
-unitFV     n = unitNameSet n
-
 -- A useful utility
 mapFvRn f xs = mapRn f xs      `thenRn` \ stuff ->
               let
@@ -682,21 +713,21 @@ mapFvRn f xs = mapRn f xs `thenRn` \ stuff ->
 %************************************************************************
 
 \begin{code}
-warnUnusedModules :: [Module] -> RnM d ()
+warnUnusedModules :: [ModuleName] -> RnM d ()
 warnUnusedModules mods
   = doptRn Opt_WarnUnusedImports `thenRn` \ warn ->
-    if warn then mapRn_ (addWarnRn . unused_mod . moduleName) mods
+    if warn then mapRn_ (addWarnRn . unused_mod) mods
            else returnRn ()
   where
     unused_mod m = vcat [ptext SLIT("Module") <+> quotes (ppr m) <+> 
                           text "is imported, but nothing from it is used",
                         parens (ptext SLIT("except perhaps to re-export instances visible in") <+>
-                                  quotes (ppr (moduleName m)))]
+                                  quotes (ppr m))]
 
 warnUnusedImports :: [(Name,Provenance)] -> RnM d ()
 warnUnusedImports names
   = doptRn Opt_WarnUnusedImports `thenRn` \ warn ->
-    if warn then warnUnusedBinds names else return ()
+    if warn then warnUnusedBinds names else returnRn ()
 
 warnUnusedLocalBinds, warnUnusedMatches :: [Name] -> RnM d ()
 warnUnusedLocalBinds names
@@ -717,15 +748,8 @@ warnUnusedBinds names
   where
        -- Group by provenance
    groups = equivClasses cmp names
-   (_,prov1) `cmp` (_,prov2) = prov1 `cmp_prov` prov2
+   (_,prov1) `cmp` (_,prov2) = prov1 `compare` prov2
  
-   cmp_prov (LocalDef _ _) (NonLocalDef _ _)       = LT
-   cmp_prov (LocalDef loc1 _) (LocalDef loc2 _)    = loc1 `compare` loc2
-   cmp_prov (NonLocalDef (UserImport m1 loc1 _) _)
-            (NonLocalDef (UserImport m2 loc2 _) _) =
-        (m1 `compare` m2) `thenCmp` (loc1 `compare` loc2)
-   cmp_prov (NonLocalDef _ _) (LocalDef _ _)       = GT
-                       -- In-scope NonLocalDefs must have UserImport info on them
 
 -------------------------
 
@@ -736,13 +760,13 @@ warnUnusedGroup names
   | otherwise
   = pushSrcLocRn def_loc       $
     addWarnRn                  $
-    sep [msg <> colon, nest 4 (fsep (punctuate comma (map ppr filtered_names)))]
+    sep [msg <> colon, nest 4 (fsep (punctuate comma (map (ppr.fst) filtered_names)))]
   where
     filtered_names = filter reportable names
     (name1, prov1) = head filtered_names
     (is_local, def_loc, msg)
        = case prov1 of
-               LocalDef loc _  -> (True, loc, text "Defined but not used")
+               LocalDef -> (True, getSrcLoc name1, text "Defined but not used")
 
                NonLocalDef (UserImport mod loc _) _ 
                        -> (True, loc, text "Imported from" <+> quotes (ppr mod) <+> text "but not used")