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) ->
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)
180 filterImports imp_mod_name import_spec avails `thenRn` \ (filtered_avails, hides, explicits) ->
183 mk_provenance name = NonLocalDef (UserImport imp_mod iloc (name `elemNameSet` explicits))
187 qualifyImports imp_mod_name
188 (not qual_only) -- Maybe want unqualified names
196 importsFromLocalDecls mod_name rec_exp_fn decls
197 = mapRn (getLocalDeclBinders (newLocalName mod rec_exp_fn)) decls `thenRn` \ avails_s ->
200 avails = concat avails_s
202 all_names :: [Name] -- All the defns; no dups eliminated
203 all_names = [name | avail <- avails, name <- availNames avail]
206 (_, dups) = removeDups compare all_names
208 -- Check for duplicate definitions
209 mapRn_ (addErrRn . dupDeclErr) dups `thenRn_`
211 -- Record that locally-defined things are available
212 recordLocalSlurps avails `thenRn_`
214 -- Build the environment
215 qualifyImports mod_name
216 True -- Want unqualified names
219 (\n -> LocalDef) -- Provenance is local
222 mod = mkModuleInThisPackage mod_name
224 ---------------------------
225 getLocalDeclBinders :: (RdrName -> SrcLoc -> RnMG Name)
226 -> RdrNameHsDecl -> RnMG Avails
227 getLocalDeclBinders new_name (ValD binds)
228 = mapRn do_one (bagToList (collectTopBinders binds))
230 do_one (rdr_name, loc) = new_name rdr_name loc `thenRn` \ name ->
231 returnRn (Avail name)
233 getLocalDeclBinders new_name (TyClD tycl_decl)
234 = getTyClDeclBinders new_name tycl_decl `thenRn` \ avail ->
237 getLocalDeclBinders new_name (ForD (ForeignDecl nm kind _ ext_nm _ loc))
238 | binds_haskell_name kind
239 = new_name nm loc `thenRn` \ name ->
240 returnRn [Avail name]
242 | otherwise -- a foreign export
243 = lookupOrigName nm `thenRn_`
246 binds_haskell_name (FoImport _) = True
247 binds_haskell_name FoLabel = True
248 binds_haskell_name FoExport = isDynamicExtName ext_nm
250 getLocalDeclBinders new_name (FixD _) = returnRn []
251 getLocalDeclBinders new_name (DeprecD _) = returnRn []
252 getLocalDeclBinders new_name (DefD _) = returnRn []
253 getLocalDeclBinders new_name (InstD _) = returnRn []
254 getLocalDeclBinders new_name (RuleD _) = returnRn []
257 ---------------------------
258 newLocalName mod rec_exp_fn rdr_name loc
259 = check_unqual rdr_name loc `thenRn_`
260 newTopBinder mod rdr_name loc `thenRn` \ name ->
261 returnRn (setLocalNameSort name (rec_exp_fn name))
263 -- There should never be a qualified name in a binding position (except in instance decls)
264 -- The parser doesn't check this because the same parser parses instance decls
265 check_unqual rdr_name loc
266 | isUnqual rdr_name = returnRn ()
267 | otherwise = qualNameErr (text "the binding for" <+> quotes (ppr rdr_name))
272 %************************************************************************
274 \subsection{Filtering imports}
276 %************************************************************************
278 @filterImports@ takes the @ExportEnv@ telling what the imported module makes
279 available, and filters it through the import spec (if any).
282 filterImports :: ModuleName -- The module being imported
283 -> Maybe (Bool, [RdrNameIE]) -- Import spec; True => hiding
284 -> [AvailInfo] -- What's available
285 -> RnMG ([AvailInfo], -- What's actually imported
286 [AvailInfo], -- What's to be hidden
287 -- (the unqualified version, that is)
288 -- (We need to return both the above sets, because
289 -- the qualified version is never hidden; so we can't
290 -- implement hiding by reducing what's imported.)
291 NameSet) -- What was imported explicitly
293 -- Complains if import spec mentions things that the module doesn't export
294 -- Warns/informs if import spec contains duplicates.
295 filterImports mod Nothing imports
296 = returnRn (imports, [], emptyNameSet)
298 filterImports mod (Just (want_hiding, import_items)) avails
299 = flatMapRn get_item import_items `thenRn` \ avails_w_explicits ->
301 (item_avails, explicits_s) = unzip avails_w_explicits
302 explicits = foldl addListToNameSet emptyNameSet explicits_s
306 -- All imported; item_avails to be hidden
307 returnRn (avails, item_avails, emptyNameSet)
309 -- Just item_avails imported; nothing to be hidden
310 returnRn (item_avails, [], explicits)
312 import_fm :: FiniteMap OccName AvailInfo
313 import_fm = listToFM [ (nameOccName name, avail)
315 name <- availNames avail]
316 -- Even though availNames returns data constructors too,
317 -- they won't make any difference because naked entities like T
318 -- in an import list map to TcOccs, not VarOccs.
320 bale_out item = addErrRn (badImportItemErr mod item) `thenRn_`
323 get_item item@(IEModuleContents _) = bale_out item
325 get_item item@(IEThingAll _)
326 = case check_item item of
327 Nothing -> bale_out item
328 Just avail@(AvailTC _ [n]) -> -- This occurs when you import T(..), but
329 -- only export T abstractly. The single [n]
330 -- in the AvailTC is the type or class itself
331 addWarnRn (dodgyImportWarn mod item) `thenRn_`
332 returnRn [(avail, [availName avail])]
333 Just avail -> returnRn [(avail, [availName avail])]
335 get_item item@(IEThingAbs n)
336 | want_hiding -- hiding( C )
337 -- Here the 'C' can be a data constructor *or* a type/class
338 = case catMaybes [check_item item, check_item (IEThingAbs data_n)] of
340 avails -> returnRn [(a, []) | a <- avails]
341 -- The 'explicits' list is irrelevant when hiding
343 data_n = setRdrNameOcc n (setOccNameSpace (rdrNameOcc n) dataName)
346 = case check_item item of
347 Nothing -> bale_out item
348 Just avail -> returnRn [(avail, availNames avail)]
351 | not (maybeToBool maybe_in_import_avails) ||
352 not (maybeToBool maybe_filtered_avail)
356 = Just filtered_avail
359 wanted_occ = rdrNameOcc (ieName item)
360 maybe_in_import_avails = lookupFM import_fm wanted_occ
362 Just avail = maybe_in_import_avails
363 maybe_filtered_avail = filterAvail item avail
364 Just filtered_avail = maybe_filtered_avail
369 %************************************************************************
371 \subsection{Qualifiying imports}
373 %************************************************************************
375 @qualifyImports@ takes the @ExportEnv@ after filtering through the import spec
376 of an import decl, and deals with producing an @RnEnv@ with the
377 right qualified names. It also turns the @Names@ in the @ExportEnv@ into
378 fully fledged @Names@.
381 qualifyImports :: ModuleName -- Imported module
382 -> Bool -- True <=> want unqualified import
383 -> Maybe ModuleName -- Optional "as M" part
384 -> [AvailInfo] -- What's to be hidden
385 -> (Name -> Provenance)
386 -> Avails -- Whats imported and how
387 -> RnMG (GlobalRdrEnv, ExportAvails)
389 qualifyImports this_mod unqual_imp as_mod hides mk_provenance avails
391 -- Make the name environment. We're talking about a
392 -- single module here, so there must be no name clashes.
393 -- In practice there only ever will be if it's the module
396 -- Add the things that are available
397 name_env1 = foldl add_avail emptyRdrEnv avails
399 -- Delete things that are hidden
400 name_env2 = foldl del_avail name_env1 hides
402 -- Create the export-availability info
403 export_avails = mkExportAvails qual_mod unqual_imp name_env2 avails
405 returnRn (name_env2, export_avails)
408 qual_mod = case as_mod of
410 Just another_name -> another_name
412 add_avail :: GlobalRdrEnv -> AvailInfo -> GlobalRdrEnv
413 add_avail env avail = foldl add_name env (availNames avail)
419 env1 = addOneToGlobalRdrEnv env (mkRdrQual qual_mod occ) (name,prov)
420 env2 = addOneToGlobalRdrEnv env1 (mkRdrUnqual occ) (name,prov)
421 occ = nameOccName name
422 prov = mk_provenance name
424 del_avail env avail = foldl delOneFromGlobalRdrEnv env rdr_names
426 rdr_names = map (mkRdrUnqual . nameOccName) (availNames avail)
429 mkEmptyExportAvails :: ModuleName -> ExportAvails
430 mkEmptyExportAvails mod_name = (unitFM mod_name [], emptyUFM)
432 mkExportAvails :: ModuleName -> Bool -> GlobalRdrEnv -> [AvailInfo] -> ExportAvails
433 mkExportAvails mod_name unqual_imp name_env avails
434 = (mod_avail_env, entity_avail_env)
436 mod_avail_env = unitFM mod_name unqual_avails
438 -- unqual_avails is the Avails that are visible in *unqualfied* form
439 -- (1.4 Report, Section 5.1.1)
441 -- import T hiding( f )
442 -- we delete f from avails
444 unqual_avails | not unqual_imp = [] -- Short cut when no unqualified imports
445 | otherwise = mapMaybe prune avails
447 prune (Avail n) | unqual_in_scope n = Just (Avail n)
448 prune (Avail n) | otherwise = Nothing
449 prune (AvailTC n ns) | null uqs = Nothing
450 | otherwise = Just (AvailTC n uqs)
452 uqs = filter unqual_in_scope ns
454 unqual_in_scope n = unQualInScope name_env n
456 entity_avail_env = listToUFM [ (name,avail) | avail <- avails,
457 name <- availNames avail]
459 plusExportAvails :: ExportAvails -> ExportAvails -> ExportAvails
460 plusExportAvails (m1, e1) (m2, e2)
461 = (plusFM_C (++) m1 m2, plusAvailEnv e1 e2)
462 -- ToDo: wasteful: we do this once for each constructor!
466 %************************************************************************
468 \subsection{Export list processing}
470 %************************************************************************
472 Processing the export list.
474 You might think that we should record things that appear in the export list
475 as ``occurrences'' (using @addOccurrenceName@), but you'd be wrong.
476 We do check (here) that they are in scope,
477 but there is no need to slurp in their actual declaration
478 (which is what @addOccurrenceName@ forces).
480 Indeed, doing so would big trouble when
481 compiling @PrelBase@, because it re-exports @GHC@, which includes @takeMVar#@,
482 whose type includes @ConcBase.StateAndSynchVar#@, and so on...
485 type ExportAccum -- The type of the accumulating parameter of
486 -- the main worker function in exportsFromAvail
487 = ([ModuleName], -- 'module M's seen so far
488 ExportOccMap, -- Tracks exported occurrence names
489 AvailEnv) -- The accumulated exported stuff, kept in an env
490 -- so we can common-up related AvailInfos
492 type ExportOccMap = FiniteMap OccName (Name, RdrNameIE)
493 -- Tracks what a particular exported OccName
494 -- in an export list refers to, and which item
495 -- it came from. It's illegal to export two distinct things
496 -- that have the same occurrence name
499 exportsFromAvail :: ModuleName
500 -> Maybe [RdrNameIE] -- Export spec
504 -- Complains if two distinct exports have same OccName
505 -- Warns about identical exports.
506 -- Complains about exports items not in scope
507 exportsFromAvail this_mod Nothing export_avails global_name_env
508 = exportsFromAvail this_mod true_exports export_avails global_name_env
510 true_exports = Just $ if this_mod == mAIN_Name
511 then [IEVar main_RDR]
512 -- export Main.main *only* unless otherwise specified,
513 else [IEModuleContents this_mod]
514 -- but for all other modules export everything.
516 exportsFromAvail this_mod (Just export_items)
517 (mod_avail_env, entity_avail_env)
519 = doptRn Opt_WarnDuplicateExports `thenRn` \ warn_dup_exports ->
520 foldlRn (exports_from_item warn_dup_exports)
521 ([], emptyFM, emptyAvailEnv) export_items
522 `thenRn` \ (_, _, export_avail_map) ->
524 export_avails :: [AvailInfo]
525 export_avails = nameEnvElts export_avail_map
527 returnRn export_avails
530 exports_from_item :: Bool -> ExportAccum -> RdrNameIE -> RnMG ExportAccum
532 exports_from_item warn_dups acc@(mods, occs, avails) ie@(IEModuleContents mod)
533 | mod `elem` mods -- Duplicate export of M
534 = warnCheckRn warn_dups (dupModuleExport mod) `thenRn_`
538 = case lookupFM mod_avail_env mod of
539 Nothing -> failWithRn acc (modExportErr mod)
540 Just mod_avails -> foldlRn (check_occs ie) occs mod_avails
543 avails' = foldl addAvail avails mod_avails
545 returnRn (mod:mods, occs', avails')
547 exports_from_item warn_dups acc@(mods, occs, avails) ie
548 | not (maybeToBool maybe_in_scope)
549 = failWithRn acc (unknownNameErr (ieName ie))
551 | not (null dup_names)
552 = addNameClashErrRn rdr_name ((name,prov):dup_names) `thenRn_`
556 -- I can't see why this should ever happen; if the thing is in scope
557 -- at all it ought to have some availability
558 | not (maybeToBool maybe_avail)
559 = pprTrace "exportsFromAvail: curious Nothing:" (ppr name)
564 = failWithRn acc (exportItemErr ie)
566 | otherwise -- Phew! It's OK! Now to check the occurrence stuff!
569 = warnCheckRn (ok_item ie avail) (dodgyExportWarn ie) `thenRn_`
570 check_occs ie occs export_avail `thenRn` \ occs' ->
571 returnRn (mods, occs', addAvail avails export_avail)
575 maybe_in_scope = lookupFM global_name_env rdr_name
576 Just ((name,prov):dup_names) = maybe_in_scope
577 maybe_avail = lookupUFM entity_avail_env name
578 Just avail = maybe_avail
579 maybe_export_avail = filterAvail ie avail
580 enough_avail = maybeToBool maybe_export_avail
581 Just export_avail = maybe_export_avail
583 ok_item (IEThingAll _) (AvailTC _ [n]) = False
584 -- This occurs when you import T(..), but
585 -- only export T abstractly. The single [n]
586 -- in the AvailTC is the type or class itself
589 check_occs :: RdrNameIE -> ExportOccMap -> AvailInfo -> RnMG ExportOccMap
590 check_occs ie occs avail
591 = doptRn Opt_WarnDuplicateExports `thenRn` \ warn_dup_exports ->
592 foldlRn (check warn_dup_exports) occs (availNames avail)
594 check warn_dup occs name
595 = case lookupFM occs name_occ of
596 Nothing -> returnRn (addToFM occs name_occ (name, ie))
598 | name == name' -> -- Duplicate export
600 (dupExportWarn name_occ ie ie')
601 `thenRn_` returnRn occs
603 | otherwise -> -- Same occ name but different names: an error
604 failWithRn occs (exportClashErr name_occ ie ie')
606 name_occ = nameOccName name
608 mk_export_fn :: NameSet -> (Name -> Bool) -- True => exported
609 mk_export_fn exported_names = \name -> name `elemNameSet` exported_names
612 %************************************************************************
616 %************************************************************************
619 badImportItemErr mod ie
620 = sep [ptext SLIT("Module"), quotes (ppr mod),
621 ptext SLIT("does not export"), quotes (ppr ie)]
623 dodgyImportWarn mod item = dodgyMsg (ptext SLIT("import")) item
624 dodgyExportWarn item = dodgyMsg (ptext SLIT("export")) item
626 dodgyMsg kind item@(IEThingAll tc)
627 = sep [ ptext SLIT("The") <+> kind <+> ptext SLIT("item") <+> quotes (ppr item),
628 ptext SLIT("suggests that") <+> quotes (ppr tc) <+> ptext SLIT("has constructor or class methods"),
629 ptext SLIT("but it has none; it is a type synonym or abstract type or class") ]
632 = hsep [ ptext SLIT("Unknown module in export list: module"), quotes (ppr mod)]
634 exportItemErr export_item
635 = sep [ ptext SLIT("The export item") <+> quotes (ppr export_item),
636 ptext SLIT("attempts to export constructors or class methods that are not visible here") ]
638 exportClashErr occ_name ie1 ie2
639 = hsep [ptext SLIT("The export items"), quotes (ppr ie1)
640 ,ptext SLIT("and"), quotes (ppr ie2)
641 ,ptext SLIT("create conflicting exports for"), quotes (ppr occ_name)]
644 = vcat [ptext SLIT("Multiple declarations of") <+> quotes (ppr n),
645 nest 4 (vcat (map ppr sorted_locs))]
647 sorted_locs = sortLt occ'ed_before (map nameSrcLoc (n:ns))
648 occ'ed_before a b = LT == compare a b
650 dupExportWarn occ_name ie1 ie2
651 = hsep [quotes (ppr occ_name),
652 ptext SLIT("is exported by"), quotes (ppr ie1),
653 ptext SLIT("and"), quotes (ppr ie2)]
656 = hsep [ptext SLIT("Duplicate"),
657 quotes (ptext SLIT("Module") <+> ppr mod),
658 ptext SLIT("in export list")]