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