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