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