[project @ 2000-10-25 15:57:33 by simonpj]
[ghc-hetmet.git] / ghc / compiler / rename / RnNames.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[RnNames]{Extracting imported and top-level names in scope}
5
6 \begin{code}
7 module RnNames (
8         getGlobalNames
9     ) where
10
11 #include "HsVersions.h"
12
13 import CmdLineOpts      ( DynFlag(..), opt_NoImplicitPrelude )
14
15 import HsSyn            ( HsModule(..), HsDecl(..), IE(..), ieName, ImportDecl(..),
16                           ForeignDecl(..), ForKind(..), isDynamicExtName,
17                           collectTopBinders
18                         )
19 import RdrHsSyn         ( RdrNameIE, RdrNameImportDecl,
20                           RdrNameHsModule, RdrNameHsDecl
21                         )
22 import RnIfaces         ( getInterfaceExports, recordLocalSlurps )
23 import RnHiFiles        ( getTyClDeclBinders )
24 import RnEnv
25 import RnMonad
26
27 import FiniteMap
28 import PrelNames        ( pRELUDE_Name, mAIN_Name, main_RDR )
29 import UniqFM           ( lookupUFM )
30 import Bag              ( bagToList )
31 import Module           ( ModuleName, mkModuleInThisPackage, WhereFrom(..) )
32 import NameSet
33 import Name             ( Name, nameSrcLoc,
34                           setLocalNameSort, nameOccName,  nameEnvElts )
35 import HscTypes         ( Provenance(..), ImportReason(..), GlobalRdrEnv,
36                           GenAvailInfo(..), AvailInfo, Avails, AvailEnv )
37 import RdrName          ( RdrName, rdrNameOcc, setRdrNameOcc, mkRdrQual, mkRdrUnqual, isUnqual )
38 import OccName          ( setOccNameSpace, dataName )
39 import NameSet          ( elemNameSet, emptyNameSet )
40 import SrcLoc           ( SrcLoc )
41 import Outputable
42 import Maybes           ( maybeToBool, catMaybes, mapMaybe )
43 import UniqFM           ( emptyUFM, listToUFM )
44 import ListSetOps       ( removeDups )
45 import Util             ( sortLt )
46 import List             ( partition )
47 \end{code}
48
49
50
51 %************************************************************************
52 %*                                                                      *
53 \subsection{Get global names}
54 %*                                                                      *
55 %************************************************************************
56
57 \begin{code}
58 getGlobalNames :: RdrNameHsModule
59                -> RnMG (Maybe (GlobalRdrEnv,    -- Maps all in-scope things
60                                GlobalRdrEnv,    -- Maps just *local* things
61                                Avails,          -- The exported stuff
62                                AvailEnv         -- Maps a name to its parent AvailInfo
63                                                 -- Just for in-scope things only
64                                ))
65                         -- Nothing => no need to recompile
66
67 getGlobalNames (HsModule this_mod _ exports imports decls _ mod_loc)
68   =     -- These two fix-loops are to get the right
69         -- provenance information into a Name
70     fixRn ( \ ~(Just (rec_gbl_env, _, rec_export_avails, _)) ->
71
72         let
73            rec_unqual_fn :: Name -> Bool        -- Is this chap in scope unqualified?
74            rec_unqual_fn = unQualInScope rec_gbl_env
75
76            rec_exp_fn :: Name -> Bool
77            rec_exp_fn = mk_export_fn (availsToNameSet rec_export_avails)
78         in
79
80                 -- PROCESS LOCAL DECLS
81                 -- Do these *first* so that the correct provenance gets
82                 -- into the global name cache.
83         importsFromLocalDecls this_mod rec_exp_fn decls
84         `thenRn` \ (local_gbl_env, local_mod_avails) ->
85
86                 -- PROCESS IMPORT DECLS
87                 -- Do the non {- SOURCE -} ones first, so that we get a helpful
88                 -- warning for {- SOURCE -} ones that are unnecessary
89         let
90           (source, ordinary) = partition is_source_import all_imports
91           is_source_import (ImportDecl _ ImportByUserSource _ _ _ _) = True
92           is_source_import other                                     = False
93         in
94         mapAndUnzipRn (importsFromImportDecl rec_unqual_fn) ordinary
95         `thenRn` \ (imp_gbl_envs1, imp_avails_s1) ->
96         mapAndUnzipRn (importsFromImportDecl rec_unqual_fn) source
97         `thenRn` \ (imp_gbl_envs2, imp_avails_s2) ->
98
99                 -- COMBINE RESULTS
100                 -- We put the local env second, so that a local provenance
101                 -- "wins", even if a module imports itself.
102         let
103             gbl_env :: GlobalRdrEnv
104             imp_gbl_env = foldr plusGlobalRdrEnv emptyRdrEnv (imp_gbl_envs2 ++ imp_gbl_envs1)
105             gbl_env     = imp_gbl_env `plusGlobalRdrEnv` local_gbl_env
106
107             all_avails :: ExportAvails
108             all_avails = foldr plusExportAvails local_mod_avails (imp_avails_s2 ++ imp_avails_s1)
109             (_, global_avail_env) = all_avails
110         in
111
112                 -- TRY FOR EARLY EXIT
113                 -- We can't go for an early exit before this because we have to check
114                 -- for name clashes.  Consider:
115                 --
116                 --      module A where          module B where
117                 --         import B                h = True
118                 --         f = h
119                 --
120                 -- Suppose I've compiled everything up, and then I add a
121                 -- new definition to module B, that defines "f".
122                 --
123                 -- Then I must detect the name clash in A before going for an early
124                 -- exit.  The early-exit code checks what's actually needed from B
125                 -- to compile A, and of course that doesn't include B.f.  That's
126                 -- why we wait till after the plusEnv stuff to do the early-exit.
127                 
128         -- Check For early exit
129         checkErrsRn                             `thenRn` \ no_errs_so_far ->
130         if not no_errs_so_far then
131                 -- Found errors already, so exit now
132                 returnRn Nothing
133         else
134         
135                 -- PROCESS EXPORT LISTS
136         exportsFromAvail this_mod exports all_avails gbl_env    `thenRn` \ export_avails ->
137         
138         
139                 -- ALL DONE
140         returnRn (Just (gbl_env, local_gbl_env, export_avails, global_avail_env))
141    )
142   where
143     all_imports = prel_imports ++ imports
144
145         -- NB: opt_NoImplicitPrelude is slightly different to import Prelude ();
146         -- because the former doesn't even look at Prelude.hi for instance declarations,
147         -- whereas the latter does.
148     prel_imports | this_mod == pRELUDE_Name ||
149                    explicit_prelude_import ||
150                    opt_NoImplicitPrelude
151                  = []
152
153                  | otherwise = [ImportDecl pRELUDE_Name
154                                            ImportByUser
155                                            False        {- Not qualified -}
156                                            Nothing      {- No "as" -}
157                                            Nothing      {- No import list -}
158                                            mod_loc]
159     
160     explicit_prelude_import
161       = not (null [ () | (ImportDecl mod _ _ _ _ _) <- imports, mod == pRELUDE_Name ])
162 \end{code}
163         
164 \begin{code}
165 importsFromImportDecl :: (Name -> Bool)         -- OK to omit qualifier
166                       -> RdrNameImportDecl
167                       -> RnMG (GlobalRdrEnv, 
168                                ExportAvails) 
169
170 importsFromImportDecl is_unqual (ImportDecl imp_mod_name from qual_only as_mod import_spec iloc)
171   = pushSrcLocRn iloc $
172     getInterfaceExports imp_mod_name from       `thenRn` \ (imp_mod, avails_by_module) ->
173
174     if null avails_by_module then
175         -- If there's an error in getInterfaceExports, (e.g. interface
176         -- file not found) we get lots of spurious errors from 'filterImports'
177         returnRn (emptyRdrEnv, mkEmptyExportAvails imp_mod_name)
178     else
179
180     let
181         avails :: Avails
182         avails = concat (map snd avails_by_module)
183     in
184     filterImports imp_mod_name import_spec avails       `thenRn` \ (filtered_avails, hides, explicits) ->
185
186     let
187         mk_provenance name = NonLocalDef (UserImport imp_mod iloc (name `elemNameSet` explicits)) 
188                                          (is_unqual name)
189     in
190
191     qualifyImports imp_mod_name
192                    (not qual_only)      -- Maybe want unqualified names
193                    as_mod hides
194                    mk_provenance
195                    filtered_avails
196 \end{code}
197
198
199 \begin{code}
200 importsFromLocalDecls mod_name rec_exp_fn decls
201   = mapRn (getLocalDeclBinders (newLocalName mod rec_exp_fn)) decls     `thenRn` \ avails_s ->
202
203     let
204         avails = concat avails_s
205
206         all_names :: [Name]     -- All the defns; no dups eliminated
207         all_names = [name | avail <- avails, name <- availNames avail]
208
209         dups :: [[Name]]
210         (_, dups) = removeDups compare all_names
211     in
212         -- Check for duplicate definitions
213     mapRn_ (addErrRn . dupDeclErr) dups         `thenRn_` 
214
215         -- Record that locally-defined things are available
216     recordLocalSlurps avails                    `thenRn_`
217
218         -- Build the environment
219     qualifyImports mod_name 
220                    True                 -- Want unqualified names
221                    Nothing              -- no 'as M'
222                    []                   -- Hide nothing
223                    (\n -> LocalDef)     -- Provenance is local
224                    avails
225   where
226     mod = mkModuleInThisPackage mod_name
227
228 ---------------------------
229 getLocalDeclBinders :: (RdrName -> SrcLoc -> RnMG Name)
230                     -> RdrNameHsDecl -> RnMG Avails
231 getLocalDeclBinders new_name (ValD binds)
232   = mapRn do_one (bagToList (collectTopBinders binds))
233   where
234     do_one (rdr_name, loc) = new_name rdr_name loc      `thenRn` \ name ->
235                              returnRn (Avail name)
236
237 getLocalDeclBinders new_name (TyClD tycl_decl)
238   = getTyClDeclBinders new_name tycl_decl       `thenRn` \ avail ->
239     returnRn [avail]
240
241 getLocalDeclBinders new_name (ForD (ForeignDecl nm kind _ ext_nm _ loc))
242   | binds_haskell_name kind
243   = new_name nm loc                 `thenRn` \ name ->
244     returnRn [Avail name]
245
246   | otherwise           -- a foreign export
247   = lookupOrigName nm `thenRn_` 
248     returnRn []
249   where
250     binds_haskell_name (FoImport _) = True
251     binds_haskell_name FoLabel      = True
252     binds_haskell_name FoExport     = isDynamicExtName ext_nm
253
254 getLocalDeclBinders new_name (FixD _)    = returnRn []
255 getLocalDeclBinders new_name (DeprecD _) = returnRn []
256 getLocalDeclBinders new_name (DefD _)    = returnRn []
257 getLocalDeclBinders new_name (InstD _)   = returnRn []
258 getLocalDeclBinders new_name (RuleD _)   = returnRn []
259
260
261 ---------------------------
262 newLocalName mod rec_exp_fn rdr_name loc 
263   = check_unqual rdr_name loc           `thenRn_`
264     newTopBinder mod rdr_name loc       `thenRn` \ name ->
265     returnRn (setLocalNameSort name (rec_exp_fn name))
266   where
267         -- There should never be a qualified name in a binding position (except in instance decls)
268         -- The parser doesn't check this because the same parser parses instance decls
269     check_unqual rdr_name loc
270         | isUnqual rdr_name = returnRn ()
271         | otherwise         = qualNameErr (text "the binding for" <+> quotes (ppr rdr_name)) 
272                                           (rdr_name,loc)
273 \end{code}
274
275
276 %************************************************************************
277 %*                                                                      *
278 \subsection{Filtering imports}
279 %*                                                                      *
280 %************************************************************************
281
282 @filterImports@ takes the @ExportEnv@ telling what the imported module makes
283 available, and filters it through the import spec (if any).
284
285 \begin{code}
286 filterImports :: ModuleName                     -- The module being imported
287               -> Maybe (Bool, [RdrNameIE])      -- Import spec; True => hiding
288               -> [AvailInfo]                    -- What's available
289               -> RnMG ([AvailInfo],             -- What's actually imported
290                        [AvailInfo],             -- What's to be hidden
291                                                 -- (the unqualified version, that is)
292                         -- (We need to return both the above sets, because
293                         --  the qualified version is never hidden; so we can't
294                         --  implement hiding by reducing what's imported.)
295                        NameSet)                 -- What was imported explicitly
296
297         -- Complains if import spec mentions things that the module doesn't export
298         -- Warns/informs if import spec contains duplicates.
299 filterImports mod Nothing imports
300   = returnRn (imports, [], emptyNameSet)
301
302 filterImports mod (Just (want_hiding, import_items)) total_avails
303   = flatMapRn get_item import_items             `thenRn` \ avails_w_explicits ->
304     let
305         (item_avails, explicits_s) = unzip avails_w_explicits
306         explicits                  = foldl addListToNameSet emptyNameSet explicits_s
307     in
308     if want_hiding 
309     then        
310         -- All imported; item_avails to be hidden
311         returnRn (total_avails, item_avails, emptyNameSet)
312     else
313         -- Just item_avails imported; nothing to be hidden
314         returnRn (item_avails, [], explicits)
315   where
316     import_fm :: FiniteMap OccName AvailInfo
317     import_fm = listToFM [ (nameOccName name, avail) 
318                          | avail <- total_avails,
319                            name  <- availNames avail]
320         -- Even though availNames returns data constructors too,
321         -- they won't make any difference because naked entities like T
322         -- in an import list map to TcOccs, not VarOccs.
323
324     bale_out item = addErrRn (badImportItemErr mod item)        `thenRn_`
325                     returnRn []
326
327     get_item item@(IEModuleContents _) = bale_out item
328
329     get_item item@(IEThingAll _)
330       = case check_item item of
331           Nothing                    -> bale_out item
332           Just avail@(AvailTC _ [n]) ->         -- This occurs when you import T(..), but
333                                                 -- only export T abstractly.  The single [n]
334                                                 -- in the AvailTC is the type or class itself
335                                         addWarnRn (dodgyImportWarn mod item)    `thenRn_`
336                                         returnRn [(avail, [availName avail])]
337           Just avail                 -> returnRn [(avail, [availName avail])]
338
339     get_item item@(IEThingAbs n)
340       | want_hiding     -- hiding( C ) 
341                         -- Here the 'C' can be a data constructor *or* a type/class
342       = case catMaybes [check_item item, check_item (IEThingAbs data_n)] of
343                 []     -> bale_out item
344                 avails -> returnRn [(a, []) | a <- avails]
345                                 -- The 'explicits' list is irrelevant when hiding
346       where
347         data_n = setRdrNameOcc n (setOccNameSpace (rdrNameOcc n) dataName)
348
349     get_item item
350       = case check_item item of
351           Nothing    -> bale_out item
352           Just avail -> returnRn [(avail, availNames avail)]
353
354     check_item item
355       | not (maybeToBool maybe_in_import_avails) ||
356         not (maybeToBool maybe_filtered_avail)
357       = Nothing
358
359       | otherwise    
360       = Just filtered_avail
361                 
362       where
363         wanted_occ             = rdrNameOcc (ieName item)
364         maybe_in_import_avails = lookupFM import_fm wanted_occ
365
366         Just avail             = maybe_in_import_avails
367         maybe_filtered_avail   = filterAvail item avail
368         Just filtered_avail    = maybe_filtered_avail
369 \end{code}
370
371
372
373 %************************************************************************
374 %*                                                                      *
375 \subsection{Qualifiying imports}
376 %*                                                                      *
377 %************************************************************************
378
379 @qualifyImports@ takes the @ExportEnv@ after filtering through the import spec
380 of an import decl, and deals with producing an @RnEnv@ with the 
381 right qualified names.  It also turns the @Names@ in the @ExportEnv@ into
382 fully fledged @Names@.
383
384 \begin{code}
385 qualifyImports :: ModuleName            -- Imported module
386                -> Bool                  -- True <=> want unqualified import
387                -> Maybe ModuleName      -- Optional "as M" part 
388                -> [AvailInfo]           -- What's to be hidden
389                -> (Name -> Provenance)
390                -> Avails                -- Whats imported and how
391                -> RnMG (GlobalRdrEnv, ExportAvails)
392
393 qualifyImports this_mod unqual_imp as_mod hides mk_provenance avails
394   = 
395         -- Make the name environment.  We're talking about a 
396         -- single module here, so there must be no name clashes.
397         -- In practice there only ever will be if it's the module
398         -- being compiled.
399     let
400         -- Add the things that are available
401         name_env1 = foldl add_avail emptyRdrEnv avails
402
403         -- Delete things that are hidden
404         name_env2 = foldl del_avail name_env1 hides
405
406         -- Create the export-availability info
407         export_avails = mkExportAvails qual_mod unqual_imp name_env2 avails
408     in
409     returnRn (name_env2, export_avails)
410
411   where
412     qual_mod = case as_mod of
413                   Nothing           -> this_mod
414                   Just another_name -> another_name
415
416     add_avail :: GlobalRdrEnv -> AvailInfo -> GlobalRdrEnv
417     add_avail env avail = foldl add_name env (availNames avail)
418
419     add_name env name
420         | unqual_imp = env2
421         | otherwise  = env1
422         where
423           env1 = addOneToGlobalRdrEnv env  (mkRdrQual qual_mod occ) (name,prov)
424           env2 = addOneToGlobalRdrEnv env1 (mkRdrUnqual occ)        (name,prov)
425           occ  = nameOccName name
426           prov = mk_provenance name
427
428     del_avail env avail = foldl delOneFromGlobalRdrEnv env rdr_names
429                         where
430                           rdr_names = map (mkRdrUnqual . nameOccName) (availNames avail)
431
432
433 mkEmptyExportAvails :: ModuleName -> ExportAvails
434 mkEmptyExportAvails mod_name = (unitFM mod_name [], emptyUFM)
435
436 mkExportAvails :: ModuleName -> Bool -> GlobalRdrEnv -> [AvailInfo] -> ExportAvails
437 mkExportAvails mod_name unqual_imp name_env avails
438   = (mod_avail_env, entity_avail_env)
439   where
440     mod_avail_env = unitFM mod_name unqual_avails 
441
442         -- unqual_avails is the Avails that are visible in *unqualfied* form
443         -- (1.4 Report, Section 5.1.1)
444         -- For example, in 
445         --      import T hiding( f )
446         -- we delete f from avails
447
448     unqual_avails | not unqual_imp = [] -- Short cut when no unqualified imports
449                   | otherwise      = mapMaybe prune avails
450
451     prune (Avail n) | unqual_in_scope n = Just (Avail n)
452     prune (Avail n) | otherwise         = Nothing
453     prune (AvailTC n ns) | null uqs     = Nothing
454                          | otherwise    = Just (AvailTC n uqs)
455                          where
456                            uqs = filter unqual_in_scope ns
457
458     unqual_in_scope n = unQualInScope name_env n
459
460     entity_avail_env = listToUFM [ (name,avail) | avail <- avails, 
461                                                   name  <- availNames avail]
462
463 plusExportAvails ::  ExportAvails ->  ExportAvails ->  ExportAvails
464 plusExportAvails (m1, e1) (m2, e2)
465   = (plusFM_C (++) m1 m2, plusAvailEnv e1 e2)
466         -- ToDo: wasteful: we do this once for each constructor!
467 \end{code}
468
469
470 %************************************************************************
471 %*                                                                      *
472 \subsection{Export list processing}
473 %*                                                                      *
474 %************************************************************************
475
476 Processing the export list.
477
478 You might think that we should record things that appear in the export list
479 as ``occurrences'' (using @addOccurrenceName@), but you'd be wrong.
480 We do check (here) that they are in scope,
481 but there is no need to slurp in their actual declaration
482 (which is what @addOccurrenceName@ forces).
483
484 Indeed, doing so would big trouble when
485 compiling @PrelBase@, because it re-exports @GHC@, which includes @takeMVar#@,
486 whose type includes @ConcBase.StateAndSynchVar#@, and so on...
487
488 \begin{code}
489 type ExportAccum        -- The type of the accumulating parameter of
490                         -- the main worker function in exportsFromAvail
491      = ([ModuleName],           -- 'module M's seen so far
492         ExportOccMap,           -- Tracks exported occurrence names
493         AvailEnv)               -- The accumulated exported stuff, kept in an env
494                                 --   so we can common-up related AvailInfos
495
496 type ExportOccMap = FiniteMap OccName (Name, RdrNameIE)
497         -- Tracks what a particular exported OccName
498         --   in an export list refers to, and which item
499         --   it came from.  It's illegal to export two distinct things
500         --   that have the same occurrence name
501
502
503 exportsFromAvail :: ModuleName
504                  -> Maybe [RdrNameIE]   -- Export spec
505                  -> ExportAvails
506                  -> GlobalRdrEnv 
507                  -> RnMG Avails
508         -- Complains if two distinct exports have same OccName
509         -- Warns about identical exports.
510         -- Complains about exports items not in scope
511 exportsFromAvail this_mod Nothing export_avails global_name_env
512   = exportsFromAvail this_mod true_exports export_avails global_name_env
513   where
514     true_exports = Just $ if this_mod == mAIN_Name
515                           then [IEVar main_RDR]
516                                -- export Main.main *only* unless otherwise specified,
517                           else [IEModuleContents this_mod]
518                                -- but for all other modules export everything.
519
520 exportsFromAvail this_mod (Just export_items) 
521                  (mod_avail_env, entity_avail_env)
522                  global_name_env
523   = doptRn Opt_WarnDuplicateExports             `thenRn` \ warn_dup_exports ->
524     foldlRn (exports_from_item warn_dup_exports)
525             ([], emptyFM, emptyAvailEnv) export_items
526                                                 `thenRn` \ (_, _, export_avail_map) ->
527     let
528         export_avails :: [AvailInfo]
529         export_avails   = nameEnvElts export_avail_map
530     in
531     returnRn export_avails
532
533   where
534     exports_from_item :: Bool -> ExportAccum -> RdrNameIE -> RnMG ExportAccum
535
536     exports_from_item warn_dups acc@(mods, occs, avails) ie@(IEModuleContents mod)
537         | mod `elem` mods       -- Duplicate export of M
538         = warnCheckRn warn_dups (dupModuleExport mod)   `thenRn_`
539           returnRn acc
540
541         | otherwise
542         = case lookupFM mod_avail_env mod of
543                 Nothing         -> failWithRn acc (modExportErr mod)
544                 Just mod_avails -> foldlRn (check_occs ie) occs mod_avails
545                                    `thenRn` \ occs' ->
546                                    let
547                                         avails' = foldl addAvail avails mod_avails
548                                    in
549                                    returnRn (mod:mods, occs', avails')
550
551     exports_from_item warn_dups acc@(mods, occs, avails) ie
552         | not (maybeToBool maybe_in_scope) 
553         = failWithRn acc (unknownNameErr (ieName ie))
554
555         | not (null dup_names)
556         = addNameClashErrRn rdr_name ((name,prov):dup_names)    `thenRn_`
557           returnRn acc
558
559 #ifdef DEBUG
560         -- I can't see why this should ever happen; if the thing is in scope
561         -- at all it ought to have some availability
562         | not (maybeToBool maybe_avail)
563         = pprTrace "exportsFromAvail: curious Nothing:" (ppr name)
564           returnRn acc
565 #endif
566
567         | not enough_avail
568         = failWithRn acc (exportItemErr ie)
569
570         | otherwise     -- Phew!  It's OK!  Now to check the occurrence stuff!
571
572
573         = warnCheckRn (ok_item ie avail) (dodgyExportWarn ie)   `thenRn_`
574           check_occs ie occs export_avail                       `thenRn` \ occs' ->
575           returnRn (mods, occs', addAvail avails export_avail)
576
577        where
578           rdr_name        = ieName ie
579           maybe_in_scope  = lookupFM global_name_env rdr_name
580           Just ((name,prov):dup_names) = maybe_in_scope
581           maybe_avail        = lookupUFM entity_avail_env name
582           Just avail         = maybe_avail
583           maybe_export_avail = filterAvail ie avail
584           enough_avail       = maybeToBool maybe_export_avail
585           Just export_avail  = maybe_export_avail
586
587     ok_item (IEThingAll _) (AvailTC _ [n]) = False
588                 -- This occurs when you import T(..), but
589                 -- only export T abstractly.  The single [n]
590                 -- in the AvailTC is the type or class itself
591     ok_item _ _ = True
592
593 check_occs :: RdrNameIE -> ExportOccMap -> AvailInfo -> RnMG ExportOccMap
594 check_occs ie occs avail 
595   = doptRn Opt_WarnDuplicateExports     `thenRn` \ warn_dup_exports ->
596     foldlRn (check warn_dup_exports) occs (availNames avail)
597   where
598     check warn_dup occs name
599       = case lookupFM occs name_occ of
600           Nothing           -> returnRn (addToFM occs name_occ (name, ie))
601           Just (name', ie') 
602             | name == name' ->  -- Duplicate export
603                                 warnCheckRn warn_dup
604                                             (dupExportWarn name_occ ie ie')
605                                 `thenRn_` returnRn occs
606
607             | otherwise     ->  -- Same occ name but different names: an error
608                                 failWithRn occs (exportClashErr name_occ ie ie')
609       where
610         name_occ = nameOccName name
611         
612 mk_export_fn :: NameSet -> (Name -> Bool)       -- True => exported
613 mk_export_fn exported_names = \name ->  name `elemNameSet` exported_names
614 \end{code}
615
616 %************************************************************************
617 %*                                                                      *
618 \subsection{Errors}
619 %*                                                                      *
620 %************************************************************************
621
622 \begin{code}
623 badImportItemErr mod ie
624   = sep [ptext SLIT("Module"), quotes (ppr mod), 
625          ptext SLIT("does not export"), quotes (ppr ie)]
626
627 dodgyImportWarn mod item = dodgyMsg (ptext SLIT("import")) item
628 dodgyExportWarn     item = dodgyMsg (ptext SLIT("export")) item
629
630 dodgyMsg kind item@(IEThingAll tc)
631   = sep [ ptext SLIT("The") <+> kind <+> ptext SLIT("item") <+> quotes (ppr item),
632           ptext SLIT("suggests that") <+> quotes (ppr tc) <+> ptext SLIT("has constructor or class methods"),
633           ptext SLIT("but it has none; it is a type synonym or abstract type or class") ]
634           
635 modExportErr mod
636   = hsep [ ptext SLIT("Unknown module in export list: module"), quotes (ppr mod)]
637
638 exportItemErr export_item
639   = sep [ ptext SLIT("The export item") <+> quotes (ppr export_item),
640           ptext SLIT("attempts to export constructors or class methods that are not visible here") ]
641
642 exportClashErr occ_name ie1 ie2
643   = hsep [ptext SLIT("The export items"), quotes (ppr ie1)
644          ,ptext SLIT("and"), quotes (ppr ie2)
645          ,ptext SLIT("create conflicting exports for"), quotes (ppr occ_name)]
646
647 dupDeclErr (n:ns)
648   = vcat [ptext SLIT("Multiple declarations of") <+> quotes (ppr n),
649           nest 4 (vcat (map ppr sorted_locs))]
650   where
651     sorted_locs = sortLt occ'ed_before (map nameSrcLoc (n:ns))
652     occ'ed_before a b = LT == compare a b
653
654 dupExportWarn occ_name ie1 ie2
655   = hsep [quotes (ppr occ_name), 
656           ptext SLIT("is exported by"), quotes (ppr ie1),
657           ptext SLIT("and"),            quotes (ppr ie2)]
658
659 dupModuleExport mod
660   = hsep [ptext SLIT("Duplicate"),
661           quotes (ptext SLIT("Module") <+> ppr mod), 
662           ptext SLIT("in export list")]
663 \end{code}