2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[RnNames]{Extracting imported and top-level names in scope}
8 ExportAvails, getGlobalNames, exportsFromAvail
11 #include "HsVersions.h"
13 import CmdLineOpts ( DynFlag(..) )
15 import HsSyn ( HsModule(..), HsDecl(..), IE(..), ieName, ImportDecl(..),
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, isUnboundName )
29 import Module ( ModuleName, moduleName, WhereFrom(..) )
30 import Name ( Name, nameSrcLoc, nameOccName )
33 import HscTypes ( Provenance(..), ImportReason(..), GlobalRdrEnv,
34 GenAvailInfo(..), AvailInfo, Avails, AvailEnv,
35 Deprecations(..), ModIface(..), emptyAvailEnv
37 import RdrName ( rdrNameOcc, setRdrNameOcc )
38 import OccName ( setOccNameSpace, dataName )
39 import NameSet ( elemNameSet, emptyNameSet )
41 import Maybes ( maybeToBool, catMaybes )
42 import ListSetOps ( removeDups )
43 import Util ( sortLt, notNull )
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 = notNull [ () | (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 $
128 loadInterface (ppr imp_mod_name <+> ptext SLIT("is directly imported"))
129 imp_mod_name from `thenRn` \ iface ->
131 imp_mod = mi_module iface
132 avails_by_module = mi_exports iface
133 deprecs = mi_deprecs iface
136 avails = [ avail | (mod_name, avails) <- avails_by_module,
137 mod_name /= this_mod_name,
139 -- If the module exports anything defined in this module, just ignore it.
140 -- Reason: otherwise it looks as if there are two local definition sites
141 -- for the thing, and an error gets reported. Easiest thing is just to
142 -- filter them out up front. This situation only arises if a module
143 -- imports itself, or another module that imported it. (Necessarily,
144 -- this invoves a loop.)
146 -- Tiresome consequence: if you say
151 -- module B( AType ) where
152 -- import {-# SOURCE #-} A( AType )
154 -- then you'll get a 'B does not export AType' message. Oh well.
157 if null avails_by_module then
158 -- If there's an error in loadInterface, (e.g. interface
159 -- file not found) we get lots of spurious errors from 'filterImports'
160 returnRn (emptyRdrEnv, mkEmptyExportAvails imp_mod_name)
163 -- Complain if we import a deprecated module
164 ifOptRn Opt_WarnDeprecations (
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, 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 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
214 gbl_env = mkGlobalRdrEnv mod_name unqual_imp mk_prov avails NoDeprecs
215 -- NoDeprecs: don't complain about locally defined names
216 -- For a start, we may be exporting a deprecated thing
217 -- Also we may use a deprecated thing in the defn of another
218 -- deprecated things. We may even use a deprecated thing in
219 -- the defn of a non-deprecated thing, when changing a module's
222 exports = mkExportAvails mod_name unqual_imp gbl_env avails
224 returnRn (gbl_env, exports)
226 ---------------------------
227 getLocalDeclBinders :: Module -> RdrNameHsDecl -> RnMG [AvailInfo]
228 getLocalDeclBinders mod (TyClD tycl_decl)
229 = -- For type and class decls, we generate Global names, with
230 -- no export indicator. They need to be global because they get
231 -- permanently bound into the TyCons and Classes. They don't need
232 -- an export indicator because they are all implicitly exported.
233 getTyClDeclBinders mod tycl_decl `thenRn` \ (avail, sys_names) ->
235 -- Record that the system names are available
236 recordLocalSlurps (mkNameSet sys_names) `thenRn_`
239 getLocalDeclBinders mod (ValD binds)
240 = mapRn new (collectLocatedHsBinders binds) `thenRn` \ avails ->
243 new (rdr_name, loc) = newTopBinder mod rdr_name loc `thenRn` \ name ->
244 returnRn (Avail name)
246 getLocalDeclBinders mod (ForD (ForeignImport nm _ _ _ loc))
247 = newTopBinder mod nm loc `thenRn` \ name ->
248 returnRn [Avail name]
249 getLocalDeclBinders mod (ForD _)
252 getLocalDeclBinders mod (FixD _) = returnRn []
253 getLocalDeclBinders mod (DeprecD _) = returnRn []
254 getLocalDeclBinders mod (DefD _) = returnRn []
255 getLocalDeclBinders mod (InstD _) = returnRn []
256 getLocalDeclBinders mod (RuleD _) = returnRn []
260 %************************************************************************
262 \subsection{Filtering imports}
264 %************************************************************************
266 @filterImports@ takes the @ExportEnv@ telling what the imported module makes
267 available, and filters it through the import spec (if any).
270 filterImports :: ModuleName -- The module being imported
271 -> WhereFrom -- Tells whether it's a {-# SOURCE #-} import
272 -> Maybe (Bool, [RdrNameIE]) -- Import spec; True => hiding
273 -> [AvailInfo] -- What's available
274 -> RnMG ([AvailInfo], -- What's imported
275 NameSet) -- What was imported explicitly
277 -- Complains if import spec mentions things that the module doesn't export
278 -- Warns/informs if import spec contains duplicates.
279 filterImports mod from Nothing imports
280 = returnRn (imports, emptyNameSet)
282 filterImports mod from (Just (want_hiding, import_items)) total_avails
283 = flatMapRn get_item import_items `thenRn` \ avails_w_explicits ->
285 (item_avails, explicits_s) = unzip avails_w_explicits
286 explicits = foldl addListToNameSet emptyNameSet explicits_s
289 let -- All imported; item_avails to be hidden
290 hidden = availsToNameSet item_avails
291 keep n = not (n `elemNameSet` hidden)
293 returnRn (pruneAvails keep total_avails, emptyNameSet)
295 -- Just item_avails imported; nothing to be hidden
296 returnRn (item_avails, explicits)
298 import_fm :: FiniteMap OccName AvailInfo
299 import_fm = listToFM [ (nameOccName name, avail)
300 | avail <- total_avails,
301 name <- availNames avail]
302 -- Even though availNames returns data constructors too,
303 -- they won't make any difference because naked entities like T
304 -- in an import list map to TcOccs, not VarOccs.
306 bale_out item = addErrRn (badImportItemErr mod from item) `thenRn_`
309 get_item :: RdrNameIE -> RnMG [(AvailInfo, [Name])]
310 -- Empty list for a bad item.
311 -- Singleton is typical case.
312 -- Can have two when we are hiding, and mention C which might be
313 -- both a class and a data constructor.
314 -- The [Name] is the list of explicitly-mentioned names
315 get_item item@(IEModuleContents _) = bale_out item
317 get_item item@(IEThingAll _)
318 = case check_item item of
319 Nothing -> bale_out item
320 Just avail@(AvailTC _ [n]) -> -- This occurs when you import T(..), but
321 -- only export T abstractly. The single [n]
322 -- in the AvailTC is the type or class itself
323 ifOptRn Opt_WarnMisc (addWarnRn (dodgyImportWarn mod item)) `thenRn_`
324 returnRn [(avail, [availName avail])]
325 Just avail -> returnRn [(avail, [availName avail])]
327 get_item item@(IEThingAbs n)
328 | want_hiding -- hiding( C )
329 -- Here the 'C' can be a data constructor *or* a type/class
330 = case catMaybes [check_item item, check_item (IEVar data_n)] of
332 avails -> returnRn [(a, []) | a <- avails]
333 -- The 'explicits' list is irrelevant when hiding
335 data_n = setRdrNameOcc n (setOccNameSpace (rdrNameOcc n) dataName)
338 = case check_item item of
339 Nothing -> bale_out item
340 Just avail -> returnRn [(avail, availNames avail)]
343 | not (maybeToBool maybe_in_import_avails) ||
344 not (maybeToBool maybe_filtered_avail)
348 = Just filtered_avail
351 wanted_occ = rdrNameOcc (ieName item)
352 maybe_in_import_avails = lookupFM import_fm wanted_occ
354 Just avail = maybe_in_import_avails
355 maybe_filtered_avail = filterAvail item avail
356 Just filtered_avail = maybe_filtered_avail
361 %************************************************************************
363 \subsection{Qualifiying imports}
365 %************************************************************************
369 = (FiniteMap ModuleName Avails,
370 -- Used to figure out "module M" export specifiers
371 -- Includes avails only from *unqualified* imports
372 -- (see 1.4 Report Section 5.1.1)
374 AvailEnv) -- All the things that are available.
375 -- Its domain is all the "main" things;
376 -- i.e. *excluding* class ops and constructors
377 -- (which appear inside their parent AvailTC)
379 mkEmptyExportAvails :: ModuleName -> ExportAvails
380 mkEmptyExportAvails mod_name = (unitFM mod_name [], emptyNameEnv)
382 plusExportAvails :: ExportAvails -> ExportAvails -> ExportAvails
383 plusExportAvails (m1, e1) (m2, e2) = (plusFM_C (++) m1 m2, plusAvailEnv e1 e2)
385 mkExportAvails :: ModuleName -> Bool -> GlobalRdrEnv -> [AvailInfo] -> ExportAvails
386 mkExportAvails mod_name unqual_imp gbl_env avails
387 = (mod_avail_env, entity_avail_env)
389 mod_avail_env = unitFM mod_name unqual_avails
391 -- unqual_avails is the Avails that are visible in *unqualified* form
392 -- We need to know this so we know what to export when we see
393 -- module M ( module P ) where ...
394 -- Then we must export whatever came from P unqualified.
396 unqual_avails | not unqual_imp = [] -- Short cut when no unqualified imports
397 | otherwise = pruneAvails (unQualInScope gbl_env) avails
399 entity_avail_env = foldl insert emptyAvailEnv avails
400 insert env avail = extendNameEnv_C plusAvail env (availName avail) avail
401 -- 'avails' may have several items with the same availName
402 -- E.g import Ix( Ix(..), index )
403 -- will give Ix(Ix,index,range) and Ix(index)
404 -- We want to combine these
408 %************************************************************************
410 \subsection{Export list processing}
412 %************************************************************************
414 Processing the export list.
416 You might think that we should record things that appear in the export list
417 as ``occurrences'' (using @addOccurrenceName@), but you'd be wrong.
418 We do check (here) that they are in scope,
419 but there is no need to slurp in their actual declaration
420 (which is what @addOccurrenceName@ forces).
422 Indeed, doing so would big trouble when
423 compiling @PrelBase@, because it re-exports @GHC@, which includes @takeMVar#@,
424 whose type includes @ConcBase.StateAndSynchVar#@, and so on...
427 type ExportAccum -- The type of the accumulating parameter of
428 -- the main worker function in exportsFromAvail
429 = ([ModuleName], -- 'module M's seen so far
430 ExportOccMap, -- Tracks exported occurrence names
431 AvailEnv) -- The accumulated exported stuff, kept in an env
432 -- so we can common-up related AvailInfos
434 type ExportOccMap = FiniteMap OccName (Name, RdrNameIE)
435 -- Tracks what a particular exported OccName
436 -- in an export list refers to, and which item
437 -- it came from. It's illegal to export two distinct things
438 -- that have the same occurrence name
441 exportsFromAvail :: ModuleName
442 -> Maybe [RdrNameIE] -- Export spec
443 -> FiniteMap ModuleName Avails -- Used for (module M) exports
444 -> NameEnv AvailInfo -- Domain is every in-scope thing
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
451 mod_avail_env entity_avail_env global_name_env
452 = exportsFromAvail this_mod (Just true_exports) mod_avail_env
453 entity_avail_env global_name_env
456 | this_mod == mAIN_Name = []
457 -- Export nothing; Main.$main is automatically exported
458 | otherwise = [IEModuleContents this_mod]
459 -- but for all other modules export everything.
461 exportsFromAvail this_mod (Just export_items)
462 mod_avail_env entity_avail_env global_name_env
463 = doptRn Opt_WarnDuplicateExports `thenRn` \ warn_dup_exports ->
464 foldlRn (exports_from_item warn_dup_exports)
465 ([], emptyFM, emptyAvailEnv) export_items
466 `thenRn` \ (_, _, export_avail_map) ->
468 export_avails :: [AvailInfo]
469 export_avails = nameEnvElts export_avail_map
471 returnRn export_avails
474 exports_from_item :: Bool -> ExportAccum -> RdrNameIE -> RnMG ExportAccum
476 exports_from_item warn_dups acc@(mods, occs, avails) ie@(IEModuleContents mod)
477 | mod `elem` mods -- Duplicate export of M
478 = warnCheckRn warn_dups (dupModuleExport mod) `thenRn_`
482 = case lookupFM mod_avail_env mod of
483 Nothing -> failWithRn acc (modExportErr mod)
484 Just mod_avails -> foldlRn (check_occs ie) occs mod_avails
487 avails' = foldl addAvail avails mod_avails
489 returnRn (mod:mods, occs', avails')
491 exports_from_item warn_dups acc@(mods, occs, avails) ie
492 = lookupSrcName global_name_env (ieName ie) `thenRn` \ name ->
494 -- See what's available in the current environment
495 case lookupNameEnv entity_avail_env name of {
496 Nothing -> -- Presumably this happens because lookupSrcName didn't find
497 -- the name and returned an unboundName, which won't be in
498 -- the entity_avail_env, of course
499 WARN( not (isUnboundName name), ppr name )
504 -- Filter out the bits we want
505 case filterAvail ie avail of {
506 Nothing -> -- Not enough availability
507 failWithRn acc (exportItemErr ie) ;
511 -- Phew! It's OK! Now to check the occurrence stuff!
512 warnCheckRn (ok_item ie avail) (dodgyExportWarn ie) `thenRn_`
513 check_occs ie occs export_avail `thenRn` \ occs' ->
514 returnRn (mods, occs', addAvail avails export_avail)
519 ok_item (IEThingAll _) (AvailTC _ [n]) = False
520 -- This occurs when you import T(..), but
521 -- only export T abstractly. The single [n]
522 -- in the AvailTC is the type or class itself
525 check_occs :: RdrNameIE -> ExportOccMap -> AvailInfo -> RnMG ExportOccMap
526 check_occs ie occs avail
527 = doptRn Opt_WarnDuplicateExports `thenRn` \ warn_dup_exports ->
528 foldlRn (check warn_dup_exports) occs (availNames avail)
530 check warn_dup occs name
531 = case lookupFM occs name_occ of
532 Nothing -> returnRn (addToFM occs name_occ (name, ie))
534 | name == name' -> -- Duplicate export
536 (dupExportWarn name_occ ie ie')
537 `thenRn_` returnRn occs
539 | otherwise -> -- Same occ name but different names: an error
540 failWithRn occs (exportClashErr name_occ ie ie')
542 name_occ = nameOccName name
545 %************************************************************************
549 %************************************************************************
552 badImportItemErr mod from ie
553 = sep [ptext SLIT("Module"), quotes (ppr mod), source_import,
554 ptext SLIT("does not export"), quotes (ppr ie)]
556 source_import = case from of
557 ImportByUserSource -> ptext SLIT("(hi-boot interface)")
560 dodgyImportWarn mod item = dodgyMsg (ptext SLIT("import")) item
561 dodgyExportWarn item = dodgyMsg (ptext SLIT("export")) item
563 dodgyMsg kind item@(IEThingAll tc)
564 = sep [ ptext SLIT("The") <+> kind <+> ptext SLIT("item") <+> quotes (ppr item),
565 ptext SLIT("suggests that") <+> quotes (ppr tc) <+> ptext SLIT("has constructor or class methods"),
566 ptext SLIT("but it has none; it is a type synonym or abstract type or class") ]
569 = hsep [ ptext SLIT("Unknown module in export list: module"), quotes (ppr mod)]
571 exportItemErr export_item
572 = sep [ ptext SLIT("The export item") <+> quotes (ppr export_item),
573 ptext SLIT("attempts to export constructors or class methods that are not visible here") ]
575 exportClashErr occ_name ie1 ie2
576 = hsep [ptext SLIT("The export items"), quotes (ppr ie1)
577 ,ptext SLIT("and"), quotes (ppr ie2)
578 ,ptext SLIT("create conflicting exports for"), quotes (ppr occ_name)]
581 = vcat [ptext SLIT("Multiple declarations of") <+> quotes (ppr n),
582 nest 4 (vcat (map ppr sorted_locs))]
584 sorted_locs = sortLt occ'ed_before (map nameSrcLoc (n:ns))
585 occ'ed_before a b = LT == compare a b
587 dupExportWarn occ_name ie1 ie2
588 = hsep [quotes (ppr occ_name),
589 ptext SLIT("is exported by"), quotes (ppr ie1),
590 ptext SLIT("and"), quotes (ppr ie2)]
593 = hsep [ptext SLIT("Duplicate"),
594 quotes (ptext SLIT("Module") <+> ppr mod),
595 ptext SLIT("in export list")]
598 = sep [ ptext SLIT("Module") <+> quotes (ppr mod) <+> ptext SLIT("is deprecated:"),