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