Add {-# OPTIONS_GHC -w #-} and some blurb to all compiler modules
[ghc-hetmet.git] / compiler / rename / RnNames.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[RnNames]{Extracting imported and top-level names in scope}
5
6 \begin{code}
7 {-# OPTIONS_GHC -w #-}
8 -- The above warning supression flag is a temporary kludge.
9 -- While working on this module you are encouraged to remove it and fix
10 -- any warnings in the module. See
11 --     http://hackage.haskell.org/trac/ghc/wiki/WorkingConventions#Warnings
12 -- for details
13
14 module RnNames (
15         rnImports, importsFromLocalDecls,
16         rnExports,
17         getLocalDeclBinders, extendRdrEnvRn,
18         reportUnusedNames, finishDeprecations
19     ) where
20
21 #include "HsVersions.h"
22
23 import DynFlags
24 import HsSyn            ( IE(..), ieName, ImportDecl(..), LImportDecl,
25                           ForeignDecl(..), HsGroup(..), HsValBinds(..),
26                           Sig(..), collectHsBindLocatedBinders, tyClDeclNames,
27                           instDeclATs, isFamInstDecl,
28                           LIE )
29 import RnEnv
30 import RnHsDoc          ( rnHsDoc )
31 import IfaceEnv         ( ifaceExportNames )
32 import LoadIface        ( loadSrcInterface, loadSysInterface )
33 import TcRnMonad hiding (LIE)
34
35 import PrelNames
36 import Module
37 import Name
38 import NameEnv
39 import NameSet
40 import OccName
41 import HscTypes
42 import RdrName
43 import Outputable
44 import Maybes
45 import SrcLoc
46 import FiniteMap
47 import ErrUtils
48 import BasicTypes       ( DeprecTxt )
49 import DriverPhases     ( isHsBoot )
50 import Util
51 import ListSetOps
52 import Data.List        ( partition, concatMap, (\\), delete )
53 import IO               ( openFile, IOMode(..) )
54 import Monad            ( when )
55 \end{code}
56
57
58
59 %************************************************************************
60 %*                                                                      *
61                 rnImports
62 %*                                                                      *
63 %************************************************************************
64
65 \begin{code}
66 rnImports :: [LImportDecl RdrName]
67            -> RnM ([LImportDecl Name], GlobalRdrEnv, ImportAvails,AnyHpcUsage)
68
69 rnImports imports
70          -- PROCESS IMPORT DECLS
71          -- Do the non {- SOURCE -} ones first, so that we get a helpful
72          -- warning for {- SOURCE -} ones that are unnecessary
73     = do this_mod <- getModule
74          implicit_prelude <- doptM Opt_ImplicitPrelude
75          let prel_imports       = mkPrelImports this_mod implicit_prelude imports
76              (source, ordinary) = partition is_source_import imports
77              is_source_import (L _ (ImportDecl _ is_boot _ _ _)) = is_boot
78
79          ifOptM Opt_WarnImplicitPrelude (
80             when (notNull prel_imports) $ addWarn (implicitPreludeWarn)
81           )
82
83          stuff1 <- mapM (rnImportDecl this_mod) (prel_imports ++ ordinary)
84          stuff2 <- mapM (rnImportDecl this_mod) source
85          let (decls, rdr_env, imp_avails,hpc_usage) = combine (stuff1 ++ stuff2)
86          return (decls, rdr_env, imp_avails,hpc_usage) 
87
88     where
89    combine :: [(LImportDecl Name,  GlobalRdrEnv, ImportAvails,AnyHpcUsage)]
90            -> ([LImportDecl Name], GlobalRdrEnv, ImportAvails,AnyHpcUsage)
91    combine = foldr plus ([], emptyGlobalRdrEnv, emptyImportAvails,False)
92         where plus (decl,  gbl_env1, imp_avails1,hpc_usage1)
93                    (decls, gbl_env2, imp_avails2,hpc_usage2)
94                 = (decl:decls, 
95                    gbl_env1 `plusGlobalRdrEnv` gbl_env2,
96                    imp_avails1 `plusImportAvails` imp_avails2,
97                    hpc_usage1 || hpc_usage2)
98
99 mkPrelImports :: Module -> Bool -> [LImportDecl RdrName] -> [LImportDecl RdrName]
100 -- Consruct the implicit declaration "import Prelude" (or not)
101 --
102 -- NB: opt_NoImplicitPrelude is slightly different to import Prelude ();
103 -- because the former doesn't even look at Prelude.hi for instance 
104 -- declarations, whereas the latter does.
105 mkPrelImports this_mod implicit_prelude import_decls
106   | this_mod == pRELUDE
107    || explicit_prelude_import
108    || not implicit_prelude
109   = []
110   | otherwise = [preludeImportDecl]
111   where
112       explicit_prelude_import
113        = notNull [ () | L _ (ImportDecl mod _ _ _ _) <- import_decls, 
114                    unLoc mod == pRELUDE_NAME ]
115
116       preludeImportDecl :: LImportDecl RdrName
117       preludeImportDecl
118         = L loc $
119           ImportDecl (L loc pRELUDE_NAME)
120                False {- Not a boot interface -}
121                False    {- Not qualified -}
122                Nothing  {- No "as" -}
123                Nothing  {- No import list -}
124
125       loc = mkGeneralSrcSpan FSLIT("Implicit import declaration")         
126
127
128 rnImportDecl  :: Module
129               -> LImportDecl RdrName
130               -> RnM (LImportDecl Name, GlobalRdrEnv, ImportAvails,AnyHpcUsage)
131
132 rnImportDecl this_mod (L loc (ImportDecl loc_imp_mod_name want_boot
133                                          qual_only as_mod imp_details))
134   = 
135     setSrcSpan loc $ do
136
137         -- If there's an error in loadInterface, (e.g. interface
138         -- file not found) we get lots of spurious errors from 'filterImports'
139     let
140         imp_mod_name = unLoc loc_imp_mod_name
141         doc = ppr imp_mod_name <+> ptext SLIT("is directly imported")
142
143     iface <- loadSrcInterface doc imp_mod_name want_boot
144
145         -- Compiler sanity check: if the import didn't say
146         -- {-# SOURCE #-} we should not get a hi-boot file
147     WARN( not want_boot && mi_boot iface, ppr imp_mod_name ) (do
148
149         -- Issue a user warning for a redundant {- SOURCE -} import
150         -- NB that we arrange to read all the ordinary imports before 
151         -- any of the {- SOURCE -} imports
152     warnIf (want_boot && not (mi_boot iface))
153            (warnRedundantSourceImport imp_mod_name)
154
155     let
156         imp_mod    = mi_module iface
157         deprecs    = mi_deprecs iface
158         orph_iface = mi_orphan iface 
159         has_finsts = mi_finsts iface 
160         deps       = mi_deps iface
161
162         filtered_exports = filter not_this_mod (mi_exports iface)
163         not_this_mod (mod,_) = mod /= this_mod
164         -- If the module exports anything defined in this module, just
165         -- ignore it.  Reason: otherwise it looks as if there are two
166         -- local definition sites for the thing, and an error gets
167         -- reported.  Easiest thing is just to filter them out up
168         -- front. This situation only arises if a module imports
169         -- itself, or another module that imported it.  (Necessarily,
170         -- this invoves a loop.)
171         --
172         -- Tiresome consequence: if you say
173         --      module A where
174         --         import B( AType )
175         --         type AType = ...
176         --
177         --      module B( AType ) where
178         --         import {-# SOURCE #-} A( AType )
179         --
180         -- then you'll get a 'B does not export AType' message.  Oh well.
181
182         qual_mod_name = case as_mod of
183                           Nothing           -> imp_mod_name
184                           Just another_name -> another_name
185         imp_spec  = ImpDeclSpec { is_mod = imp_mod_name, is_qual = qual_only,  
186                                   is_dloc = loc, is_as = qual_mod_name }
187     -- in
188
189         -- Get the total exports from this module
190     total_avails <- ifaceExportNames filtered_exports
191
192         -- filter the imports according to the import declaration
193     (new_imp_details, gbl_env) <- 
194         filterImports iface imp_spec imp_details total_avails
195
196     dflags <- getDOpts
197
198     let
199         -- Compute new transitive dependencies
200
201         orphans | orph_iface = ASSERT( not (imp_mod `elem` dep_orphs deps) )
202                                imp_mod : dep_orphs deps
203                 | otherwise  = dep_orphs deps
204
205         finsts | has_finsts = ASSERT( not (imp_mod `elem` dep_finsts deps) )
206                               imp_mod : dep_finsts deps
207                 | otherwise = dep_finsts deps
208
209         pkg = modulePackageId (mi_module iface)
210
211         (dependent_mods, dependent_pkgs) 
212            | pkg == thisPackage dflags =
213                 -- Imported module is from the home package
214                 -- Take its dependent modules and add imp_mod itself
215                 -- Take its dependent packages unchanged
216                 --
217                 -- NB: (dep_mods deps) might include a hi-boot file
218                 -- for the module being compiled, CM. Do *not* filter
219                 -- this out (as we used to), because when we've
220                 -- finished dealing with the direct imports we want to
221                 -- know if any of them depended on CM.hi-boot, in
222                 -- which case we should do the hi-boot consistency
223                 -- check.  See LoadIface.loadHiBootInterface
224                   ((imp_mod_name, want_boot) : dep_mods deps, dep_pkgs deps)
225
226            | otherwise =
227                 -- Imported module is from another package
228                 -- Dump the dependent modules
229                 -- Add the package imp_mod comes from to the dependent packages
230                  ASSERT2( not (pkg `elem` dep_pkgs deps), ppr pkg <+> ppr (dep_pkgs deps) )
231                  ([], pkg : dep_pkgs deps)
232
233         -- True <=> import M ()
234         import_all = case imp_details of
235                         Just (is_hiding, ls) -> not is_hiding && null ls        
236                         other                -> False
237
238         imports   = ImportAvails { 
239                         imp_mods     = unitModuleEnv imp_mod (imp_mod, [(qual_mod_name, import_all, loc)]),
240                         imp_orphs    = orphans,
241                         imp_finsts   = finsts,
242                         imp_dep_mods = mkModDeps dependent_mods,
243                         imp_dep_pkgs = dependent_pkgs
244                    }
245
246         -- Complain if we import a deprecated module
247     ifOptM Opt_WarnDeprecations (
248        case deprecs of  
249           DeprecAll txt -> addWarn (moduleDeprec imp_mod_name txt)
250           other         -> returnM ()
251      )
252
253     let new_imp_decl = L loc (ImportDecl loc_imp_mod_name want_boot
254                                          qual_only as_mod new_imp_details)
255
256     returnM (new_imp_decl, gbl_env, imports, mi_hpc iface)
257     )
258
259 warnRedundantSourceImport mod_name
260   = ptext SLIT("Unnecessary {-# SOURCE #-} in the import of module")
261           <+> quotes (ppr mod_name)
262 \end{code}
263
264
265 %************************************************************************
266 %*                                                                      *
267                 importsFromLocalDecls
268 %*                                                                      *
269 %************************************************************************
270
271 From the top-level declarations of this module produce
272         * the lexical environment
273         * the ImportAvails
274 created by its bindings.  
275         
276 Complain about duplicate bindings
277
278 \begin{code}
279 importsFromLocalDecls :: HsGroup RdrName -> RnM TcGblEnv
280 importsFromLocalDecls group
281   = do  { gbl_env  <- getGblEnv
282
283         ; avails <- getLocalDeclBinders gbl_env group
284
285         ; rdr_env' <- extendRdrEnvRn (tcg_rdr_env gbl_env) avails
286
287         ; traceRn (text "local avails: " <> ppr avails)
288
289         ; returnM (gbl_env { tcg_rdr_env = rdr_env' })
290         }
291
292 extendRdrEnvRn :: GlobalRdrEnv -> [AvailInfo] -> RnM GlobalRdrEnv
293 -- Add the new locally-bound names one by one, checking for duplicates as
294 -- we do so.  Remember that in Template Haskell the duplicates
295 -- might *already be* in the GlobalRdrEnv from higher up the module
296 extendRdrEnvRn rdr_env avails
297   = foldlM add_local rdr_env (gresFromAvails LocalDef avails)
298   where
299     add_local rdr_env gre
300         | gres <- lookupGlobalRdrEnv rdr_env (nameOccName (gre_name gre))
301         , (dup_gre:_) <- filter isLocalGRE gres -- Check for existing *local* defns
302         = do { addDupDeclErr (gre_name dup_gre) (gre_name gre)
303              ; return rdr_env }
304         | otherwise
305         = return (extendGlobalRdrEnv rdr_env gre)
306 \end{code}
307
308 @getLocalDeclBinders@ returns the names for an @HsDecl@.  It's
309 used for source code.
310
311         *** See "THE NAMING STORY" in HsDecls ****
312
313 Instances of type families
314 ~~~~~~~~~~~~~~~~~~~~~~~~~~
315 Indexed data/newtype instances contain data constructors that we need to
316 collect, too.  Moreover, we need to descend into the data/newtypes instances
317 of associated families.
318
319 We need to be careful with the handling of the type constructor of each type
320 instance as the family constructor is already defined, and we want to avoid
321 raising a duplicate declaration error.  So, we make a new name for it, but
322 don't return it in the 'AvailInfo'.
323
324 \begin{code}
325 getLocalDeclBinders :: TcGblEnv -> HsGroup RdrName -> RnM [AvailInfo]
326 getLocalDeclBinders gbl_env (HsGroup {hs_valds = ValBindsIn val_decls val_sigs,
327                                       hs_tyclds = tycl_decls, 
328                                       hs_instds = inst_decls,
329                                       hs_fords = foreign_decls })
330   = do  { tc_names_s <- mappM new_tc tycl_decls
331         ; at_names_s <- mappM inst_ats inst_decls
332         ; val_names  <- mappM new_simple val_bndrs
333         ; return (val_names ++ tc_names_s ++ concat at_names_s) }
334   where
335     mod        = tcg_mod gbl_env
336     is_hs_boot = isHsBoot (tcg_src gbl_env) ;
337     val_bndrs | is_hs_boot = sig_hs_bndrs
338               | otherwise  = for_hs_bndrs ++ val_hs_bndrs
339         -- In a hs-boot file, the value binders come from the
340         --  *signatures*, and there should be no foreign binders 
341
342     new_simple rdr_name = do
343         nm <- newTopSrcBinder mod rdr_name
344         return (Avail nm)
345
346     sig_hs_bndrs = [nm | L _ (TypeSig nm _) <- val_sigs]
347     val_hs_bndrs = collectHsBindLocatedBinders val_decls
348     for_hs_bndrs = [nm | L _ (ForeignImport nm _ _) <- foreign_decls]
349
350     new_tc tc_decl 
351       | isFamInstDecl (unLoc tc_decl)
352         = do { main_name <- lookupFamInstDeclBndr mod main_rdr
353              ; sub_names <- mappM (newTopSrcBinder mod) sub_rdrs
354              ; return (AvailTC main_name sub_names) }
355                         -- main_name is not bound here!
356       | otherwise
357         = do { main_name <- newTopSrcBinder mod main_rdr
358              ; sub_names <- mappM (newTopSrcBinder mod) sub_rdrs
359              ; return (AvailTC main_name (main_name : sub_names)) }
360       where
361         (main_rdr : sub_rdrs) = tyClDeclNames (unLoc tc_decl)
362
363     inst_ats inst_decl 
364         = mappM new_tc (instDeclATs (unLoc inst_decl))
365
366 getLocalDeclBinders _ _ = panic "getLocalDeclBinders"   -- ValBindsOut can't happen
367 \end{code}
368
369
370 %************************************************************************
371 %*                                                                      *
372 \subsection{Filtering imports}
373 %*                                                                      *
374 %************************************************************************
375
376 @filterImports@ takes the @ExportEnv@ telling what the imported module makes
377 available, and filters it through the import spec (if any).
378
379 \begin{code}
380 filterImports :: ModIface
381               -> ImpDeclSpec                    -- The span for the entire import decl
382               -> Maybe (Bool, [LIE RdrName])    -- Import spec; True => hiding
383               -> [AvailInfo]                    -- What's available
384               -> RnM (Maybe (Bool, [LIE Name]), -- Import spec w/ Names
385                       GlobalRdrEnv)             -- Same again, but in GRE form
386                         
387 filterImports iface decl_spec Nothing all_avails
388   = return (Nothing, mkGlobalRdrEnv (gresFromAvails prov all_avails))
389   where
390     prov = Imported [ImpSpec { is_decl = decl_spec, is_item = ImpAll }]
391
392
393 filterImports iface decl_spec (Just (want_hiding, import_items)) all_avails
394   = do   -- check for errors, convert RdrNames to Names
395         opt_typeFamilies <- doptM Opt_TypeFamilies
396         items1 <- mapM (lookup_lie opt_typeFamilies) import_items
397
398         let items2 :: [(LIE Name, AvailInfo)]
399             items2 = concat items1
400                 -- NB the AvailInfo may have duplicates, and several items
401                 --    for the same parent; e.g N(x) and N(y)
402
403             names  = availsToNameSet (map snd items2)
404             keep n = not (n `elemNameSet` names)
405             pruned_avails = filterAvails keep all_avails
406             hiding_prov = Imported [ImpSpec { is_decl = decl_spec, is_item = ImpAll }]
407
408             gres | want_hiding = gresFromAvails hiding_prov pruned_avails
409                  | otherwise   = concatMap (gresFromIE decl_spec) items2
410
411         return (Just (want_hiding, map fst items2), mkGlobalRdrEnv gres)
412   where
413         -- This environment is how we map names mentioned in the import
414         -- list to the actual Name they correspond to, and the name family
415         -- that the Name belongs to (the AvailInfo).  The situation is
416         -- complicated by associated families, which introduce a three-level
417         -- hierachy, where class = grand parent, assoc family = parent, and
418         -- data constructors = children.  The occ_env entries for associated
419         -- families needs to capture all this information; hence, we have the
420         -- third component of the environment that gives the class name (=
421         -- grand parent) in case of associated families.
422         --
423         -- This env will have entries for data constructors too,
424         -- they won't make any difference because naked entities like T
425         -- in an import list map to TcOccs, not VarOccs.
426     occ_env :: OccEnv (Name,        -- the name
427                        AvailInfo,   -- the export item providing the name
428                        Maybe Name)  -- the parent of associated types
429     occ_env = mkOccEnv_C combine [ (nameOccName n, (n, a, Nothing)) 
430                                  | a <- all_avails, n <- availNames a]
431       where
432         -- we know that (1) there are at most entries for one name, (2) their
433         -- first component is identical, (3) they are for tys/cls, and (4) one
434         -- entry has the name in its parent position (the other doesn't)
435         combine (name, AvailTC p1 subs1, Nothing)
436                 (_   , AvailTC p2 subs2, Nothing)
437           = let
438               (parent, subs) = if p1 == name then (p2, subs1) else (p1, subs2)
439             in
440             (name, AvailTC name subs, Just parent)
441
442     lookup_lie :: Bool -> LIE RdrName -> TcRn [(LIE Name, AvailInfo)]
443     lookup_lie opt_typeFamilies (L loc ieRdr)
444         = do 
445              stuff <- setSrcSpan loc $ 
446                       case lookup_ie opt_typeFamilies ieRdr of
447                             Failed err  -> addErr err >> return []
448                             Succeeded a -> return a
449              checkDodgyImport stuff
450              return [ (L loc ie, avail) | (ie,avail) <- stuff ]
451         where
452                 -- Warn when importing T(..) if T was exported abstractly
453             checkDodgyImport stuff
454                 | IEThingAll n <- ieRdr, (_, AvailTC _ [one]):_ <- stuff
455                 = ifOptM Opt_WarnDodgyImports (addWarn (dodgyImportWarn n))
456                 -- NB. use the RdrName for reporting the warning
457             checkDodgyImport _
458                 = return ()
459
460         -- For each import item, we convert its RdrNames to Names,
461         -- and at the same time construct an AvailInfo corresponding
462         -- to what is actually imported by this item.
463         -- Returns Nothing on error.
464         -- We return a list here, because in the case of an import
465         -- item like C, if we are hiding, then C refers to *both* a
466         -- type/class and a data constructor.  Moreover, when we import
467         -- data constructors of an associated family, we need separate
468         -- AvailInfos for the data constructors and the family (as they have
469         -- different parents).  See the discussion at occ_env.
470     lookup_ie :: Bool -> IE RdrName -> MaybeErr Message [(IE Name,AvailInfo)]
471     lookup_ie opt_typeFamilies ie 
472       = let bad_ie = Failed (badImportItemErr iface decl_spec ie)
473
474             lookup_name rdrName = 
475                 case lookupOccEnv occ_env (rdrNameOcc rdrName) of
476                    Nothing -> bad_ie
477                    Just n  -> return n
478         in
479         case ie of
480          IEVar n -> do
481              (name, avail, _) <- lookup_name n
482              return [(IEVar name, trimAvail avail name)]
483
484          IEThingAll tc -> do
485              (name, avail@(AvailTC name2 subs), mb_parent) <- lookup_name tc
486              case mb_parent of
487                -- non-associated ty/cls
488                Nothing     -> return [(IEThingAll name, avail)]
489                -- associated ty
490                Just parent -> return [(IEThingAll name, 
491                                        AvailTC name2 (subs \\ [name])),
492                                       (IEThingAll name, AvailTC parent [name])]
493
494          IEThingAbs tc
495              | want_hiding   -- hiding ( C )
496                         -- Here the 'C' can be a data constructor 
497                         --  *or* a type/class, or even both
498              -> let tc_name = lookup_name tc
499                     dc_name = lookup_name (setRdrNameSpace tc srcDataName)
500                 in
501                 case catMaybeErr [ tc_name, dc_name ] of
502                   []    -> bad_ie
503                   names -> return [mkIEThingAbs name | name <- names]
504              | otherwise
505              -> do nameAvail <- lookup_name tc
506                    return [mkIEThingAbs nameAvail]
507
508          IEThingWith tc ns -> do
509             (name, AvailTC name2 subnames, mb_parent) <- lookup_name tc
510             let 
511               env         = mkOccEnv [(nameOccName s, s) | s <- subnames]
512               mb_children = map (lookupOccEnv env . rdrNameOcc) ns
513             children <- if any isNothing mb_children
514                         then bad_ie
515                         else return (catMaybes mb_children)
516               -- check for proper import of type families
517             when (not opt_typeFamilies && any isTyConName children) $
518               Failed (typeItemErr (head . filter isTyConName $ children)
519                                   (text "in import list"))
520             case mb_parent of
521                -- non-associated ty/cls
522               Nothing     -> return [(IEThingWith name children, 
523                                       AvailTC name (name:children))]
524                -- associated ty
525               Just parent -> return [(IEThingWith name children, 
526                                       AvailTC name children),
527                                      (IEThingWith name children, 
528                                       AvailTC parent [name])]
529
530          _other -> Failed illegalImportItemErr
531          -- could be IEModuleContents, IEGroup, IEDoc, IEDocNamed
532          -- all errors.
533
534       where
535         mkIEThingAbs (n, av, Nothing    ) = (IEThingAbs n, trimAvail av n) 
536         mkIEThingAbs (n, av, Just parent) = (IEThingAbs n, AvailTC parent [n]) 
537
538
539 catMaybeErr :: [MaybeErr err a] -> [a]
540 catMaybeErr ms =  [ a | Succeeded a <- ms ]
541 \end{code}
542
543 %************************************************************************
544 %*                                                                      *
545         Import/Export Utils
546 %*                                                                      *
547 %************************************************************************
548
549 \begin{code}
550 -- | make a 'GlobalRdrEnv' where all the elements point to the same
551 -- import declaration (useful for "hiding" imports, or imports with
552 -- no details).
553 gresFromAvails :: Provenance -> [AvailInfo] -> [GlobalRdrElt]
554 gresFromAvails prov avails
555   = concatMap (gresFromAvail (const prov)) avails
556
557 gresFromAvail :: (Name -> Provenance) -> AvailInfo -> [GlobalRdrElt]
558 gresFromAvail prov_fn avail
559   = [ GRE {gre_name = n, 
560            gre_par = availParent n avail, 
561            gre_prov = prov_fn n}
562     | n <- availNames avail ]
563   
564 greAvail :: GlobalRdrElt -> AvailInfo
565 greAvail gre = mkUnitAvail (gre_name gre) (gre_par gre)
566
567 mkUnitAvail :: Name -> Parent -> AvailInfo
568 mkUnitAvail me (ParentIs p)              = AvailTC p  [me]
569 mkUnitAvail me NoParent | isTyConName me = AvailTC me [me]
570                         | otherwise      = Avail me
571
572 plusAvail (Avail n1)       (Avail n2)       = Avail n1
573 plusAvail (AvailTC n1 ns1) (AvailTC n2 ns2) = AvailTC n2 (ns1 `unionLists` ns2)
574 plusAvail a1 a2 = pprPanic "RnEnv.plusAvail" (hsep [ppr a1,ppr a2])
575
576 availParent :: Name -> AvailInfo -> Parent
577 availParent n (Avail _)                  = NoParent
578 availParent n (AvailTC m ms) | n==m      = NoParent
579                              | otherwise = ParentIs m
580
581 trimAvail :: AvailInfo -> Name -> AvailInfo
582 trimAvail (Avail n)      m = Avail n
583 trimAvail (AvailTC n ns) m = ASSERT( m `elem` ns) AvailTC n [m]
584
585 -- | filters 'AvailInfo's by the given predicate
586 filterAvails  :: (Name -> Bool) -> [AvailInfo] -> [AvailInfo]
587 filterAvails keep avails = foldr (filterAvail keep) [] avails
588
589 -- | filters an 'AvailInfo' by the given predicate
590 filterAvail :: (Name -> Bool) -> AvailInfo -> [AvailInfo] -> [AvailInfo]
591 filterAvail keep ie rest =
592   case ie of
593     Avail n | keep n    -> ie : rest
594             | otherwise -> rest
595     AvailTC tc ns ->
596         let left = filter keep ns in
597         if null left then rest else AvailTC tc left : rest
598
599 -- | Given an import/export spec, construct the appropriate 'GlobalRdrElt's.
600 gresFromIE :: ImpDeclSpec -> (LIE Name, AvailInfo) -> [GlobalRdrElt]
601 gresFromIE decl_spec (L loc ie, avail)
602   = gresFromAvail prov_fn avail
603   where
604     is_explicit = case ie of
605                     IEThingAll name -> \n -> n==name
606                     other           -> \n -> True
607     prov_fn name = Imported [imp_spec]
608         where
609           imp_spec  = ImpSpec { is_decl = decl_spec, is_item = item_spec }
610           item_spec = ImpSome { is_explicit = is_explicit name, is_iloc = loc }
611
612 mkChildEnv :: [GlobalRdrElt] -> NameEnv [Name]
613 mkChildEnv gres = foldr add emptyNameEnv gres
614     where
615         add (GRE { gre_name = n, gre_par = ParentIs p }) env = extendNameEnv_C (++) env p [n]
616         add other_gre                                    env = env
617
618 findChildren :: NameEnv [Name] -> Name -> [Name]
619 findChildren env n = lookupNameEnv env n `orElse` []
620 \end{code}
621
622 ---------------------------------------
623         AvailEnv and friends
624
625 All this AvailEnv stuff is hardly used; only in a very small
626 part of RnNames.  Todo: remove?
627 ---------------------------------------
628
629 \begin{code}
630 type AvailEnv = NameEnv AvailInfo       -- Maps a Name to the AvailInfo that contains it
631
632 emptyAvailEnv :: AvailEnv
633 emptyAvailEnv = emptyNameEnv
634
635 unitAvailEnv :: AvailInfo -> AvailEnv
636 unitAvailEnv a = unitNameEnv (availName a) a
637
638 plusAvailEnv :: AvailEnv -> AvailEnv -> AvailEnv
639 plusAvailEnv = plusNameEnv_C plusAvail
640
641 availEnvElts :: AvailEnv -> [AvailInfo]
642 availEnvElts = nameEnvElts
643
644 addAvail :: AvailEnv -> AvailInfo -> AvailEnv
645 addAvail avails avail = extendNameEnv_C plusAvail avails (availName avail) avail
646
647 mkAvailEnv :: [AvailInfo] -> AvailEnv
648         -- 'avails' may have several items with the same availName
649         -- E.g  import Ix( Ix(..), index )
650         -- will give Ix(Ix,index,range) and Ix(index)
651         -- We want to combine these; addAvail does that
652 mkAvailEnv avails = foldl addAvail emptyAvailEnv avails
653
654 -- After combining the avails, we need to ensure that the parent name is the
655 -- first entry in the list of subnames, if it is included at all.  (Subsequent
656 -- functions rely on that.)
657 normaliseAvail :: AvailInfo -> AvailInfo
658 normaliseAvail avail@(Avail _)     = avail
659 normaliseAvail (AvailTC name subs) = AvailTC name subs'
660   where
661     subs' = if name `elem` subs then name : (delete name subs) else subs
662
663 -- | combines 'AvailInfo's from the same family
664 nubAvails :: [AvailInfo] -> [AvailInfo]
665 nubAvails avails = map normaliseAvail . nameEnvElts . mkAvailEnv $ avails
666 \end{code}
667
668
669 %************************************************************************
670 %*                                                                      *
671 \subsection{Export list processing}
672 %*                                                                      *
673 %************************************************************************
674
675 Processing the export list.
676
677 You might think that we should record things that appear in the export
678 list as ``occurrences'' (using @addOccurrenceName@), but you'd be
679 wrong.  We do check (here) that they are in scope, but there is no
680 need to slurp in their actual declaration (which is what
681 @addOccurrenceName@ forces).
682
683 Indeed, doing so would big trouble when compiling @PrelBase@, because
684 it re-exports @GHC@, which includes @takeMVar#@, whose type includes
685 @ConcBase.StateAndSynchVar#@, and so on...
686
687 \begin{code}
688 type ExportAccum        -- The type of the accumulating parameter of
689                         -- the main worker function in rnExports
690      = ([LIE Name],             -- Export items with Names
691         ExportOccMap,           -- Tracks exported occurrence names
692         [AvailInfo])            -- The accumulated exported stuff
693                                 --   Not nub'd!
694
695 emptyExportAccum = ([], emptyOccEnv, []) 
696
697 type ExportOccMap = OccEnv (Name, IE RdrName)
698         -- Tracks what a particular exported OccName
699         --   in an export list refers to, and which item
700         --   it came from.  It's illegal to export two distinct things
701         --   that have the same occurrence name
702
703 rnExports :: Bool       -- False => no 'module M(..) where' header at all
704           -> Maybe [LIE RdrName]        -- Nothing => no explicit export list
705           -> TcGblEnv
706           -> RnM TcGblEnv
707
708         -- Complains if two distinct exports have same OccName
709         -- Warns about identical exports.
710         -- Complains about exports items not in scope
711
712 rnExports explicit_mod exports 
713           tcg_env@(TcGblEnv { tcg_mod     = this_mod,
714                               tcg_rdr_env = rdr_env, 
715                               tcg_imports = imports })
716  = do   {  
717         -- If the module header is omitted altogether, then behave
718         -- as if the user had written "module Main(main) where..."
719         -- EXCEPT in interactive mode, when we behave as if he had
720         -- written "module Main where ..."
721         -- Reason: don't want to complain about 'main' not in scope
722         --         in interactive mode
723         ; dflags <- getDOpts
724         ; let real_exports 
725                  | explicit_mod = exports
726                  | ghcLink dflags == LinkInMemory = Nothing
727                  | otherwise = Just ([noLoc (IEVar main_RDR_Unqual)])
728                         -- ToDo: the 'noLoc' here is unhelpful if 'main' 
729                         --       turns out to be out of scope
730
731         ; (rn_exports, avails) <- exports_from_avail real_exports rdr_env imports this_mod
732         ; let final_avails = nubAvails avails        -- Combine families
733         
734         ; return (tcg_env { tcg_exports    = final_avails,
735                             tcg_rn_exports = case tcg_rn_exports tcg_env of
736                                                 Nothing -> Nothing
737                                                 Just _  -> rn_exports,
738                             tcg_dus = tcg_dus tcg_env `plusDU` 
739                                       usesOnly (availsToNameSet final_avails) }) }
740
741
742 exports_from_avail :: Maybe [LIE RdrName]
743                          -- Nothing => no explicit export list
744                    -> GlobalRdrEnv
745                    -> ImportAvails
746                    -> Module
747                    -> RnM (Maybe [LIE Name], [AvailInfo])
748
749 exports_from_avail Nothing rdr_env imports this_mod
750  = -- The same as (module M) where M is the current module name,
751    -- so that's how we handle it.
752    let
753        avails = [ greAvail gre | gre <- globalRdrEnvElts rdr_env,
754                                  isLocalGRE gre ]
755    in
756    return (Nothing, avails)
757
758 exports_from_avail (Just rdr_items) rdr_env imports this_mod
759   = do (ie_names, _, exports) <- foldlM do_litem emptyExportAccum rdr_items
760
761        return (Just ie_names, exports)
762   where
763     do_litem :: ExportAccum -> LIE RdrName -> RnM ExportAccum
764     do_litem acc lie = setSrcSpan (getLoc lie) (exports_from_item acc lie)
765
766     kids_env :: NameEnv [Name]  -- Maps a parent to its in-scope children
767     kids_env = mkChildEnv (globalRdrEnvElts rdr_env)
768
769     imported_modules = [ qual_name
770                        | (_, xs) <- moduleEnvElts $ imp_mods imports,
771                          (qual_name, _, _) <- xs ]
772
773     exports_from_item :: ExportAccum -> LIE RdrName -> RnM ExportAccum
774     exports_from_item acc@(ie_names, occs, exports) 
775                       (L loc ie@(IEModuleContents mod))
776         | let earlier_mods = [ mod | (L _ (IEModuleContents mod)) <- ie_names ]
777         , mod `elem` earlier_mods       -- Duplicate export of M
778         = do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
779                warnIf warn_dup_exports (dupModuleExport mod) ;
780                returnM acc }
781
782         | otherwise
783         = do { implicit_prelude <- doptM Opt_ImplicitPrelude
784          ; let { exportValid = (mod `elem` imported_modules)
785                             || (moduleName this_mod == mod)
786                ; gres = filter (isModuleExported implicit_prelude mod)
787                                (globalRdrEnvElts rdr_env)
788                }
789
790          ; checkErr exportValid (moduleNotImported mod)
791              ; warnIf (exportValid && null gres) (nullModuleExport mod)
792
793              ; occs' <- check_occs ie occs (map gre_name gres)
794                       -- This check_occs not only finds conflicts
795                       -- between this item and others, but also
796                       -- internally within this item.  That is, if
797                       -- 'M.x' is in scope in several ways, we'll have
798                       -- several members of mod_avails with the same
799                       -- OccName.
800              ; return (L loc (IEModuleContents mod) : ie_names,
801                        occs', map greAvail gres ++ exports) }
802
803     exports_from_item acc@(lie_names, occs, exports) (L loc ie)
804         | isDoc ie
805         = do new_ie <- lookup_doc_ie ie
806              return (L loc new_ie : lie_names, occs, exports)
807
808         | otherwise
809         = do (new_ie, avail) <- lookup_ie ie
810              if isUnboundName (ieName new_ie)
811                   then return acc       -- Avoid error cascade
812                   else do
813
814              occs' <- check_occs ie occs (availNames avail)
815
816              return (L loc new_ie : lie_names, occs', avail : exports)
817
818     -------------
819     lookup_ie :: IE RdrName -> RnM (IE Name, AvailInfo)
820     lookup_ie (IEVar rdr) 
821         = do gre <- lookupGreRn rdr
822              return (IEVar (gre_name gre), greAvail gre)
823
824     lookup_ie (IEThingAbs rdr) 
825         = do gre <- lookupGreRn rdr
826              let name = gre_name gre
827              case gre_par gre of
828                 NoParent   -> return (IEThingAbs name, 
829                                       AvailTC name [name])
830                 ParentIs p -> return (IEThingAbs name, 
831                                       AvailTC p [name])
832
833     lookup_ie ie@(IEThingAll rdr) 
834         = do name <- lookupGlobalOccRn rdr
835              let kids = findChildren kids_env name
836              when (null kids)
837                   (if (isTyConName name) then addWarn (dodgyExportWarn name)
838                                 -- This occurs when you export T(..), but
839                                 -- only import T abstractly, or T is a synonym.  
840                    else addErr (exportItemErr ie))
841                         
842              return (IEThingAll name, AvailTC name (name:kids))
843
844     lookup_ie ie@(IEThingWith rdr sub_rdrs)
845         = do name <- lookupGlobalOccRn rdr
846              if isUnboundName name
847                 then return (IEThingWith name [], AvailTC name [name])
848                 else do
849              let env = mkOccEnv [ (nameOccName s, s) 
850                                 | s <- findChildren kids_env name ]
851                  mb_names = map (lookupOccEnv env . rdrNameOcc) sub_rdrs
852              if any isNothing mb_names
853                 then do addErr (exportItemErr ie)
854                         return (IEThingWith name [], AvailTC name [name])
855                 else do let names = catMaybes mb_names
856                         optTyFam <- doptM Opt_TypeFamilies
857                         when (not optTyFam && any isTyConName names) $
858                           addErr (typeItemErr ( head
859                                               . filter isTyConName 
860                                               $ names )
861                                               (text "in export list"))
862                         return (IEThingWith name names, AvailTC name (name:names))
863
864     lookup_ie ie = panic "lookup_ie"    -- Other cases covered earlier
865
866     -------------
867     lookup_doc_ie :: IE RdrName -> RnM (IE Name)
868     lookup_doc_ie (IEGroup lev doc) = do rn_doc <- rnHsDoc doc
869                                          return (IEGroup lev rn_doc)
870     lookup_doc_ie (IEDoc doc)       = do rn_doc <- rnHsDoc doc
871                                          return (IEDoc rn_doc)
872     lookup_doc_ie (IEDocNamed str)  = return (IEDocNamed str)
873     lookup_doc_ie ie = panic "lookup_doc_ie"    -- Other cases covered earlier
874
875
876 isDoc (IEDoc _)      = True
877 isDoc (IEDocNamed _) = True
878 isDoc (IEGroup _ _)  = True
879 isDoc _ = False
880
881 -------------------------------
882 isModuleExported :: Bool -> ModuleName -> GlobalRdrElt -> Bool
883 -- True if the thing is in scope *both* unqualified, *and* with qualifier M
884 isModuleExported implicit_prelude mod (GRE { gre_name = name, gre_prov = prov })
885   | implicit_prelude && isBuiltInSyntax name = False
886         -- Optimisation: filter out names for built-in syntax
887         -- They just clutter up the environment (esp tuples), and the parser
888         -- will generate Exact RdrNames for them, so the cluttered
889         -- envt is no use.  To avoid doing this filter all the time,
890         -- we use -fno-implicit-prelude as a clue that the filter is
891         -- worth while.  Really, it's only useful for GHC.Base and GHC.Tuple.
892         --
893         -- It's worth doing because it makes the environment smaller for
894         -- every module that imports the Prelude
895   | otherwise
896   = case prov of
897         LocalDef    -> moduleName (nameModule name) == mod
898         Imported is -> any unQualSpecOK is && any (qualSpecOK mod) is
899
900 -------------------------------
901 check_occs :: IE RdrName -> ExportOccMap -> [Name] -> RnM ExportOccMap
902 check_occs ie occs names
903   = foldlM check occs names
904   where
905     check occs name
906       = case lookupOccEnv occs name_occ of
907           Nothing -> returnM (extendOccEnv occs name_occ (name, ie))
908
909           Just (name', ie') 
910             | name == name'     -- Duplicate export
911             ->  do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
912                      warnIf warn_dup_exports (dupExportWarn name_occ ie ie') ;
913                      returnM occs }
914
915             | otherwise         -- Same occ name but different names: an error
916             ->  do { global_env <- getGlobalRdrEnv ;
917                      addErr (exportClashErr global_env name' name ie' ie) ;
918                      returnM occs }
919       where
920         name_occ = nameOccName name
921 \end{code}
922
923 %*********************************************************
924 %*                                                       *
925                 Deprecations
926 %*                                                       *
927 %*********************************************************
928
929 \begin{code}
930 finishDeprecations :: DynFlags -> Maybe DeprecTxt 
931                    -> TcGblEnv -> RnM TcGblEnv
932 -- (a) Report usasge of deprecated imports
933 -- (b) If the whole module is deprecated, update tcg_deprecs
934 --              All this happens only once per module
935 finishDeprecations dflags mod_deprec tcg_env
936   = do  { (eps,hpt) <- getEpsAndHpt
937         ; ifOptM Opt_WarnDeprecations   $
938           mapM_ (check hpt (eps_PIT eps)) all_gres
939                 -- By this time, typechecking is complete, 
940                 -- so the PIT is fully populated
941
942         -- Deal with a module deprecation; it overrides all existing deprecs
943         ; let new_deprecs = case mod_deprec of
944                                 Just txt -> DeprecAll txt
945                                 Nothing  -> tcg_deprecs tcg_env
946         ; return (tcg_env { tcg_deprecs = new_deprecs }) }
947   where
948     used_names = allUses (tcg_dus tcg_env) 
949         -- Report on all deprecated uses; hence allUses
950     all_gres   = globalRdrEnvElts (tcg_rdr_env tcg_env)
951
952     check hpt pit gre@(GRE {gre_name = name, gre_prov = Imported (imp_spec:_)})
953       | name `elemNameSet` used_names
954       , Just deprec_txt <- lookupImpDeprec dflags hpt pit gre
955       = addWarnAt (importSpecLoc imp_spec)
956                   (sep [ptext SLIT("Deprecated use of") <+> 
957                         pprNonVarNameSpace (occNameSpace (nameOccName name)) <+> 
958                         quotes (ppr name),
959                       (parens imp_msg) <> colon,
960                       (ppr deprec_txt) ])
961         where
962           name_mod = nameModule name
963           imp_mod  = importSpecModule imp_spec
964           imp_msg  = ptext SLIT("imported from") <+> ppr imp_mod <> extra
965           extra | imp_mod == moduleName name_mod = empty
966                 | otherwise = ptext SLIT(", but defined in") <+> ppr name_mod
967
968     check hpt pit ok_gre = returnM ()   -- Local, or not used, or not deprectated
969             -- The Imported pattern-match: don't deprecate locally defined names
970             -- For a start, we may be exporting a deprecated thing
971             -- Also we may use a deprecated thing in the defn of another
972             -- deprecated things.  We may even use a deprecated thing in
973             -- the defn of a non-deprecated thing, when changing a module's 
974             -- interface
975
976 lookupImpDeprec :: DynFlags -> HomePackageTable -> PackageIfaceTable 
977                 -> GlobalRdrElt -> Maybe DeprecTxt
978 -- The name is definitely imported, so look in HPT, PIT
979 lookupImpDeprec dflags hpt pit gre
980   = case lookupIfaceByModule dflags hpt pit (nameModule name) of
981         Just iface -> mi_dep_fn iface name `seqMaybe`   -- Bleat if the thing, *or
982                       case gre_par gre of       
983                         ParentIs p -> mi_dep_fn iface p -- its parent*, is deprec'd
984                         NoParent   -> Nothing
985
986         Nothing -> Nothing      -- See Note [Used names with interface not loaded]
987   where
988         name = gre_name gre
989 \end{code}
990
991 Note [Used names with interface not loaded]
992 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
993 By now all the interfaces should have been loaded,
994 because reportDeprecations happens after typechecking.
995 However, it's still (just) possible to to find a used 
996 Name whose interface hasn't been loaded:
997
998 a) It might be a WiredInName; in that case we may not load 
999    its interface (although we could).
1000
1001 b) It might be GHC.Real.fromRational, or GHC.Num.fromInteger
1002    These are seen as "used" by the renamer (if -fno-implicit-prelude) 
1003    is on), but the typechecker may discard their uses 
1004    if in fact the in-scope fromRational is GHC.Read.fromRational,
1005    (see tcPat.tcOverloadedLit), and the typechecker sees that the type 
1006    is fixed, say, to GHC.Base.Float (see Inst.lookupSimpleInst).
1007    In that obscure case it won't force the interface in.
1008
1009 In both cases we simply don't permit deprecations; 
1010 this is, after all, wired-in stuff.
1011
1012
1013 %*********************************************************
1014 %*                                                       *
1015                 Unused names
1016 %*                                                       *
1017 %*********************************************************
1018
1019 \begin{code}
1020 reportUnusedNames :: Maybe [LIE RdrName]        -- Export list
1021                   -> TcGblEnv -> RnM ()
1022 reportUnusedNames export_decls gbl_env 
1023   = do  { traceRn ((text "RUN") <+> (ppr (tcg_dus gbl_env)))
1024         ; warnUnusedTopBinds   unused_locals
1025         ; warnUnusedModules    unused_imp_mods
1026         ; warnUnusedImports    unused_imports   
1027         ; warnDuplicateImports defined_and_used
1028         ; printMinimalImports  minimal_imports }
1029   where
1030     used_names :: NameSet
1031     used_names = findUses (tcg_dus gbl_env) emptyNameSet
1032         -- NB: currently, if f x = g, we only treat 'g' as used if 'f' is used
1033         -- Hence findUses
1034
1035         -- Collect the defined names from the in-scope environment
1036     defined_names :: [GlobalRdrElt]
1037     defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)
1038
1039         -- Note that defined_and_used, defined_but_not_used
1040         -- are both [GRE]; that's why we need defined_and_used
1041         -- rather than just used_names
1042     defined_and_used, defined_but_not_used :: [GlobalRdrElt]
1043     (defined_and_used, defined_but_not_used) 
1044         = partition (gre_is_used used_names) defined_names
1045     
1046     kids_env = mkChildEnv defined_names
1047         -- This is done in mkExports too; duplicated work
1048
1049     gre_is_used :: NameSet -> GlobalRdrElt -> Bool
1050     gre_is_used used_names (GRE {gre_name = name})
1051         = name `elemNameSet` used_names
1052           || any (`elemNameSet` used_names) (findChildren kids_env name)
1053                 -- A use of C implies a use of T,
1054                 -- if C was brought into scope by T(..) or T(C)
1055
1056         -- Filter out the ones that are 
1057         --  (a) defined in this module, and
1058         --  (b) not defined by a 'deriving' clause 
1059         -- The latter have an Internal Name, so we can filter them out easily
1060     unused_locals :: [GlobalRdrElt]
1061     unused_locals = filter is_unused_local defined_but_not_used
1062     is_unused_local :: GlobalRdrElt -> Bool
1063     is_unused_local gre = isLocalGRE gre && isExternalName (gre_name gre)
1064     
1065     unused_imports :: [GlobalRdrElt]    
1066     unused_imports = mapCatMaybes unused_imp defined_but_not_used
1067     unused_imp :: GlobalRdrElt -> Maybe GlobalRdrElt    -- Result has trimmed Imported provenances
1068     unused_imp gre@(GRE {gre_prov = LocalDef}) = Nothing
1069     unused_imp gre@(GRE {gre_prov = Imported imp_specs}) 
1070         | null trimmed_specs = Nothing
1071         | otherwise          = Just (gre {gre_prov = Imported trimmed_specs})
1072         where
1073           trimmed_specs = filter report_if_unused imp_specs
1074     
1075     -- To figure out the minimal set of imports, start with the things
1076     -- that are in scope (i.e. in gbl_env).  Then just combine them
1077     -- into a bunch of avails, so they are properly grouped
1078     --
1079     -- BUG WARNING: this does not deal properly with qualified imports!
1080     minimal_imports :: FiniteMap ModuleName AvailEnv
1081     minimal_imports0 = foldr add_expall   emptyFM          expall_mods
1082     minimal_imports1 = foldr add_name     minimal_imports0 defined_and_used
1083     minimal_imports  = foldr add_inst_mod minimal_imports1 direct_import_mods
1084         -- The last line makes sure that we retain all direct imports
1085         -- even if we import nothing explicitly.
1086         -- It's not necessarily redundant to import such modules. Consider 
1087         --            module This
1088         --              import M ()
1089         --
1090         -- The import M() is not *necessarily* redundant, even if
1091         -- we suck in no instance decls from M (e.g. it contains 
1092         -- no instance decls, or This contains no code).  It may be 
1093         -- that we import M solely to ensure that M's orphan instance 
1094         -- decls (or those in its imports) are visible to people who 
1095         -- import This.  Sigh. 
1096         -- There's really no good way to detect this, so the error message 
1097         -- in RnEnv.warnUnusedModules is weakened instead
1098     
1099         -- We've carefully preserved the provenance so that we can
1100         -- construct minimal imports that import the name by (one of)
1101         -- the same route(s) as the programmer originally did.
1102     add_name gre@(GRE {gre_prov = Imported (imp_spec:_)}) acc 
1103         = addToFM_C plusAvailEnv acc 
1104                     (importSpecModule imp_spec) (unitAvailEnv (greAvail gre))
1105     add_name gre acc = acc      -- Local
1106
1107         -- Modules mentioned as 'module M' in the export list
1108     expall_mods = case export_decls of
1109                     Nothing -> []
1110                     Just es -> [m | L _ (IEModuleContents m) <- es]
1111
1112         -- This is really bogus.  The idea is that if we see 'module M' in 
1113         -- the export list we must retain the import decls that drive it
1114         -- If we aren't careful we might see
1115         --      module A( module M ) where
1116         --        import M
1117         --        import N
1118         -- and suppose that N exports everything that M does.  Then we 
1119         -- must not drop the import of M even though N brings it all into
1120         -- scope.
1121         --
1122         -- BUG WARNING: 'module M' exports aside, what if M.x is mentioned?!
1123         --
1124         -- The reason that add_expall is bogus is that it doesn't take
1125         -- qualified imports into account.  But it's an improvement.
1126     add_expall mod acc = addToFM_C plusAvailEnv acc mod emptyAvailEnv
1127
1128     add_inst_mod (mod, _) acc 
1129       | mod_name `elemFM` acc = acc     -- We import something already
1130       | otherwise             = addToFM acc mod_name emptyAvailEnv
1131       where
1132         mod_name = moduleName mod
1133         -- Add an empty collection of imports for a module
1134         -- from which we have sucked only instance decls
1135    
1136     imports = tcg_imports gbl_env
1137
1138     direct_import_mods :: [(Module, [(ModuleName, Bool, SrcSpan)])]
1139         -- See the type of the imp_mods for this triple
1140     direct_import_mods = moduleEnvElts (imp_mods imports)
1141
1142     -- unused_imp_mods are the directly-imported modules 
1143     -- that are not mentioned in minimal_imports1
1144     -- [Note: not 'minimal_imports', because that includes directly-imported
1145     --        modules even if we use nothing from them; see notes above]
1146     --
1147     -- BUG WARNING: this code is generally buggy
1148     unused_imp_mods :: [(ModuleName, SrcSpan)]
1149     unused_imp_mods = [(mod_name,loc)
1150                     | (mod, xs) <- direct_import_mods,
1151                       (_, no_imp, loc) <- xs,
1152                        let mod_name = moduleName mod,
1153                        not (mod_name `elemFM` minimal_imports1),
1154                        mod /= pRELUDE,
1155                        not no_imp]
1156         -- The not no_imp part is not to complain about
1157         -- import M (), which is an idiom for importing
1158         -- instance declarations
1159     
1160     module_unused :: ModuleName -> Bool
1161     module_unused mod = any (((==) mod) . fst) unused_imp_mods
1162
1163     report_if_unused :: ImportSpec -> Bool
1164         -- Do we want to report this as an unused import?  
1165     report_if_unused (ImpSpec {is_decl = d, is_item = i})
1166         = not (module_unused (is_mod d)) -- Not if we've already said entire import is unused
1167           && isExplicitItem i            -- Only if the import was explicit
1168                         
1169 ---------------------
1170 warnDuplicateImports :: [GlobalRdrElt] -> RnM ()
1171 -- Given the GREs for names that are used, figure out which imports 
1172 -- could be omitted without changing the top-level environment.
1173 --
1174 -- NB: Given import Foo( T )
1175 --           import qualified Foo
1176 -- we do not report a duplicate import, even though Foo.T is brought
1177 -- into scope by both, because there's nothing you can *omit* without
1178 -- changing the top-level environment.  So we complain only if it's
1179 -- explicitly named in both imports or neither.
1180 --
1181 -- Furthermore, we complain about Foo.T only if 
1182 -- there is no complaint about (unqualified) T
1183
1184 warnDuplicateImports gres
1185   = ifOptM Opt_WarnUnusedImports $ 
1186     sequenceM_  [ warn name pr
1187                 | GRE { gre_name = name, gre_prov = Imported imps } <- gres
1188                 , pr <- redundants imps ]
1189   where
1190     warn name (red_imp, cov_imp)
1191         = addWarnAt (importSpecLoc red_imp)
1192             (vcat [ptext SLIT("Redundant import of:") <+> quotes pp_name,
1193                    ptext SLIT("It is also") <+> ppr cov_imp])
1194         where
1195           pp_name | is_qual red_decl = ppr (is_as red_decl) <> dot <> ppr occ
1196                   | otherwise       = ppr occ
1197           occ = nameOccName name
1198           red_decl = is_decl red_imp
1199     
1200     redundants :: [ImportSpec] -> [(ImportSpec,ImportSpec)]
1201         -- The returned pair is (redundant-import, covering-import)
1202     redundants imps 
1203         = [ (red_imp, cov_imp) 
1204           | red_imp <- imps
1205           , isExplicitItem (is_item red_imp)
1206                 -- Complain only about redundant imports
1207                 -- mentioned explicitly by the user                             
1208           , cov_imp <- take 1 (filter (covers red_imp) imps) ]
1209                         -- The 'take 1' picks the first offending group
1210                         -- for this particular name
1211
1212         -- "red_imp" is a putative redundant import
1213         -- "cov_imp" potentially covers it
1214         -- This test decides whether red_imp could be dropped 
1215         --
1216         -- NOTE: currently the test does not warn about
1217         --              import M( x )
1218         --              imoprt N( x )
1219         -- even if the same underlying 'x' is involved, because dropping
1220         -- either import would change the qualified names in scope (M.x, N.x)
1221         -- But if the qualified names aren't used, the import is indeed redundant
1222         -- Sadly we don't know that.  Oh well.
1223     covers red_imp@(ImpSpec { is_decl = red_decl, is_item = red_item }) 
1224            cov_imp@(ImpSpec { is_decl = cov_decl, is_item = cov_item })
1225         | red_loc == cov_loc
1226         = False         -- Ignore diagonal elements
1227         | not (is_as red_decl == is_as cov_decl)
1228         = False         -- They bring into scope different qualified names
1229         | not (is_qual red_decl) && is_qual cov_decl
1230         = False         -- Covering one doesn't bring unqualified name into scope
1231         | otherwise
1232         = not (isExplicitItem cov_item) -- Redundant one is selective and covering one isn't
1233           || red_later                  -- or both are explicit; tie-break using red_later
1234 {-
1235         | red_selective
1236         = not cov_selective     -- Redundant one is selective and covering one isn't
1237           || red_later          -- Both are explicit; tie-break using red_later
1238         | otherwise             
1239         = not cov_selective     -- Neither import is selective
1240           && (is_mod red_decl == is_mod cov_decl)       -- They import the same module
1241           && red_later          -- Tie-break
1242 -}
1243         where
1244           red_loc   = importSpecLoc red_imp
1245           cov_loc   = importSpecLoc cov_imp
1246           red_later = red_loc > cov_loc
1247
1248 -- ToDo: deal with original imports with 'qualified' and 'as M' clauses
1249 printMinimalImports :: FiniteMap ModuleName AvailEnv    -- Minimal imports
1250                     -> RnM ()
1251 printMinimalImports imps
1252  = ifOptM Opt_D_dump_minimal_imports $ do {
1253
1254    mod_ies  <-  initIfaceTcRn $ mappM to_ies (fmToList imps) ;
1255    this_mod <- getModule ;
1256    rdr_env  <- getGlobalRdrEnv ;
1257    ioToTcRn (do { h <- openFile (mkFilename this_mod) WriteMode ;
1258                   printForUser h (mkPrintUnqualified rdr_env) 
1259                                  (vcat (map ppr_mod_ie mod_ies)) })
1260    }
1261   where
1262     mkFilename this_mod = moduleNameString (moduleName this_mod) ++ ".imports"
1263     ppr_mod_ie (mod_name, ies) 
1264         | mod_name == moduleName pRELUDE
1265         = empty
1266         | null ies      -- Nothing except instances comes from here
1267         = ptext SLIT("import") <+> ppr mod_name <> ptext SLIT("()    -- Instances only")
1268         | otherwise
1269         = ptext SLIT("import") <+> ppr mod_name <> 
1270                     parens (fsep (punctuate comma (map ppr ies)))
1271
1272     to_ies (mod, avail_env) = do ies <- mapM to_ie (availEnvElts avail_env)
1273                                  returnM (mod, ies)
1274
1275     to_ie :: AvailInfo -> IfG (IE Name)
1276         -- The main trick here is that if we're importing all the constructors
1277         -- we want to say "T(..)", but if we're importing only a subset we want
1278         -- to say "T(A,B,C)".  So we have to find out what the module exports.
1279     to_ie (Avail n)       = returnM (IEVar n)
1280     to_ie (AvailTC n [m]) = ASSERT( n==m ) 
1281                             returnM (IEThingAbs n)
1282     to_ie (AvailTC n ns)  
1283         = loadSysInterface doc n_mod                    `thenM` \ iface ->
1284           case [xs | (m,as) <- mi_exports iface,
1285                      m == n_mod,
1286                      AvailTC x xs <- as, 
1287                      x == nameOccName n] of
1288               [xs] | all_used xs -> returnM (IEThingAll n)
1289                    | otherwise   -> returnM (IEThingWith n (filter (/= n) ns))
1290               other              -> pprTrace "to_ie" (ppr n <+> ppr n_mod <+> ppr other) $
1291                                     returnM (IEVar n)
1292         where
1293           all_used avail_occs = all (`elem` map nameOccName ns) avail_occs
1294           doc = text "Compute minimal imports from" <+> ppr n
1295           n_mod = nameModule n
1296 \end{code}
1297
1298
1299 %************************************************************************
1300 %*                                                                      *
1301 \subsection{Errors}
1302 %*                                                                      *
1303 %************************************************************************
1304
1305 \begin{code}
1306 badImportItemErr iface decl_spec ie
1307   = sep [ptext SLIT("Module"), quotes (ppr (is_mod decl_spec)), source_import,
1308          ptext SLIT("does not export"), quotes (ppr ie)]
1309   where
1310     source_import | mi_boot iface = ptext SLIT("(hi-boot interface)")
1311                   | otherwise     = empty
1312
1313 illegalImportItemErr = ptext SLIT("Illegal import item")
1314
1315 dodgyImportWarn item = dodgyMsg (ptext SLIT("import")) item
1316 dodgyExportWarn item = dodgyMsg (ptext SLIT("export")) item
1317
1318 dodgyMsg kind tc
1319   = sep [ ptext SLIT("The") <+> kind <+> ptext SLIT("item") <+> quotes (ppr (IEThingAll tc)),
1320           ptext SLIT("suggests that") <+> quotes (ppr tc) <+> ptext SLIT("has constructors or class methods,"),
1321           ptext SLIT("but it has none") ]
1322           
1323 exportItemErr export_item
1324   = sep [ ptext SLIT("The export item") <+> quotes (ppr export_item),
1325           ptext SLIT("attempts to export constructors or class methods that are not visible here") ]
1326
1327 typeItemErr name wherestr
1328   = sep [ ptext SLIT("Using 'type' tag on") <+> quotes (ppr name) <+> wherestr,
1329           ptext SLIT("Use -ftype-families to enable this extension") ]
1330
1331 exportClashErr :: GlobalRdrEnv -> Name -> Name -> IE RdrName -> IE RdrName
1332                -> Message
1333 exportClashErr global_env name1 name2 ie1 ie2
1334   = vcat [ ptext SLIT("Conflicting exports for") <+> quotes (ppr occ) <> colon
1335          , ppr_export ie1' name1'
1336          , ppr_export ie2' name2' ]
1337   where
1338     occ = nameOccName name1
1339     ppr_export ie name = nest 2 (quotes (ppr ie) <+> ptext SLIT("exports") <+> 
1340                                  quotes (ppr name) <+> pprNameProvenance (get_gre name))
1341
1342         -- get_gre finds a GRE for the Name, so that we can show its provenance
1343     get_gre name
1344         = case lookupGRE_Name global_env name of
1345              (gre:_) -> gre
1346              []      -> pprPanic "exportClashErr" (ppr name)
1347     get_loc name = nameSrcLoc $ gre_name $ get_gre name
1348     (name1', ie1', name2', ie2') = if get_loc name1 < get_loc name2
1349                                    then (name1, ie1, name2, ie2)
1350                                    else (name2, ie2, name1, ie1)
1351
1352 addDupDeclErr :: Name -> Name -> TcRn ()
1353 addDupDeclErr name_a name_b
1354   = addErrAt (srcLocSpan loc2) $
1355     vcat [ptext SLIT("Multiple declarations of") <+> quotes (ppr name1),
1356           ptext SLIT("Declared at:") <+> vcat [ppr (nameSrcLoc name1), ppr loc2]]
1357   where
1358     loc2 = nameSrcLoc name2
1359     (name1,name2) | nameSrcLoc name_a > nameSrcLoc name_b = (name_b,name_a)
1360                   | otherwise                             = (name_a,name_b)
1361         -- Report the error at the later location
1362
1363 dupExportWarn occ_name ie1 ie2
1364   = hsep [quotes (ppr occ_name), 
1365           ptext SLIT("is exported by"), quotes (ppr ie1),
1366           ptext SLIT("and"),            quotes (ppr ie2)]
1367
1368 dupModuleExport mod
1369   = hsep [ptext SLIT("Duplicate"),
1370           quotes (ptext SLIT("Module") <+> ppr mod), 
1371           ptext SLIT("in export list")]
1372
1373 moduleNotImported :: ModuleName -> SDoc
1374 moduleNotImported mod
1375   = ptext SLIT("The export item `module") <+> ppr mod <>
1376     ptext SLIT("' is not imported")
1377
1378 nullModuleExport mod
1379   = ptext SLIT("The export item `module") <+> ppr mod <> ptext SLIT("' exports nothing")
1380
1381 moduleDeprec mod txt
1382   = sep [ ptext SLIT("Module") <+> quotes (ppr mod) <+> ptext SLIT("is deprecated:"), 
1383           nest 4 (ppr txt) ]      
1384
1385 implicitPreludeWarn
1386   = ptext SLIT("Module `Prelude' implicitly imported")
1387 \end{code}