2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[RnNames]{Extracting imported and top-level names in scope}
8 getGlobalNames, exportsFromAvail
11 #include "HsVersions.h"
13 import CmdLineOpts ( DynFlag(..) )
15 import HsSyn ( HsModule(..), HsDecl(..), IE(..), ieName, ImportDecl(..),
16 ForeignDecl(..), ForKind(..), isDynamicExtName,
19 import RdrHsSyn ( RdrNameIE, RdrNameImportDecl,
20 RdrNameHsModule, RdrNameHsDecl
22 import RnIfaces ( getInterfaceExports, recordLocalSlurps )
23 import RnHiFiles ( getTyClDeclBinders )
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(..) )
33 import Name ( Name, nameSrcLoc, nameOccName, nameEnvElts )
34 import HscTypes ( Provenance(..), ImportReason(..), GlobalRdrEnv,
35 GenAvailInfo(..), AvailInfo, Avails, AvailEnv )
36 import RdrName ( RdrName, rdrNameOcc, setRdrNameOcc, mkRdrQual, mkRdrUnqual )
37 import OccName ( setOccNameSpace, dataName )
38 import NameSet ( elemNameSet, emptyNameSet )
40 import Maybes ( maybeToBool, catMaybes, mapMaybe )
41 import UniqFM ( emptyUFM, listToUFM )
42 import ListSetOps ( removeDups )
43 import Util ( sortLt )
44 import List ( partition )
49 %************************************************************************
51 \subsection{Get global names}
53 %************************************************************************
56 getGlobalNames :: Module -> RdrNameHsModule
57 -> RnMG (GlobalRdrEnv, -- Maps all in-scope things
58 GlobalRdrEnv, -- Maps just *local* things
59 ExportAvails) -- The exported stuff
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) ->
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 ->
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
77 get_imports = importsFromImportDecl this_mod_name
79 mapAndUnzipRn get_imports ordinary `thenRn` \ (imp_gbl_envs1, imp_avails_s1) ->
80 mapAndUnzipRn get_imports source `thenRn` \ (imp_gbl_envs2, imp_avails_s2) ->
83 -- We put the local env second, so that a local provenance
84 -- "wins", even if a module imports itself.
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
90 all_avails :: ExportAvails
91 all_avails = foldr plusExportAvails local_mod_avails (imp_avails_s2 ++ imp_avails_s1)
95 returnRn (gbl_env, local_gbl_env, all_avails)
97 this_mod_name = moduleName this_mod
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 ||
108 | otherwise = [ImportDecl pRELUDE_Name
110 False {- Not qualified -}
111 Nothing {- No "as" -}
112 Nothing {- No import list -}
115 explicit_prelude_import
116 = not (null [ () | (ImportDecl mod _ _ _ _ _) <- imports, mod == pRELUDE_Name ])
120 importsFromImportDecl :: ModuleName
122 -> RnMG (GlobalRdrEnv,
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) ->
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)
137 avails = [ avail | (mod_name, avails) <- avails_by_module,
138 mod_name /= this_mod_name,
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.)
147 -- Tiresome consequence: if you say
152 -- module B( AType ) where
153 -- import {-# SOURCE #-} A( AType )
155 -- then you'll get a 'B does not export AType' message. Oh well.
158 filterImports imp_mod_name from import_spec avails `thenRn` \ (filtered_avails, hides, explicits) ->
161 mk_provenance name = NonLocalDef (UserImport imp_mod iloc (name `elemNameSet` explicits))
164 qualifyImports imp_mod_name
165 (not qual_only) -- Maybe want unqualified names
173 importsFromLocalDecls this_mod decls
174 = mapRn (getLocalDeclBinders this_mod) decls `thenRn` \ avails_s ->
177 avails = concat avails_s
179 all_names :: [Name] -- All the defns; no dups eliminated
180 all_names = [name | avail <- avails, name <- availNames avail]
183 (_, dups) = removeDups compare all_names
185 -- Check for duplicate definitions
186 mapRn_ (addErrRn . dupDeclErr) dups `thenRn_`
188 -- Record that locally-defined things are available
189 recordLocalSlurps (availsToNameSet avails) `thenRn_`
191 -- Build the environment
192 qualifyImports (moduleName this_mod)
193 True -- Want unqualified names
196 (\n -> LocalDef) -- Provenance is local
199 ---------------------------
200 getLocalDeclBinders :: Module
201 -> RdrNameHsDecl -> RnMG Avails
202 getLocalDeclBinders mod (TyClD tycl_decl)
203 = -- For type and class decls, we generate Global names, with
204 -- no export indicator. They need to be global because they get
205 -- permanently bound into the TyCons and Classes. They don't need
206 -- an export indicator because they are all implicitly exported.
207 getTyClDeclBinders mod tycl_decl `thenRn` \ avail ->
210 getLocalDeclBinders mod (ValD binds)
211 = mapRn new (bagToList (collectTopBinders binds))
213 new (rdr_name, loc) = newTopBinder mod rdr_name loc `thenRn` \ name ->
214 returnRn (Avail name)
216 getLocalDeclBinders mod (ForD (ForeignDecl nm kind _ ext_nm _ loc))
217 | binds_haskell_name kind
218 = newTopBinder mod nm loc `thenRn` \ name ->
219 returnRn [Avail name]
221 | otherwise -- a foreign export
224 binds_haskell_name (FoImport _) = True
225 binds_haskell_name FoLabel = True
226 binds_haskell_name FoExport = isDynamicExtName ext_nm
228 getLocalDeclBinders mod (FixD _) = returnRn []
229 getLocalDeclBinders mod (DeprecD _) = returnRn []
230 getLocalDeclBinders mod (DefD _) = returnRn []
231 getLocalDeclBinders mod (InstD _) = returnRn []
232 getLocalDeclBinders mod (RuleD _) = returnRn []
236 %************************************************************************
238 \subsection{Filtering imports}
240 %************************************************************************
242 @filterImports@ takes the @ExportEnv@ telling what the imported module makes
243 available, and filters it through the import spec (if any).
246 filterImports :: ModuleName -- The module being imported
247 -> WhereFrom -- Tells whether it's a {-# SOURCE #-} import
248 -> Maybe (Bool, [RdrNameIE]) -- Import spec; True => hiding
249 -> [AvailInfo] -- What's available
250 -> RnMG ([AvailInfo], -- What's actually imported
251 [AvailInfo], -- What's to be hidden
252 -- (the unqualified version, that is)
253 -- (We need to return both the above sets, because
254 -- the qualified version is never hidden; so we can't
255 -- implement hiding by reducing what's imported.)
256 NameSet) -- What was imported explicitly
258 -- Complains if import spec mentions things that the module doesn't export
259 -- Warns/informs if import spec contains duplicates.
260 filterImports mod from Nothing imports
261 = returnRn (imports, [], emptyNameSet)
263 filterImports mod from (Just (want_hiding, import_items)) total_avails
264 = flatMapRn get_item import_items `thenRn` \ avails_w_explicits ->
266 (item_avails, explicits_s) = unzip avails_w_explicits
267 explicits = foldl addListToNameSet emptyNameSet explicits_s
271 -- All imported; item_avails to be hidden
272 returnRn (total_avails, item_avails, emptyNameSet)
274 -- Just item_avails imported; nothing to be hidden
275 returnRn (item_avails, [], explicits)
277 import_fm :: FiniteMap OccName AvailInfo
278 import_fm = listToFM [ (nameOccName name, avail)
279 | avail <- total_avails,
280 name <- availNames avail]
281 -- Even though availNames returns data constructors too,
282 -- they won't make any difference because naked entities like T
283 -- in an import list map to TcOccs, not VarOccs.
285 bale_out item = addErrRn (badImportItemErr mod from item) `thenRn_`
288 get_item item@(IEModuleContents _) = bale_out item
290 get_item item@(IEThingAll _)
291 = case check_item item of
292 Nothing -> bale_out item
293 Just avail@(AvailTC _ [n]) -> -- This occurs when you import T(..), but
294 -- only export T abstractly. The single [n]
295 -- in the AvailTC is the type or class itself
296 addWarnRn (dodgyImportWarn mod item) `thenRn_`
297 returnRn [(avail, [availName avail])]
298 Just avail -> returnRn [(avail, [availName avail])]
300 get_item item@(IEThingAbs n)
301 | want_hiding -- hiding( C )
302 -- Here the 'C' can be a data constructor *or* a type/class
303 = case catMaybes [check_item item, check_item (IEThingAbs data_n)] of
305 avails -> returnRn [(a, []) | a <- avails]
306 -- The 'explicits' list is irrelevant when hiding
308 data_n = setRdrNameOcc n (setOccNameSpace (rdrNameOcc n) dataName)
311 = case check_item item of
312 Nothing -> bale_out item
313 Just avail -> returnRn [(avail, availNames avail)]
316 | not (maybeToBool maybe_in_import_avails) ||
317 not (maybeToBool maybe_filtered_avail)
321 = Just filtered_avail
324 wanted_occ = rdrNameOcc (ieName item)
325 maybe_in_import_avails = lookupFM import_fm wanted_occ
327 Just avail = maybe_in_import_avails
328 maybe_filtered_avail = filterAvail item avail
329 Just filtered_avail = maybe_filtered_avail
334 %************************************************************************
336 \subsection{Qualifiying imports}
338 %************************************************************************
340 @qualifyImports@ takes the @ExportEnv@ after filtering through the import spec
341 of an import decl, and deals with producing an @RnEnv@ with the
342 right qualified names. It also turns the @Names@ in the @ExportEnv@ into
343 fully fledged @Names@.
346 qualifyImports :: ModuleName -- Imported module
347 -> Bool -- True <=> want unqualified import
348 -> Maybe ModuleName -- Optional "as M" part
349 -> [AvailInfo] -- What's to be hidden (but only the unqualified
350 -- version is hidden)
351 -> (Name -> Provenance)
352 -> Avails -- Whats imported and how
353 -> RnMG (GlobalRdrEnv, ExportAvails)
355 qualifyImports this_mod unqual_imp as_mod hides mk_provenance avails
357 -- Make the name environment. We're talking about a
358 -- single module here, so there must be no name clashes.
359 -- In practice there only ever will be if it's the module
362 -- Add the things that are available
363 name_env1 = foldl add_avail emptyRdrEnv avails
365 -- Delete things that are hidden
366 name_env2 = foldl del_avail name_env1 hides
368 -- Create the export-availability info
369 export_avails = mkExportAvails qual_mod unqual_imp name_env2 avails
371 returnRn (name_env2, export_avails)
374 qual_mod = case as_mod of
376 Just another_name -> another_name
378 add_avail :: GlobalRdrEnv -> AvailInfo -> GlobalRdrEnv
379 add_avail env avail = foldl add_name env (availNames avail)
385 env1 = addOneToGlobalRdrEnv env (mkRdrQual qual_mod occ) (name,prov)
386 env2 = addOneToGlobalRdrEnv env1 (mkRdrUnqual occ) (name,prov)
387 occ = nameOccName name
388 prov = mk_provenance name
390 del_avail env avail = foldl delOneFromGlobalRdrEnv env rdr_names
392 rdr_names = map (mkRdrUnqual . nameOccName) (availNames avail)
395 mkEmptyExportAvails :: ModuleName -> ExportAvails
396 mkEmptyExportAvails mod_name = (unitFM mod_name [], emptyUFM)
398 mkExportAvails :: ModuleName -> Bool -> GlobalRdrEnv -> [AvailInfo] -> ExportAvails
399 mkExportAvails mod_name unqual_imp name_env avails
400 = (mod_avail_env, entity_avail_env)
402 mod_avail_env = unitFM mod_name unqual_avails
404 -- unqual_avails is the Avails that are visible in *unqualfied* form
405 -- (1.4 Report, Section 5.1.1)
407 -- import T hiding( f )
408 -- we delete f from avails
410 unqual_avails | not unqual_imp = [] -- Short cut when no unqualified imports
411 | otherwise = mapMaybe prune avails
413 prune (Avail n) | unqual_in_scope n = Just (Avail n)
414 prune (Avail n) | otherwise = Nothing
415 prune (AvailTC n ns) | null uqs = Nothing
416 | otherwise = Just (AvailTC n uqs)
418 uqs = filter unqual_in_scope ns
420 unqual_in_scope n = unQualInScope name_env n
422 entity_avail_env = listToUFM [ (name,avail) | avail <- avails,
423 name <- availNames avail]
425 plusExportAvails :: ExportAvails -> ExportAvails -> ExportAvails
426 plusExportAvails (m1, e1) (m2, e2)
427 = (plusFM_C (++) m1 m2, plusAvailEnv e1 e2)
428 -- ToDo: wasteful: we do this once for each constructor!
432 %************************************************************************
434 \subsection{Export list processing}
436 %************************************************************************
438 Processing the export list.
440 You might think that we should record things that appear in the export list
441 as ``occurrences'' (using @addOccurrenceName@), but you'd be wrong.
442 We do check (here) that they are in scope,
443 but there is no need to slurp in their actual declaration
444 (which is what @addOccurrenceName@ forces).
446 Indeed, doing so would big trouble when
447 compiling @PrelBase@, because it re-exports @GHC@, which includes @takeMVar#@,
448 whose type includes @ConcBase.StateAndSynchVar#@, and so on...
451 type ExportAccum -- The type of the accumulating parameter of
452 -- the main worker function in exportsFromAvail
453 = ([ModuleName], -- 'module M's seen so far
454 ExportOccMap, -- Tracks exported occurrence names
455 AvailEnv) -- The accumulated exported stuff, kept in an env
456 -- so we can common-up related AvailInfos
458 type ExportOccMap = FiniteMap OccName (Name, RdrNameIE)
459 -- Tracks what a particular exported OccName
460 -- in an export list refers to, and which item
461 -- it came from. It's illegal to export two distinct things
462 -- that have the same occurrence name
465 exportsFromAvail :: ModuleName
466 -> Maybe [RdrNameIE] -- Export spec
470 -- Complains if two distinct exports have same OccName
471 -- Warns about identical exports.
472 -- Complains about exports items not in scope
473 exportsFromAvail this_mod Nothing export_avails global_name_env
474 = exportsFromAvail this_mod true_exports export_avails global_name_env
476 true_exports = Just $ if this_mod == mAIN_Name
477 then [IEVar main_RDR_Unqual]
478 -- export Main.main *only* unless otherwise specified,
479 else [IEModuleContents this_mod]
480 -- but for all other modules export everything.
482 exportsFromAvail this_mod (Just export_items)
483 (mod_avail_env, entity_avail_env)
485 = doptRn Opt_WarnDuplicateExports `thenRn` \ warn_dup_exports ->
486 foldlRn (exports_from_item warn_dup_exports)
487 ([], emptyFM, emptyAvailEnv) export_items
488 `thenRn` \ (_, _, export_avail_map) ->
490 export_avails :: [AvailInfo]
491 export_avails = nameEnvElts export_avail_map
493 returnRn export_avails
496 exports_from_item :: Bool -> ExportAccum -> RdrNameIE -> RnMG ExportAccum
498 exports_from_item warn_dups acc@(mods, occs, avails) ie@(IEModuleContents mod)
499 | mod `elem` mods -- Duplicate export of M
500 = warnCheckRn warn_dups (dupModuleExport mod) `thenRn_`
504 = case lookupFM mod_avail_env mod of
505 Nothing -> failWithRn acc (modExportErr mod)
506 Just mod_avails -> foldlRn (check_occs ie) occs mod_avails
509 avails' = foldl addAvail avails mod_avails
511 returnRn (mod:mods, occs', avails')
513 exports_from_item warn_dups acc@(mods, occs, avails) ie
514 = lookupSrcName global_name_env (ieName ie) `thenRn` \ name ->
516 -- See what's available in the current environment
517 case lookupUFM entity_avail_env name of {
518 Nothing -> -- Presumably this happens because lookupSrcName didn't find
519 -- the name and returned an unboundName, which won't be in
520 -- the entity_avail_env, of course
521 WARN( not (isUnboundName name), ppr name )
526 -- Filter out the bits we want
527 case filterAvail ie avail of {
528 Nothing -> -- Not enough availability
529 failWithRn acc (exportItemErr ie) ;
533 -- Phew! It's OK! Now to check the occurrence stuff!
534 warnCheckRn (ok_item ie avail) (dodgyExportWarn ie) `thenRn_`
535 check_occs ie occs export_avail `thenRn` \ occs' ->
536 returnRn (mods, occs', addAvail avails export_avail)
541 ok_item (IEThingAll _) (AvailTC _ [n]) = False
542 -- This occurs when you import T(..), but
543 -- only export T abstractly. The single [n]
544 -- in the AvailTC is the type or class itself
547 check_occs :: RdrNameIE -> ExportOccMap -> AvailInfo -> RnMG ExportOccMap
548 check_occs ie occs avail
549 = doptRn Opt_WarnDuplicateExports `thenRn` \ warn_dup_exports ->
550 foldlRn (check warn_dup_exports) occs (availNames avail)
552 check warn_dup occs name
553 = case lookupFM occs name_occ of
554 Nothing -> returnRn (addToFM occs name_occ (name, ie))
556 | name == name' -> -- Duplicate export
558 (dupExportWarn name_occ ie ie')
559 `thenRn_` returnRn occs
561 | otherwise -> -- Same occ name but different names: an error
562 failWithRn occs (exportClashErr name_occ ie ie')
564 name_occ = nameOccName name
567 %************************************************************************
571 %************************************************************************
574 badImportItemErr mod from ie
575 = sep [ptext SLIT("Module"), quotes (ppr mod), source_import,
576 ptext SLIT("does not export"), quotes (ppr ie)]
578 source_import = case from of
579 ImportByUserSource -> ptext SLIT("(hi-boot interface)")
582 dodgyImportWarn mod item = dodgyMsg (ptext SLIT("import")) item
583 dodgyExportWarn item = dodgyMsg (ptext SLIT("export")) item
585 dodgyMsg kind item@(IEThingAll tc)
586 = sep [ ptext SLIT("The") <+> kind <+> ptext SLIT("item") <+> quotes (ppr item),
587 ptext SLIT("suggests that") <+> quotes (ppr tc) <+> ptext SLIT("has constructor or class methods"),
588 ptext SLIT("but it has none; it is a type synonym or abstract type or class") ]
591 = hsep [ ptext SLIT("Unknown module in export list: module"), quotes (ppr mod)]
593 exportItemErr export_item
594 = sep [ ptext SLIT("The export item") <+> quotes (ppr export_item),
595 ptext SLIT("attempts to export constructors or class methods that are not visible here") ]
597 exportClashErr occ_name ie1 ie2
598 = hsep [ptext SLIT("The export items"), quotes (ppr ie1)
599 ,ptext SLIT("and"), quotes (ppr ie2)
600 ,ptext SLIT("create conflicting exports for"), quotes (ppr occ_name)]
603 = vcat [ptext SLIT("Multiple declarations of") <+> quotes (ppr n),
604 nest 4 (vcat (map ppr sorted_locs))]
606 sorted_locs = sortLt occ'ed_before (map nameSrcLoc (n:ns))
607 occ'ed_before a b = LT == compare a b
609 dupExportWarn occ_name ie1 ie2
610 = hsep [quotes (ppr occ_name),
611 ptext SLIT("is exported by"), quotes (ppr ie1),
612 ptext SLIT("and"), quotes (ppr ie2)]
615 = hsep [ptext SLIT("Duplicate"),
616 quotes (ptext SLIT("Module") <+> ppr mod),
617 ptext SLIT("in export list")]