[project @ 1999-12-09 12:30:56 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                         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      `thenRn` \ exported_avails ->
146
147         -- DONE
148       returnRn (gbl_env, exported_avails, Just all_avails)
149     )           `thenRn` \ (gbl_env, exported_avails, maybe_stuff) ->
150
151     case maybe_stuff of {
152         Nothing -> returnRn Nothing ;
153         Just all_avails ->
154
155         -- DEAL WITH FIXITIES
156    fixitiesFromLocalDecls gbl_env decls         `thenRn` \ local_fixity_env ->
157    let
158         -- Export only those fixities that are for names that are
159         --      (a) defined in this module
160         --      (b) exported
161         exported_fixities :: [(Name,Fixity)]
162         exported_fixities = [(name,fixity)
163                             | FixitySig name fixity _ <- nameEnvElts local_fixity_env,
164                               isLocallyDefined name
165                             ]
166
167         -- CONSTRUCT RESULTS
168         export_mods = case exports of
169                         Nothing -> []
170                         Just es -> [mod | IEModuleContents mod <- es, mod /= this_mod]
171
172         export_env            = ExportEnv exported_avails exported_fixities export_mods
173         (_, global_avail_env) = all_avails
174    in
175    traceRn (text "fixity env" <+> vcat (map ppr (nameEnvElts local_fixity_env)))        `thenRn_`
176
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     (if up_to_date 
222         then putDocRn (text "Compilation IS NOT required")
223         else returnRn ())                                       `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) = removeDups compare all_names
279     in
280         -- Check for duplicate definitions
281     mapRn_ (addErrRn . dupDeclErr) dups         `thenRn_` 
282
283         -- Record that locally-defined things are available
284     mapRn_ (recordSlurp Nothing) avails         `thenRn_`
285
286         -- Build the environment
287     qualifyImports mod_name 
288                    True         -- Want unqualified names
289                    Nothing      -- no 'as M'
290                    []           -- Hide nothing
291                    avails
292                    (\n -> n)
293
294   where
295     mod = mkThisModule mod_name
296
297     newLocalName rdr_name loc 
298         = (if isQual rdr_name then
299                 qualNameErr (text "the binding for" <+> quotes (ppr rdr_name)) (rdr_name,loc)
300                 -- There should never be a qualified name in a binding position (except in instance decls)
301                 -- The parser doesn't check this because the same parser parses instance decls
302             else 
303                 returnRn ())                    `thenRn_`
304
305           newLocalTopBinder mod (rdrNameOcc rdr_name) rec_exp_fn loc
306
307
308 getLocalDeclBinders :: (RdrName -> SrcLoc -> RnMG Name) -- New-name function
309                     -> RdrNameHsDecl
310                     -> RnMG Avails
311 getLocalDeclBinders new_name (ValD binds)
312   = mapRn do_one (bagToList (collectTopBinders binds))
313   where
314     do_one (rdr_name, loc) = new_name rdr_name loc      `thenRn` \ name ->
315                              returnRn (Avail name)
316
317 getLocalDeclBinders new_name decl
318   = getDeclBinders new_name decl        `thenRn` \ maybe_avail ->
319     case maybe_avail of
320         Nothing    -> returnRn []               -- Instance decls and suchlike
321         Just avail -> getDeclSysBinders new_sys_name decl               `thenRn_`  
322                       returnRn [avail]
323   where
324         -- The getDeclSysBinders is just to get the names of superclass selectors
325         -- etc, into the cache
326     new_sys_name rdr_name loc = newImplicitBinder (rdrNameOcc rdr_name) loc
327
328 fixitiesFromLocalDecls :: GlobalRdrEnv -> [RdrNameHsDecl] -> RnMG FixityEnv
329 fixitiesFromLocalDecls gbl_env decls
330   = foldlRn getFixities emptyNameEnv decls
331   where
332     getFixities :: FixityEnv -> RdrNameHsDecl -> RnMG FixityEnv
333     getFixities acc (FixD fix)
334       = fix_decl acc fix
335
336     getFixities acc (TyClD (ClassDecl _ _ _ _ sigs _ _ _ _ _ _))
337       = foldlRn fix_decl acc [sig | FixSig sig <- sigs]
338                 -- Get fixities from class decl sigs too.
339     getFixities acc other_decl
340       = returnRn acc
341
342     fix_decl acc sig@(FixitySig rdr_name fixity loc)
343         =       -- Check for fixity decl for something not declared
344           case lookupRdrEnv gbl_env rdr_name of {
345             Nothing | opt_WarnUnusedBinds 
346                     -> pushSrcLocRn loc (addWarnRn (unusedFixityDecl rdr_name fixity))
347                        `thenRn_` returnRn acc 
348                     | otherwise -> returnRn acc ;
349         
350             Just (name:_) ->
351
352                 -- Check for duplicate fixity decl
353           case lookupNameEnv acc name of {
354             Just (FixitySig _ _ loc') -> addErrRn (dupFixityDecl rdr_name loc loc')
355                                          `thenRn_` returnRn acc ;
356
357             Nothing -> returnRn (addToNameEnv acc name (FixitySig name fixity loc))
358           }}
359 \end{code}
360
361 %************************************************************************
362 %*                                                                      *
363 \subsection{Filtering imports}
364 %*                                                                      *
365 %************************************************************************
366
367 @filterImports@ takes the @ExportEnv@ telling what the imported module makes
368 available, and filters it through the import spec (if any).
369
370 \begin{code}
371 filterImports :: ModuleName                     -- The module being imported
372               -> Maybe (Bool, [RdrNameIE])      -- Import spec; True => hiding
373               -> [AvailInfo]                    -- What's available
374               -> RnMG ([AvailInfo],             -- What's actually imported
375                        [AvailInfo],             -- What's to be hidden
376                                                 -- (the unqualified version, that is)
377                        NameSet)                 -- What was imported explicitly
378
379         -- Complains if import spec mentions things that the module doesn't export
380         -- Warns/informs if import spec contains duplicates.
381 filterImports mod Nothing imports
382   = returnRn (imports, [], emptyNameSet)
383
384 filterImports mod (Just (want_hiding, import_items)) avails
385   = mapMaybeRn check_item import_items          `thenRn` \ avails_w_explicits ->
386     let
387         (item_avails, explicits_s) = unzip avails_w_explicits
388         explicits                  = foldl addListToNameSet emptyNameSet explicits_s
389     in
390     if want_hiding 
391     then        
392         -- All imported; item_avails to be hidden
393         returnRn (avails, item_avails, emptyNameSet)
394     else
395         -- Just item_avails imported; nothing to be hidden
396         returnRn (item_avails, [], explicits)
397   where
398     import_fm :: FiniteMap OccName AvailInfo
399     import_fm = listToFM [ (nameOccName name, avail) 
400                          | avail <- avails,
401                            name  <- availNames avail]
402         -- Even though availNames returns data constructors too,
403         -- they won't make any difference because naked entities like T
404         -- in an import list map to TcOccs, not VarOccs.
405
406     check_item item@(IEModuleContents _)
407       = addErrRn (badImportItemErr mod item)    `thenRn_`
408         returnRn Nothing
409
410     check_item item
411       | not (maybeToBool maybe_in_import_avails) ||
412         not (maybeToBool maybe_filtered_avail)
413       = addErrRn (badImportItemErr mod item)    `thenRn_`
414         returnRn Nothing
415
416       | dodgy_import = addWarnRn (dodgyImportWarn mod item)     `thenRn_`
417                        returnRn (Just (filtered_avail, explicits))
418
419       | otherwise    = returnRn (Just (filtered_avail, explicits))
420                 
421       where
422         wanted_occ             = rdrNameOcc (ieName item)
423         maybe_in_import_avails = lookupFM import_fm wanted_occ
424
425         Just avail             = maybe_in_import_avails
426         maybe_filtered_avail   = filterAvail item avail
427         Just filtered_avail    = maybe_filtered_avail
428         explicits              | dot_dot   = [availName filtered_avail]
429                                | otherwise = availNames filtered_avail
430
431         dot_dot = case item of 
432                     IEThingAll _    -> True
433                     other           -> False
434
435         dodgy_import = case (item, avail) of
436                           (IEThingAll _, AvailTC _ [n]) -> True
437                                 -- This occurs when you import T(..), but
438                                 -- only export T abstractly.  The single [n]
439                                 -- in the AvailTC is the type or class itself
440                                         
441                           other -> False
442 \end{code}
443
444
445
446 %************************************************************************
447 %*                                                                      *
448 \subsection{Qualifiying imports}
449 %*                                                                      *
450 %************************************************************************
451
452 @qualifyImports@ takes the @ExportEnv@ after filtering through the import spec
453 of an import decl, and deals with producing an @RnEnv@ with the 
454 right qualified names.  It also turns the @Names@ in the @ExportEnv@ into
455 fully fledged @Names@.
456
457 \begin{code}
458 qualifyImports :: ModuleName            -- Imported module
459                -> Bool                  -- True <=> want unqualified import
460                -> Maybe ModuleName      -- Optional "as M" part 
461                -> [AvailInfo]           -- What's to be hidden
462                -> Avails                -- Whats imported and how
463                -> (Name -> Name)        -- Improves the provenance on imported things
464                -> RnMG (GlobalRdrEnv, ExportAvails)
465         -- NB: the Names in ExportAvails don't have the improve-provenance
466         --     function applied to them
467         -- We could fix that, but I don't think it matters
468
469 qualifyImports this_mod unqual_imp as_mod hides
470                avails improve_prov
471   = 
472         -- Make the name environment.  We're talking about a 
473         -- single module here, so there must be no name clashes.
474         -- In practice there only ever will be if it's the module
475         -- being compiled.
476     let
477         -- Add the things that are available
478         name_env1 = foldl add_avail emptyRdrEnv avails
479
480         -- Delete things that are hidden
481         name_env2 = foldl del_avail name_env1 hides
482
483         -- Create the export-availability info
484         export_avails = mkExportAvails qual_mod unqual_imp name_env2 avails
485     in
486     returnRn (name_env2, export_avails)
487
488   where
489     qual_mod = case as_mod of
490                   Nothing           -> this_mod
491                   Just another_name -> another_name
492
493     add_avail :: GlobalRdrEnv -> AvailInfo -> GlobalRdrEnv
494     add_avail env avail = foldl add_name env (availNames avail)
495
496     add_name env name
497         | unqual_imp = env2
498         | otherwise  = env1
499         where
500           env1 = addOneToGlobalRdrEnv env  (mkRdrQual qual_mod occ) better_name
501           env2 = addOneToGlobalRdrEnv env1 (mkRdrUnqual occ)        better_name
502           occ         = nameOccName name
503           better_name = improve_prov name
504
505     del_avail env avail = foldl delOneFromGlobalRdrEnv env rdr_names
506                         where
507                           rdr_names = map (mkRdrUnqual . nameOccName) (availNames avail)
508 \end{code}
509
510
511 %************************************************************************
512 %*                                                                      *
513 \subsection{Export list processing}
514 %*                                                                      *
515 %************************************************************************
516
517 Processing the export list.
518
519 You might think that we should record things that appear in the export list
520 as ``occurrences'' (using @addOccurrenceName@), but you'd be wrong.
521 We do check (here) that they are in scope,
522 but there is no need to slurp in their actual declaration
523 (which is what @addOccurrenceName@ forces).
524
525 Indeed, doing so would big trouble when
526 compiling @PrelBase@, because it re-exports @GHC@, which includes @takeMVar#@,
527 whose type includes @ConcBase.StateAndSynchVar#@, and so on...
528
529 \begin{code}
530 type ExportAccum        -- The type of the accumulating parameter of
531                         -- the main worker function in exportsFromAvail
532      = ([ModuleName],           -- 'module M's seen so far
533         ExportOccMap,           -- Tracks exported occurrence names
534         NameEnv AvailInfo)      -- The accumulated exported stuff, kept in an env
535                                 --   so we can common-up related AvailInfos
536
537 type ExportOccMap = FiniteMap OccName (Name, RdrNameIE)
538         -- Tracks what a particular exported OccName
539         --   in an export list refers to, and which item
540         --   it came from.  It's illegal to export two distinct things
541         --   that have the same occurrence name
542
543
544 exportsFromAvail :: ModuleName
545                  -> Maybe [RdrNameIE]   -- Export spec
546                  -> ExportAvails
547                  -> GlobalRdrEnv 
548                  -> RnMG Avails
549         -- Complains if two distinct exports have same OccName
550         -- Warns about identical exports.
551         -- Complains about exports items not in scope
552 exportsFromAvail this_mod Nothing export_avails global_name_env
553   = exportsFromAvail this_mod true_exports export_avails global_name_env
554   where
555     true_exports = Just $ if this_mod == mAIN_Name
556                           then [IEVar main_RDR]
557                                -- export Main.main *only* unless otherwise specified,
558                           else [IEModuleContents this_mod]
559                                -- but for all other modules export everything.
560
561 exportsFromAvail this_mod (Just export_items) 
562                  (mod_avail_env, entity_avail_env)
563                  global_name_env
564   = foldlRn exports_from_item
565             ([], emptyFM, emptyNameEnv) export_items    `thenRn` \ (_, _, export_avail_map) ->
566     let
567         export_avails :: [AvailInfo]
568         export_avails   = nameEnvElts export_avail_map
569     in
570     returnRn export_avails
571
572   where
573     exports_from_item :: ExportAccum -> RdrNameIE -> RnMG ExportAccum
574
575     exports_from_item acc@(mods, occs, avails) ie@(IEModuleContents mod)
576         | mod `elem` mods       -- Duplicate export of M
577         = warnCheckRn opt_WarnDuplicateExports
578                       (dupModuleExport mod)     `thenRn_`
579           returnRn acc
580
581         | otherwise
582         = case lookupFM mod_avail_env mod of
583                 Nothing         -> failWithRn acc (modExportErr mod)
584                 Just mod_avails -> foldlRn (check_occs ie) occs mod_avails
585                                    `thenRn` \ occs' ->
586                                    let
587                                         avails' = foldl add_avail avails mod_avails
588                                    in
589                                    returnRn (mod:mods, occs', avails')
590
591     exports_from_item acc@(mods, occs, avails) ie
592         | not (maybeToBool maybe_in_scope) 
593         = failWithRn acc (unknownNameErr (ieName ie))
594
595         | not (null dup_names)
596         = addNameClashErrRn rdr_name (name:dup_names)   `thenRn_`
597           returnRn acc
598
599 #ifdef DEBUG
600         -- I can't see why this should ever happen; if the thing is in scope
601         -- at all it ought to have some availability
602         | not (maybeToBool maybe_avail)
603         = pprTrace "exportsFromAvail: curious Nothing:" (ppr name)
604           returnRn acc
605 #endif
606
607         | not enough_avail
608         = failWithRn acc (exportItemErr ie)
609
610         | otherwise     -- Phew!  It's OK!  Now to check the occurrence stuff!
611         = check_occs ie occs export_avail       `thenRn` \ occs' ->
612           returnRn (mods, occs', add_avail avails export_avail)
613
614        where
615           rdr_name        = ieName ie
616           maybe_in_scope  = lookupFM global_name_env rdr_name
617           Just (name:dup_names) = maybe_in_scope
618           maybe_avail        = lookupUFM entity_avail_env name
619           Just avail         = maybe_avail
620           maybe_export_avail = filterAvail ie avail
621           enough_avail       = maybeToBool maybe_export_avail
622           Just export_avail  = maybe_export_avail
623
624 add_avail avails avail = addToNameEnv_C plusAvail avails (availName avail) avail
625
626 check_occs :: RdrNameIE -> ExportOccMap -> AvailInfo -> RnMG ExportOccMap
627 check_occs ie occs avail 
628   = foldlRn check occs (availNames avail)
629   where
630     check occs name
631       = case lookupFM occs name_occ of
632           Nothing           -> returnRn (addToFM occs name_occ (name, ie))
633           Just (name', ie') 
634             | name == name' ->  -- Duplicate export
635                                 warnCheckRn opt_WarnDuplicateExports
636                                             (dupExportWarn name_occ ie ie')
637                                 `thenRn_` returnRn occs
638
639             | otherwise     ->  -- Same occ name but different names: an error
640                                 failWithRn occs (exportClashErr name_occ ie ie')
641       where
642         name_occ = nameOccName name
643         
644 mk_export_fn :: NameSet -> (Name -> ExportFlag)
645 mk_export_fn exported_names
646   = \name -> if name `elemNameSet` exported_names
647              then Exported
648              else NotExported
649 \end{code}
650
651 %************************************************************************
652 %*                                                                      *
653 \subsection{Errors}
654 %*                                                                      *
655 %************************************************************************
656
657 \begin{code}
658 badImportItemErr mod ie
659   = sep [ptext SLIT("Module"), quotes (pprModuleName mod), 
660          ptext SLIT("does not export"), quotes (ppr ie)]
661
662 dodgyImportWarn mod (IEThingAll tc)
663   = sep [ptext SLIT("Module") <+> quotes (pprModuleName mod)
664                               <+> ptext SLIT("exports") <+> quotes (ppr tc), 
665          ptext SLIT("with no constructors/class operations;"),
666          ptext SLIT("yet it is imported with a (..)")]
667
668 modExportErr mod
669   = hsep [ ptext SLIT("Unknown module in export list: module"), quotes (pprModuleName mod)]
670
671 exportItemErr export_item
672   = sep [ ptext SLIT("Bad export item"), quotes (ppr export_item)]
673
674 exportClashErr occ_name ie1 ie2
675   = hsep [ptext SLIT("The export items"), quotes (ppr ie1)
676          ,ptext SLIT("and"), quotes (ppr ie2)
677          ,ptext SLIT("create conflicting exports for"), quotes (ppr occ_name)]
678
679 dupDeclErr (n:ns)
680   = vcat [ptext SLIT("Multiple declarations of") <+> quotes (ppr n),
681           nest 4 (vcat (map pp sorted_ns))]
682   where
683     sorted_ns = sortLt occ'ed_before (n:ns)
684
685     occ'ed_before a b = LT == compare (getSrcLoc a) (getSrcLoc b)
686
687     pp n      = pprProvenance (getNameProvenance n)
688
689 dupExportWarn occ_name ie1 ie2
690   = hsep [quotes (ppr occ_name), 
691           ptext SLIT("is exported by"), quotes (ppr ie1),
692           ptext SLIT("and"),            quotes (ppr ie2)]
693
694 dupModuleExport mod
695   = hsep [ptext SLIT("Duplicate"),
696           quotes (ptext SLIT("Module") <+> pprModuleName mod), 
697           ptext SLIT("in export list")]
698
699 unusedFixityDecl rdr_name fixity
700   = hsep [ptext SLIT("Unused fixity declaration for"), quotes (ppr rdr_name)]
701
702 dupFixityDecl rdr_name loc1 loc2
703   = vcat [ptext SLIT("Multiple fixity declarations for") <+> quotes (ppr rdr_name),
704           ptext SLIT("at ") <+> ppr loc1,
705           ptext SLIT("and") <+> ppr loc2]
706
707 \end{code}