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