[project @ 2002-10-24 14:17:46 by simonpj]
[ghc-hetmet.git] / ghc / 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, importsFromLocalDecls, exportsFromAvail,
9         reportUnusedNames, mkModDeps
10     ) where
11
12 #include "HsVersions.h"
13
14 import {-# SOURCE #-} RnHiFiles ( loadInterface )
15
16 import CmdLineOpts      ( DynFlag(..) )
17
18 import HsSyn            ( IE(..), ieName, ImportDecl(..),
19                           ForeignDecl(..), HsGroup(..),
20                           collectLocatedHsBinders, tyClDeclNames 
21                         )
22 import RdrHsSyn         ( RdrNameIE, RdrNameImportDecl )
23 import RnEnv
24 import TcRnMonad
25
26 import FiniteMap
27 import PrelNames        ( pRELUDE_Name, mAIN_Name, isBuiltInSyntaxName )
28 import Module           ( Module, ModuleName, ModuleEnv, moduleName, 
29                           moduleNameUserString, isHomeModule,
30                           emptyModuleEnv, unitModuleEnvByName, unitModuleEnv, 
31                           lookupModuleEnvByName, extendModuleEnvByName, moduleEnvElts )
32 import Name             ( Name, nameSrcLoc, nameOccName, nameModule, isExternalName )
33 import NameSet
34 import NameEnv
35 import OccName          ( OccName, dataName, isTcOcc )
36 import HscTypes         ( Provenance(..), ImportReason(..), GlobalRdrEnv,
37                           GenAvailInfo(..), AvailInfo, Avails, 
38                           IsBootInterface, WhetherHasOrphans,
39                           availName, availNames, availsToNameSet, 
40                           Deprecations(..), ModIface(..), 
41                           GlobalRdrElt(..), unQualInScope, isLocalGRE
42                         )
43 import RdrName          ( RdrName, rdrNameOcc, setRdrNameSpace, 
44                           emptyRdrEnv, foldRdrEnv, isQual )
45 import Outputable
46 import Maybes           ( maybeToBool, catMaybes )
47 import ListSetOps       ( removeDups )
48 import Util             ( sortLt, notNull )
49 import List             ( partition, insert )
50 import IO               ( openFile, IOMode(..) )
51 \end{code}
52
53
54
55 %************************************************************************
56 %*                                                                      *
57                 rnImports
58 %*                                                                      *
59 %************************************************************************
60
61 \begin{code}
62 rnImports :: [RdrNameImportDecl]
63           -> TcRn m (GlobalRdrEnv, ImportAvails)
64
65 rnImports imports
66   =             -- PROCESS IMPORT DECLS
67                 -- Do the non {- SOURCE -} ones first, so that we get a helpful
68                 -- warning for {- SOURCE -} ones that are unnecessary
69         getModule                               `thenM` \ this_mod ->
70         getSrcLocM                              `thenM` \ loc ->
71         doptM Opt_NoImplicitPrelude             `thenM` \ opt_no_prelude -> 
72         let
73           all_imports        = mk_prel_imports this_mod loc opt_no_prelude ++ imports
74           (source, ordinary) = partition is_source_import all_imports
75           is_source_import (ImportDecl _ is_boot _ _ _ _) = is_boot
76
77           get_imports = importsFromImportDecl this_mod
78         in
79         mappM get_imports ordinary      `thenM` \ stuff1 ->
80         mappM get_imports source        `thenM` \ stuff2 ->
81
82                 -- COMBINE RESULTS
83         let
84             (imp_gbl_envs, imp_avails) = unzip (stuff1 ++ stuff2)
85             gbl_env :: GlobalRdrEnv
86             gbl_env = foldr plusGlobalRdrEnv emptyRdrEnv imp_gbl_envs
87
88             all_avails :: ImportAvails
89             all_avails = foldr plusImportAvails emptyImportAvails imp_avails
90         in
91                 -- ALL DONE
92         returnM (gbl_env, all_avails)
93   where
94         -- NB: opt_NoImplicitPrelude is slightly different to import Prelude ();
95         -- because the former doesn't even look at Prelude.hi for instance 
96         -- declarations, whereas the latter does.
97     mk_prel_imports this_mod loc no_prelude
98         |  moduleName this_mod == pRELUDE_Name
99         || explicit_prelude_import
100         || no_prelude
101         = []
102
103         | otherwise = [preludeImportDecl loc]
104
105     explicit_prelude_import
106       = notNull [ () | (ImportDecl mod _ _ _ _ _) <- imports, 
107                        mod == pRELUDE_Name ]
108
109 preludeImportDecl loc
110   = ImportDecl pRELUDE_Name
111                False {- Not a boot interface -}
112                False    {- Not qualified -}
113                Nothing  {- No "as" -}
114                Nothing  {- No import list -}
115                loc
116 \end{code}
117         
118 \begin{code}
119 importsFromImportDecl :: Module
120                       -> RdrNameImportDecl
121                       -> TcRn m (GlobalRdrEnv, ImportAvails)
122
123 importsFromImportDecl this_mod
124         (ImportDecl imp_mod_name is_boot qual_only as_mod imp_spec iloc)
125   = addSrcLoc iloc $
126     let
127         doc = ppr imp_mod_name <+> ptext SLIT("is directly imported")
128     in
129
130         -- If there's an error in loadInterface, (e.g. interface
131         -- file not found) we get lots of spurious errors from 'filterImports'
132     tryM (loadInterface doc imp_mod_name (ImportByUser is_boot))        `thenM` \ mb_iface ->
133
134     case mb_iface of {
135         Left exn    -> returnM (emptyRdrEnv, emptyImportAvails ) ;
136         Right iface ->    
137
138     let
139         imp_mod          = mi_module iface
140         avails_by_module = mi_exports iface
141         deprecs          = mi_deprecs iface
142         is_orph          = mi_orphan iface 
143
144         avails :: Avails
145         avails = [ avail | (mod_name, avails) <- avails_by_module,
146                            mod_name /= this_mod_name,
147                            avail <- avails ]
148         this_mod_name = moduleName this_mod
149         -- If the module exports anything defined in this module, just ignore it.
150         -- Reason: otherwise it looks as if there are two local definition sites
151         -- for the thing, and an error gets reported.  Easiest thing is just to
152         -- filter them out up front. This situation only arises if a module
153         -- imports itself, or another module that imported it.  (Necessarily,
154         -- this invoves a loop.)  
155         --
156         -- Tiresome consequence: if you say
157         --      module A where
158         --         import B( AType )
159         --         type AType = ...
160         --
161         --      module B( AType ) where
162         --         import {-# SOURCE #-} A( AType )
163         --
164         -- then you'll get a 'B does not export AType' message.  Oh well.
165
166     in
167         -- Filter the imports according to the import list
168     filterImports imp_mod is_boot imp_spec avails    `thenM` \ (filtered_avails, explicits) ->
169
170     let
171         (sub_dep_mods, sub_dep_pkgs) = mi_deps iface
172
173         -- Compute new transitive dependencies: take the ones in 
174         -- the interface and add 
175         (dependent_mods, dependent_pkgs) 
176            | isHomeModule imp_mod 
177            =    -- Imported module is from the home package
178                 -- Take its dependent modules and
179                 --      (a) remove this_mod (might be there as a hi-boot)
180                 --      (b) add imp_mod itself
181                 -- Take its dependent packages unchanged
182              ((imp_mod_name, is_orph, is_boot) : filter not_self sub_dep_mods, 
183               sub_dep_pkgs)
184            | otherwise  
185            =    -- Imported module is from another package
186                 -- Take only the orphan modules from its dependent modules
187                 --      (sigh!  it would be better to dump them entirely)
188                 -- Add the package imp_mod comes from to the dependent packages
189                 -- from imp_mod
190              (filter sub_is_orph sub_dep_mods, 
191               insert (mi_package iface) sub_dep_pkgs)
192
193         not_self    (m, _, _)    = m /= this_mod_name
194         sub_is_orph (_, orph, _) = orph
195
196         import_all = case imp_spec of
197                         (Just (False, _)) -> False      -- Imports are spec'd explicitly
198                         other             -> True       -- Everything is imported, 
199                                                         -- (or almost everything [hiding])
200
201         qual_mod_name = case as_mod of
202                           Nothing           -> imp_mod_name
203                           Just another_name -> another_name
204
205         -- unqual_avails is the Avails that are visible in *unqualified* form
206         -- We need to know this so we know what to export when we see
207         --      module M ( module P ) where ...
208         -- Then we must export whatever came from P unqualified.
209         avail_env = mkAvailEnv filtered_avails
210         unqual_avails | qual_only = emptyAvailEnv       -- Qualified import
211                       | otherwise = avail_env           -- Unqualified import
212
213         mk_prov name = NonLocalDef (UserImport imp_mod iloc (name `elemNameSet` explicits)) 
214         gbl_env      = mkGlobalRdrEnv qual_mod_name (not qual_only) 
215                                       mk_prov filtered_avails deprecs
216         imports      = ImportAvails { 
217                         imp_unqual = unitModuleEnvByName qual_mod_name unqual_avails,
218                         imp_env    = avail_env,
219                         imp_mods   = unitModuleEnv imp_mod (imp_mod, import_all),
220                         dep_mods   = mkModDeps dependent_mods,
221                         dep_pkgs   = dependent_pkgs }
222
223     in
224         -- Complain if we import a deprecated module
225     ifOptM Opt_WarnDeprecations (
226        case deprecs of  
227           DeprecAll txt -> addWarn (moduleDeprec imp_mod_name txt)
228           other         -> returnM ()
229     )                                                   `thenM_`
230
231     returnM (gbl_env, imports)
232     }
233
234 mkModDeps :: [(ModuleName, WhetherHasOrphans, IsBootInterface)]
235           -> ModuleEnv (ModuleName, WhetherHasOrphans, IsBootInterface)
236 mkModDeps deps = foldl add emptyModuleEnv deps
237                where
238                  add env elt@(m,_,_) = extendModuleEnvByName env m elt
239 \end{code}
240
241
242 %************************************************************************
243 %*                                                                      *
244                 importsFromLocalDecls
245 %*                                                                      *
246 %************************************************************************
247
248 From the top-level declarations of this module produce
249         * the lexical environment
250         * the ImportAvails
251 created by its bindings.  
252         
253 Complain about duplicate bindings
254
255 \begin{code}
256 importsFromLocalDecls :: HsGroup RdrName
257                       -> TcRn m (GlobalRdrEnv, ImportAvails)
258 importsFromLocalDecls group
259   = getModule                           `thenM` \ this_mod ->
260     getLocalDeclBinders this_mod group  `thenM` \ avails ->
261         -- The avails that are returned don't include the "system" names
262     let
263         all_names :: [Name]     -- All the defns; no dups eliminated
264         all_names = [name | avail <- avails, name <- availNames avail]
265
266         dups :: [[Name]]
267         (_, dups) = removeDups compare all_names
268     in
269         -- Check for duplicate definitions
270         -- The complaint will come out as "Multiple declarations of Foo.f" because
271         -- since 'f' is in the env twice, the unQualInScope used by the error-msg
272         -- printer returns False.  It seems awkward to fix, unfortunately.
273     mappM_ (addErr . dupDeclErr) dups                   `thenM_` 
274
275     doptM Opt_NoImplicitPrelude                 `thenM` \ implicit_prelude ->
276     let
277         mod_name   = moduleName this_mod
278         mk_prov n  = LocalDef   -- Provenance is local
279
280         unqual_imp = True       -- Want unqualified names in scope
281         gbl_env = mkGlobalRdrEnv mod_name unqual_imp mk_prov avails NoDeprecs
282             -- NoDeprecs: don't complain about locally defined names
283             -- For a start, we may be exporting a deprecated thing
284             -- Also we may use a deprecated thing in the defn of another
285             -- deprecated things.  We may even use a deprecated thing in
286             -- the defn of a non-deprecated thing, when changing a module's 
287             -- interface
288
289
290             -- Optimisation: filter out names for built-in syntax
291             -- They just clutter up the environment (esp tuples), and the parser
292             -- will generate Exact RdrNames for them, so the cluttered
293             -- envt is no use.  To avoid doing this filter all the time,
294             -- we use -fno-implicit-prelude as a clue that the filter is
295             -- worth while.  Really, it's only useful for GHC.Base and GHC.Tuple.
296             --
297             -- It's worth doing because it makes the environment smaller for
298             -- every module that imports the Prelude
299             --
300             -- Note: don't filter the gbl_env (hence avails, not avails' in
301             -- defn of gbl_env above).      Stupid reason: when parsing 
302             -- data type decls, the constructors start as Exact tycon-names,
303             -- and then get turned into data con names by zapping the name space;
304             -- but that stops them being Exact, so they get looked up.  Sigh.
305             -- It doesn't matter because it only affects the Data.Tuple really.
306             -- The important thing is to trim down the exports.
307
308         avails' | implicit_prelude = filter not_built_in_syntax avails
309                 | otherwise        = avails
310         not_built_in_syntax a = not (all isBuiltInSyntaxName (availNames a))
311                 -- Only filter it if all the names of the avail are built-in
312                 -- In particular, lists have (:) which is not built in syntax
313                 -- so we don't filter it out.
314
315         avail_env = mkAvailEnv avails'
316         imports   = emptyImportAvails {
317                         imp_unqual = unitModuleEnv this_mod avail_env,
318                         imp_env    = avail_env
319                     }
320     in
321     returnM (gbl_env, imports)
322 \end{code}
323
324
325 %*********************************************************
326 %*                                                      *
327 \subsection{Getting binders out of a declaration}
328 %*                                                      *
329 %*********************************************************
330
331 @getLocalDeclBinders@ returns the names for a @RdrNameHsDecl@.  It's
332 used for both source code (from @importsFromLocalDecls@) and interface
333 files (@loadDecl@ calls @getTyClDeclBinders@).
334
335         *** See "THE NAMING STORY" in HsDecls ****
336
337 \begin{code}
338 getLocalDeclBinders :: Module -> HsGroup RdrName -> TcRn m [AvailInfo]
339 getLocalDeclBinders mod (HsGroup {hs_valds = val_decls, 
340                                   hs_tyclds = tycl_decls, 
341                                   hs_fords = foreign_decls })
342   =     -- For type and class decls, we generate Global names, with
343         -- no export indicator.  They need to be global because they get
344         -- permanently bound into the TyCons and Classes.  They don't need
345         -- an export indicator because they are all implicitly exported.
346
347     mappM new_tc tycl_decls                             `thenM` \ tc_avails ->
348     mappM new_bndr (for_hs_bndrs ++ val_hs_bndrs)       `thenM` \ simple_bndrs ->
349
350     returnM (tc_avails ++ map Avail simple_bndrs)
351   where
352     new_bndr (rdr_name,loc) = newTopBinder mod rdr_name loc
353
354     val_hs_bndrs = collectLocatedHsBinders val_decls
355     for_hs_bndrs = [(nm,loc) | ForeignImport nm _ _ _ loc <- foreign_decls]
356
357     new_tc tc_decl = mappM new_bndr (tyClDeclNames tc_decl)     `thenM` \ names@(main_name:_) ->
358                      returnM (AvailTC main_name names)
359 \end{code}
360
361
362 %************************************************************************
363 %*                                                                      *
364 \subsection{Filtering imports}
365 %*                                                                      *
366 %************************************************************************
367
368 @filterImports@ takes the @ExportEnv@ telling what the imported module makes
369 available, and filters it through the import spec (if any).
370
371 \begin{code}
372 filterImports :: Module                         -- The module being imported
373               -> IsBootInterface                -- Tells whether it's a {-# SOURCE #-} import
374               -> Maybe (Bool, [RdrNameIE])      -- Import spec; True => hiding
375               -> [AvailInfo]                    -- What's available
376               -> TcRn m ([AvailInfo],           -- What's imported
377                        NameSet)                 -- What was imported explicitly
378
379         -- Complains if import spec mentions things that the module doesn't export
380         -- Warns/informs if import spec contains duplicates.
381 filterImports mod from Nothing imports
382   = returnM (imports, emptyNameSet)
383
384 filterImports mod from (Just (want_hiding, import_items)) total_avails
385   = mappM get_item import_items         `thenM` \ avails_w_explicits_s ->
386     let
387         (item_avails, explicits_s) = unzip (concat avails_w_explicits_s)
388         explicits                  = foldl addListToNameSet emptyNameSet explicits_s
389     in
390     if want_hiding then
391         let     -- All imported; item_avails to be hidden
392            hidden = availsToNameSet item_avails
393            keep n = not (n `elemNameSet` hidden)
394         in
395         returnM (pruneAvails keep total_avails, emptyNameSet)
396     else
397         -- Just item_avails imported; nothing to be hidden
398         returnM (item_avails, explicits)
399   where
400     import_fm :: FiniteMap OccName AvailInfo
401     import_fm = listToFM [ (nameOccName name, avail) 
402                          | avail <- total_avails,
403                            name  <- availNames avail]
404         -- Even though availNames returns data constructors too,
405         -- they won't make any difference because naked entities like T
406         -- in an import list map to TcOccs, not VarOccs.
407
408     bale_out item = addErr (badImportItemErr mod from item)     `thenM_`
409                     returnM []
410
411     get_item :: RdrNameIE -> TcRn m [(AvailInfo, [Name])]
412         -- Empty list for a bad item.
413         -- Singleton is typical case.
414         -- Can have two when we are hiding, and mention C which might be
415         --      both a class and a data constructor.  
416         -- The [Name] is the list of explicitly-mentioned names
417     get_item item@(IEModuleContents _) = bale_out item
418
419     get_item item@(IEThingAll _)
420       = case check_item item of
421           Nothing                    -> bale_out item
422           Just avail@(AvailTC _ [n]) ->         -- This occurs when you import T(..), but
423                                                 -- only export T abstractly.  The single [n]
424                                                 -- in the AvailTC is the type or class itself
425                                         ifOptM Opt_WarnMisc (addWarn (dodgyImportWarn mod item))        `thenM_`
426                                         returnM [(avail, [availName avail])]
427           Just avail                 -> returnM [(avail, [availName avail])]
428
429     get_item item@(IEThingAbs n)
430       | want_hiding     -- hiding( C ) 
431                         -- Here the 'C' can be a data constructor *or* a type/class
432       = case catMaybes [check_item item, check_item (IEVar data_n)] of
433                 []     -> bale_out item
434                 avails -> returnM [(a, []) | a <- avails]
435                                 -- The 'explicits' list is irrelevant when hiding
436       where
437         data_n = setRdrNameSpace n dataName
438
439     get_item item
440       = case check_item item of
441           Nothing    -> bale_out item
442           Just avail -> returnM [(avail, availNames avail)]
443
444     check_item item
445       | not (maybeToBool maybe_in_import_avails) ||
446         not (maybeToBool maybe_filtered_avail)
447       = Nothing
448
449       | otherwise    
450       = Just filtered_avail
451                 
452       where
453         wanted_occ             = rdrNameOcc (ieName item)
454         maybe_in_import_avails = lookupFM import_fm wanted_occ
455
456         Just avail             = maybe_in_import_avails
457         maybe_filtered_avail   = filterAvail item avail
458         Just filtered_avail    = maybe_filtered_avail
459 \end{code}
460
461 \begin{code}
462 filterAvail :: RdrNameIE        -- Wanted
463             -> AvailInfo        -- Available
464             -> Maybe AvailInfo  -- Resulting available; 
465                                 -- Nothing if (any of the) wanted stuff isn't there
466
467 filterAvail ie@(IEThingWith want wants) avail@(AvailTC n ns)
468   | sub_names_ok = Just (AvailTC n (filter is_wanted ns))
469   | otherwise    = Nothing
470   where
471     is_wanted name = nameOccName name `elem` wanted_occs
472     sub_names_ok   = all (`elem` avail_occs) wanted_occs
473     avail_occs     = map nameOccName ns
474     wanted_occs    = map rdrNameOcc (want:wants)
475
476 filterAvail (IEThingAbs _) (AvailTC n ns)       = ASSERT( n `elem` ns ) 
477                                                   Just (AvailTC n [n])
478
479 filterAvail (IEThingAbs _) avail@(Avail n)      = Just avail            -- Type synonyms
480
481 filterAvail (IEVar _)      avail@(Avail n)      = Just avail
482 filterAvail (IEVar v)      avail@(AvailTC n ns) = Just (AvailTC n (filter wanted ns))
483                                                 where
484                                                   wanted n = nameOccName n == occ
485                                                   occ      = rdrNameOcc v
486         -- The second equation happens if we import a class op, thus
487         --      import A( op ) 
488         -- where op is a class operation
489
490 filterAvail (IEThingAll _) avail@(AvailTC _ _)   = Just avail
491         -- We don't complain even if the IE says T(..), but
492         -- no constrs/class ops of T are available
493         -- Instead that's caught with a warning by the caller
494
495 filterAvail ie avail = Nothing
496 \end{code}
497
498
499 %************************************************************************
500 %*                                                                      *
501 \subsection{Export list processing}
502 %*                                                                      *
503 %************************************************************************
504
505 Processing the export list.
506
507 You might think that we should record things that appear in the export
508 list as ``occurrences'' (using @addOccurrenceName@), but you'd be
509 wrong.  We do check (here) that they are in scope, but there is no
510 need to slurp in their actual declaration (which is what
511 @addOccurrenceName@ forces).
512
513 Indeed, doing so would big trouble when compiling @PrelBase@, because
514 it re-exports @GHC@, which includes @takeMVar#@, whose type includes
515 @ConcBase.StateAndSynchVar#@, and so on...
516
517 \begin{code}
518 type ExportAccum        -- The type of the accumulating parameter of
519                         -- the main worker function in exportsFromAvail
520      = ([ModuleName],           -- 'module M's seen so far
521         ExportOccMap,           -- Tracks exported occurrence names
522         AvailEnv)               -- The accumulated exported stuff, kept in an env
523                                 --   so we can common-up related AvailInfos
524 emptyExportAccum = ([], emptyFM, emptyAvailEnv) 
525
526 type ExportOccMap = FiniteMap OccName (Name, RdrNameIE)
527         -- Tracks what a particular exported OccName
528         --   in an export list refers to, and which item
529         --   it came from.  It's illegal to export two distinct things
530         --   that have the same occurrence name
531
532
533 exportsFromAvail :: Maybe [RdrNameIE] -> TcRn m Avails
534         -- Complains if two distinct exports have same OccName
535         -- Warns about identical exports.
536         -- Complains about exports items not in scope
537 exportsFromAvail Nothing 
538  = do { this_mod <- getModule ;
539         if moduleName this_mod == mAIN_Name then
540            return []
541               -- Export nothing; Main.$main is automatically exported
542         else
543           exportsFromAvail (Just [IEModuleContents (moduleName this_mod)])
544               -- but for all other modules export everything.
545     }
546
547 exportsFromAvail (Just exports)
548  = do { TcGblEnv { tcg_imports = imports } <- getGblEnv ;
549         warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
550         exports_from_avail exports warn_dup_exports imports }
551
552 exports_from_avail export_items warn_dup_exports
553                    (ImportAvails { imp_unqual = mod_avail_env, 
554                                    imp_env = entity_avail_env }) 
555   = foldlM exports_from_item emptyExportAccum
556             export_items                        `thenM` \ (_, _, export_avail_map) ->
557     returnM (nameEnvElts export_avail_map)
558
559   where
560     exports_from_item :: ExportAccum -> RdrNameIE -> TcRn m ExportAccum
561
562     exports_from_item acc@(mods, occs, avails) ie@(IEModuleContents mod)
563         | mod `elem` mods       -- Duplicate export of M
564         = warnIf warn_dup_exports (dupModuleExport mod) `thenM_`
565           returnM acc
566
567         | otherwise
568         = case lookupModuleEnvByName mod_avail_env mod of
569             Nothing             -> addErr (modExportErr mod)    `thenM_`
570                                    returnM acc
571             Just avail_env
572                 -> let
573                         mod_avails = availEnvElts avail_env
574                         avails' = foldl addAvail avails mod_avails
575                    in
576                    foldlM (check_occs warn_dup_exports ie) 
577                           occs mod_avails       `thenM` \ occs' ->
578
579                    returnM (mod:mods, occs', avails')
580
581     exports_from_item acc@(mods, occs, avails) ie
582         = lookupGRE (ieName ie)                 `thenM` \ mb_gre -> 
583           case mb_gre of {
584                 Nothing -> addErr (unknownNameErr (ieName ie))  `thenM_`
585                            returnM acc ;
586                 Just gre ->             
587
588                 -- Get the AvailInfo for the parent of the specified name
589           case lookupAvailEnv entity_avail_env (gre_parent gre) of {
590              Nothing -> pprPanic "exportsFromAvail" 
591                                 ((ppr (ieName ie)) <+> ppr gre) ;
592              Just avail ->
593
594                 -- Filter out the bits we want
595           case filterAvail ie avail of {
596             Nothing ->  -- Not enough availability
597                         addErr (exportItemErr ie) `thenM_`
598                         returnM acc ;
599
600             Just export_avail ->        
601
602                 -- Phew!  It's OK!  Now to check the occurrence stuff!
603           warnIf (not (ok_item ie avail)) (dodgyExportWarn ie)  `thenM_`
604           check_occs warn_dup_exports ie occs export_avail      `thenM` \ occs' ->
605           returnM (mods, occs', addAvail avails export_avail)
606           }}}
607
608
609
610 ok_item (IEThingAll _) (AvailTC _ [n]) = False
611   -- This occurs when you import T(..), but
612   -- only export T abstractly.  The single [n]
613   -- in the AvailTC is the type or class itself
614 ok_item _ _ = True
615
616 check_occs :: Bool -> RdrNameIE -> ExportOccMap -> AvailInfo -> TcRn m ExportOccMap
617 check_occs warn_dup_exports ie occs avail 
618   = foldlM check occs (availNames avail)
619   where
620     check occs name
621       = case lookupFM occs name_occ of
622           Nothing           -> returnM (addToFM occs name_occ (name, ie))
623           Just (name', ie') 
624             | name == name' ->  -- Duplicate export
625                                 warnIf warn_dup_exports
626                                         (dupExportWarn name_occ ie ie')
627                                 `thenM_` returnM occs
628
629             | otherwise     ->  -- Same occ name but different names: an error
630                                 addErr (exportClashErr name_occ ie ie') `thenM_`
631                                 returnM occs
632       where
633         name_occ = nameOccName name
634 \end{code}
635
636 %*********************************************************
637 %*                                                       *
638 \subsection{Unused names}
639 %*                                                       *
640 %*********************************************************
641
642 \begin{code}
643 reportUnusedNames :: TcGblEnv
644                   -> NameSet            -- Used in this module
645                   -> TcRn m ()
646 reportUnusedNames gbl_env used_names
647   = warnUnusedModules unused_imp_mods                   `thenM_`
648     warnUnusedTopBinds bad_locals                       `thenM_`
649     warnUnusedImports bad_imports                       `thenM_`
650     printMinimalImports minimal_imports
651   where
652     direct_import_mods :: [ModuleName]
653     direct_import_mods = map (moduleName . fst) 
654                              (moduleEnvElts (imp_mods (tcg_imports gbl_env)))
655
656     -- Now, a use of C implies a use of T,
657     -- if C was brought into scope by T(..) or T(C)
658     really_used_names :: NameSet
659     really_used_names = used_names `unionNameSets`
660                         mkNameSet [ gre_parent gre
661                                   | gre <- defined_names,
662                                     gre_name gre `elemNameSet` used_names]
663
664         -- Collect the defined names from the in-scope environment
665         -- Look for the qualified ones only, else get duplicates
666     defined_names :: [GlobalRdrElt]
667     defined_names = foldRdrEnv add [] (tcg_rdr_env gbl_env)
668     add rdr_name ns acc | isQual rdr_name = ns ++ acc
669                         | otherwise       = acc
670
671     defined_and_used, defined_but_not_used :: [GlobalRdrElt]
672     (defined_and_used, defined_but_not_used) = partition used defined_names
673     used gre = gre_name gre `elemNameSet` really_used_names
674     
675     -- Filter out the ones that are 
676     --  (a) defined in this module, and
677     --  (b) not defined by a 'deriving' clause 
678     -- The latter have an Internal Name, so we can filter them out easily
679     bad_locals :: [GlobalRdrElt]
680     bad_locals = filter is_bad defined_but_not_used
681
682     is_bad :: GlobalRdrElt -> Bool
683     is_bad gre = isLocalGRE gre && isExternalName (gre_name gre)
684     
685     bad_imports :: [GlobalRdrElt]
686     bad_imports = filter bad_imp defined_but_not_used
687     bad_imp (GRE {gre_prov = NonLocalDef (UserImport mod _ True)}) = not (module_unused mod)
688     bad_imp other                                                  = False
689     
690     -- To figure out the minimal set of imports, start with the things
691     -- that are in scope (i.e. in gbl_env).  Then just combine them
692     -- into a bunch of avails, so they are properly grouped
693     minimal_imports :: FiniteMap ModuleName AvailEnv
694     minimal_imports0 = emptyFM
695     minimal_imports1 = foldr add_name     minimal_imports0 defined_and_used
696     minimal_imports  = foldr add_inst_mod minimal_imports1 direct_import_mods
697         -- The last line makes sure that we retain all direct imports
698         -- even if we import nothing explicitly.
699         -- It's not necessarily redundant to import such modules. Consider 
700         --            module This
701         --              import M ()
702         --
703         -- The import M() is not *necessarily* redundant, even if
704         -- we suck in no instance decls from M (e.g. it contains 
705         -- no instance decls, or This contains no code).  It may be 
706         -- that we import M solely to ensure that M's orphan instance 
707         -- decls (or those in its imports) are visible to people who 
708         -- import This.  Sigh. 
709         -- There's really no good way to detect this, so the error message 
710         -- in RnEnv.warnUnusedModules is weakened instead
711     
712
713         -- We've carefully preserved the provenance so that we can
714         -- construct minimal imports that import the name by (one of)
715         -- the same route(s) as the programmer originally did.
716     add_name (GRE {gre_name = n, gre_parent = p,
717                    gre_prov = NonLocalDef (UserImport m _ _)}) acc 
718         = addToFM_C plusAvailEnv acc (moduleName m) 
719                     (unitAvailEnv (mk_avail n p))
720     add_name other acc 
721         = acc
722
723         -- n is the name of the thing, p is the name of its parent
724     mk_avail n p | n/=p                    = AvailTC p [p,n]
725                  | isTcOcc (nameOccName p) = AvailTC n [n]
726                  | otherwise               = Avail n
727     
728     add_inst_mod m acc 
729       | m `elemFM` acc = acc    -- We import something already
730       | otherwise      = addToFM acc m emptyAvailEnv
731         -- Add an empty collection of imports for a module
732         -- from which we have sucked only instance decls
733    
734     -- unused_imp_mods are the directly-imported modules 
735     -- that are not mentioned in minimal_imports1
736     -- [Note: not 'minimal_imports', because that includes direcly-imported
737     --        modules even if we use nothing from them; see notes above]
738     unused_imp_mods = [m | m <- direct_import_mods,
739                        not (maybeToBool (lookupFM minimal_imports1 m)),
740                        m /= pRELUDE_Name]
741     
742     module_unused :: Module -> Bool
743     module_unused mod = moduleName mod `elem` unused_imp_mods
744
745
746 -- ToDo: deal with original imports with 'qualified' and 'as M' clauses
747 printMinimalImports :: FiniteMap ModuleName AvailEnv    -- Minimal imports
748                     -> TcRn m ()
749 printMinimalImports imps
750  = ifOptM Opt_D_dump_minimal_imports $ do {
751
752    mod_ies  <-  mappM to_ies (fmToList imps) ;
753    this_mod <- getModule ;
754    rdr_env  <- getGlobalRdrEnv ;
755    ioToTcRn (do { h <- openFile (mkFilename this_mod) WriteMode ;
756                   printForUser h (unQualInScope rdr_env) 
757                                  (vcat (map ppr_mod_ie mod_ies)) })
758    }
759   where
760     mkFilename this_mod = moduleNameUserString (moduleName this_mod) ++ ".imports"
761     ppr_mod_ie (mod_name, ies) 
762         | mod_name == pRELUDE_Name 
763         = empty
764         | null ies      -- Nothing except instances comes from here
765         = ptext SLIT("import") <+> ppr mod_name <> ptext SLIT("()    -- Instances only")
766         | otherwise
767         = ptext SLIT("import") <+> ppr mod_name <> 
768                     parens (fsep (punctuate comma (map ppr ies)))
769
770     to_ies (mod, avail_env) = mappM to_ie (availEnvElts avail_env)      `thenM` \ ies ->
771                               returnM (mod, ies)
772
773     to_ie :: AvailInfo -> TcRn m (IE Name)
774         -- The main trick here is that if we're importing all the constructors
775         -- we want to say "T(..)", but if we're importing only a subset we want
776         -- to say "T(A,B,C)".  So we have to find out what the module exports.
777     to_ie (Avail n)       = returnM (IEVar n)
778     to_ie (AvailTC n [m]) = ASSERT( n==m ) 
779                             returnM (IEThingAbs n)
780     to_ie (AvailTC n ns)  
781         = loadInterface (text "Compute minimal imports from" <+> ppr n_mod) 
782                         n_mod ImportBySystem                            `thenM` \ iface ->
783           case [xs | (m,as) <- mi_exports iface,
784                      m == n_mod,
785                      AvailTC x xs <- as, 
786                      x == n] of
787               [xs] | all (`elem` ns) xs -> returnM (IEThingAll n)
788                    | otherwise          -> returnM (IEThingWith n (filter (/= n) ns))
789               other                     -> pprTrace "to_ie" (ppr n <+> ppr (nameModule n) <+> ppr other) $
790                                            returnM (IEVar n)
791         where
792           n_mod = moduleName (nameModule n)
793 \end{code}
794
795
796 %************************************************************************
797 %*                                                                      *
798 \subsection{Errors}
799 %*                                                                      *
800 %************************************************************************
801
802 \begin{code}
803 badImportItemErr mod from ie
804   = sep [ptext SLIT("Module"), quotes (ppr mod), source_import,
805          ptext SLIT("does not export"), quotes (ppr ie)]
806   where
807     source_import = case from of
808                       True  -> ptext SLIT("(hi-boot interface)")
809                       other -> empty
810
811 dodgyImportWarn mod item = dodgyMsg (ptext SLIT("import")) item
812 dodgyExportWarn     item = dodgyMsg (ptext SLIT("export")) item
813
814 dodgyMsg kind item@(IEThingAll tc)
815   = sep [ ptext SLIT("The") <+> kind <+> ptext SLIT("item") <+> quotes (ppr item),
816           ptext SLIT("suggests that") <+> quotes (ppr tc) <+> ptext SLIT("has constructor or class methods"),
817           ptext SLIT("but it has none; it is a type synonym or abstract type or class") ]
818           
819 modExportErr mod
820   = hsep [ ptext SLIT("Unknown module in export list: module"), quotes (ppr mod)]
821
822 exportItemErr export_item
823   = sep [ ptext SLIT("The export item") <+> quotes (ppr export_item),
824           ptext SLIT("attempts to export constructors or class methods that are not visible here") ]
825
826 exportClashErr occ_name ie1 ie2
827   = hsep [ptext SLIT("The export items"), quotes (ppr ie1)
828          ,ptext SLIT("and"), quotes (ppr ie2)
829          ,ptext SLIT("create conflicting exports for"), quotes (ppr occ_name)]
830
831 dupDeclErr (n:ns)
832   = vcat [ptext SLIT("Multiple declarations of") <+> quotes (ppr n),
833           nest 4 (vcat (map ppr sorted_locs))]
834   where
835     sorted_locs = sortLt occ'ed_before (map nameSrcLoc (n:ns))
836     occ'ed_before a b = LT == compare a b
837
838 dupExportWarn occ_name ie1 ie2
839   = hsep [quotes (ppr occ_name), 
840           ptext SLIT("is exported by"), quotes (ppr ie1),
841           ptext SLIT("and"),            quotes (ppr ie2)]
842
843 dupModuleExport mod
844   = hsep [ptext SLIT("Duplicate"),
845           quotes (ptext SLIT("Module") <+> ppr mod), 
846           ptext SLIT("in export list")]
847
848 moduleDeprec mod txt
849   = sep [ ptext SLIT("Module") <+> quotes (ppr mod) <+> ptext SLIT("is deprecated:"), 
850           nest 4 (ppr txt) ]      
851 \end{code}