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, checkModUsage,
23 outOfDate, findAndReadIface )
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,
39 import OccName ( setOccNameSpace, dataName )
40 import NameSet ( elemNameSet, emptyNameSet )
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
64 Maybe ParsedIface -- The old interface file, if any
66 -- Nothing => no need to recompile
68 getGlobalNames (HsModule this_mod _ exports imports decls _ mod_loc)
69 = -- These two fix-loops are to get the right
70 -- provenance information into a Name
71 fixRn ( \ ~(Just (rec_gbl_env, _, rec_export_avails, _, _)) ->
74 rec_unqual_fn :: Name -> Bool -- Is this chap in scope unqualified?
75 rec_unqual_fn = unQualInScope rec_gbl_env
77 rec_exp_fn :: Name -> Bool
78 rec_exp_fn = mk_export_fn (availsToNameSet rec_export_avails)
81 -- PROCESS LOCAL DECLS
82 -- Do these *first* so that the correct provenance gets
83 -- into the global name cache.
84 importsFromLocalDecls this_mod rec_exp_fn decls
85 `thenRn` \ (local_gbl_env, local_mod_avails) ->
87 -- PROCESS IMPORT DECLS
88 -- Do the non {- SOURCE -} ones first, so that we get a helpful
89 -- warning for {- SOURCE -} ones that are unnecessary
91 (source, ordinary) = partition is_source_import all_imports
92 is_source_import (ImportDecl _ ImportByUserSource _ _ _ _) = True
93 is_source_import other = False
95 mapAndUnzipRn (importsFromImportDecl rec_unqual_fn) ordinary
96 `thenRn` \ (imp_gbl_envs1, imp_avails_s1) ->
97 mapAndUnzipRn (importsFromImportDecl rec_unqual_fn) source
98 `thenRn` \ (imp_gbl_envs2, imp_avails_s2) ->
101 -- We put the local env second, so that a local provenance
102 -- "wins", even if a module imports itself.
104 gbl_env :: GlobalRdrEnv
105 imp_gbl_env = foldr plusGlobalRdrEnv emptyRdrEnv (imp_gbl_envs2 ++ imp_gbl_envs1)
106 gbl_env = imp_gbl_env `plusGlobalRdrEnv` local_gbl_env
108 all_avails :: ExportAvails
109 all_avails = foldr plusExportAvails local_mod_avails (imp_avails_s2 ++ imp_avails_s1)
110 (_, global_avail_env) = all_avails
113 -- TRY FOR EARLY EXIT
114 -- We can't go for an early exit before this because we have to check
115 -- for name clashes. Consider:
117 -- module A where module B where
121 -- Suppose I've compiled everything up, and then I add a
122 -- new definition to module B, that defines "f".
124 -- Then I must detect the name clash in A before going for an early
125 -- exit. The early-exit code checks what's actually needed from B
126 -- to compile A, and of course that doesn't include B.f. That's
127 -- why we wait till after the plusEnv stuff to do the early-exit.
129 -- Check For eacly exit
130 checkErrsRn `thenRn` \ no_errs_so_far ->
131 if not no_errs_so_far then
132 -- Found errors already, so exit now
135 checkEarlyExit this_mod `thenRn` \ (up_to_date, old_iface) ->
137 -- Interface files are sufficiently unchanged
138 putDocRn (text "Compilation IS NOT required") `thenRn_`
142 -- PROCESS EXPORT LISTS
143 exportsFromAvail this_mod exports all_avails gbl_env `thenRn` \ export_avails ->
147 returnRn (Just (gbl_env, local_gbl_env, export_avails, global_avail_env, old_iface))
150 all_imports = prel_imports ++ imports
152 -- NB: opt_NoImplicitPrelude is slightly different to import Prelude ();
153 -- because the former doesn't even look at Prelude.hi for instance declarations,
154 -- whereas the latter does.
155 prel_imports | this_mod == pRELUDE_Name ||
156 explicit_prelude_import ||
157 opt_NoImplicitPrelude
160 | otherwise = [ImportDecl pRELUDE_Name
162 False {- Not qualified -}
163 Nothing {- No "as" -}
164 Nothing {- No import list -}
167 explicit_prelude_import
168 = not (null [ () | (ImportDecl mod _ _ _ _ _) <- imports, mod == pRELUDE_Name ])
172 checkEarlyExit mod_name
173 = traceRn (text "Considering whether compilation is required...") `thenRn_`
175 -- Read the old interface file, if any, for the module being compiled
176 findAndReadIface doc_str mod_name False {- Not hi-boot -} `thenRn` \ maybe_iface ->
178 -- CHECK WHETHER WE HAVE IT ALREADY
180 Left err -> -- Old interface file not found, so we'd better bail out
181 traceRn (vcat [ptext SLIT("No old interface file for") <+> ppr mod_name,
183 returnRn (outOfDate, Nothing)
186 | panic "checkEarlyExit: ???: not opt_SourceUnchanged"
187 -> -- Source code changed
188 traceRn (nest 4 (text "source file changed or recompilation check turned off")) `thenRn_`
189 returnRn (False, Just iface)
192 -> -- Source code unchanged and no errors yet... carry on
193 checkModUsage (pi_usages iface) `thenRn` \ up_to_date ->
194 returnRn (up_to_date, Just iface)
196 -- Only look in current directory, with suffix .hi
197 doc_str = sep [ptext SLIT("need usage info from"), ppr mod_name]
201 importsFromImportDecl :: (Name -> Bool) -- OK to omit qualifier
203 -> RnMG (GlobalRdrEnv,
206 importsFromImportDecl is_unqual (ImportDecl imp_mod_name from qual_only as_mod import_spec iloc)
207 = pushSrcLocRn iloc $
208 getInterfaceExports imp_mod_name from `thenRn` \ (imp_mod, avails) ->
211 -- If there's an error in getInterfaceExports, (e.g. interface
212 -- file not found) we get lots of spurious errors from 'filterImports'
213 returnRn (emptyRdrEnv, mkEmptyExportAvails imp_mod_name)
216 filterImports imp_mod_name import_spec avails `thenRn` \ (filtered_avails, hides, explicits) ->
219 mk_provenance name = NonLocalDef (UserImport imp_mod iloc (name `elemNameSet` explicits))
223 qualifyImports imp_mod_name
224 (not qual_only) -- Maybe want unqualified names
232 importsFromLocalDecls mod_name rec_exp_fn decls
233 = mapRn (getLocalDeclBinders mod rec_exp_fn) decls `thenRn` \ avails_s ->
236 avails = concat avails_s
238 all_names :: [Name] -- All the defns; no dups eliminated
239 all_names = [name | avail <- avails, name <- availNames avail]
242 (_, dups) = removeDups compare all_names
244 -- Check for duplicate definitions
245 mapRn_ (addErrRn . dupDeclErr) dups `thenRn_`
247 -- Record that locally-defined things are available
248 recordLocalSlurps avails `thenRn_`
250 -- Build the environment
251 qualifyImports mod_name
252 True -- Want unqualified names
255 (\n -> LocalDef) -- Provenance is local
258 mod = mkModuleInThisPackage mod_name
260 getLocalDeclBinders :: Module
261 -> (Name -> Bool) -- Is-exported predicate
262 -> RdrNameHsDecl -> RnMG Avails
263 getLocalDeclBinders mod rec_exp_fn (ValD binds)
264 = mapRn do_one (bagToList (collectTopBinders binds))
266 do_one (rdr_name, loc) = newLocalName mod rec_exp_fn rdr_name loc `thenRn` \ name ->
267 returnRn (Avail name)
269 getLocalDeclBinders mod rec_exp_fn decl
270 = getDeclBinders (newLocalName mod rec_exp_fn) decl `thenRn` \ maybe_avail ->
272 Nothing -> returnRn [] -- Instance decls and suchlike
273 Just avail -> returnRn [avail]
275 newLocalName mod rec_exp_fn rdr_name loc
276 = check_unqual rdr_name loc `thenRn_`
277 newTopBinder mod rdr_name loc `thenRn` \ name ->
278 returnRn (setLocalNameSort name (rec_exp_fn name))
280 -- There should never be a qualified name in a binding position (except in instance decls)
281 -- The parser doesn't check this because the same parser parses instance decls
282 check_unqual rdr_name loc
283 | isUnqual rdr_name = returnRn ()
284 | otherwise = qualNameErr (text "the binding for" <+> quotes (ppr rdr_name))
289 %************************************************************************
291 \subsection{Filtering imports}
293 %************************************************************************
295 @filterImports@ takes the @ExportEnv@ telling what the imported module makes
296 available, and filters it through the import spec (if any).
299 filterImports :: ModuleName -- The module being imported
300 -> Maybe (Bool, [RdrNameIE]) -- Import spec; True => hiding
301 -> [AvailInfo] -- What's available
302 -> RnMG ([AvailInfo], -- What's actually imported
303 [AvailInfo], -- What's to be hidden
304 -- (the unqualified version, that is)
305 -- (We need to return both the above sets, because
306 -- the qualified version is never hidden; so we can't
307 -- implement hiding by reducing what's imported.)
308 NameSet) -- What was imported explicitly
310 -- Complains if import spec mentions things that the module doesn't export
311 -- Warns/informs if import spec contains duplicates.
312 filterImports mod Nothing imports
313 = returnRn (imports, [], emptyNameSet)
315 filterImports mod (Just (want_hiding, import_items)) avails
316 = flatMapRn get_item import_items `thenRn` \ avails_w_explicits ->
318 (item_avails, explicits_s) = unzip avails_w_explicits
319 explicits = foldl addListToNameSet emptyNameSet explicits_s
323 -- All imported; item_avails to be hidden
324 returnRn (avails, item_avails, emptyNameSet)
326 -- Just item_avails imported; nothing to be hidden
327 returnRn (item_avails, [], explicits)
329 import_fm :: FiniteMap OccName AvailInfo
330 import_fm = listToFM [ (nameOccName name, avail)
332 name <- availNames avail]
333 -- Even though availNames returns data constructors too,
334 -- they won't make any difference because naked entities like T
335 -- in an import list map to TcOccs, not VarOccs.
337 bale_out item = addErrRn (badImportItemErr mod item) `thenRn_`
340 get_item item@(IEModuleContents _) = bale_out item
342 get_item item@(IEThingAll _)
343 = case check_item item of
344 Nothing -> bale_out item
345 Just avail@(AvailTC _ [n]) -> -- This occurs when you import T(..), but
346 -- only export T abstractly. The single [n]
347 -- in the AvailTC is the type or class itself
348 addWarnRn (dodgyImportWarn mod item) `thenRn_`
349 returnRn [(avail, [availName avail])]
350 Just avail -> returnRn [(avail, [availName avail])]
352 get_item item@(IEThingAbs n)
353 | want_hiding -- hiding( C )
354 -- Here the 'C' can be a data constructor *or* a type/class
355 = case catMaybes [check_item item, check_item (IEThingAbs data_n)] of
357 avails -> returnRn [(a, []) | a <- avails]
358 -- The 'explicits' list is irrelevant when hiding
360 data_n = setRdrNameOcc n (setOccNameSpace (rdrNameOcc n) dataName)
363 = case check_item item of
364 Nothing -> bale_out item
365 Just avail -> returnRn [(avail, availNames avail)]
368 | not (maybeToBool maybe_in_import_avails) ||
369 not (maybeToBool maybe_filtered_avail)
373 = Just filtered_avail
376 wanted_occ = rdrNameOcc (ieName item)
377 maybe_in_import_avails = lookupFM import_fm wanted_occ
379 Just avail = maybe_in_import_avails
380 maybe_filtered_avail = filterAvail item avail
381 Just filtered_avail = maybe_filtered_avail
386 %************************************************************************
388 \subsection{Qualifiying imports}
390 %************************************************************************
392 @qualifyImports@ takes the @ExportEnv@ after filtering through the import spec
393 of an import decl, and deals with producing an @RnEnv@ with the
394 right qualified names. It also turns the @Names@ in the @ExportEnv@ into
395 fully fledged @Names@.
398 qualifyImports :: ModuleName -- Imported module
399 -> Bool -- True <=> want unqualified import
400 -> Maybe ModuleName -- Optional "as M" part
401 -> [AvailInfo] -- What's to be hidden
402 -> (Name -> Provenance)
403 -> Avails -- Whats imported and how
404 -> RnMG (GlobalRdrEnv, ExportAvails)
406 qualifyImports this_mod unqual_imp as_mod hides mk_provenance avails
408 -- Make the name environment. We're talking about a
409 -- single module here, so there must be no name clashes.
410 -- In practice there only ever will be if it's the module
413 -- Add the things that are available
414 name_env1 = foldl add_avail emptyRdrEnv avails
416 -- Delete things that are hidden
417 name_env2 = foldl del_avail name_env1 hides
419 -- Create the export-availability info
420 export_avails = mkExportAvails qual_mod unqual_imp name_env2 avails
422 returnRn (name_env2, export_avails)
425 qual_mod = case as_mod of
427 Just another_name -> another_name
429 add_avail :: GlobalRdrEnv -> AvailInfo -> GlobalRdrEnv
430 add_avail env avail = foldl add_name env (availNames avail)
436 env1 = addOneToGlobalRdrEnv env (mkRdrQual qual_mod occ) (name,prov)
437 env2 = addOneToGlobalRdrEnv env1 (mkRdrUnqual occ) (name,prov)
438 occ = nameOccName name
439 prov = mk_provenance name
441 del_avail env avail = foldl delOneFromGlobalRdrEnv env rdr_names
443 rdr_names = map (mkRdrUnqual . nameOccName) (availNames avail)
446 mkEmptyExportAvails :: ModuleName -> ExportAvails
447 mkEmptyExportAvails mod_name = (unitFM mod_name [], emptyUFM)
449 mkExportAvails :: ModuleName -> Bool -> GlobalRdrEnv -> [AvailInfo] -> ExportAvails
450 mkExportAvails mod_name unqual_imp name_env avails
451 = (mod_avail_env, entity_avail_env)
453 mod_avail_env = unitFM mod_name unqual_avails
455 -- unqual_avails is the Avails that are visible in *unqualfied* form
456 -- (1.4 Report, Section 5.1.1)
458 -- import T hiding( f )
459 -- we delete f from avails
461 unqual_avails | not unqual_imp = [] -- Short cut when no unqualified imports
462 | otherwise = mapMaybe prune avails
464 prune (Avail n) | unqual_in_scope n = Just (Avail n)
465 prune (Avail n) | otherwise = Nothing
466 prune (AvailTC n ns) | null uqs = Nothing
467 | otherwise = Just (AvailTC n uqs)
469 uqs = filter unqual_in_scope ns
471 unqual_in_scope n = unQualInScope name_env n
473 entity_avail_env = listToUFM [ (name,avail) | avail <- avails,
474 name <- availNames avail]
476 plusExportAvails :: ExportAvails -> ExportAvails -> ExportAvails
477 plusExportAvails (m1, e1) (m2, e2)
478 = (plusFM_C (++) m1 m2, plusAvailEnv e1 e2)
479 -- ToDo: wasteful: we do this once for each constructor!
483 %************************************************************************
485 \subsection{Export list processing}
487 %************************************************************************
489 Processing the export list.
491 You might think that we should record things that appear in the export list
492 as ``occurrences'' (using @addOccurrenceName@), but you'd be wrong.
493 We do check (here) that they are in scope,
494 but there is no need to slurp in their actual declaration
495 (which is what @addOccurrenceName@ forces).
497 Indeed, doing so would big trouble when
498 compiling @PrelBase@, because it re-exports @GHC@, which includes @takeMVar#@,
499 whose type includes @ConcBase.StateAndSynchVar#@, and so on...
502 type ExportAccum -- The type of the accumulating parameter of
503 -- the main worker function in exportsFromAvail
504 = ([ModuleName], -- 'module M's seen so far
505 ExportOccMap, -- Tracks exported occurrence names
506 AvailEnv) -- The accumulated exported stuff, kept in an env
507 -- so we can common-up related AvailInfos
509 type ExportOccMap = FiniteMap OccName (Name, RdrNameIE)
510 -- Tracks what a particular exported OccName
511 -- in an export list refers to, and which item
512 -- it came from. It's illegal to export two distinct things
513 -- that have the same occurrence name
516 exportsFromAvail :: ModuleName
517 -> Maybe [RdrNameIE] -- Export spec
521 -- Complains if two distinct exports have same OccName
522 -- Warns about identical exports.
523 -- Complains about exports items not in scope
524 exportsFromAvail this_mod Nothing export_avails global_name_env
525 = exportsFromAvail this_mod true_exports export_avails global_name_env
527 true_exports = Just $ if this_mod == mAIN_Name
528 then [IEVar main_RDR]
529 -- export Main.main *only* unless otherwise specified,
530 else [IEModuleContents this_mod]
531 -- but for all other modules export everything.
533 exportsFromAvail this_mod (Just export_items)
534 (mod_avail_env, entity_avail_env)
536 = doptRn Opt_WarnDuplicateExports `thenRn` \ warn_dup_exports ->
537 foldlRn (exports_from_item warn_dup_exports)
538 ([], emptyFM, emptyAvailEnv) export_items
539 `thenRn` \ (_, _, export_avail_map) ->
541 export_avails :: [AvailInfo]
542 export_avails = nameEnvElts export_avail_map
544 returnRn export_avails
547 exports_from_item :: Bool -> ExportAccum -> RdrNameIE -> RnMG ExportAccum
549 exports_from_item warn_dups acc@(mods, occs, avails) ie@(IEModuleContents mod)
550 | mod `elem` mods -- Duplicate export of M
551 = warnCheckRn warn_dups (dupModuleExport mod) `thenRn_`
555 = case lookupFM mod_avail_env mod of
556 Nothing -> failWithRn acc (modExportErr mod)
557 Just mod_avails -> foldlRn (check_occs ie) occs mod_avails
560 avails' = foldl addAvail avails mod_avails
562 returnRn (mod:mods, occs', avails')
564 exports_from_item warn_dups acc@(mods, occs, avails) ie
565 | not (maybeToBool maybe_in_scope)
566 = failWithRn acc (unknownNameErr (ieName ie))
568 | not (null dup_names)
569 = addNameClashErrRn rdr_name ((name,prov):dup_names) `thenRn_`
573 -- I can't see why this should ever happen; if the thing is in scope
574 -- at all it ought to have some availability
575 | not (maybeToBool maybe_avail)
576 = pprTrace "exportsFromAvail: curious Nothing:" (ppr name)
581 = failWithRn acc (exportItemErr ie)
583 | otherwise -- Phew! It's OK! Now to check the occurrence stuff!
586 = warnCheckRn (ok_item ie avail) (dodgyExportWarn ie) `thenRn_`
587 check_occs ie occs export_avail `thenRn` \ occs' ->
588 returnRn (mods, occs', addAvail avails export_avail)
592 maybe_in_scope = lookupFM global_name_env rdr_name
593 Just ((name,prov):dup_names) = maybe_in_scope
594 maybe_avail = lookupUFM entity_avail_env name
595 Just avail = maybe_avail
596 maybe_export_avail = filterAvail ie avail
597 enough_avail = maybeToBool maybe_export_avail
598 Just export_avail = maybe_export_avail
600 ok_item (IEThingAll _) (AvailTC _ [n]) = False
601 -- This occurs when you import T(..), but
602 -- only export T abstractly. The single [n]
603 -- in the AvailTC is the type or class itself
606 check_occs :: RdrNameIE -> ExportOccMap -> AvailInfo -> RnMG ExportOccMap
607 check_occs ie occs avail
608 = doptRn Opt_WarnDuplicateExports `thenRn` \ warn_dup_exports ->
609 foldlRn (check warn_dup_exports) occs (availNames avail)
611 check warn_dup occs name
612 = case lookupFM occs name_occ of
613 Nothing -> returnRn (addToFM occs name_occ (name, ie))
615 | name == name' -> -- Duplicate export
617 (dupExportWarn name_occ ie ie')
618 `thenRn_` returnRn occs
620 | otherwise -> -- Same occ name but different names: an error
621 failWithRn occs (exportClashErr name_occ ie ie')
623 name_occ = nameOccName name
625 mk_export_fn :: NameSet -> (Name -> Bool) -- True => exported
626 mk_export_fn exported_names = \name -> name `elemNameSet` exported_names
629 %************************************************************************
633 %************************************************************************
636 badImportItemErr mod ie
637 = sep [ptext SLIT("Module"), quotes (ppr mod),
638 ptext SLIT("does not export"), quotes (ppr ie)]
640 dodgyImportWarn mod item = dodgyMsg (ptext SLIT("import")) item
641 dodgyExportWarn item = dodgyMsg (ptext SLIT("export")) item
643 dodgyMsg kind item@(IEThingAll tc)
644 = sep [ ptext SLIT("The") <+> kind <+> ptext SLIT("item") <+> quotes (ppr item),
645 ptext SLIT("suggests that") <+> quotes (ppr tc) <+> ptext SLIT("has constructor or class methods"),
646 ptext SLIT("but it has none; it is a type synonym or abstract type or class") ]
649 = hsep [ ptext SLIT("Unknown module in export list: module"), quotes (ppr mod)]
651 exportItemErr export_item
652 = sep [ ptext SLIT("The export item") <+> quotes (ppr export_item),
653 ptext SLIT("attempts to export constructors or class methods that are not visible here") ]
655 exportClashErr occ_name ie1 ie2
656 = hsep [ptext SLIT("The export items"), quotes (ppr ie1)
657 ,ptext SLIT("and"), quotes (ppr ie2)
658 ,ptext SLIT("create conflicting exports for"), quotes (ppr occ_name)]
661 = vcat [ptext SLIT("Multiple declarations of") <+> quotes (ppr n),
662 nest 4 (vcat (map ppr sorted_locs))]
664 sorted_locs = sortLt occ'ed_before (map nameSrcLoc (n:ns))
665 occ'ed_before a b = LT == compare a b
667 dupExportWarn occ_name ie1 ie2
668 = hsep [quotes (ppr occ_name),
669 ptext SLIT("is exported by"), quotes (ppr ie1),
670 ptext SLIT("and"), quotes (ppr ie2)]
673 = hsep [ptext SLIT("Duplicate"),
674 quotes (ptext SLIT("Module") <+> ppr mod),
675 ptext SLIT("in export list")]