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