2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[RnNames]{Extracting imported and top-level names in scope}
11 #include "HsVersions.h"
13 import CmdLineOpts ( DynFlag(..), opt_NoImplicitPrelude )
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 )
29 import UniqFM ( lookupUFM )
30 import Bag ( bagToList )
31 import Module ( ModuleName, moduleName, WhereFrom(..) )
33 import Name ( Name, nameSrcLoc,
34 setLocalNameSort, nameOccName, nameEnvElts )
35 import HscTypes ( Provenance(..), ImportReason(..), GlobalRdrEnv,
36 GenAvailInfo(..), AvailInfo, Avails, AvailEnv )
37 import RdrName ( RdrName, rdrNameOcc, setRdrNameOcc, mkRdrQual, mkRdrUnqual )
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 Avails, -- The exported stuff
61 AvailEnv) -- Maps a name to its parent AvailInfo
62 -- Just for in-scope things only
64 getGlobalNames this_mod (HsModule _ _ exports imports decls _ mod_loc)
65 = -- These two fix-loops are to get the right
66 -- provenance information into a Name
67 fixRn ( \ ~(rec_gbl_env, _, rec_export_avails, _) ->
70 rec_unqual_fn :: Name -> Bool -- Is this chap in scope unqualified?
71 rec_unqual_fn = unQualInScope rec_gbl_env
73 rec_exp_fn :: Name -> Bool
74 rec_exp_fn = mk_export_fn (availsToNameSet rec_export_avails)
77 -- PROCESS LOCAL DECLS
78 -- Do these *first* so that the correct provenance gets
79 -- into the global name cache.
80 importsFromLocalDecls this_mod rec_exp_fn decls `thenRn` \ (local_gbl_env, local_mod_avails) ->
82 -- PROCESS IMPORT DECLS
83 -- Do the non {- SOURCE -} ones first, so that we get a helpful
84 -- warning for {- SOURCE -} ones that are unnecessary
86 (source, ordinary) = partition is_source_import all_imports
87 is_source_import (ImportDecl _ ImportByUserSource _ _ _ _) = True
88 is_source_import other = False
90 mapAndUnzipRn (importsFromImportDecl rec_unqual_fn) ordinary `thenRn` \ (imp_gbl_envs1, imp_avails_s1) ->
91 mapAndUnzipRn (importsFromImportDecl rec_unqual_fn) source `thenRn` \ (imp_gbl_envs2, imp_avails_s2) ->
94 -- We put the local env second, so that a local provenance
95 -- "wins", even if a module imports itself.
97 gbl_env :: GlobalRdrEnv
98 imp_gbl_env = foldr plusGlobalRdrEnv emptyRdrEnv (imp_gbl_envs2 ++ imp_gbl_envs1)
99 gbl_env = imp_gbl_env `plusGlobalRdrEnv` local_gbl_env
101 all_avails :: ExportAvails
102 all_avails = foldr plusExportAvails local_mod_avails (imp_avails_s2 ++ imp_avails_s1)
104 (_, global_avail_env) = all_avails
107 -- PROCESS EXPORT LIST (but not if we've had errors already)
108 checkErrsRn `thenRn` \ no_errs_so_far ->
109 (if no_errs_so_far then
110 exportsFromAvail this_mod_name exports all_avails gbl_env
113 ) `thenRn` \ export_avails ->
116 returnRn (gbl_env, local_gbl_env, export_avails, global_avail_env)
119 this_mod_name = moduleName this_mod
120 all_imports = prel_imports ++ imports
122 -- NB: opt_NoImplicitPrelude is slightly different to import Prelude ();
123 -- because the former doesn't even look at Prelude.hi for instance declarations,
124 -- whereas the latter does.
125 prel_imports | this_mod_name == pRELUDE_Name ||
126 explicit_prelude_import ||
127 opt_NoImplicitPrelude
130 | otherwise = [ImportDecl pRELUDE_Name
132 False {- Not qualified -}
133 Nothing {- No "as" -}
134 Nothing {- No import list -}
137 explicit_prelude_import
138 = not (null [ () | (ImportDecl mod _ _ _ _ _) <- imports, mod == pRELUDE_Name ])
142 importsFromImportDecl :: (Name -> Bool) -- OK to omit qualifier
144 -> RnMG (GlobalRdrEnv,
147 importsFromImportDecl is_unqual (ImportDecl imp_mod_name from qual_only as_mod import_spec iloc)
148 = pushSrcLocRn iloc $
149 getInterfaceExports imp_mod_name from `thenRn` \ (imp_mod, avails_by_module) ->
151 if null avails_by_module then
152 -- If there's an error in getInterfaceExports, (e.g. interface
153 -- file not found) we get lots of spurious errors from 'filterImports'
154 returnRn (emptyRdrEnv, mkEmptyExportAvails imp_mod_name)
159 avails = concat (map snd avails_by_module)
161 filterImports imp_mod_name import_spec avails `thenRn` \ (filtered_avails, hides, explicits) ->
164 mk_provenance name = NonLocalDef (UserImport imp_mod iloc (name `elemNameSet` explicits))
168 qualifyImports imp_mod_name
169 (not qual_only) -- Maybe want unqualified names
177 importsFromLocalDecls this_mod rec_exp_fn decls
178 = mapRn (getLocalDeclBinders this_mod rec_exp_fn) decls `thenRn` \ avails_s ->
181 avails = concat avails_s
183 all_names :: [Name] -- All the defns; no dups eliminated
184 all_names = [name | avail <- avails, name <- availNames avail]
187 (_, dups) = removeDups compare all_names
189 -- Check for duplicate definitions
190 mapRn_ (addErrRn . dupDeclErr) dups `thenRn_`
192 -- Record that locally-defined things are available
193 recordLocalSlurps avails `thenRn_`
195 -- Build the environment
196 qualifyImports (moduleName this_mod)
197 True -- Want unqualified names
200 (\n -> LocalDef) -- Provenance is local
203 ---------------------------
204 getLocalDeclBinders :: Module
205 -> (Name -> Bool) -- Whether exported
206 -> RdrNameHsDecl -> RnMG Avails
207 getLocalDeclBinders mod rec_exp_fn (TyClD tycl_decl)
208 = -- For type and class decls, we generate Global names, with
209 -- no export indicator. They need to be global because they get
210 -- permanently bound into the TyCons and Classes. They don't need
211 -- an export indicator because they are all implicitly exported.
212 getTyClDeclBinders mod tycl_decl `thenRn` \ avail ->
215 getLocalDeclBinders mod rec_exp_fn (ValD binds)
216 = mapRn (newLocalBinder mod rec_exp_fn)
217 (bagToList (collectTopBinders binds))
219 getLocalDeclBinders mod rec_exp_fn (ForD (ForeignDecl nm kind _ ext_nm _ loc))
220 | binds_haskell_name kind
221 = newLocalBinder mod rec_exp_fn (nm, loc) `thenRn` \ avail ->
224 | otherwise -- a foreign export
225 = lookupOrigName nm `thenRn_`
228 binds_haskell_name (FoImport _) = True
229 binds_haskell_name FoLabel = True
230 binds_haskell_name FoExport = isDynamicExtName ext_nm
232 getLocalDeclBinders mod rec_exp_fn (FixD _) = returnRn []
233 getLocalDeclBinders mod rec_exp_fn (DeprecD _) = returnRn []
234 getLocalDeclBinders mod rec_exp_fn (DefD _) = returnRn []
235 getLocalDeclBinders mod rec_exp_fn (InstD _) = returnRn []
236 getLocalDeclBinders mod rec_exp_fn (RuleD _) = returnRn []
238 ---------------------------
239 newLocalBinder mod rec_exp_fn (rdr_name, loc)
240 = -- Generate a local name, and with a suitable export indicator
241 newTopBinder mod rdr_name loc `thenRn` \ name ->
242 returnRn (Avail (setLocalNameSort name (rec_exp_fn name)))
246 %************************************************************************
248 \subsection{Filtering imports}
250 %************************************************************************
252 @filterImports@ takes the @ExportEnv@ telling what the imported module makes
253 available, and filters it through the import spec (if any).
256 filterImports :: ModuleName -- The module being imported
257 -> Maybe (Bool, [RdrNameIE]) -- Import spec; True => hiding
258 -> [AvailInfo] -- What's available
259 -> RnMG ([AvailInfo], -- What's actually imported
260 [AvailInfo], -- What's to be hidden
261 -- (the unqualified version, that is)
262 -- (We need to return both the above sets, because
263 -- the qualified version is never hidden; so we can't
264 -- implement hiding by reducing what's imported.)
265 NameSet) -- What was imported explicitly
267 -- Complains if import spec mentions things that the module doesn't export
268 -- Warns/informs if import spec contains duplicates.
269 filterImports mod Nothing imports
270 = returnRn (imports, [], emptyNameSet)
272 filterImports mod (Just (want_hiding, import_items)) total_avails
273 = flatMapRn get_item import_items `thenRn` \ avails_w_explicits ->
275 (item_avails, explicits_s) = unzip avails_w_explicits
276 explicits = foldl addListToNameSet emptyNameSet explicits_s
280 -- All imported; item_avails to be hidden
281 returnRn (total_avails, item_avails, emptyNameSet)
283 -- Just item_avails imported; nothing to be hidden
284 returnRn (item_avails, [], explicits)
286 import_fm :: FiniteMap OccName AvailInfo
287 import_fm = listToFM [ (nameOccName name, avail)
288 | avail <- total_avails,
289 name <- availNames avail]
290 -- Even though availNames returns data constructors too,
291 -- they won't make any difference because naked entities like T
292 -- in an import list map to TcOccs, not VarOccs.
294 bale_out item = addErrRn (badImportItemErr mod item) `thenRn_`
297 get_item item@(IEModuleContents _) = bale_out item
299 get_item item@(IEThingAll _)
300 = case check_item item of
301 Nothing -> bale_out item
302 Just avail@(AvailTC _ [n]) -> -- This occurs when you import T(..), but
303 -- only export T abstractly. The single [n]
304 -- in the AvailTC is the type or class itself
305 addWarnRn (dodgyImportWarn mod item) `thenRn_`
306 returnRn [(avail, [availName avail])]
307 Just avail -> returnRn [(avail, [availName avail])]
309 get_item item@(IEThingAbs n)
310 | want_hiding -- hiding( C )
311 -- Here the 'C' can be a data constructor *or* a type/class
312 = case catMaybes [check_item item, check_item (IEThingAbs data_n)] of
314 avails -> returnRn [(a, []) | a <- avails]
315 -- The 'explicits' list is irrelevant when hiding
317 data_n = setRdrNameOcc n (setOccNameSpace (rdrNameOcc n) dataName)
320 = case check_item item of
321 Nothing -> bale_out item
322 Just avail -> returnRn [(avail, availNames avail)]
325 | not (maybeToBool maybe_in_import_avails) ||
326 not (maybeToBool maybe_filtered_avail)
330 = Just filtered_avail
333 wanted_occ = rdrNameOcc (ieName item)
334 maybe_in_import_avails = lookupFM import_fm wanted_occ
336 Just avail = maybe_in_import_avails
337 maybe_filtered_avail = filterAvail item avail
338 Just filtered_avail = maybe_filtered_avail
343 %************************************************************************
345 \subsection{Qualifiying imports}
347 %************************************************************************
349 @qualifyImports@ takes the @ExportEnv@ after filtering through the import spec
350 of an import decl, and deals with producing an @RnEnv@ with the
351 right qualified names. It also turns the @Names@ in the @ExportEnv@ into
352 fully fledged @Names@.
355 qualifyImports :: ModuleName -- Imported module
356 -> Bool -- True <=> want unqualified import
357 -> Maybe ModuleName -- Optional "as M" part
358 -> [AvailInfo] -- What's to be hidden
359 -> (Name -> Provenance)
360 -> Avails -- Whats imported and how
361 -> RnMG (GlobalRdrEnv, ExportAvails)
363 qualifyImports this_mod unqual_imp as_mod hides mk_provenance avails
365 -- Make the name environment. We're talking about a
366 -- single module here, so there must be no name clashes.
367 -- In practice there only ever will be if it's the module
370 -- Add the things that are available
371 name_env1 = foldl add_avail emptyRdrEnv avails
373 -- Delete things that are hidden
374 name_env2 = foldl del_avail name_env1 hides
376 -- Create the export-availability info
377 export_avails = mkExportAvails qual_mod unqual_imp name_env2 avails
379 returnRn (name_env2, export_avails)
382 qual_mod = case as_mod of
384 Just another_name -> another_name
386 add_avail :: GlobalRdrEnv -> AvailInfo -> GlobalRdrEnv
387 add_avail env avail = foldl add_name env (availNames avail)
393 env1 = addOneToGlobalRdrEnv env (mkRdrQual qual_mod occ) (name,prov)
394 env2 = addOneToGlobalRdrEnv env1 (mkRdrUnqual occ) (name,prov)
395 occ = nameOccName name
396 prov = mk_provenance name
398 del_avail env avail = foldl delOneFromGlobalRdrEnv env rdr_names
400 rdr_names = map (mkRdrUnqual . nameOccName) (availNames avail)
403 mkEmptyExportAvails :: ModuleName -> ExportAvails
404 mkEmptyExportAvails mod_name = (unitFM mod_name [], emptyUFM)
406 mkExportAvails :: ModuleName -> Bool -> GlobalRdrEnv -> [AvailInfo] -> ExportAvails
407 mkExportAvails mod_name unqual_imp name_env avails
408 = (mod_avail_env, entity_avail_env)
410 mod_avail_env = unitFM mod_name unqual_avails
412 -- unqual_avails is the Avails that are visible in *unqualfied* form
413 -- (1.4 Report, Section 5.1.1)
415 -- import T hiding( f )
416 -- we delete f from avails
418 unqual_avails | not unqual_imp = [] -- Short cut when no unqualified imports
419 | otherwise = mapMaybe prune avails
421 prune (Avail n) | unqual_in_scope n = Just (Avail n)
422 prune (Avail n) | otherwise = Nothing
423 prune (AvailTC n ns) | null uqs = Nothing
424 | otherwise = Just (AvailTC n uqs)
426 uqs = filter unqual_in_scope ns
428 unqual_in_scope n = unQualInScope name_env n
430 entity_avail_env = listToUFM [ (name,avail) | avail <- avails,
431 name <- availNames avail]
433 plusExportAvails :: ExportAvails -> ExportAvails -> ExportAvails
434 plusExportAvails (m1, e1) (m2, e2)
435 = (plusFM_C (++) m1 m2, plusAvailEnv e1 e2)
436 -- ToDo: wasteful: we do this once for each constructor!
440 %************************************************************************
442 \subsection{Export list processing}
444 %************************************************************************
446 Processing the export list.
448 You might think that we should record things that appear in the export list
449 as ``occurrences'' (using @addOccurrenceName@), but you'd be wrong.
450 We do check (here) that they are in scope,
451 but there is no need to slurp in their actual declaration
452 (which is what @addOccurrenceName@ forces).
454 Indeed, doing so would big trouble when
455 compiling @PrelBase@, because it re-exports @GHC@, which includes @takeMVar#@,
456 whose type includes @ConcBase.StateAndSynchVar#@, and so on...
459 type ExportAccum -- The type of the accumulating parameter of
460 -- the main worker function in exportsFromAvail
461 = ([ModuleName], -- 'module M's seen so far
462 ExportOccMap, -- Tracks exported occurrence names
463 AvailEnv) -- The accumulated exported stuff, kept in an env
464 -- so we can common-up related AvailInfos
466 type ExportOccMap = FiniteMap OccName (Name, RdrNameIE)
467 -- Tracks what a particular exported OccName
468 -- in an export list refers to, and which item
469 -- it came from. It's illegal to export two distinct things
470 -- that have the same occurrence name
473 exportsFromAvail :: ModuleName
474 -> Maybe [RdrNameIE] -- Export spec
478 -- Complains if two distinct exports have same OccName
479 -- Warns about identical exports.
480 -- Complains about exports items not in scope
481 exportsFromAvail this_mod Nothing export_avails global_name_env
482 = exportsFromAvail this_mod true_exports export_avails global_name_env
484 true_exports = Just $ if this_mod == mAIN_Name
485 then [IEVar main_RDR]
486 -- export Main.main *only* unless otherwise specified,
487 else [IEModuleContents this_mod]
488 -- but for all other modules export everything.
490 exportsFromAvail this_mod (Just export_items)
491 (mod_avail_env, entity_avail_env)
493 = doptRn Opt_WarnDuplicateExports `thenRn` \ warn_dup_exports ->
494 foldlRn (exports_from_item warn_dup_exports)
495 ([], emptyFM, emptyAvailEnv) export_items
496 `thenRn` \ (_, _, export_avail_map) ->
498 export_avails :: [AvailInfo]
499 export_avails = nameEnvElts export_avail_map
501 returnRn export_avails
504 exports_from_item :: Bool -> ExportAccum -> RdrNameIE -> RnMG ExportAccum
506 exports_from_item warn_dups acc@(mods, occs, avails) ie@(IEModuleContents mod)
507 | mod `elem` mods -- Duplicate export of M
508 = warnCheckRn warn_dups (dupModuleExport mod) `thenRn_`
512 = case lookupFM mod_avail_env mod of
513 Nothing -> failWithRn acc (modExportErr mod)
514 Just mod_avails -> foldlRn (check_occs ie) occs mod_avails
517 avails' = foldl addAvail avails mod_avails
519 returnRn (mod:mods, occs', avails')
521 exports_from_item warn_dups acc@(mods, occs, avails) ie
522 | not (maybeToBool maybe_in_scope)
523 = failWithRn acc (unknownNameErr (ieName ie))
525 | not (null dup_names)
526 = addNameClashErrRn rdr_name ((name,prov):dup_names) `thenRn_`
530 -- I can't see why this should ever happen; if the thing is in scope
531 -- at all it ought to have some availability
532 | not (maybeToBool maybe_avail)
533 = pprTrace "exportsFromAvail: curious Nothing:" (ppr name)
538 = failWithRn acc (exportItemErr ie)
540 | otherwise -- Phew! It's OK! Now to check the occurrence stuff!
543 = warnCheckRn (ok_item ie avail) (dodgyExportWarn ie) `thenRn_`
544 check_occs ie occs export_avail `thenRn` \ occs' ->
545 returnRn (mods, occs', addAvail avails export_avail)
549 maybe_in_scope = lookupFM global_name_env rdr_name
550 Just ((name,prov):dup_names) = maybe_in_scope
551 maybe_avail = lookupUFM entity_avail_env name
552 Just avail = maybe_avail
553 maybe_export_avail = filterAvail ie avail
554 enough_avail = maybeToBool maybe_export_avail
555 Just export_avail = maybe_export_avail
557 ok_item (IEThingAll _) (AvailTC _ [n]) = False
558 -- This occurs when you import T(..), but
559 -- only export T abstractly. The single [n]
560 -- in the AvailTC is the type or class itself
563 check_occs :: RdrNameIE -> ExportOccMap -> AvailInfo -> RnMG ExportOccMap
564 check_occs ie occs avail
565 = doptRn Opt_WarnDuplicateExports `thenRn` \ warn_dup_exports ->
566 foldlRn (check warn_dup_exports) occs (availNames avail)
568 check warn_dup occs name
569 = case lookupFM occs name_occ of
570 Nothing -> returnRn (addToFM occs name_occ (name, ie))
572 | name == name' -> -- Duplicate export
574 (dupExportWarn name_occ ie ie')
575 `thenRn_` returnRn occs
577 | otherwise -> -- Same occ name but different names: an error
578 failWithRn occs (exportClashErr name_occ ie ie')
580 name_occ = nameOccName name
582 mk_export_fn :: NameSet -> (Name -> Bool) -- True => exported
583 mk_export_fn exported_names = \name -> name `elemNameSet` exported_names
586 %************************************************************************
590 %************************************************************************
593 badImportItemErr mod ie
594 = sep [ptext SLIT("Module"), quotes (ppr mod),
595 ptext SLIT("does not export"), quotes (ppr ie)]
597 dodgyImportWarn mod item = dodgyMsg (ptext SLIT("import")) item
598 dodgyExportWarn item = dodgyMsg (ptext SLIT("export")) item
600 dodgyMsg kind item@(IEThingAll tc)
601 = sep [ ptext SLIT("The") <+> kind <+> ptext SLIT("item") <+> quotes (ppr item),
602 ptext SLIT("suggests that") <+> quotes (ppr tc) <+> ptext SLIT("has constructor or class methods"),
603 ptext SLIT("but it has none; it is a type synonym or abstract type or class") ]
606 = hsep [ ptext SLIT("Unknown module in export list: module"), quotes (ppr mod)]
608 exportItemErr export_item
609 = sep [ ptext SLIT("The export item") <+> quotes (ppr export_item),
610 ptext SLIT("attempts to export constructors or class methods that are not visible here") ]
612 exportClashErr occ_name ie1 ie2
613 = hsep [ptext SLIT("The export items"), quotes (ppr ie1)
614 ,ptext SLIT("and"), quotes (ppr ie2)
615 ,ptext SLIT("create conflicting exports for"), quotes (ppr occ_name)]
618 = vcat [ptext SLIT("Multiple declarations of") <+> quotes (ppr n),
619 nest 4 (vcat (map ppr sorted_locs))]
621 sorted_locs = sortLt occ'ed_before (map nameSrcLoc (n:ns))
622 occ'ed_before a b = LT == compare a b
624 dupExportWarn occ_name ie1 ie2
625 = hsep [quotes (ppr occ_name),
626 ptext SLIT("is exported by"), quotes (ppr ie1),
627 ptext SLIT("and"), quotes (ppr ie2)]
630 = hsep [ptext SLIT("Duplicate"),
631 quotes (ptext SLIT("Module") <+> ppr mod),
632 ptext SLIT("in export list")]