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,
17 collectLocatedHsBinders
19 import RdrHsSyn ( RdrNameIE, RdrNameImportDecl,
20 RdrNameHsModule, RdrNameHsDecl
22 import RnIfaces ( recordLocalSlurps )
23 import RnHiFiles ( getTyClDeclBinders, loadInterface )
28 import PrelNames ( pRELUDE_Name, mAIN_Name, main_RDR_Unqual, isUnboundName )
29 import UniqFM ( lookupUFM )
30 import Module ( ModuleName, moduleName, WhereFrom(..) )
32 import Name ( Name, nameSrcLoc, nameOccName, nameEnvElts )
33 import HscTypes ( Provenance(..), ImportReason(..), GlobalRdrEnv,
34 GenAvailInfo(..), AvailInfo, Avails, AvailEnv,
35 Deprecations(..), ModIface(..)
37 import RdrName ( rdrNameOcc, setRdrNameOcc )
38 import OccName ( setOccNameSpace, dataName )
39 import NameSet ( elemNameSet, emptyNameSet )
41 import Maybes ( maybeToBool, catMaybes, mapMaybe )
42 import UniqFM ( emptyUFM, listToUFM )
43 import ListSetOps ( removeDups )
44 import Util ( sortLt )
45 import List ( partition )
50 %************************************************************************
52 \subsection{Get global names}
54 %************************************************************************
57 getGlobalNames :: Module -> RdrNameHsModule
58 -> RnMG (GlobalRdrEnv, -- Maps all in-scope things
59 GlobalRdrEnv, -- Maps just *local* things
60 ExportAvails) -- The exported stuff
62 getGlobalNames this_mod (HsModule _ _ _ imports decls _ mod_loc)
63 = -- PROCESS LOCAL DECLS
64 -- Do these *first* so that the correct provenance gets
65 -- into the global name cache.
66 importsFromLocalDecls this_mod decls `thenRn` \ (local_gbl_env, local_mod_avails) ->
68 -- PROCESS IMPORT DECLS
69 -- Do the non {- SOURCE -} ones first, so that we get a helpful
70 -- warning for {- SOURCE -} ones that are unnecessary
71 doptRn Opt_NoImplicitPrelude `thenRn` \ opt_no_prelude ->
73 all_imports = mk_prel_imports opt_no_prelude ++ imports
74 (source, ordinary) = partition is_source_import all_imports
75 is_source_import (ImportDecl _ ImportByUserSource _ _ _ _) = True
76 is_source_import other = False
78 get_imports = importsFromImportDecl this_mod_name
80 mapAndUnzipRn get_imports ordinary `thenRn` \ (imp_gbl_envs1, imp_avails_s1) ->
81 mapAndUnzipRn get_imports source `thenRn` \ (imp_gbl_envs2, imp_avails_s2) ->
84 -- We put the local env second, so that a local provenance
85 -- "wins", even if a module imports itself.
87 gbl_env :: GlobalRdrEnv
88 imp_gbl_env = foldr plusGlobalRdrEnv emptyRdrEnv (imp_gbl_envs2 ++ imp_gbl_envs1)
89 gbl_env = imp_gbl_env `plusGlobalRdrEnv` local_gbl_env
91 all_avails :: ExportAvails
92 all_avails = foldr plusExportAvails local_mod_avails (imp_avails_s2 ++ imp_avails_s1)
96 returnRn (gbl_env, local_gbl_env, all_avails)
98 this_mod_name = moduleName this_mod
100 -- NB: opt_NoImplicitPrelude is slightly different to import Prelude ();
101 -- because the former doesn't even look at Prelude.hi for instance declarations,
102 -- whereas the latter does.
103 mk_prel_imports no_prelude
104 | this_mod_name == pRELUDE_Name ||
105 explicit_prelude_import ||
109 | otherwise = [ImportDecl pRELUDE_Name
111 False {- Not qualified -}
112 Nothing {- No "as" -}
113 Nothing {- No import list -}
116 explicit_prelude_import
117 = not (null [ () | (ImportDecl mod _ _ _ _ _) <- imports, mod == pRELUDE_Name ])
121 importsFromImportDecl :: ModuleName
123 -> RnMG (GlobalRdrEnv,
126 importsFromImportDecl this_mod_name (ImportDecl imp_mod_name from qual_only as_mod import_spec iloc)
127 = pushSrcLocRn iloc $
129 loadInterface (ppr imp_mod_name <+> ptext SLIT("is directly imported"))
130 imp_mod_name from `thenRn` \ iface ->
132 imp_mod = mi_module iface
133 avails_by_module = mi_exports iface
134 deprecs = mi_deprecs iface
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 if null avails_by_module then
159 -- If there's an error in loadInterface, (e.g. interface
160 -- file not found) we get lots of spurious errors from 'filterImports'
161 returnRn (emptyRdrEnv, mkEmptyExportAvails imp_mod_name)
164 -- Complain if we import a deprecated module
166 DeprecAll txt -> addWarnRn (moduleDeprec imp_mod_name txt)
170 -- Filter the imports according to the import list
171 filterImports imp_mod_name from import_spec avails `thenRn` \ (filtered_avails, hides, explicits) ->
174 unqual_imp = not qual_only -- Maybe want unqualified names
175 qual_mod = case as_mod of
176 Nothing -> imp_mod_name
177 Just another_name -> another_name
179 mk_prov name = NonLocalDef (UserImport imp_mod iloc (name `elemNameSet` explicits))
180 gbl_env = mkGlobalRdrEnv qual_mod unqual_imp True hides mk_prov filtered_avails deprecs
181 exports = mkExportAvails qual_mod unqual_imp gbl_env filtered_avails
183 returnRn (gbl_env, exports)
188 importsFromLocalDecls this_mod decls
189 = mapRn (getLocalDeclBinders this_mod) decls `thenRn` \ avails_s ->
190 -- The avails that are returned don't include the "system" names
192 avails = concat avails_s
194 all_names :: [Name] -- All the defns; no dups eliminated
195 all_names = [name | avail <- avails, name <- availNames avail]
198 (_, dups) = removeDups compare all_names
200 -- Check for duplicate definitions
201 -- The complaint will come out as "Multiple declarations of Foo.f" because
202 -- since 'f' is in the env twice, the unQualInScope used by the error-msg
203 -- printer returns False. It seems awkward to fix, unfortunately.
204 mapRn_ (addErrRn . dupDeclErr) dups `thenRn_`
207 -- Record that locally-defined things are available
208 recordLocalSlurps (availsToNameSet avails) `thenRn_`
210 mod_name = moduleName this_mod
211 unqual_imp = True -- Want unqualified names
212 mk_prov n = LocalDef -- Provenance is local
213 hides = [] -- Hide nothing
215 gbl_env = mkGlobalRdrEnv mod_name unqual_imp True hides mk_prov avails NoDeprecs
216 -- NoDeprecs: don't complain about locally defined names
217 -- For a start, we may be exporting a deprecated thing
218 -- Also we may use a deprecated thing in the defn of another
219 -- deprecated things. We may even use a deprecated thing in
220 -- the defn of a non-deprecated thing, when changing a module's
223 exports = mkExportAvails mod_name unqual_imp gbl_env avails
225 returnRn (gbl_env, exports)
227 ---------------------------
228 getLocalDeclBinders :: Module -> RdrNameHsDecl -> RnMG [AvailInfo]
229 getLocalDeclBinders mod (TyClD tycl_decl)
230 = -- For type and class decls, we generate Global names, with
231 -- no export indicator. They need to be global because they get
232 -- permanently bound into the TyCons and Classes. They don't need
233 -- an export indicator because they are all implicitly exported.
234 getTyClDeclBinders mod tycl_decl `thenRn` \ (avail, sys_names) ->
236 -- Record that the system names are available
237 recordLocalSlurps (mkNameSet sys_names) `thenRn_`
240 getLocalDeclBinders mod (ValD binds)
241 = mapRn new (collectLocatedHsBinders binds) `thenRn` \ avails ->
244 new (rdr_name, loc) = newTopBinder mod rdr_name loc `thenRn` \ name ->
245 returnRn (Avail name)
247 getLocalDeclBinders mod (ForD (ForeignDecl nm kind _ ext_nm _ loc))
248 | binds_haskell_name kind
249 = newTopBinder mod nm loc `thenRn` \ name ->
250 returnRn [Avail name]
252 | otherwise -- a foreign export
255 binds_haskell_name (FoImport _) = True
256 binds_haskell_name FoLabel = True
257 binds_haskell_name FoExport = isDynamicExtName ext_nm
259 getLocalDeclBinders mod (FixD _) = returnRn []
260 getLocalDeclBinders mod (DeprecD _) = returnRn []
261 getLocalDeclBinders mod (DefD _) = returnRn []
262 getLocalDeclBinders mod (InstD _) = returnRn []
263 getLocalDeclBinders mod (RuleD _) = returnRn []
267 %************************************************************************
269 \subsection{Filtering imports}
271 %************************************************************************
273 @filterImports@ takes the @ExportEnv@ telling what the imported module makes
274 available, and filters it through the import spec (if any).
277 filterImports :: ModuleName -- The module being imported
278 -> WhereFrom -- Tells whether it's a {-# SOURCE #-} import
279 -> Maybe (Bool, [RdrNameIE]) -- Import spec; True => hiding
280 -> [AvailInfo] -- What's available
281 -> RnMG ([AvailInfo], -- What's actually imported
282 [AvailInfo], -- What's to be hidden
283 -- (the unqualified version, that is)
284 -- (We need to return both the above sets, because
285 -- the qualified version is never hidden; so we can't
286 -- implement hiding by reducing what's imported.)
287 NameSet) -- What was imported explicitly
289 -- Complains if import spec mentions things that the module doesn't export
290 -- Warns/informs if import spec contains duplicates.
291 filterImports mod from Nothing imports
292 = returnRn (imports, [], emptyNameSet)
294 filterImports mod from (Just (want_hiding, import_items)) total_avails
295 = flatMapRn get_item import_items `thenRn` \ avails_w_explicits ->
297 (item_avails, explicits_s) = unzip avails_w_explicits
298 explicits = foldl addListToNameSet emptyNameSet explicits_s
302 -- All imported; item_avails to be hidden
303 returnRn (total_avails, item_avails, emptyNameSet)
305 -- Just item_avails imported; nothing to be hidden
306 returnRn (item_avails, [], explicits)
308 import_fm :: FiniteMap OccName AvailInfo
309 import_fm = listToFM [ (nameOccName name, avail)
310 | avail <- total_avails,
311 name <- availNames avail]
312 -- Even though availNames returns data constructors too,
313 -- they won't make any difference because naked entities like T
314 -- in an import list map to TcOccs, not VarOccs.
316 bale_out item = addErrRn (badImportItemErr mod from item) `thenRn_`
319 get_item item@(IEModuleContents _) = bale_out item
321 get_item item@(IEThingAll _)
322 = case check_item item of
323 Nothing -> bale_out item
324 Just avail@(AvailTC _ [n]) -> -- This occurs when you import T(..), but
325 -- only export T abstractly. The single [n]
326 -- in the AvailTC is the type or class itself
327 addWarnRn (dodgyImportWarn mod item) `thenRn_`
328 returnRn [(avail, [availName avail])]
329 Just avail -> returnRn [(avail, [availName avail])]
331 get_item item@(IEThingAbs n)
332 | want_hiding -- hiding( C )
333 -- Here the 'C' can be a data constructor *or* a type/class
334 = case catMaybes [check_item item, check_item (IEThingAbs data_n)] of
336 avails -> returnRn [(a, []) | a <- avails]
337 -- The 'explicits' list is irrelevant when hiding
339 data_n = setRdrNameOcc n (setOccNameSpace (rdrNameOcc n) dataName)
342 = case check_item item of
343 Nothing -> bale_out item
344 Just avail -> returnRn [(avail, availNames avail)]
347 | not (maybeToBool maybe_in_import_avails) ||
348 not (maybeToBool maybe_filtered_avail)
352 = Just filtered_avail
355 wanted_occ = rdrNameOcc (ieName item)
356 maybe_in_import_avails = lookupFM import_fm wanted_occ
358 Just avail = maybe_in_import_avails
359 maybe_filtered_avail = filterAvail item avail
360 Just filtered_avail = maybe_filtered_avail
365 %************************************************************************
367 \subsection{Qualifiying imports}
369 %************************************************************************
372 mkEmptyExportAvails :: ModuleName -> ExportAvails
373 mkEmptyExportAvails mod_name = (unitFM mod_name [], emptyUFM)
375 mkExportAvails :: ModuleName -> Bool -> GlobalRdrEnv -> [AvailInfo] -> ExportAvails
376 mkExportAvails mod_name unqual_imp gbl_env avails
377 = (mod_avail_env, entity_avail_env)
379 mod_avail_env = unitFM mod_name unqual_avails
381 -- unqual_avails is the Avails that are visible in *unqualfied* form
382 -- (1.4 Report, Section 5.1.1)
384 -- import T hiding( f )
385 -- we delete f from avails
387 unqual_avails | not unqual_imp = [] -- Short cut when no unqualified imports
388 | otherwise = mapMaybe prune avails
390 prune (Avail n) | unqual_in_scope n = Just (Avail n)
391 prune (Avail n) | otherwise = Nothing
392 prune (AvailTC n ns) | null uqs = Nothing
393 | otherwise = Just (AvailTC n uqs)
395 uqs = filter unqual_in_scope ns
397 unqual_in_scope n = unQualInScope gbl_env n
399 entity_avail_env = listToUFM [ (name,avail) | avail <- avails,
400 name <- availNames avail]
402 plusExportAvails :: ExportAvails -> ExportAvails -> ExportAvails
403 plusExportAvails (m1, e1) (m2, e2)
404 = (plusFM_C (++) m1 m2, plusAvailEnv e1 e2)
405 -- ToDo: wasteful: we do this once for each constructor!
409 %************************************************************************
411 \subsection{Export list processing}
413 %************************************************************************
415 Processing the export list.
417 You might think that we should record things that appear in the export list
418 as ``occurrences'' (using @addOccurrenceName@), but you'd be wrong.
419 We do check (here) that they are in scope,
420 but there is no need to slurp in their actual declaration
421 (which is what @addOccurrenceName@ forces).
423 Indeed, doing so would big trouble when
424 compiling @PrelBase@, because it re-exports @GHC@, which includes @takeMVar#@,
425 whose type includes @ConcBase.StateAndSynchVar#@, and so on...
428 type ExportAccum -- The type of the accumulating parameter of
429 -- the main worker function in exportsFromAvail
430 = ([ModuleName], -- 'module M's seen so far
431 ExportOccMap, -- Tracks exported occurrence names
432 AvailEnv) -- The accumulated exported stuff, kept in an env
433 -- so we can common-up related AvailInfos
435 type ExportOccMap = FiniteMap OccName (Name, RdrNameIE)
436 -- Tracks what a particular exported OccName
437 -- in an export list refers to, and which item
438 -- it came from. It's illegal to export two distinct things
439 -- that have the same occurrence name
442 exportsFromAvail :: ModuleName
443 -> Maybe [RdrNameIE] -- Export spec
447 -- Complains if two distinct exports have same OccName
448 -- Warns about identical exports.
449 -- Complains about exports items not in scope
450 exportsFromAvail this_mod Nothing export_avails global_name_env
451 = exportsFromAvail this_mod true_exports export_avails global_name_env
453 true_exports = Just $ if this_mod == mAIN_Name
454 then [IEVar main_RDR_Unqual]
455 -- export Main.main *only* unless otherwise specified,
456 else [IEModuleContents this_mod]
457 -- but for all other modules export everything.
459 exportsFromAvail this_mod (Just export_items)
460 (mod_avail_env, entity_avail_env)
462 = doptRn Opt_WarnDuplicateExports `thenRn` \ warn_dup_exports ->
463 foldlRn (exports_from_item warn_dup_exports)
464 ([], emptyFM, emptyAvailEnv) export_items
465 `thenRn` \ (_, _, export_avail_map) ->
467 export_avails :: [AvailInfo]
468 export_avails = nameEnvElts export_avail_map
470 returnRn export_avails
473 exports_from_item :: Bool -> ExportAccum -> RdrNameIE -> RnMG ExportAccum
475 exports_from_item warn_dups acc@(mods, occs, avails) ie@(IEModuleContents mod)
476 | mod `elem` mods -- Duplicate export of M
477 = warnCheckRn warn_dups (dupModuleExport mod) `thenRn_`
481 = case lookupFM mod_avail_env mod of
482 Nothing -> failWithRn acc (modExportErr mod)
483 Just mod_avails -> foldlRn (check_occs ie) occs mod_avails
486 avails' = foldl addAvail avails mod_avails
488 returnRn (mod:mods, occs', avails')
490 exports_from_item warn_dups acc@(mods, occs, avails) ie
491 = lookupSrcName global_name_env (ieName ie) `thenRn` \ name ->
493 -- See what's available in the current environment
494 case lookupUFM entity_avail_env name of {
495 Nothing -> -- Presumably this happens because lookupSrcName didn't find
496 -- the name and returned an unboundName, which won't be in
497 -- the entity_avail_env, of course
498 WARN( not (isUnboundName name), ppr name )
503 -- Filter out the bits we want
504 case filterAvail ie avail of {
505 Nothing -> -- Not enough availability
506 failWithRn acc (exportItemErr ie) ;
510 -- Phew! It's OK! Now to check the occurrence stuff!
511 warnCheckRn (ok_item ie avail) (dodgyExportWarn ie) `thenRn_`
512 check_occs ie occs export_avail `thenRn` \ occs' ->
513 returnRn (mods, occs', addAvail avails export_avail)
518 ok_item (IEThingAll _) (AvailTC _ [n]) = False
519 -- This occurs when you import T(..), but
520 -- only export T abstractly. The single [n]
521 -- in the AvailTC is the type or class itself
524 check_occs :: RdrNameIE -> ExportOccMap -> AvailInfo -> RnMG ExportOccMap
525 check_occs ie occs avail
526 = doptRn Opt_WarnDuplicateExports `thenRn` \ warn_dup_exports ->
527 foldlRn (check warn_dup_exports) occs (availNames avail)
529 check warn_dup occs name
530 = case lookupFM occs name_occ of
531 Nothing -> returnRn (addToFM occs name_occ (name, ie))
533 | name == name' -> -- Duplicate export
535 (dupExportWarn name_occ ie ie')
536 `thenRn_` returnRn occs
538 | otherwise -> -- Same occ name but different names: an error
539 failWithRn occs (exportClashErr name_occ ie ie')
541 name_occ = nameOccName name
544 %************************************************************************
548 %************************************************************************
551 badImportItemErr mod from ie
552 = sep [ptext SLIT("Module"), quotes (ppr mod), source_import,
553 ptext SLIT("does not export"), quotes (ppr ie)]
555 source_import = case from of
556 ImportByUserSource -> ptext SLIT("(hi-boot interface)")
559 dodgyImportWarn mod item = dodgyMsg (ptext SLIT("import")) item
560 dodgyExportWarn item = dodgyMsg (ptext SLIT("export")) item
562 dodgyMsg kind item@(IEThingAll tc)
563 = sep [ ptext SLIT("The") <+> kind <+> ptext SLIT("item") <+> quotes (ppr item),
564 ptext SLIT("suggests that") <+> quotes (ppr tc) <+> ptext SLIT("has constructor or class methods"),
565 ptext SLIT("but it has none; it is a type synonym or abstract type or class") ]
568 = hsep [ ptext SLIT("Unknown module in export list: module"), quotes (ppr mod)]
570 exportItemErr export_item
571 = sep [ ptext SLIT("The export item") <+> quotes (ppr export_item),
572 ptext SLIT("attempts to export constructors or class methods that are not visible here") ]
574 exportClashErr occ_name ie1 ie2
575 = hsep [ptext SLIT("The export items"), quotes (ppr ie1)
576 ,ptext SLIT("and"), quotes (ppr ie2)
577 ,ptext SLIT("create conflicting exports for"), quotes (ppr occ_name)]
580 = vcat [ptext SLIT("Multiple declarations of") <+> quotes (ppr n),
581 nest 4 (vcat (map ppr sorted_locs))]
583 sorted_locs = sortLt occ'ed_before (map nameSrcLoc (n:ns))
584 occ'ed_before a b = LT == compare a b
586 dupExportWarn occ_name ie1 ie2
587 = hsep [quotes (ppr occ_name),
588 ptext SLIT("is exported by"), quotes (ppr ie1),
589 ptext SLIT("and"), quotes (ppr ie2)]
592 = hsep [ptext SLIT("Duplicate"),
593 quotes (ptext SLIT("Module") <+> ppr mod),
594 ptext SLIT("in export list")]
597 = sep [ ptext SLIT("Module") <+> quotes (ppr mod) <+> ptext SLIT("is deprecated:"),