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