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