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