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