[project @ 2000-11-21 13:13: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, exportsFromAvail
9     ) where
10
11 #include "HsVersions.h"
12
13 import CmdLineOpts      ( DynFlag(..) )
14
15 import HsSyn            ( HsModule(..), HsDecl(..), IE(..), ieName, ImportDecl(..),
16                           ForeignDecl(..), ForKind(..), isDynamicExtName,
17                           collectTopBinders
18                         )
19 import RdrHsSyn         ( RdrNameIE, RdrNameImportDecl,
20                           RdrNameHsModule, RdrNameHsDecl
21                         )
22 import RnIfaces         ( getInterfaceExports, recordLocalSlurps )
23 import RnHiFiles        ( getTyClDeclBinders )
24 import RnEnv
25 import RnMonad
26
27 import FiniteMap
28 import PrelNames        ( pRELUDE_Name, mAIN_Name, main_RDR_Unqual, isUnboundName )
29 import UniqFM           ( lookupUFM )
30 import Bag              ( bagToList )
31 import Module           ( ModuleName, moduleName, WhereFrom(..) )
32 import NameSet
33 import Name             ( Name, nameSrcLoc, nameOccName,  nameEnvElts )
34 import HscTypes         ( Provenance(..), ImportReason(..), GlobalRdrEnv,
35                           GenAvailInfo(..), AvailInfo, Avails, AvailEnv )
36 import RdrName          ( RdrName, rdrNameOcc, setRdrNameOcc )
37 import OccName          ( setOccNameSpace, dataName )
38 import NameSet          ( elemNameSet, emptyNameSet )
39 import Outputable
40 import Maybes           ( maybeToBool, catMaybes, mapMaybe )
41 import UniqFM           ( emptyUFM, listToUFM )
42 import ListSetOps       ( removeDups )
43 import Util             ( sortLt )
44 import List             ( partition )
45 \end{code}
46
47
48
49 %************************************************************************
50 %*                                                                      *
51 \subsection{Get global names}
52 %*                                                                      *
53 %************************************************************************
54
55 \begin{code}
56 getGlobalNames :: Module -> RdrNameHsModule
57                -> RnMG (GlobalRdrEnv,   -- Maps all in-scope things
58                         GlobalRdrEnv,   -- Maps just *local* things
59                         ExportAvails)   -- The exported stuff
60
61 getGlobalNames this_mod (HsModule _ _ _ imports decls _ mod_loc)
62   =             -- PROCESS LOCAL DECLS
63                 -- Do these *first* so that the correct provenance gets
64                 -- into the global name cache.
65         importsFromLocalDecls this_mod decls            `thenRn` \ (local_gbl_env, local_mod_avails) ->
66
67                 -- PROCESS IMPORT DECLS
68                 -- Do the non {- SOURCE -} ones first, so that we get a helpful
69                 -- warning for {- SOURCE -} ones that are unnecessary
70         doptRn Opt_NoImplicitPrelude                            `thenRn` \ opt_no_prelude -> 
71         let
72           all_imports        = mk_prel_imports opt_no_prelude ++ imports
73           (source, ordinary) = partition is_source_import all_imports
74           is_source_import (ImportDecl _ ImportByUserSource _ _ _ _) = True
75           is_source_import other                                     = False
76
77           get_imports = importsFromImportDecl this_mod_name
78         in
79         mapAndUnzipRn get_imports ordinary      `thenRn` \ (imp_gbl_envs1, imp_avails_s1) ->
80         mapAndUnzipRn get_imports source        `thenRn` \ (imp_gbl_envs2, imp_avails_s2) ->
81
82                 -- COMBINE RESULTS
83                 -- We put the local env second, so that a local provenance
84                 -- "wins", even if a module imports itself.
85         let
86             gbl_env :: GlobalRdrEnv
87             imp_gbl_env = foldr plusGlobalRdrEnv emptyRdrEnv (imp_gbl_envs2 ++ imp_gbl_envs1)
88             gbl_env     = imp_gbl_env `plusGlobalRdrEnv` local_gbl_env
89
90             all_avails :: ExportAvails
91             all_avails = foldr plusExportAvails local_mod_avails (imp_avails_s2 ++ imp_avails_s1)
92         in
93
94                 -- ALL DONE
95         returnRn (gbl_env, local_gbl_env, all_avails)
96   where
97     this_mod_name = moduleName this_mod
98
99         -- NB: opt_NoImplicitPrelude is slightly different to import Prelude ();
100         -- because the former doesn't even look at Prelude.hi for instance declarations,
101         -- whereas the latter does.
102     mk_prel_imports no_prelude
103         | this_mod_name == pRELUDE_Name ||
104           explicit_prelude_import ||
105           no_prelude
106         = []
107
108         | otherwise = [ImportDecl pRELUDE_Name
109                                   ImportByUser
110                                   False {- Not qualified -}
111                                   Nothing       {- No "as" -}
112                                   Nothing       {- No import list -}
113                                   mod_loc]
114     
115     explicit_prelude_import
116       = not (null [ () | (ImportDecl mod _ _ _ _ _) <- imports, mod == pRELUDE_Name ])
117 \end{code}
118         
119 \begin{code}
120 importsFromImportDecl :: ModuleName
121                       -> RdrNameImportDecl
122                       -> RnMG (GlobalRdrEnv, 
123                                ExportAvails) 
124
125 importsFromImportDecl this_mod_name (ImportDecl imp_mod_name from qual_only as_mod import_spec iloc)
126   = pushSrcLocRn iloc $
127     getInterfaceExports imp_mod_name from       `thenRn` \ (imp_mod, avails_by_module) ->
128
129     if null avails_by_module then
130         -- If there's an error in getInterfaceExports, (e.g. interface
131         -- file not found) we get lots of spurious errors from 'filterImports'
132         returnRn (emptyRdrEnv, mkEmptyExportAvails imp_mod_name)
133     else
134
135     let
136         avails :: Avails
137         avails = [ avail | (mod_name, avails) <- avails_by_module,
138                            mod_name /= this_mod_name,
139                            avail <- avails ]
140         -- If the module exports anything defined in this module, just ignore it.
141         -- Reason: otherwise it looks as if there are two local definition sites
142         -- for the thing, and an error gets reported.  Easiest thing is just to
143         -- filter them out up front. This situation only arises if a module
144         -- imports itself, or another module that imported it.  (Necessarily,
145         -- this invoves a loop.)  
146         --
147         -- Tiresome consequence: if you say
148         --      module A where
149         --         import B( AType )
150         --         type AType = ...
151         --
152         --      module B( AType ) where
153         --         import {-# SOURCE #-} A( AType )
154         --
155         -- then you'll get a 'B does not export AType' message.  Oh well.
156
157     in
158     filterImports imp_mod_name from import_spec avails  `thenRn` \ (filtered_avails, hides, explicits) ->
159
160     let
161         unqual_imp = not qual_only              -- Maybe want unqualified names
162         qual_mod   = case as_mod of
163                         Nothing           -> imp_mod_name
164                         Just another_name -> another_name
165
166         mk_prov name = NonLocalDef (UserImport imp_mod iloc (name `elemNameSet` explicits)) 
167         gbl_env      = mkGlobalRdrEnv qual_mod unqual_imp hides mk_prov filtered_avails
168         exports      = mkExportAvails qual_mod unqual_imp gbl_env       filtered_avails
169     in
170     returnRn (gbl_env, exports)
171 \end{code}
172
173
174 \begin{code}
175 importsFromLocalDecls this_mod decls
176   = mapRn (getLocalDeclBinders this_mod) decls  `thenRn` \ avails_s ->
177
178     let
179         avails = concat avails_s
180
181         all_names :: [Name]     -- All the defns; no dups eliminated
182         all_names = [name | avail <- avails, name <- availNames avail]
183
184         dups :: [[Name]]
185         (_, dups) = removeDups compare all_names
186     in
187         -- Check for duplicate definitions
188     mapRn_ (addErrRn . dupDeclErr) dups                 `thenRn_` 
189
190         -- Record that locally-defined things are available
191     recordLocalSlurps (availsToNameSet avails)          `thenRn_`
192
193     let
194         mod_name   = moduleName this_mod
195         unqual_imp = True       -- Want unqualified names
196         mk_prov n  = LocalDef   -- Provenance is local
197         hides      = []         -- Hide nothing
198         gbl_env    = mkGlobalRdrEnv mod_name unqual_imp [] mk_prov avails
199         exports    = mkExportAvails mod_name unqual_imp gbl_env    avails
200     in
201     returnRn (gbl_env, exports)
202
203 ---------------------------
204 getLocalDeclBinders :: Module 
205                     -> RdrNameHsDecl -> RnMG Avails
206 getLocalDeclBinders mod (TyClD tycl_decl)
207   =     -- For type and class decls, we generate Global names, with
208         -- no export indicator.  They need to be global because they get
209         -- permanently bound into the TyCons and Classes.  They don't need
210         -- an export indicator because they are all implicitly exported.
211     getTyClDeclBinders mod tycl_decl    `thenRn` \ avail ->
212     returnRn [avail]
213
214 getLocalDeclBinders mod (ValD binds)
215   = mapRn new (bagToList (collectTopBinders binds))
216   where
217     new (rdr_name, loc) = newTopBinder mod rdr_name loc         `thenRn` \ name ->
218                           returnRn (Avail name)
219
220 getLocalDeclBinders mod (ForD (ForeignDecl nm kind _ ext_nm _ loc))
221   | binds_haskell_name kind
222   = newTopBinder mod nm loc         `thenRn` \ name ->
223     returnRn [Avail name]
224
225   | otherwise           -- a foreign export
226   = returnRn []
227   where
228     binds_haskell_name (FoImport _) = True
229     binds_haskell_name FoLabel      = True
230     binds_haskell_name FoExport     = isDynamicExtName ext_nm
231
232 getLocalDeclBinders mod (FixD _)    = returnRn []
233 getLocalDeclBinders mod (DeprecD _) = returnRn []
234 getLocalDeclBinders mod (DefD _)    = returnRn []
235 getLocalDeclBinders mod (InstD _)   = returnRn []
236 getLocalDeclBinders mod (RuleD _)   = returnRn []
237 \end{code}
238
239
240 %************************************************************************
241 %*                                                                      *
242 \subsection{Filtering imports}
243 %*                                                                      *
244 %************************************************************************
245
246 @filterImports@ takes the @ExportEnv@ telling what the imported module makes
247 available, and filters it through the import spec (if any).
248
249 \begin{code}
250 filterImports :: ModuleName                     -- The module being imported
251               -> WhereFrom                      -- Tells whether it's a {-# SOURCE #-} import
252               -> Maybe (Bool, [RdrNameIE])      -- Import spec; True => hiding
253               -> [AvailInfo]                    -- What's available
254               -> RnMG ([AvailInfo],             -- What's actually imported
255                        [AvailInfo],             -- What's to be hidden
256                                                 -- (the unqualified version, that is)
257                         -- (We need to return both the above sets, because
258                         --  the qualified version is never hidden; so we can't
259                         --  implement hiding by reducing what's imported.)
260                        NameSet)                 -- What was imported explicitly
261
262         -- Complains if import spec mentions things that the module doesn't export
263         -- Warns/informs if import spec contains duplicates.
264 filterImports mod from Nothing imports
265   = returnRn (imports, [], emptyNameSet)
266
267 filterImports mod from (Just (want_hiding, import_items)) total_avails
268   = flatMapRn get_item import_items             `thenRn` \ avails_w_explicits ->
269     let
270         (item_avails, explicits_s) = unzip avails_w_explicits
271         explicits                  = foldl addListToNameSet emptyNameSet explicits_s
272     in
273     if want_hiding 
274     then        
275         -- All imported; item_avails to be hidden
276         returnRn (total_avails, item_avails, emptyNameSet)
277     else
278         -- Just item_avails imported; nothing to be hidden
279         returnRn (item_avails, [], explicits)
280   where
281     import_fm :: FiniteMap OccName AvailInfo
282     import_fm = listToFM [ (nameOccName name, avail) 
283                          | avail <- total_avails,
284                            name  <- availNames avail]
285         -- Even though availNames returns data constructors too,
286         -- they won't make any difference because naked entities like T
287         -- in an import list map to TcOccs, not VarOccs.
288
289     bale_out item = addErrRn (badImportItemErr mod from item)   `thenRn_`
290                     returnRn []
291
292     get_item item@(IEModuleContents _) = bale_out item
293
294     get_item item@(IEThingAll _)
295       = case check_item item of
296           Nothing                    -> bale_out item
297           Just avail@(AvailTC _ [n]) ->         -- This occurs when you import T(..), but
298                                                 -- only export T abstractly.  The single [n]
299                                                 -- in the AvailTC is the type or class itself
300                                         addWarnRn (dodgyImportWarn mod item)    `thenRn_`
301                                         returnRn [(avail, [availName avail])]
302           Just avail                 -> returnRn [(avail, [availName avail])]
303
304     get_item item@(IEThingAbs n)
305       | want_hiding     -- hiding( C ) 
306                         -- Here the 'C' can be a data constructor *or* a type/class
307       = case catMaybes [check_item item, check_item (IEThingAbs data_n)] of
308                 []     -> bale_out item
309                 avails -> returnRn [(a, []) | a <- avails]
310                                 -- The 'explicits' list is irrelevant when hiding
311       where
312         data_n = setRdrNameOcc n (setOccNameSpace (rdrNameOcc n) dataName)
313
314     get_item item
315       = case check_item item of
316           Nothing    -> bale_out item
317           Just avail -> returnRn [(avail, availNames avail)]
318
319     check_item item
320       | not (maybeToBool maybe_in_import_avails) ||
321         not (maybeToBool maybe_filtered_avail)
322       = Nothing
323
324       | otherwise    
325       = Just filtered_avail
326                 
327       where
328         wanted_occ             = rdrNameOcc (ieName item)
329         maybe_in_import_avails = lookupFM import_fm wanted_occ
330
331         Just avail             = maybe_in_import_avails
332         maybe_filtered_avail   = filterAvail item avail
333         Just filtered_avail    = maybe_filtered_avail
334 \end{code}
335
336
337
338 %************************************************************************
339 %*                                                                      *
340 \subsection{Qualifiying imports}
341 %*                                                                      *
342 %************************************************************************
343
344 \begin{code}
345 mkEmptyExportAvails :: ModuleName -> ExportAvails
346 mkEmptyExportAvails mod_name = (unitFM mod_name [], emptyUFM)
347
348 mkExportAvails :: ModuleName -> Bool -> GlobalRdrEnv -> [AvailInfo] -> ExportAvails
349 mkExportAvails mod_name unqual_imp gbl_env avails
350   = (mod_avail_env, entity_avail_env)
351   where
352     mod_avail_env = unitFM mod_name unqual_avails 
353
354         -- unqual_avails is the Avails that are visible in *unqualfied* form
355         -- (1.4 Report, Section 5.1.1)
356         -- For example, in 
357         --      import T hiding( f )
358         -- we delete f from avails
359
360     unqual_avails | not unqual_imp = [] -- Short cut when no unqualified imports
361                   | otherwise      = mapMaybe prune avails
362
363     prune (Avail n) | unqual_in_scope n = Just (Avail n)
364     prune (Avail n) | otherwise         = Nothing
365     prune (AvailTC n ns) | null uqs     = Nothing
366                          | otherwise    = Just (AvailTC n uqs)
367                          where
368                            uqs = filter unqual_in_scope ns
369
370     unqual_in_scope n = unQualInScope gbl_env n
371
372     entity_avail_env = listToUFM [ (name,avail) | avail <- avails, 
373                                                   name  <- availNames avail]
374
375 plusExportAvails ::  ExportAvails ->  ExportAvails ->  ExportAvails
376 plusExportAvails (m1, e1) (m2, e2)
377   = (plusFM_C (++) m1 m2, plusAvailEnv e1 e2)
378         -- ToDo: wasteful: we do this once for each constructor!
379 \end{code}
380
381
382 %************************************************************************
383 %*                                                                      *
384 \subsection{Export list processing}
385 %*                                                                      *
386 %************************************************************************
387
388 Processing the export list.
389
390 You might think that we should record things that appear in the export list
391 as ``occurrences'' (using @addOccurrenceName@), but you'd be wrong.
392 We do check (here) that they are in scope,
393 but there is no need to slurp in their actual declaration
394 (which is what @addOccurrenceName@ forces).
395
396 Indeed, doing so would big trouble when
397 compiling @PrelBase@, because it re-exports @GHC@, which includes @takeMVar#@,
398 whose type includes @ConcBase.StateAndSynchVar#@, and so on...
399
400 \begin{code}
401 type ExportAccum        -- The type of the accumulating parameter of
402                         -- the main worker function in exportsFromAvail
403      = ([ModuleName],           -- 'module M's seen so far
404         ExportOccMap,           -- Tracks exported occurrence names
405         AvailEnv)               -- The accumulated exported stuff, kept in an env
406                                 --   so we can common-up related AvailInfos
407
408 type ExportOccMap = FiniteMap OccName (Name, RdrNameIE)
409         -- Tracks what a particular exported OccName
410         --   in an export list refers to, and which item
411         --   it came from.  It's illegal to export two distinct things
412         --   that have the same occurrence name
413
414
415 exportsFromAvail :: ModuleName
416                  -> Maybe [RdrNameIE]   -- Export spec
417                  -> ExportAvails
418                  -> GlobalRdrEnv 
419                  -> RnMG Avails
420         -- Complains if two distinct exports have same OccName
421         -- Warns about identical exports.
422         -- Complains about exports items not in scope
423 exportsFromAvail this_mod Nothing export_avails global_name_env
424   = exportsFromAvail this_mod true_exports export_avails global_name_env
425   where
426     true_exports = Just $ if this_mod == mAIN_Name
427                           then [IEVar main_RDR_Unqual]
428                                -- export Main.main *only* unless otherwise specified,
429                           else [IEModuleContents this_mod]
430                                -- but for all other modules export everything.
431
432 exportsFromAvail this_mod (Just export_items) 
433                  (mod_avail_env, entity_avail_env)
434                  global_name_env
435   = doptRn Opt_WarnDuplicateExports             `thenRn` \ warn_dup_exports ->
436     foldlRn (exports_from_item warn_dup_exports)
437             ([], emptyFM, emptyAvailEnv) export_items
438                                                 `thenRn` \ (_, _, export_avail_map) ->
439     let
440         export_avails :: [AvailInfo]
441         export_avails   = nameEnvElts export_avail_map
442     in
443     returnRn export_avails
444
445   where
446     exports_from_item :: Bool -> ExportAccum -> RdrNameIE -> RnMG ExportAccum
447
448     exports_from_item warn_dups acc@(mods, occs, avails) ie@(IEModuleContents mod)
449         | mod `elem` mods       -- Duplicate export of M
450         = warnCheckRn warn_dups (dupModuleExport mod)   `thenRn_`
451           returnRn acc
452
453         | otherwise
454         = case lookupFM mod_avail_env mod of
455                 Nothing         -> failWithRn acc (modExportErr mod)
456                 Just mod_avails -> foldlRn (check_occs ie) occs mod_avails
457                                    `thenRn` \ occs' ->
458                                    let
459                                         avails' = foldl addAvail avails mod_avails
460                                    in
461                                    returnRn (mod:mods, occs', avails')
462
463     exports_from_item warn_dups acc@(mods, occs, avails) ie
464         = lookupSrcName global_name_env (ieName ie)     `thenRn` \ name -> 
465
466                 -- See what's available in the current environment
467           case lookupUFM entity_avail_env name of {
468             Nothing ->  -- Presumably this happens because lookupSrcName didn't find
469                         -- the name and returned an unboundName, which won't be in
470                         -- the entity_avail_env, of course
471                         WARN( not (isUnboundName name), ppr name )
472                         returnRn acc ;
473
474             Just avail ->
475
476                 -- Filter out the bits we want
477           case filterAvail ie avail of {
478             Nothing ->  -- Not enough availability
479                            failWithRn acc (exportItemErr ie) ;
480
481             Just export_avail ->        
482
483                 -- Phew!  It's OK!  Now to check the occurrence stuff!
484           warnCheckRn (ok_item ie avail) (dodgyExportWarn ie)   `thenRn_`
485           check_occs ie occs export_avail                       `thenRn` \ occs' ->
486           returnRn (mods, occs', addAvail avails export_avail)
487           }}
488
489
490
491 ok_item (IEThingAll _) (AvailTC _ [n]) = False
492   -- This occurs when you import T(..), but
493   -- only export T abstractly.  The single [n]
494   -- in the AvailTC is the type or class itself
495 ok_item _ _ = True
496
497 check_occs :: RdrNameIE -> ExportOccMap -> AvailInfo -> RnMG ExportOccMap
498 check_occs ie occs avail 
499   = doptRn Opt_WarnDuplicateExports     `thenRn` \ warn_dup_exports ->
500     foldlRn (check warn_dup_exports) occs (availNames avail)
501   where
502     check warn_dup occs name
503       = case lookupFM occs name_occ of
504           Nothing           -> returnRn (addToFM occs name_occ (name, ie))
505           Just (name', ie') 
506             | name == name' ->  -- Duplicate export
507                                 warnCheckRn warn_dup
508                                             (dupExportWarn name_occ ie ie')
509                                 `thenRn_` returnRn occs
510
511             | otherwise     ->  -- Same occ name but different names: an error
512                                 failWithRn occs (exportClashErr name_occ ie ie')
513       where
514         name_occ = nameOccName name
515 \end{code}
516
517 %************************************************************************
518 %*                                                                      *
519 \subsection{Errors}
520 %*                                                                      *
521 %************************************************************************
522
523 \begin{code}
524 badImportItemErr mod from ie
525   = sep [ptext SLIT("Module"), quotes (ppr mod), source_import,
526          ptext SLIT("does not export"), quotes (ppr ie)]
527   where
528     source_import = case from of
529                       ImportByUserSource -> ptext SLIT("(hi-boot interface)")
530                       other              -> empty
531
532 dodgyImportWarn mod item = dodgyMsg (ptext SLIT("import")) item
533 dodgyExportWarn     item = dodgyMsg (ptext SLIT("export")) item
534
535 dodgyMsg kind item@(IEThingAll tc)
536   = sep [ ptext SLIT("The") <+> kind <+> ptext SLIT("item") <+> quotes (ppr item),
537           ptext SLIT("suggests that") <+> quotes (ppr tc) <+> ptext SLIT("has constructor or class methods"),
538           ptext SLIT("but it has none; it is a type synonym or abstract type or class") ]
539           
540 modExportErr mod
541   = hsep [ ptext SLIT("Unknown module in export list: module"), quotes (ppr mod)]
542
543 exportItemErr export_item
544   = sep [ ptext SLIT("The export item") <+> quotes (ppr export_item),
545           ptext SLIT("attempts to export constructors or class methods that are not visible here") ]
546
547 exportClashErr occ_name ie1 ie2
548   = hsep [ptext SLIT("The export items"), quotes (ppr ie1)
549          ,ptext SLIT("and"), quotes (ppr ie2)
550          ,ptext SLIT("create conflicting exports for"), quotes (ppr occ_name)]
551
552 dupDeclErr (n:ns)
553   = vcat [ptext SLIT("Multiple declarations of") <+> quotes (ppr n),
554           nest 4 (vcat (map ppr sorted_locs))]
555   where
556     sorted_locs = sortLt occ'ed_before (map nameSrcLoc (n:ns))
557     occ'ed_before a b = LT == compare a b
558
559 dupExportWarn occ_name ie1 ie2
560   = hsep [quotes (ppr occ_name), 
561           ptext SLIT("is exported by"), quotes (ppr ie1),
562           ptext SLIT("and"),            quotes (ppr ie2)]
563
564 dupModuleExport mod
565   = hsep [ptext SLIT("Duplicate"),
566           quotes (ptext SLIT("Module") <+> ppr mod), 
567           ptext SLIT("in export list")]
568 \end{code}