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