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