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