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