[project @ 2000-10-24 15:55:35 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) ->
173
174     if null avails 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     filterImports imp_mod_name import_spec avails   `thenRn` \ (filtered_avails, hides, explicits) ->
181
182     let
183         mk_provenance name = NonLocalDef (UserImport imp_mod iloc (name `elemNameSet` explicits)) 
184                                          (is_unqual name)
185     in
186
187     qualifyImports imp_mod_name
188                    (not qual_only)      -- Maybe want unqualified names
189                    as_mod hides
190                    mk_provenance
191                    filtered_avails
192 \end{code}
193
194
195 \begin{code}
196 importsFromLocalDecls mod_name rec_exp_fn decls
197   = mapRn (getLocalDeclBinders (newLocalName mod rec_exp_fn)) decls     `thenRn` \ avails_s ->
198
199     let
200         avails = concat avails_s
201
202         all_names :: [Name]     -- All the defns; no dups eliminated
203         all_names = [name | avail <- avails, name <- availNames avail]
204
205         dups :: [[Name]]
206         (_, dups) = removeDups compare all_names
207     in
208         -- Check for duplicate definitions
209     mapRn_ (addErrRn . dupDeclErr) dups         `thenRn_` 
210
211         -- Record that locally-defined things are available
212     recordLocalSlurps avails                    `thenRn_`
213
214         -- Build the environment
215     qualifyImports mod_name 
216                    True                 -- Want unqualified names
217                    Nothing              -- no 'as M'
218                    []                   -- Hide nothing
219                    (\n -> LocalDef)     -- Provenance is local
220                    avails
221   where
222     mod = mkModuleInThisPackage mod_name
223
224 ---------------------------
225 getLocalDeclBinders :: (RdrName -> SrcLoc -> RnMG Name)
226                     -> RdrNameHsDecl -> RnMG Avails
227 getLocalDeclBinders new_name (ValD binds)
228   = mapRn do_one (bagToList (collectTopBinders binds))
229   where
230     do_one (rdr_name, loc) = new_name rdr_name loc      `thenRn` \ name ->
231                              returnRn (Avail name)
232
233 getLocalDeclBinders new_name (TyClD tycl_decl)
234   = getTyClDeclBinders new_name tycl_decl       `thenRn` \ avail ->
235     returnRn [avail]
236
237 getLocalDeclBinders new_name (ForD (ForeignDecl nm kind _ ext_nm _ loc))
238   | binds_haskell_name kind
239   = new_name nm loc                 `thenRn` \ name ->
240     returnRn [Avail name]
241
242   | otherwise           -- a foreign export
243   = lookupOrigName nm `thenRn_` 
244     returnRn []
245   where
246     binds_haskell_name (FoImport _) = True
247     binds_haskell_name FoLabel      = True
248     binds_haskell_name FoExport     = isDynamicExtName ext_nm
249
250 getLocalDeclBinders new_name (FixD _)    = returnRn []
251 getLocalDeclBinders new_name (DeprecD _) = returnRn []
252 getLocalDeclBinders new_name (DefD _)    = returnRn []
253 getLocalDeclBinders new_name (InstD _)   = returnRn []
254 getLocalDeclBinders new_name (RuleD _)   = returnRn []
255
256
257 ---------------------------
258 newLocalName mod rec_exp_fn rdr_name loc 
259   = check_unqual rdr_name loc           `thenRn_`
260     newTopBinder mod rdr_name loc       `thenRn` \ name ->
261     returnRn (setLocalNameSort name (rec_exp_fn name))
262   where
263         -- There should never be a qualified name in a binding position (except in instance decls)
264         -- The parser doesn't check this because the same parser parses instance decls
265     check_unqual rdr_name loc
266         | isUnqual rdr_name = returnRn ()
267         | otherwise         = qualNameErr (text "the binding for" <+> quotes (ppr rdr_name)) 
268                                           (rdr_name,loc)
269 \end{code}
270
271
272 %************************************************************************
273 %*                                                                      *
274 \subsection{Filtering imports}
275 %*                                                                      *
276 %************************************************************************
277
278 @filterImports@ takes the @ExportEnv@ telling what the imported module makes
279 available, and filters it through the import spec (if any).
280
281 \begin{code}
282 filterImports :: ModuleName                     -- The module being imported
283               -> Maybe (Bool, [RdrNameIE])      -- Import spec; True => hiding
284               -> [AvailInfo]                    -- What's available
285               -> RnMG ([AvailInfo],             -- What's actually imported
286                        [AvailInfo],             -- What's to be hidden
287                                                 -- (the unqualified version, that is)
288                         -- (We need to return both the above sets, because
289                         --  the qualified version is never hidden; so we can't
290                         --  implement hiding by reducing what's imported.)
291                        NameSet)                 -- What was imported explicitly
292
293         -- Complains if import spec mentions things that the module doesn't export
294         -- Warns/informs if import spec contains duplicates.
295 filterImports mod Nothing imports
296   = returnRn (imports, [], emptyNameSet)
297
298 filterImports mod (Just (want_hiding, import_items)) avails
299   = flatMapRn get_item import_items             `thenRn` \ avails_w_explicits ->
300     let
301         (item_avails, explicits_s) = unzip avails_w_explicits
302         explicits                  = foldl addListToNameSet emptyNameSet explicits_s
303     in
304     if want_hiding 
305     then        
306         -- All imported; item_avails to be hidden
307         returnRn (avails, item_avails, emptyNameSet)
308     else
309         -- Just item_avails imported; nothing to be hidden
310         returnRn (item_avails, [], explicits)
311   where
312     import_fm :: FiniteMap OccName AvailInfo
313     import_fm = listToFM [ (nameOccName name, avail) 
314                          | avail <- avails,
315                            name  <- availNames avail]
316         -- Even though availNames returns data constructors too,
317         -- they won't make any difference because naked entities like T
318         -- in an import list map to TcOccs, not VarOccs.
319
320     bale_out item = addErrRn (badImportItemErr mod item)        `thenRn_`
321                     returnRn []
322
323     get_item item@(IEModuleContents _) = bale_out item
324
325     get_item item@(IEThingAll _)
326       = case check_item item of
327           Nothing                    -> bale_out item
328           Just avail@(AvailTC _ [n]) ->         -- This occurs when you import T(..), but
329                                                 -- only export T abstractly.  The single [n]
330                                                 -- in the AvailTC is the type or class itself
331                                         addWarnRn (dodgyImportWarn mod item)    `thenRn_`
332                                         returnRn [(avail, [availName avail])]
333           Just avail                 -> returnRn [(avail, [availName avail])]
334
335     get_item item@(IEThingAbs n)
336       | want_hiding     -- hiding( C ) 
337                         -- Here the 'C' can be a data constructor *or* a type/class
338       = case catMaybes [check_item item, check_item (IEThingAbs data_n)] of
339                 []     -> bale_out item
340                 avails -> returnRn [(a, []) | a <- avails]
341                                 -- The 'explicits' list is irrelevant when hiding
342       where
343         data_n = setRdrNameOcc n (setOccNameSpace (rdrNameOcc n) dataName)
344
345     get_item item
346       = case check_item item of
347           Nothing    -> bale_out item
348           Just avail -> returnRn [(avail, availNames avail)]
349
350     check_item item
351       | not (maybeToBool maybe_in_import_avails) ||
352         not (maybeToBool maybe_filtered_avail)
353       = Nothing
354
355       | otherwise    
356       = Just filtered_avail
357                 
358       where
359         wanted_occ             = rdrNameOcc (ieName item)
360         maybe_in_import_avails = lookupFM import_fm wanted_occ
361
362         Just avail             = maybe_in_import_avails
363         maybe_filtered_avail   = filterAvail item avail
364         Just filtered_avail    = maybe_filtered_avail
365 \end{code}
366
367
368
369 %************************************************************************
370 %*                                                                      *
371 \subsection{Qualifiying imports}
372 %*                                                                      *
373 %************************************************************************
374
375 @qualifyImports@ takes the @ExportEnv@ after filtering through the import spec
376 of an import decl, and deals with producing an @RnEnv@ with the 
377 right qualified names.  It also turns the @Names@ in the @ExportEnv@ into
378 fully fledged @Names@.
379
380 \begin{code}
381 qualifyImports :: ModuleName            -- Imported module
382                -> Bool                  -- True <=> want unqualified import
383                -> Maybe ModuleName      -- Optional "as M" part 
384                -> [AvailInfo]           -- What's to be hidden
385                -> (Name -> Provenance)
386                -> Avails                -- Whats imported and how
387                -> RnMG (GlobalRdrEnv, ExportAvails)
388
389 qualifyImports this_mod unqual_imp as_mod hides mk_provenance avails
390   = 
391         -- Make the name environment.  We're talking about a 
392         -- single module here, so there must be no name clashes.
393         -- In practice there only ever will be if it's the module
394         -- being compiled.
395     let
396         -- Add the things that are available
397         name_env1 = foldl add_avail emptyRdrEnv avails
398
399         -- Delete things that are hidden
400         name_env2 = foldl del_avail name_env1 hides
401
402         -- Create the export-availability info
403         export_avails = mkExportAvails qual_mod unqual_imp name_env2 avails
404     in
405     returnRn (name_env2, export_avails)
406
407   where
408     qual_mod = case as_mod of
409                   Nothing           -> this_mod
410                   Just another_name -> another_name
411
412     add_avail :: GlobalRdrEnv -> AvailInfo -> GlobalRdrEnv
413     add_avail env avail = foldl add_name env (availNames avail)
414
415     add_name env name
416         | unqual_imp = env2
417         | otherwise  = env1
418         where
419           env1 = addOneToGlobalRdrEnv env  (mkRdrQual qual_mod occ) (name,prov)
420           env2 = addOneToGlobalRdrEnv env1 (mkRdrUnqual occ)        (name,prov)
421           occ  = nameOccName name
422           prov = mk_provenance name
423
424     del_avail env avail = foldl delOneFromGlobalRdrEnv env rdr_names
425                         where
426                           rdr_names = map (mkRdrUnqual . nameOccName) (availNames avail)
427
428
429 mkEmptyExportAvails :: ModuleName -> ExportAvails
430 mkEmptyExportAvails mod_name = (unitFM mod_name [], emptyUFM)
431
432 mkExportAvails :: ModuleName -> Bool -> GlobalRdrEnv -> [AvailInfo] -> ExportAvails
433 mkExportAvails mod_name unqual_imp name_env avails
434   = (mod_avail_env, entity_avail_env)
435   where
436     mod_avail_env = unitFM mod_name unqual_avails 
437
438         -- unqual_avails is the Avails that are visible in *unqualfied* form
439         -- (1.4 Report, Section 5.1.1)
440         -- For example, in 
441         --      import T hiding( f )
442         -- we delete f from avails
443
444     unqual_avails | not unqual_imp = [] -- Short cut when no unqualified imports
445                   | otherwise      = mapMaybe prune avails
446
447     prune (Avail n) | unqual_in_scope n = Just (Avail n)
448     prune (Avail n) | otherwise         = Nothing
449     prune (AvailTC n ns) | null uqs     = Nothing
450                          | otherwise    = Just (AvailTC n uqs)
451                          where
452                            uqs = filter unqual_in_scope ns
453
454     unqual_in_scope n = unQualInScope name_env n
455
456     entity_avail_env = listToUFM [ (name,avail) | avail <- avails, 
457                                                   name  <- availNames avail]
458
459 plusExportAvails ::  ExportAvails ->  ExportAvails ->  ExportAvails
460 plusExportAvails (m1, e1) (m2, e2)
461   = (plusFM_C (++) m1 m2, plusAvailEnv e1 e2)
462         -- ToDo: wasteful: we do this once for each constructor!
463 \end{code}
464
465
466 %************************************************************************
467 %*                                                                      *
468 \subsection{Export list processing}
469 %*                                                                      *
470 %************************************************************************
471
472 Processing the export list.
473
474 You might think that we should record things that appear in the export list
475 as ``occurrences'' (using @addOccurrenceName@), but you'd be wrong.
476 We do check (here) that they are in scope,
477 but there is no need to slurp in their actual declaration
478 (which is what @addOccurrenceName@ forces).
479
480 Indeed, doing so would big trouble when
481 compiling @PrelBase@, because it re-exports @GHC@, which includes @takeMVar#@,
482 whose type includes @ConcBase.StateAndSynchVar#@, and so on...
483
484 \begin{code}
485 type ExportAccum        -- The type of the accumulating parameter of
486                         -- the main worker function in exportsFromAvail
487      = ([ModuleName],           -- 'module M's seen so far
488         ExportOccMap,           -- Tracks exported occurrence names
489         AvailEnv)               -- The accumulated exported stuff, kept in an env
490                                 --   so we can common-up related AvailInfos
491
492 type ExportOccMap = FiniteMap OccName (Name, RdrNameIE)
493         -- Tracks what a particular exported OccName
494         --   in an export list refers to, and which item
495         --   it came from.  It's illegal to export two distinct things
496         --   that have the same occurrence name
497
498
499 exportsFromAvail :: ModuleName
500                  -> Maybe [RdrNameIE]   -- Export spec
501                  -> ExportAvails
502                  -> GlobalRdrEnv 
503                  -> RnMG Avails
504         -- Complains if two distinct exports have same OccName
505         -- Warns about identical exports.
506         -- Complains about exports items not in scope
507 exportsFromAvail this_mod Nothing export_avails global_name_env
508   = exportsFromAvail this_mod true_exports export_avails global_name_env
509   where
510     true_exports = Just $ if this_mod == mAIN_Name
511                           then [IEVar main_RDR]
512                                -- export Main.main *only* unless otherwise specified,
513                           else [IEModuleContents this_mod]
514                                -- but for all other modules export everything.
515
516 exportsFromAvail this_mod (Just export_items) 
517                  (mod_avail_env, entity_avail_env)
518                  global_name_env
519   = doptRn Opt_WarnDuplicateExports             `thenRn` \ warn_dup_exports ->
520     foldlRn (exports_from_item warn_dup_exports)
521             ([], emptyFM, emptyAvailEnv) export_items
522                                                 `thenRn` \ (_, _, export_avail_map) ->
523     let
524         export_avails :: [AvailInfo]
525         export_avails   = nameEnvElts export_avail_map
526     in
527     returnRn export_avails
528
529   where
530     exports_from_item :: Bool -> ExportAccum -> RdrNameIE -> RnMG ExportAccum
531
532     exports_from_item warn_dups acc@(mods, occs, avails) ie@(IEModuleContents mod)
533         | mod `elem` mods       -- Duplicate export of M
534         = warnCheckRn warn_dups (dupModuleExport mod)   `thenRn_`
535           returnRn acc
536
537         | otherwise
538         = case lookupFM mod_avail_env mod of
539                 Nothing         -> failWithRn acc (modExportErr mod)
540                 Just mod_avails -> foldlRn (check_occs ie) occs mod_avails
541                                    `thenRn` \ occs' ->
542                                    let
543                                         avails' = foldl addAvail avails mod_avails
544                                    in
545                                    returnRn (mod:mods, occs', avails')
546
547     exports_from_item warn_dups acc@(mods, occs, avails) ie
548         | not (maybeToBool maybe_in_scope) 
549         = failWithRn acc (unknownNameErr (ieName ie))
550
551         | not (null dup_names)
552         = addNameClashErrRn rdr_name ((name,prov):dup_names)    `thenRn_`
553           returnRn acc
554
555 #ifdef DEBUG
556         -- I can't see why this should ever happen; if the thing is in scope
557         -- at all it ought to have some availability
558         | not (maybeToBool maybe_avail)
559         = pprTrace "exportsFromAvail: curious Nothing:" (ppr name)
560           returnRn acc
561 #endif
562
563         | not enough_avail
564         = failWithRn acc (exportItemErr ie)
565
566         | otherwise     -- Phew!  It's OK!  Now to check the occurrence stuff!
567
568
569         = warnCheckRn (ok_item ie avail) (dodgyExportWarn ie)   `thenRn_`
570           check_occs ie occs export_avail                       `thenRn` \ occs' ->
571           returnRn (mods, occs', addAvail avails export_avail)
572
573        where
574           rdr_name        = ieName ie
575           maybe_in_scope  = lookupFM global_name_env rdr_name
576           Just ((name,prov):dup_names) = maybe_in_scope
577           maybe_avail        = lookupUFM entity_avail_env name
578           Just avail         = maybe_avail
579           maybe_export_avail = filterAvail ie avail
580           enough_avail       = maybeToBool maybe_export_avail
581           Just export_avail  = maybe_export_avail
582
583     ok_item (IEThingAll _) (AvailTC _ [n]) = False
584                 -- This occurs when you import T(..), but
585                 -- only export T abstractly.  The single [n]
586                 -- in the AvailTC is the type or class itself
587     ok_item _ _ = True
588
589 check_occs :: RdrNameIE -> ExportOccMap -> AvailInfo -> RnMG ExportOccMap
590 check_occs ie occs avail 
591   = doptRn Opt_WarnDuplicateExports     `thenRn` \ warn_dup_exports ->
592     foldlRn (check warn_dup_exports) occs (availNames avail)
593   where
594     check warn_dup occs name
595       = case lookupFM occs name_occ of
596           Nothing           -> returnRn (addToFM occs name_occ (name, ie))
597           Just (name', ie') 
598             | name == name' ->  -- Duplicate export
599                                 warnCheckRn warn_dup
600                                             (dupExportWarn name_occ ie ie')
601                                 `thenRn_` returnRn occs
602
603             | otherwise     ->  -- Same occ name but different names: an error
604                                 failWithRn occs (exportClashErr name_occ ie ie')
605       where
606         name_occ = nameOccName name
607         
608 mk_export_fn :: NameSet -> (Name -> Bool)       -- True => exported
609 mk_export_fn exported_names = \name ->  name `elemNameSet` exported_names
610 \end{code}
611
612 %************************************************************************
613 %*                                                                      *
614 \subsection{Errors}
615 %*                                                                      *
616 %************************************************************************
617
618 \begin{code}
619 badImportItemErr mod ie
620   = sep [ptext SLIT("Module"), quotes (ppr mod), 
621          ptext SLIT("does not export"), quotes (ppr ie)]
622
623 dodgyImportWarn mod item = dodgyMsg (ptext SLIT("import")) item
624 dodgyExportWarn     item = dodgyMsg (ptext SLIT("export")) item
625
626 dodgyMsg kind item@(IEThingAll tc)
627   = sep [ ptext SLIT("The") <+> kind <+> ptext SLIT("item") <+> quotes (ppr item),
628           ptext SLIT("suggests that") <+> quotes (ppr tc) <+> ptext SLIT("has constructor or class methods"),
629           ptext SLIT("but it has none; it is a type synonym or abstract type or class") ]
630           
631 modExportErr mod
632   = hsep [ ptext SLIT("Unknown module in export list: module"), quotes (ppr mod)]
633
634 exportItemErr export_item
635   = sep [ ptext SLIT("The export item") <+> quotes (ppr export_item),
636           ptext SLIT("attempts to export constructors or class methods that are not visible here") ]
637
638 exportClashErr occ_name ie1 ie2
639   = hsep [ptext SLIT("The export items"), quotes (ppr ie1)
640          ,ptext SLIT("and"), quotes (ppr ie2)
641          ,ptext SLIT("create conflicting exports for"), quotes (ppr occ_name)]
642
643 dupDeclErr (n:ns)
644   = vcat [ptext SLIT("Multiple declarations of") <+> quotes (ppr n),
645           nest 4 (vcat (map ppr sorted_locs))]
646   where
647     sorted_locs = sortLt occ'ed_before (map nameSrcLoc (n:ns))
648     occ'ed_before a b = LT == compare a b
649
650 dupExportWarn occ_name ie1 ie2
651   = hsep [quotes (ppr occ_name), 
652           ptext SLIT("is exported by"), quotes (ppr ie1),
653           ptext SLIT("and"),            quotes (ppr ie2)]
654
655 dupModuleExport mod
656   = hsep [ptext SLIT("Duplicate"),
657           quotes (ptext SLIT("Module") <+> ppr mod), 
658           ptext SLIT("in export list")]
659 \end{code}