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