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