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