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