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