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