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 ( DynFlags, DynFlag(..), dopt, opt_NoImplicitPrelude )
15 import HsSyn ( HsModule(..), HsDecl(..), IE(..), ieName, ImportDecl(..),
18 import RdrHsSyn ( RdrNameIE, RdrNameImportDecl,
19 RdrNameHsModule, RdrNameHsDecl
21 import RnIfaces ( getInterfaceExports, getDeclBinders,
22 recordLocalSlurps, findAndReadIface )
27 import PrelNames ( pRELUDE_Name, mAIN_Name, main_RDR )
28 import UniqFM ( lookupUFM )
29 import Bag ( bagToList )
30 import Module ( ModuleName, mkModuleInThisPackage, WhereFrom(..) )
32 import Name ( Name, nameSrcLoc,
33 setLocalNameSort, nameOccName, nameEnvElts )
34 import HscTypes ( Provenance(..), ImportReason(..), GlobalRdrEnv,
35 GenAvailInfo(..), AvailInfo, Avails, AvailEnv )
36 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 :: RdrNameHsModule
58 -> RnMG (Maybe (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 -- Nothing => no need to recompile
66 getGlobalNames (HsModule this_mod _ exports imports decls _ mod_loc)
67 = -- These two fix-loops are to get the right
68 -- provenance information into a Name
69 fixRn ( \ ~(Just (rec_gbl_env, _, rec_export_avails, _)) ->
72 rec_unqual_fn :: Name -> Bool -- Is this chap in scope unqualified?
73 rec_unqual_fn = unQualInScope rec_gbl_env
75 rec_exp_fn :: Name -> Bool
76 rec_exp_fn = mk_export_fn (availsToNameSet rec_export_avails)
79 -- PROCESS LOCAL DECLS
80 -- Do these *first* so that the correct provenance gets
81 -- into the global name cache.
82 importsFromLocalDecls this_mod rec_exp_fn decls
83 `thenRn` \ (local_gbl_env, local_mod_avails) ->
85 -- PROCESS IMPORT DECLS
86 -- Do the non {- SOURCE -} ones first, so that we get a helpful
87 -- warning for {- SOURCE -} ones that are unnecessary
89 (source, ordinary) = partition is_source_import all_imports
90 is_source_import (ImportDecl _ ImportByUserSource _ _ _ _) = True
91 is_source_import other = False
93 mapAndUnzipRn (importsFromImportDecl rec_unqual_fn) ordinary
94 `thenRn` \ (imp_gbl_envs1, imp_avails_s1) ->
95 mapAndUnzipRn (importsFromImportDecl rec_unqual_fn) source
96 `thenRn` \ (imp_gbl_envs2, imp_avails_s2) ->
99 -- We put the local env second, so that a local provenance
100 -- "wins", even if a module imports itself.
102 gbl_env :: GlobalRdrEnv
103 imp_gbl_env = foldr plusGlobalRdrEnv emptyRdrEnv (imp_gbl_envs2 ++ imp_gbl_envs1)
104 gbl_env = imp_gbl_env `plusGlobalRdrEnv` local_gbl_env
106 all_avails :: ExportAvails
107 all_avails = foldr plusExportAvails local_mod_avails (imp_avails_s2 ++ imp_avails_s1)
108 (_, global_avail_env) = all_avails
111 -- TRY FOR EARLY EXIT
112 -- We can't go for an early exit before this because we have to check
113 -- for name clashes. Consider:
115 -- module A where module B where
119 -- Suppose I've compiled everything up, and then I add a
120 -- new definition to module B, that defines "f".
122 -- Then I must detect the name clash in A before going for an early
123 -- exit. The early-exit code checks what's actually needed from B
124 -- to compile A, and of course that doesn't include B.f. That's
125 -- why we wait till after the plusEnv stuff to do the early-exit.
127 -- Check For early exit
128 checkErrsRn `thenRn` \ no_errs_so_far ->
129 if not no_errs_so_far then
130 -- Found errors already, so exit now
134 -- PROCESS EXPORT LISTS
135 exportsFromAvail this_mod exports all_avails gbl_env `thenRn` \ export_avails ->
139 returnRn (Just (gbl_env, local_gbl_env, export_avails, global_avail_env))
142 all_imports = prel_imports ++ imports
144 -- NB: opt_NoImplicitPrelude is slightly different to import Prelude ();
145 -- because the former doesn't even look at Prelude.hi for instance declarations,
146 -- whereas the latter does.
147 prel_imports | this_mod == pRELUDE_Name ||
148 explicit_prelude_import ||
149 opt_NoImplicitPrelude
152 | otherwise = [ImportDecl pRELUDE_Name
154 False {- Not qualified -}
155 Nothing {- No "as" -}
156 Nothing {- No import list -}
159 explicit_prelude_import
160 = not (null [ () | (ImportDecl mod _ _ _ _ _) <- imports, mod == pRELUDE_Name ])
164 importsFromImportDecl :: (Name -> Bool) -- OK to omit qualifier
166 -> RnMG (GlobalRdrEnv,
169 importsFromImportDecl is_unqual (ImportDecl imp_mod_name from qual_only as_mod import_spec iloc)
170 = pushSrcLocRn iloc $
171 getInterfaceExports imp_mod_name from `thenRn` \ (imp_mod, avails) ->
174 -- If there's an error in getInterfaceExports, (e.g. interface
175 -- file not found) we get lots of spurious errors from 'filterImports'
176 returnRn (emptyRdrEnv, mkEmptyExportAvails imp_mod_name)
179 filterImports imp_mod_name import_spec avails `thenRn` \ (filtered_avails, hides, explicits) ->
182 mk_provenance name = NonLocalDef (UserImport imp_mod iloc (name `elemNameSet` explicits))
186 qualifyImports imp_mod_name
187 (not qual_only) -- Maybe want unqualified names
195 importsFromLocalDecls mod_name rec_exp_fn decls
196 = mapRn (getLocalDeclBinders mod rec_exp_fn) decls `thenRn` \ avails_s ->
199 avails = concat avails_s
201 all_names :: [Name] -- All the defns; no dups eliminated
202 all_names = [name | avail <- avails, name <- availNames avail]
205 (_, dups) = removeDups compare all_names
207 -- Check for duplicate definitions
208 mapRn_ (addErrRn . dupDeclErr) dups `thenRn_`
210 -- Record that locally-defined things are available
211 recordLocalSlurps avails `thenRn_`
213 -- Build the environment
214 qualifyImports mod_name
215 True -- Want unqualified names
218 (\n -> LocalDef) -- Provenance is local
221 mod = mkModuleInThisPackage mod_name
223 getLocalDeclBinders :: Module
224 -> (Name -> Bool) -- Is-exported predicate
225 -> RdrNameHsDecl -> RnMG Avails
226 getLocalDeclBinders mod rec_exp_fn (ValD binds)
227 = mapRn do_one (bagToList (collectTopBinders binds))
229 do_one (rdr_name, loc) = newLocalName mod rec_exp_fn rdr_name loc `thenRn` \ name ->
230 returnRn (Avail name)
232 getLocalDeclBinders mod rec_exp_fn decl
233 = getDeclBinders (newLocalName mod rec_exp_fn) decl `thenRn` \ maybe_avail ->
235 Nothing -> returnRn [] -- Instance decls and suchlike
236 Just avail -> returnRn [avail]
238 newLocalName mod rec_exp_fn rdr_name loc
239 = check_unqual rdr_name loc `thenRn_`
240 newTopBinder mod rdr_name loc `thenRn` \ name ->
241 returnRn (setLocalNameSort name (rec_exp_fn name))
243 -- There should never be a qualified name in a binding position (except in instance decls)
244 -- The parser doesn't check this because the same parser parses instance decls
245 check_unqual rdr_name loc
246 | isUnqual rdr_name = returnRn ()
247 | otherwise = qualNameErr (text "the binding for" <+> quotes (ppr rdr_name))
252 %************************************************************************
254 \subsection{Filtering imports}
256 %************************************************************************
258 @filterImports@ takes the @ExportEnv@ telling what the imported module makes
259 available, and filters it through the import spec (if any).
262 filterImports :: ModuleName -- The module being imported
263 -> Maybe (Bool, [RdrNameIE]) -- Import spec; True => hiding
264 -> [AvailInfo] -- What's available
265 -> RnMG ([AvailInfo], -- What's actually imported
266 [AvailInfo], -- What's to be hidden
267 -- (the unqualified version, that is)
268 -- (We need to return both the above sets, because
269 -- the qualified version is never hidden; so we can't
270 -- implement hiding by reducing what's imported.)
271 NameSet) -- What was imported explicitly
273 -- Complains if import spec mentions things that the module doesn't export
274 -- Warns/informs if import spec contains duplicates.
275 filterImports mod Nothing imports
276 = returnRn (imports, [], emptyNameSet)
278 filterImports mod (Just (want_hiding, import_items)) avails
279 = flatMapRn get_item import_items `thenRn` \ avails_w_explicits ->
281 (item_avails, explicits_s) = unzip avails_w_explicits
282 explicits = foldl addListToNameSet emptyNameSet explicits_s
286 -- All imported; item_avails to be hidden
287 returnRn (avails, item_avails, emptyNameSet)
289 -- Just item_avails imported; nothing to be hidden
290 returnRn (item_avails, [], explicits)
292 import_fm :: FiniteMap OccName AvailInfo
293 import_fm = listToFM [ (nameOccName name, avail)
295 name <- availNames avail]
296 -- Even though availNames returns data constructors too,
297 -- they won't make any difference because naked entities like T
298 -- in an import list map to TcOccs, not VarOccs.
300 bale_out item = addErrRn (badImportItemErr mod item) `thenRn_`
303 get_item item@(IEModuleContents _) = bale_out item
305 get_item item@(IEThingAll _)
306 = case check_item item of
307 Nothing -> bale_out item
308 Just avail@(AvailTC _ [n]) -> -- This occurs when you import T(..), but
309 -- only export T abstractly. The single [n]
310 -- in the AvailTC is the type or class itself
311 addWarnRn (dodgyImportWarn mod item) `thenRn_`
312 returnRn [(avail, [availName avail])]
313 Just avail -> returnRn [(avail, [availName avail])]
315 get_item item@(IEThingAbs n)
316 | want_hiding -- hiding( C )
317 -- Here the 'C' can be a data constructor *or* a type/class
318 = case catMaybes [check_item item, check_item (IEThingAbs data_n)] of
320 avails -> returnRn [(a, []) | a <- avails]
321 -- The 'explicits' list is irrelevant when hiding
323 data_n = setRdrNameOcc n (setOccNameSpace (rdrNameOcc n) dataName)
326 = case check_item item of
327 Nothing -> bale_out item
328 Just avail -> returnRn [(avail, availNames avail)]
331 | not (maybeToBool maybe_in_import_avails) ||
332 not (maybeToBool maybe_filtered_avail)
336 = Just filtered_avail
339 wanted_occ = rdrNameOcc (ieName item)
340 maybe_in_import_avails = lookupFM import_fm wanted_occ
342 Just avail = maybe_in_import_avails
343 maybe_filtered_avail = filterAvail item avail
344 Just filtered_avail = maybe_filtered_avail
349 %************************************************************************
351 \subsection{Qualifiying imports}
353 %************************************************************************
355 @qualifyImports@ takes the @ExportEnv@ after filtering through the import spec
356 of an import decl, and deals with producing an @RnEnv@ with the
357 right qualified names. It also turns the @Names@ in the @ExportEnv@ into
358 fully fledged @Names@.
361 qualifyImports :: ModuleName -- Imported module
362 -> Bool -- True <=> want unqualified import
363 -> Maybe ModuleName -- Optional "as M" part
364 -> [AvailInfo] -- What's to be hidden
365 -> (Name -> Provenance)
366 -> Avails -- Whats imported and how
367 -> RnMG (GlobalRdrEnv, ExportAvails)
369 qualifyImports this_mod unqual_imp as_mod hides mk_provenance avails
371 -- Make the name environment. We're talking about a
372 -- single module here, so there must be no name clashes.
373 -- In practice there only ever will be if it's the module
376 -- Add the things that are available
377 name_env1 = foldl add_avail emptyRdrEnv avails
379 -- Delete things that are hidden
380 name_env2 = foldl del_avail name_env1 hides
382 -- Create the export-availability info
383 export_avails = mkExportAvails qual_mod unqual_imp name_env2 avails
385 returnRn (name_env2, export_avails)
388 qual_mod = case as_mod of
390 Just another_name -> another_name
392 add_avail :: GlobalRdrEnv -> AvailInfo -> GlobalRdrEnv
393 add_avail env avail = foldl add_name env (availNames avail)
399 env1 = addOneToGlobalRdrEnv env (mkRdrQual qual_mod occ) (name,prov)
400 env2 = addOneToGlobalRdrEnv env1 (mkRdrUnqual occ) (name,prov)
401 occ = nameOccName name
402 prov = mk_provenance name
404 del_avail env avail = foldl delOneFromGlobalRdrEnv env rdr_names
406 rdr_names = map (mkRdrUnqual . nameOccName) (availNames avail)
409 mkEmptyExportAvails :: ModuleName -> ExportAvails
410 mkEmptyExportAvails mod_name = (unitFM mod_name [], emptyUFM)
412 mkExportAvails :: ModuleName -> Bool -> GlobalRdrEnv -> [AvailInfo] -> ExportAvails
413 mkExportAvails mod_name unqual_imp name_env avails
414 = (mod_avail_env, entity_avail_env)
416 mod_avail_env = unitFM mod_name unqual_avails
418 -- unqual_avails is the Avails that are visible in *unqualfied* form
419 -- (1.4 Report, Section 5.1.1)
421 -- import T hiding( f )
422 -- we delete f from avails
424 unqual_avails | not unqual_imp = [] -- Short cut when no unqualified imports
425 | otherwise = mapMaybe prune avails
427 prune (Avail n) | unqual_in_scope n = Just (Avail n)
428 prune (Avail n) | otherwise = Nothing
429 prune (AvailTC n ns) | null uqs = Nothing
430 | otherwise = Just (AvailTC n uqs)
432 uqs = filter unqual_in_scope ns
434 unqual_in_scope n = unQualInScope name_env n
436 entity_avail_env = listToUFM [ (name,avail) | avail <- avails,
437 name <- availNames avail]
439 plusExportAvails :: ExportAvails -> ExportAvails -> ExportAvails
440 plusExportAvails (m1, e1) (m2, e2)
441 = (plusFM_C (++) m1 m2, plusAvailEnv e1 e2)
442 -- ToDo: wasteful: we do this once for each constructor!
446 %************************************************************************
448 \subsection{Export list processing}
450 %************************************************************************
452 Processing the export list.
454 You might think that we should record things that appear in the export list
455 as ``occurrences'' (using @addOccurrenceName@), but you'd be wrong.
456 We do check (here) that they are in scope,
457 but there is no need to slurp in their actual declaration
458 (which is what @addOccurrenceName@ forces).
460 Indeed, doing so would big trouble when
461 compiling @PrelBase@, because it re-exports @GHC@, which includes @takeMVar#@,
462 whose type includes @ConcBase.StateAndSynchVar#@, and so on...
465 type ExportAccum -- The type of the accumulating parameter of
466 -- the main worker function in exportsFromAvail
467 = ([ModuleName], -- 'module M's seen so far
468 ExportOccMap, -- Tracks exported occurrence names
469 AvailEnv) -- The accumulated exported stuff, kept in an env
470 -- so we can common-up related AvailInfos
472 type ExportOccMap = FiniteMap OccName (Name, RdrNameIE)
473 -- Tracks what a particular exported OccName
474 -- in an export list refers to, and which item
475 -- it came from. It's illegal to export two distinct things
476 -- that have the same occurrence name
479 exportsFromAvail :: ModuleName
480 -> Maybe [RdrNameIE] -- Export spec
484 -- Complains if two distinct exports have same OccName
485 -- Warns about identical exports.
486 -- Complains about exports items not in scope
487 exportsFromAvail this_mod Nothing export_avails global_name_env
488 = exportsFromAvail this_mod true_exports export_avails global_name_env
490 true_exports = Just $ if this_mod == mAIN_Name
491 then [IEVar main_RDR]
492 -- export Main.main *only* unless otherwise specified,
493 else [IEModuleContents this_mod]
494 -- but for all other modules export everything.
496 exportsFromAvail this_mod (Just export_items)
497 (mod_avail_env, entity_avail_env)
499 = doptRn Opt_WarnDuplicateExports `thenRn` \ warn_dup_exports ->
500 foldlRn (exports_from_item warn_dup_exports)
501 ([], emptyFM, emptyAvailEnv) export_items
502 `thenRn` \ (_, _, export_avail_map) ->
504 export_avails :: [AvailInfo]
505 export_avails = nameEnvElts export_avail_map
507 returnRn export_avails
510 exports_from_item :: Bool -> ExportAccum -> RdrNameIE -> RnMG ExportAccum
512 exports_from_item warn_dups acc@(mods, occs, avails) ie@(IEModuleContents mod)
513 | mod `elem` mods -- Duplicate export of M
514 = warnCheckRn warn_dups (dupModuleExport mod) `thenRn_`
518 = case lookupFM mod_avail_env mod of
519 Nothing -> failWithRn acc (modExportErr mod)
520 Just mod_avails -> foldlRn (check_occs ie) occs mod_avails
523 avails' = foldl addAvail avails mod_avails
525 returnRn (mod:mods, occs', avails')
527 exports_from_item warn_dups acc@(mods, occs, avails) ie
528 | not (maybeToBool maybe_in_scope)
529 = failWithRn acc (unknownNameErr (ieName ie))
531 | not (null dup_names)
532 = addNameClashErrRn rdr_name ((name,prov):dup_names) `thenRn_`
536 -- I can't see why this should ever happen; if the thing is in scope
537 -- at all it ought to have some availability
538 | not (maybeToBool maybe_avail)
539 = pprTrace "exportsFromAvail: curious Nothing:" (ppr name)
544 = failWithRn acc (exportItemErr ie)
546 | otherwise -- Phew! It's OK! Now to check the occurrence stuff!
549 = warnCheckRn (ok_item ie avail) (dodgyExportWarn ie) `thenRn_`
550 check_occs ie occs export_avail `thenRn` \ occs' ->
551 returnRn (mods, occs', addAvail avails export_avail)
555 maybe_in_scope = lookupFM global_name_env rdr_name
556 Just ((name,prov):dup_names) = maybe_in_scope
557 maybe_avail = lookupUFM entity_avail_env name
558 Just avail = maybe_avail
559 maybe_export_avail = filterAvail ie avail
560 enough_avail = maybeToBool maybe_export_avail
561 Just export_avail = maybe_export_avail
563 ok_item (IEThingAll _) (AvailTC _ [n]) = False
564 -- This occurs when you import T(..), but
565 -- only export T abstractly. The single [n]
566 -- in the AvailTC is the type or class itself
569 check_occs :: RdrNameIE -> ExportOccMap -> AvailInfo -> RnMG ExportOccMap
570 check_occs ie occs avail
571 = doptRn Opt_WarnDuplicateExports `thenRn` \ warn_dup_exports ->
572 foldlRn (check warn_dup_exports) occs (availNames avail)
574 check warn_dup occs name
575 = case lookupFM occs name_occ of
576 Nothing -> returnRn (addToFM occs name_occ (name, ie))
578 | name == name' -> -- Duplicate export
580 (dupExportWarn name_occ ie ie')
581 `thenRn_` returnRn occs
583 | otherwise -> -- Same occ name but different names: an error
584 failWithRn occs (exportClashErr name_occ ie ie')
586 name_occ = nameOccName name
588 mk_export_fn :: NameSet -> (Name -> Bool) -- True => exported
589 mk_export_fn exported_names = \name -> name `elemNameSet` exported_names
592 %************************************************************************
596 %************************************************************************
599 badImportItemErr mod ie
600 = sep [ptext SLIT("Module"), quotes (ppr mod),
601 ptext SLIT("does not export"), quotes (ppr ie)]
603 dodgyImportWarn mod item = dodgyMsg (ptext SLIT("import")) item
604 dodgyExportWarn item = dodgyMsg (ptext SLIT("export")) item
606 dodgyMsg kind item@(IEThingAll tc)
607 = sep [ ptext SLIT("The") <+> kind <+> ptext SLIT("item") <+> quotes (ppr item),
608 ptext SLIT("suggests that") <+> quotes (ppr tc) <+> ptext SLIT("has constructor or class methods"),
609 ptext SLIT("but it has none; it is a type synonym or abstract type or class") ]
612 = hsep [ ptext SLIT("Unknown module in export list: module"), quotes (ppr mod)]
614 exportItemErr export_item
615 = sep [ ptext SLIT("The export item") <+> quotes (ppr export_item),
616 ptext SLIT("attempts to export constructors or class methods that are not visible here") ]
618 exportClashErr occ_name ie1 ie2
619 = hsep [ptext SLIT("The export items"), quotes (ppr ie1)
620 ,ptext SLIT("and"), quotes (ppr ie2)
621 ,ptext SLIT("create conflicting exports for"), quotes (ppr occ_name)]
624 = vcat [ptext SLIT("Multiple declarations of") <+> quotes (ppr n),
625 nest 4 (vcat (map ppr sorted_locs))]
627 sorted_locs = sortLt occ'ed_before (map nameSrcLoc (n:ns))
628 occ'ed_before a b = LT == compare a b
630 dupExportWarn occ_name ie1 ie2
631 = hsep [quotes (ppr occ_name),
632 ptext SLIT("is exported by"), quotes (ppr ie1),
633 ptext SLIT("and"), quotes (ppr ie2)]
636 = hsep [ptext SLIT("Duplicate"),
637 quotes (ptext SLIT("Module") <+> ppr mod),
638 ptext SLIT("in export list")]