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