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, mkModuleInThisPackage, 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, isUnqual )
38 import OccName ( setOccNameSpace, dataName )
39 import NameSet ( elemNameSet, emptyNameSet )
40 import SrcLoc ( SrcLoc )
42 import Maybes ( maybeToBool, catMaybes, mapMaybe )
43 import UniqFM ( emptyUFM, listToUFM )
44 import ListSetOps ( removeDups )
45 import Util ( sortLt )
46 import List ( partition )
51 %************************************************************************
53 \subsection{Get global names}
55 %************************************************************************
58 getGlobalNames :: RdrNameHsModule
59 -> RnMG (Maybe (GlobalRdrEnv, -- Maps all in-scope things
60 GlobalRdrEnv, -- Maps just *local* things
61 Avails, -- The exported stuff
62 AvailEnv -- Maps a name to its parent AvailInfo
63 -- Just for in-scope things only
65 -- Nothing => no need to recompile
67 getGlobalNames (HsModule this_mod _ exports imports decls _ mod_loc)
68 = -- These two fix-loops are to get the right
69 -- provenance information into a Name
70 fixRn ( \ ~(Just (rec_gbl_env, _, rec_export_avails, _)) ->
73 rec_unqual_fn :: Name -> Bool -- Is this chap in scope unqualified?
74 rec_unqual_fn = unQualInScope rec_gbl_env
76 rec_exp_fn :: Name -> Bool
77 rec_exp_fn = mk_export_fn (availsToNameSet rec_export_avails)
80 -- PROCESS LOCAL DECLS
81 -- Do these *first* so that the correct provenance gets
82 -- into the global name cache.
83 importsFromLocalDecls this_mod rec_exp_fn decls
84 `thenRn` \ (local_gbl_env, local_mod_avails) ->
86 -- PROCESS IMPORT DECLS
87 -- Do the non {- SOURCE -} ones first, so that we get a helpful
88 -- warning for {- SOURCE -} ones that are unnecessary
90 (source, ordinary) = partition is_source_import all_imports
91 is_source_import (ImportDecl _ ImportByUserSource _ _ _ _) = True
92 is_source_import other = False
94 mapAndUnzipRn (importsFromImportDecl rec_unqual_fn) ordinary
95 `thenRn` \ (imp_gbl_envs1, imp_avails_s1) ->
96 mapAndUnzipRn (importsFromImportDecl rec_unqual_fn) source
97 `thenRn` \ (imp_gbl_envs2, imp_avails_s2) ->
100 -- We put the local env second, so that a local provenance
101 -- "wins", even if a module imports itself.
103 gbl_env :: GlobalRdrEnv
104 imp_gbl_env = foldr plusGlobalRdrEnv emptyRdrEnv (imp_gbl_envs2 ++ imp_gbl_envs1)
105 gbl_env = imp_gbl_env `plusGlobalRdrEnv` local_gbl_env
107 all_avails :: ExportAvails
108 all_avails = foldr plusExportAvails local_mod_avails (imp_avails_s2 ++ imp_avails_s1)
109 (_, global_avail_env) = all_avails
112 -- TRY FOR EARLY EXIT
113 -- We can't go for an early exit before this because we have to check
114 -- for name clashes. Consider:
116 -- module A where module B where
120 -- Suppose I've compiled everything up, and then I add a
121 -- new definition to module B, that defines "f".
123 -- Then I must detect the name clash in A before going for an early
124 -- exit. The early-exit code checks what's actually needed from B
125 -- to compile A, and of course that doesn't include B.f. That's
126 -- why we wait till after the plusEnv stuff to do the early-exit.
128 -- Check For early exit
129 checkErrsRn `thenRn` \ no_errs_so_far ->
130 if not no_errs_so_far then
131 -- Found errors already, so exit now
135 -- PROCESS EXPORT LISTS
136 exportsFromAvail this_mod exports all_avails gbl_env `thenRn` \ export_avails ->
140 returnRn (Just (gbl_env, local_gbl_env, export_avails, global_avail_env))
143 all_imports = prel_imports ++ imports
145 -- NB: opt_NoImplicitPrelude is slightly different to import Prelude ();
146 -- because the former doesn't even look at Prelude.hi for instance declarations,
147 -- whereas the latter does.
148 prel_imports | this_mod == pRELUDE_Name ||
149 explicit_prelude_import ||
150 opt_NoImplicitPrelude
153 | otherwise = [ImportDecl pRELUDE_Name
155 False {- Not qualified -}
156 Nothing {- No "as" -}
157 Nothing {- No import list -}
160 explicit_prelude_import
161 = not (null [ () | (ImportDecl mod _ _ _ _ _) <- imports, mod == pRELUDE_Name ])
165 importsFromImportDecl :: (Name -> Bool) -- OK to omit qualifier
167 -> RnMG (GlobalRdrEnv,
170 importsFromImportDecl is_unqual (ImportDecl imp_mod_name from qual_only as_mod import_spec iloc)
171 = pushSrcLocRn iloc $
172 getInterfaceExports imp_mod_name from `thenRn` \ (imp_mod, avails_by_module) ->
174 if null avails_by_module then
175 -- If there's an error in getInterfaceExports, (e.g. interface
176 -- file not found) we get lots of spurious errors from 'filterImports'
177 returnRn (emptyRdrEnv, mkEmptyExportAvails imp_mod_name)
182 avails = concat (map snd avails_by_module)
184 filterImports imp_mod_name import_spec avails `thenRn` \ (filtered_avails, hides, explicits) ->
187 mk_provenance name = NonLocalDef (UserImport imp_mod iloc (name `elemNameSet` explicits))
191 qualifyImports imp_mod_name
192 (not qual_only) -- Maybe want unqualified names
200 importsFromLocalDecls mod_name rec_exp_fn decls
201 = mapRn (getLocalDeclBinders (newLocalName mod rec_exp_fn)) decls `thenRn` \ avails_s ->
204 avails = concat avails_s
206 all_names :: [Name] -- All the defns; no dups eliminated
207 all_names = [name | avail <- avails, name <- availNames avail]
210 (_, dups) = removeDups compare all_names
212 -- Check for duplicate definitions
213 mapRn_ (addErrRn . dupDeclErr) dups `thenRn_`
215 -- Record that locally-defined things are available
216 recordLocalSlurps avails `thenRn_`
218 -- Build the environment
219 qualifyImports mod_name
220 True -- Want unqualified names
223 (\n -> LocalDef) -- Provenance is local
226 mod = mkModuleInThisPackage mod_name
228 ---------------------------
229 getLocalDeclBinders :: (RdrName -> SrcLoc -> RnMG Name)
230 -> RdrNameHsDecl -> RnMG Avails
231 getLocalDeclBinders new_name (ValD binds)
232 = mapRn do_one (bagToList (collectTopBinders binds))
234 do_one (rdr_name, loc) = new_name rdr_name loc `thenRn` \ name ->
235 returnRn (Avail name)
237 getLocalDeclBinders new_name (TyClD tycl_decl)
238 = getTyClDeclBinders new_name tycl_decl `thenRn` \ avail ->
241 getLocalDeclBinders new_name (ForD (ForeignDecl nm kind _ ext_nm _ loc))
242 | binds_haskell_name kind
243 = new_name nm loc `thenRn` \ name ->
244 returnRn [Avail name]
246 | otherwise -- a foreign export
247 = lookupOrigName nm `thenRn_`
250 binds_haskell_name (FoImport _) = True
251 binds_haskell_name FoLabel = True
252 binds_haskell_name FoExport = isDynamicExtName ext_nm
254 getLocalDeclBinders new_name (FixD _) = returnRn []
255 getLocalDeclBinders new_name (DeprecD _) = returnRn []
256 getLocalDeclBinders new_name (DefD _) = returnRn []
257 getLocalDeclBinders new_name (InstD _) = returnRn []
258 getLocalDeclBinders new_name (RuleD _) = returnRn []
261 ---------------------------
262 newLocalName mod rec_exp_fn rdr_name loc
263 = check_unqual rdr_name loc `thenRn_`
264 newTopBinder mod rdr_name loc `thenRn` \ name ->
265 returnRn (setLocalNameSort name (rec_exp_fn name))
267 -- There should never be a qualified name in a binding position (except in instance decls)
268 -- The parser doesn't check this because the same parser parses instance decls
269 check_unqual rdr_name loc
270 | isUnqual rdr_name = returnRn ()
271 | otherwise = qualNameErr (text "the binding for" <+> quotes (ppr rdr_name))
276 %************************************************************************
278 \subsection{Filtering imports}
280 %************************************************************************
282 @filterImports@ takes the @ExportEnv@ telling what the imported module makes
283 available, and filters it through the import spec (if any).
286 filterImports :: ModuleName -- The module being imported
287 -> Maybe (Bool, [RdrNameIE]) -- Import spec; True => hiding
288 -> [AvailInfo] -- What's available
289 -> RnMG ([AvailInfo], -- What's actually imported
290 [AvailInfo], -- What's to be hidden
291 -- (the unqualified version, that is)
292 -- (We need to return both the above sets, because
293 -- the qualified version is never hidden; so we can't
294 -- implement hiding by reducing what's imported.)
295 NameSet) -- What was imported explicitly
297 -- Complains if import spec mentions things that the module doesn't export
298 -- Warns/informs if import spec contains duplicates.
299 filterImports mod Nothing imports
300 = returnRn (imports, [], emptyNameSet)
302 filterImports mod (Just (want_hiding, import_items)) total_avails
303 = flatMapRn get_item import_items `thenRn` \ avails_w_explicits ->
305 (item_avails, explicits_s) = unzip avails_w_explicits
306 explicits = foldl addListToNameSet emptyNameSet explicits_s
310 -- All imported; item_avails to be hidden
311 returnRn (total_avails, item_avails, emptyNameSet)
313 -- Just item_avails imported; nothing to be hidden
314 returnRn (item_avails, [], explicits)
316 import_fm :: FiniteMap OccName AvailInfo
317 import_fm = listToFM [ (nameOccName name, avail)
318 | avail <- total_avails,
319 name <- availNames avail]
320 -- Even though availNames returns data constructors too,
321 -- they won't make any difference because naked entities like T
322 -- in an import list map to TcOccs, not VarOccs.
324 bale_out item = addErrRn (badImportItemErr mod item) `thenRn_`
327 get_item item@(IEModuleContents _) = bale_out item
329 get_item item@(IEThingAll _)
330 = case check_item item of
331 Nothing -> bale_out item
332 Just avail@(AvailTC _ [n]) -> -- This occurs when you import T(..), but
333 -- only export T abstractly. The single [n]
334 -- in the AvailTC is the type or class itself
335 addWarnRn (dodgyImportWarn mod item) `thenRn_`
336 returnRn [(avail, [availName avail])]
337 Just avail -> returnRn [(avail, [availName avail])]
339 get_item item@(IEThingAbs n)
340 | want_hiding -- hiding( C )
341 -- Here the 'C' can be a data constructor *or* a type/class
342 = case catMaybes [check_item item, check_item (IEThingAbs data_n)] of
344 avails -> returnRn [(a, []) | a <- avails]
345 -- The 'explicits' list is irrelevant when hiding
347 data_n = setRdrNameOcc n (setOccNameSpace (rdrNameOcc n) dataName)
350 = case check_item item of
351 Nothing -> bale_out item
352 Just avail -> returnRn [(avail, availNames avail)]
355 | not (maybeToBool maybe_in_import_avails) ||
356 not (maybeToBool maybe_filtered_avail)
360 = Just filtered_avail
363 wanted_occ = rdrNameOcc (ieName item)
364 maybe_in_import_avails = lookupFM import_fm wanted_occ
366 Just avail = maybe_in_import_avails
367 maybe_filtered_avail = filterAvail item avail
368 Just filtered_avail = maybe_filtered_avail
373 %************************************************************************
375 \subsection{Qualifiying imports}
377 %************************************************************************
379 @qualifyImports@ takes the @ExportEnv@ after filtering through the import spec
380 of an import decl, and deals with producing an @RnEnv@ with the
381 right qualified names. It also turns the @Names@ in the @ExportEnv@ into
382 fully fledged @Names@.
385 qualifyImports :: ModuleName -- Imported module
386 -> Bool -- True <=> want unqualified import
387 -> Maybe ModuleName -- Optional "as M" part
388 -> [AvailInfo] -- What's to be hidden
389 -> (Name -> Provenance)
390 -> Avails -- Whats imported and how
391 -> RnMG (GlobalRdrEnv, ExportAvails)
393 qualifyImports this_mod unqual_imp as_mod hides mk_provenance avails
395 -- Make the name environment. We're talking about a
396 -- single module here, so there must be no name clashes.
397 -- In practice there only ever will be if it's the module
400 -- Add the things that are available
401 name_env1 = foldl add_avail emptyRdrEnv avails
403 -- Delete things that are hidden
404 name_env2 = foldl del_avail name_env1 hides
406 -- Create the export-availability info
407 export_avails = mkExportAvails qual_mod unqual_imp name_env2 avails
409 returnRn (name_env2, export_avails)
412 qual_mod = case as_mod of
414 Just another_name -> another_name
416 add_avail :: GlobalRdrEnv -> AvailInfo -> GlobalRdrEnv
417 add_avail env avail = foldl add_name env (availNames avail)
423 env1 = addOneToGlobalRdrEnv env (mkRdrQual qual_mod occ) (name,prov)
424 env2 = addOneToGlobalRdrEnv env1 (mkRdrUnqual occ) (name,prov)
425 occ = nameOccName name
426 prov = mk_provenance name
428 del_avail env avail = foldl delOneFromGlobalRdrEnv env rdr_names
430 rdr_names = map (mkRdrUnqual . nameOccName) (availNames avail)
433 mkEmptyExportAvails :: ModuleName -> ExportAvails
434 mkEmptyExportAvails mod_name = (unitFM mod_name [], emptyUFM)
436 mkExportAvails :: ModuleName -> Bool -> GlobalRdrEnv -> [AvailInfo] -> ExportAvails
437 mkExportAvails mod_name unqual_imp name_env avails
438 = (mod_avail_env, entity_avail_env)
440 mod_avail_env = unitFM mod_name unqual_avails
442 -- unqual_avails is the Avails that are visible in *unqualfied* form
443 -- (1.4 Report, Section 5.1.1)
445 -- import T hiding( f )
446 -- we delete f from avails
448 unqual_avails | not unqual_imp = [] -- Short cut when no unqualified imports
449 | otherwise = mapMaybe prune avails
451 prune (Avail n) | unqual_in_scope n = Just (Avail n)
452 prune (Avail n) | otherwise = Nothing
453 prune (AvailTC n ns) | null uqs = Nothing
454 | otherwise = Just (AvailTC n uqs)
456 uqs = filter unqual_in_scope ns
458 unqual_in_scope n = unQualInScope name_env n
460 entity_avail_env = listToUFM [ (name,avail) | avail <- avails,
461 name <- availNames avail]
463 plusExportAvails :: ExportAvails -> ExportAvails -> ExportAvails
464 plusExportAvails (m1, e1) (m2, e2)
465 = (plusFM_C (++) m1 m2, plusAvailEnv e1 e2)
466 -- ToDo: wasteful: we do this once for each constructor!
470 %************************************************************************
472 \subsection{Export list processing}
474 %************************************************************************
476 Processing the export list.
478 You might think that we should record things that appear in the export list
479 as ``occurrences'' (using @addOccurrenceName@), but you'd be wrong.
480 We do check (here) that they are in scope,
481 but there is no need to slurp in their actual declaration
482 (which is what @addOccurrenceName@ forces).
484 Indeed, doing so would big trouble when
485 compiling @PrelBase@, because it re-exports @GHC@, which includes @takeMVar#@,
486 whose type includes @ConcBase.StateAndSynchVar#@, and so on...
489 type ExportAccum -- The type of the accumulating parameter of
490 -- the main worker function in exportsFromAvail
491 = ([ModuleName], -- 'module M's seen so far
492 ExportOccMap, -- Tracks exported occurrence names
493 AvailEnv) -- The accumulated exported stuff, kept in an env
494 -- so we can common-up related AvailInfos
496 type ExportOccMap = FiniteMap OccName (Name, RdrNameIE)
497 -- Tracks what a particular exported OccName
498 -- in an export list refers to, and which item
499 -- it came from. It's illegal to export two distinct things
500 -- that have the same occurrence name
503 exportsFromAvail :: ModuleName
504 -> Maybe [RdrNameIE] -- Export spec
508 -- Complains if two distinct exports have same OccName
509 -- Warns about identical exports.
510 -- Complains about exports items not in scope
511 exportsFromAvail this_mod Nothing export_avails global_name_env
512 = exportsFromAvail this_mod true_exports export_avails global_name_env
514 true_exports = Just $ if this_mod == mAIN_Name
515 then [IEVar main_RDR]
516 -- export Main.main *only* unless otherwise specified,
517 else [IEModuleContents this_mod]
518 -- but for all other modules export everything.
520 exportsFromAvail this_mod (Just export_items)
521 (mod_avail_env, entity_avail_env)
523 = doptRn Opt_WarnDuplicateExports `thenRn` \ warn_dup_exports ->
524 foldlRn (exports_from_item warn_dup_exports)
525 ([], emptyFM, emptyAvailEnv) export_items
526 `thenRn` \ (_, _, export_avail_map) ->
528 export_avails :: [AvailInfo]
529 export_avails = nameEnvElts export_avail_map
531 returnRn export_avails
534 exports_from_item :: Bool -> ExportAccum -> RdrNameIE -> RnMG ExportAccum
536 exports_from_item warn_dups acc@(mods, occs, avails) ie@(IEModuleContents mod)
537 | mod `elem` mods -- Duplicate export of M
538 = warnCheckRn warn_dups (dupModuleExport mod) `thenRn_`
542 = case lookupFM mod_avail_env mod of
543 Nothing -> failWithRn acc (modExportErr mod)
544 Just mod_avails -> foldlRn (check_occs ie) occs mod_avails
547 avails' = foldl addAvail avails mod_avails
549 returnRn (mod:mods, occs', avails')
551 exports_from_item warn_dups acc@(mods, occs, avails) ie
552 | not (maybeToBool maybe_in_scope)
553 = failWithRn acc (unknownNameErr (ieName ie))
555 | not (null dup_names)
556 = addNameClashErrRn rdr_name ((name,prov):dup_names) `thenRn_`
560 -- I can't see why this should ever happen; if the thing is in scope
561 -- at all it ought to have some availability
562 | not (maybeToBool maybe_avail)
563 = pprTrace "exportsFromAvail: curious Nothing:" (ppr name)
568 = failWithRn acc (exportItemErr ie)
570 | otherwise -- Phew! It's OK! Now to check the occurrence stuff!
573 = warnCheckRn (ok_item ie avail) (dodgyExportWarn ie) `thenRn_`
574 check_occs ie occs export_avail `thenRn` \ occs' ->
575 returnRn (mods, occs', addAvail avails export_avail)
579 maybe_in_scope = lookupFM global_name_env rdr_name
580 Just ((name,prov):dup_names) = maybe_in_scope
581 maybe_avail = lookupUFM entity_avail_env name
582 Just avail = maybe_avail
583 maybe_export_avail = filterAvail ie avail
584 enough_avail = maybeToBool maybe_export_avail
585 Just export_avail = maybe_export_avail
587 ok_item (IEThingAll _) (AvailTC _ [n]) = False
588 -- This occurs when you import T(..), but
589 -- only export T abstractly. The single [n]
590 -- in the AvailTC is the type or class itself
593 check_occs :: RdrNameIE -> ExportOccMap -> AvailInfo -> RnMG ExportOccMap
594 check_occs ie occs avail
595 = doptRn Opt_WarnDuplicateExports `thenRn` \ warn_dup_exports ->
596 foldlRn (check warn_dup_exports) occs (availNames avail)
598 check warn_dup occs name
599 = case lookupFM occs name_occ of
600 Nothing -> returnRn (addToFM occs name_occ (name, ie))
602 | name == name' -> -- Duplicate export
604 (dupExportWarn name_occ ie ie')
605 `thenRn_` returnRn occs
607 | otherwise -> -- Same occ name but different names: an error
608 failWithRn occs (exportClashErr name_occ ie ie')
610 name_occ = nameOccName name
612 mk_export_fn :: NameSet -> (Name -> Bool) -- True => exported
613 mk_export_fn exported_names = \name -> name `elemNameSet` exported_names
616 %************************************************************************
620 %************************************************************************
623 badImportItemErr mod ie
624 = sep [ptext SLIT("Module"), quotes (ppr mod),
625 ptext SLIT("does not export"), quotes (ppr ie)]
627 dodgyImportWarn mod item = dodgyMsg (ptext SLIT("import")) item
628 dodgyExportWarn item = dodgyMsg (ptext SLIT("export")) item
630 dodgyMsg kind item@(IEThingAll tc)
631 = sep [ ptext SLIT("The") <+> kind <+> ptext SLIT("item") <+> quotes (ppr item),
632 ptext SLIT("suggests that") <+> quotes (ppr tc) <+> ptext SLIT("has constructor or class methods"),
633 ptext SLIT("but it has none; it is a type synonym or abstract type or class") ]
636 = hsep [ ptext SLIT("Unknown module in export list: module"), quotes (ppr mod)]
638 exportItemErr export_item
639 = sep [ ptext SLIT("The export item") <+> quotes (ppr export_item),
640 ptext SLIT("attempts to export constructors or class methods that are not visible here") ]
642 exportClashErr occ_name ie1 ie2
643 = hsep [ptext SLIT("The export items"), quotes (ppr ie1)
644 ,ptext SLIT("and"), quotes (ppr ie2)
645 ,ptext SLIT("create conflicting exports for"), quotes (ppr occ_name)]
648 = vcat [ptext SLIT("Multiple declarations of") <+> quotes (ppr n),
649 nest 4 (vcat (map ppr sorted_locs))]
651 sorted_locs = sortLt occ'ed_before (map nameSrcLoc (n:ns))
652 occ'ed_before a b = LT == compare a b
654 dupExportWarn occ_name ie1 ie2
655 = hsep [quotes (ppr occ_name),
656 ptext SLIT("is exported by"), quotes (ppr ie1),
657 ptext SLIT("and"), quotes (ppr ie2)]
660 = hsep [ptext SLIT("Duplicate"),
661 quotes (ptext SLIT("Module") <+> ppr mod),
662 ptext SLIT("in export list")]