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