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