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