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 ( opt_NoImplicitPrelude, opt_WarnDuplicateExports )
15 import HsSyn ( HsModule(..), HsDecl(..), IE(..), ieName, ImportDecl(..),
18 import RdrHsSyn ( RdrNameIE, RdrNameImportDecl,
19 RdrNameHsModule, RdrNameHsDecl
21 import RnIfaces ( getInterfaceExports, getDeclBinders,
22 recordLocalSlurps, checkModUsage, findAndReadIface, outOfDate
28 import PrelNames ( pRELUDE_Name, mAIN_Name, main_RDR )
29 import UniqFM ( lookupUFM )
30 import Bag ( bagToList )
31 import Module ( ModuleName, mkThisModule, pprModuleName, WhereFrom(..) )
33 import Name ( Name, ExportFlag(..), ImportReason(..), Provenance(..),
34 setLocalNameSort, nameOccName, nameEnvElts
36 import RdrName ( RdrName, rdrNameOcc, setRdrNameOcc, mkRdrQual, mkRdrUnqual, isQual, isUnqual )
37 import OccName ( setOccNameSpace, dataName )
38 import NameSet ( elemNameSet, emptyNameSet )
40 import Maybes ( maybeToBool, catMaybes, mapMaybe )
41 import UniqFM ( emptyUFM, listToUFM )
42 import ListSetOps ( removeDups )
43 import Util ( sortLt )
44 import List ( partition )
49 %************************************************************************
51 \subsection{Get global names}
53 %************************************************************************
56 getGlobalNames :: RdrNameHsModule
57 -> RnMG (Maybe (GlobalRdrEnv, -- Maps all in-scope things
58 GlobalRdrEnv, -- Maps just *local* things
59 Avails, -- The exported stuff
60 AvailEnv, -- Maps a name to its parent AvailInfo
61 -- Just for in-scope things only
62 Maybe ParsedIface -- The old interface file, if any
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 -> ExportFlag
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 eacly exit
128 checkErrsRn `thenRn` \ no_errs_so_far ->
129 if not no_errs_so_far then
130 -- Found errors already, so exit now
133 checkEarlyExit this_mod `thenRn` \ (up_to_date, old_iface) ->
135 -- Interface files are sufficiently unchanged
136 putDocRn (text "Compilation IS NOT required") `thenRn_`
140 -- PROCESS EXPORT LISTS
141 exportsFromAvail this_mod exports all_avails gbl_env `thenRn` \ export_avails ->
145 returnRn (Just (gbl_env, local_gbl_env, export_avails, global_avail_env, old_iface))
148 all_imports = prel_imports ++ imports
150 -- NB: opt_NoImplicitPrelude is slightly different to import Prelude ();
151 -- because the former doesn't even look at Prelude.hi for instance declarations,
152 -- whereas the latter does.
153 prel_imports | this_mod == pRELUDE_Name ||
154 explicit_prelude_import ||
155 opt_NoImplicitPrelude
158 | otherwise = [ImportDecl pRELUDE_Name
160 False {- Not qualified -}
161 Nothing {- No "as" -}
162 Nothing {- No import list -}
165 explicit_prelude_import
166 = not (null [ () | (ImportDecl mod _ _ _ _ _) <- imports, mod == pRELUDE_Name ])
170 checkEarlyExit mod_name
171 = traceRn (text "Considering whether compilation is required...") `thenRn_`
173 -- Read the old interface file, if any, for the module being compiled
174 findAndReadIface doc_str mod_name False {- Not hi-boot -} `thenRn` \ maybe_iface ->
176 -- CHECK WHETHER WE HAVE IT ALREADY
178 Left err -> -- Old interface file not found, so we'd better bail out
179 traceRn (vcat [ptext SLIT("No old interface file for") <+> pprModuleName mod_name,
181 returnRn (outOfDate, Nothing)
184 | panic "checkEarlyExit: ???: not opt_SourceUnchanged"
185 -> -- Source code changed
186 traceRn (nest 4 (text "source file changed or recompilation check turned off")) `thenRn_`
187 returnRn (False, Just iface)
190 -> -- Source code unchanged and no errors yet... carry on
191 checkModUsage (pi_usages iface) `thenRn` \ up_to_date ->
192 returnRn (up_to_date, Just iface)
194 -- Only look in current directory, with suffix .hi
195 doc_str = sep [ptext SLIT("need usage info from"), pprModuleName mod_name]
199 importsFromImportDecl :: (Name -> Bool) -- OK to omit qualifier
201 -> RnMG (GlobalRdrEnv,
204 importsFromImportDecl is_unqual (ImportDecl imp_mod_name from qual_only as_mod import_spec iloc)
205 = pushSrcLocRn iloc $
206 getInterfaceExports imp_mod_name from `thenRn` \ (imp_mod, avails) ->
209 -- If there's an error in getInterfaceExports, (e.g. interface
210 -- file not found) we get lots of spurious errors from 'filterImports'
211 returnRn (emptyRdrEnv, mkEmptyExportAvails imp_mod_name)
214 filterImports imp_mod_name import_spec avails `thenRn` \ (filtered_avails, hides, explicits) ->
217 mk_provenance name = NonLocalDef (UserImport imp_mod iloc (name `elemNameSet` explicits))
221 qualifyImports imp_mod_name
222 (not qual_only) -- Maybe want unqualified names
230 importsFromLocalDecls mod_name rec_exp_fn decls
231 = mapRn (getLocalDeclBinders mod rec_exp_fn) decls `thenRn` \ avails_s ->
234 avails = concat avails_s
236 all_names :: [Name] -- All the defns; no dups eliminated
237 all_names = [name | avail <- avails, name <- availNames avail]
240 (_, dups) = removeDups compare all_names
242 -- Check for duplicate definitions
243 mapRn_ (addErrRn . dupDeclErr) dups `thenRn_`
245 -- Record that locally-defined things are available
246 recordLocalSlurps avails `thenRn_`
248 -- Build the environment
249 qualifyImports mod_name
250 True -- Want unqualified names
253 (\n -> LocalDef) -- Provenance is local
256 mod = mkThisModule mod_name
258 getLocalDeclBinders :: Module
259 -> (Name -> Bool) -- Is-exported predicate
260 -> RdrNameHsDecl -> RnMG Avails
261 getLocalDeclBinders mod rec_exp_fn (ValD binds)
262 = mapRn do_one (bagToList (collectTopBinders binds))
264 do_one (rdr_name, loc) = newLocalName mod rec_exp_fn rdr_name loc `thenRn` \ name ->
265 returnRn (Avail name)
267 getLocalDeclBinders mod rec_exp_fn decl
268 = getDeclBinders (newLocalName mod rec_exp_fn) decl `thenRn` \ maybe_avail ->
270 Nothing -> returnRn [] -- Instance decls and suchlike
271 Just avail -> returnRn [avail]
273 newLocalName mod rec_exp_fn rdr_name loc
274 = check_unqual rdr_name loc `thenRn_`
275 newTopBinder mod rdr_name loc `thenRn` \ name ->
276 returnRn (setLocalNameSort name (rec_exp_fn name))
278 -- There should never be a qualified name in a binding position (except in instance decls)
279 -- The parser doesn't check this because the same parser parses instance decls
280 check_unqual rdr_name loc
281 | isUnqual rdr_name = returnRn ()
282 | otherwise = qualNameErr (text "the binding for" <+> quotes (ppr rdr_name))
287 %************************************************************************
289 \subsection{Filtering imports}
291 %************************************************************************
293 @filterImports@ takes the @ExportEnv@ telling what the imported module makes
294 available, and filters it through the import spec (if any).
297 filterImports :: ModuleName -- The module being imported
298 -> Maybe (Bool, [RdrNameIE]) -- Import spec; True => hiding
299 -> [AvailInfo] -- What's available
300 -> RnMG ([AvailInfo], -- What's actually imported
301 [AvailInfo], -- What's to be hidden
302 -- (the unqualified version, that is)
303 -- (We need to return both the above sets, because
304 -- the qualified version is never hidden; so we can't
305 -- implement hiding by reducing what's imported.)
306 NameSet) -- What was imported explicitly
308 -- Complains if import spec mentions things that the module doesn't export
309 -- Warns/informs if import spec contains duplicates.
310 filterImports mod Nothing imports
311 = returnRn (imports, [], emptyNameSet)
313 filterImports mod (Just (want_hiding, import_items)) avails
314 = flatMapRn get_item import_items `thenRn` \ avails_w_explicits ->
316 (item_avails, explicits_s) = unzip avails_w_explicits
317 explicits = foldl addListToNameSet emptyNameSet explicits_s
321 -- All imported; item_avails to be hidden
322 returnRn (avails, item_avails, emptyNameSet)
324 -- Just item_avails imported; nothing to be hidden
325 returnRn (item_avails, [], explicits)
327 import_fm :: FiniteMap OccName AvailInfo
328 import_fm = listToFM [ (nameOccName name, avail)
330 name <- availNames avail]
331 -- Even though availNames returns data constructors too,
332 -- they won't make any difference because naked entities like T
333 -- in an import list map to TcOccs, not VarOccs.
335 bale_out item = addErrRn (badImportItemErr mod item) `thenRn_`
338 get_item item@(IEModuleContents _) = bale_out item
340 get_item item@(IEThingAll _)
341 = case check_item item of
342 Nothing -> bale_out item
343 Just avail@(AvailTC _ [n]) -> -- This occurs when you import T(..), but
344 -- only export T abstractly. The single [n]
345 -- in the AvailTC is the type or class itself
346 addWarnRn (dodgyImportWarn mod item) `thenRn_`
347 returnRn [(avail, [availName avail])]
348 Just avail -> returnRn [(avail, [availName avail])]
350 get_item item@(IEThingAbs n)
351 | want_hiding -- hiding( C )
352 -- Here the 'C' can be a data constructor *or* a type/class
353 = case catMaybes [check_item item, check_item (IEThingAbs data_n)] of
355 avails -> returnRn [(a, []) | a <- avails]
356 -- The 'explicits' list is irrelevant when hiding
358 data_n = setRdrNameOcc n (setOccNameSpace (rdrNameOcc n) dataName)
361 = case check_item item of
362 Nothing -> bale_out item
363 Just avail -> returnRn [(avail, availNames avail)]
366 | not (maybeToBool maybe_in_import_avails) ||
367 not (maybeToBool maybe_filtered_avail)
371 = Just filtered_avail
374 wanted_occ = rdrNameOcc (ieName item)
375 maybe_in_import_avails = lookupFM import_fm wanted_occ
377 Just avail = maybe_in_import_avails
378 maybe_filtered_avail = filterAvail item avail
379 Just filtered_avail = maybe_filtered_avail
384 %************************************************************************
386 \subsection{Qualifiying imports}
388 %************************************************************************
390 @qualifyImports@ takes the @ExportEnv@ after filtering through the import spec
391 of an import decl, and deals with producing an @RnEnv@ with the
392 right qualified names. It also turns the @Names@ in the @ExportEnv@ into
393 fully fledged @Names@.
396 qualifyImports :: ModuleName -- Imported module
397 -> Bool -- True <=> want unqualified import
398 -> Maybe ModuleName -- Optional "as M" part
399 -> [AvailInfo] -- What's to be hidden
400 -> (Name -> Provenance)
401 -> Avails -- Whats imported and how
402 -> RnMG (GlobalRdrEnv, ExportAvails)
404 qualifyImports this_mod unqual_imp as_mod hides mk_provenance avails
406 -- Make the name environment. We're talking about a
407 -- single module here, so there must be no name clashes.
408 -- In practice there only ever will be if it's the module
411 -- Add the things that are available
412 name_env1 = foldl add_avail emptyRdrEnv avails
414 -- Delete things that are hidden
415 name_env2 = foldl del_avail name_env1 hides
417 -- Create the export-availability info
418 export_avails = mkExportAvails qual_mod unqual_imp name_env2 avails
420 returnRn (name_env2, export_avails)
423 qual_mod = case as_mod of
425 Just another_name -> another_name
427 add_avail :: GlobalRdrEnv -> AvailInfo -> GlobalRdrEnv
428 add_avail env avail = foldl add_name env (availNames avail)
434 env1 = addOneToGlobalRdrEnv env (mkRdrQual qual_mod occ) (name,prov)
435 env2 = addOneToGlobalRdrEnv env1 (mkRdrUnqual occ) (name,prov)
436 occ = nameOccName name
437 prov = mk_provenance name
439 del_avail env avail = foldl delOneFromGlobalRdrEnv env rdr_names
441 rdr_names = map (mkRdrUnqual . nameOccName) (availNames avail)
444 mkEmptyExportAvails :: ModuleName -> ExportAvails
445 mkEmptyExportAvails mod_name = (unitFM mod_name [], emptyUFM)
447 mkExportAvails :: ModuleName -> Bool -> GlobalRdrEnv -> [AvailInfo] -> ExportAvails
448 mkExportAvails mod_name unqual_imp name_env avails
449 = (mod_avail_env, entity_avail_env)
451 mod_avail_env = unitFM mod_name unqual_avails
453 -- unqual_avails is the Avails that are visible in *unqualfied* form
454 -- (1.4 Report, Section 5.1.1)
456 -- import T hiding( f )
457 -- we delete f from avails
459 unqual_avails | not unqual_imp = [] -- Short cut when no unqualified imports
460 | otherwise = mapMaybe prune avails
462 prune (Avail n) | unqual_in_scope n = Just (Avail n)
463 prune (Avail n) | otherwise = Nothing
464 prune (AvailTC n ns) | null uqs = Nothing
465 | otherwise = Just (AvailTC n uqs)
467 uqs = filter unqual_in_scope ns
469 unqual_in_scope n = unQualInScope name_env n
471 entity_avail_env = listToUFM [ (name,avail) | avail <- avails,
472 name <- availNames avail]
474 plusExportAvails :: ExportAvails -> ExportAvails -> ExportAvails
475 plusExportAvails (m1, e1) (m2, e2)
476 = (plusFM_C (++) m1 m2, plusAvailEnv e1 e2)
477 -- ToDo: wasteful: we do this once for each constructor!
481 %************************************************************************
483 \subsection{Export list processing}
485 %************************************************************************
487 Processing the export list.
489 You might think that we should record things that appear in the export list
490 as ``occurrences'' (using @addOccurrenceName@), but you'd be wrong.
491 We do check (here) that they are in scope,
492 but there is no need to slurp in their actual declaration
493 (which is what @addOccurrenceName@ forces).
495 Indeed, doing so would big trouble when
496 compiling @PrelBase@, because it re-exports @GHC@, which includes @takeMVar#@,
497 whose type includes @ConcBase.StateAndSynchVar#@, and so on...
500 type ExportAccum -- The type of the accumulating parameter of
501 -- the main worker function in exportsFromAvail
502 = ([ModuleName], -- 'module M's seen so far
503 ExportOccMap, -- Tracks exported occurrence names
504 AvailEnv) -- The accumulated exported stuff, kept in an env
505 -- so we can common-up related AvailInfos
507 type ExportOccMap = FiniteMap OccName (Name, RdrNameIE)
508 -- Tracks what a particular exported OccName
509 -- in an export list refers to, and which item
510 -- it came from. It's illegal to export two distinct things
511 -- that have the same occurrence name
514 exportsFromAvail :: ModuleName
515 -> Maybe [RdrNameIE] -- Export spec
519 -- Complains if two distinct exports have same OccName
520 -- Warns about identical exports.
521 -- Complains about exports items not in scope
522 exportsFromAvail this_mod Nothing export_avails global_name_env
523 = exportsFromAvail this_mod true_exports export_avails global_name_env
525 true_exports = Just $ if this_mod == mAIN_Name
526 then [IEVar main_RDR]
527 -- export Main.main *only* unless otherwise specified,
528 else [IEModuleContents this_mod]
529 -- but for all other modules export everything.
531 exportsFromAvail this_mod (Just export_items)
532 (mod_avail_env, entity_avail_env)
534 = foldlRn exports_from_item
535 ([], emptyFM, emptyAvailEnv) export_items `thenRn` \ (_, _, export_avail_map) ->
537 export_avails :: [AvailInfo]
538 export_avails = nameEnvElts export_avail_map
540 returnRn export_avails
543 exports_from_item :: ExportAccum -> RdrNameIE -> RnMG ExportAccum
545 exports_from_item acc@(mods, occs, avails) ie@(IEModuleContents mod)
546 | mod `elem` mods -- Duplicate export of M
547 = warnCheckRn opt_WarnDuplicateExports
548 (dupModuleExport mod) `thenRn_`
552 = case lookupFM mod_avail_env mod of
553 Nothing -> failWithRn acc (modExportErr mod)
554 Just mod_avails -> foldlRn (check_occs ie) occs mod_avails
557 avails' = foldl addAvail avails mod_avails
559 returnRn (mod:mods, occs', avails')
561 exports_from_item acc@(mods, occs, avails) ie
562 | not (maybeToBool maybe_in_scope)
563 = failWithRn acc (unknownNameErr (ieName ie))
565 | not (null dup_names)
566 = addNameClashErrRn rdr_name (name:dup_names) `thenRn_`
570 -- I can't see why this should ever happen; if the thing is in scope
571 -- at all it ought to have some availability
572 | not (maybeToBool maybe_avail)
573 = pprTrace "exportsFromAvail: curious Nothing:" (ppr name)
578 = failWithRn acc (exportItemErr ie)
580 | otherwise -- Phew! It's OK! Now to check the occurrence stuff!
583 = warnCheckRn (ok_item ie avail) (dodgyExportWarn ie) `thenRn_`
584 check_occs ie occs export_avail `thenRn` \ occs' ->
585 returnRn (mods, occs', addAvail avails export_avail)
589 maybe_in_scope = lookupFM global_name_env rdr_name
590 Just ((name,_):dup_names) = maybe_in_scope
591 maybe_avail = lookupUFM entity_avail_env name
592 Just avail = maybe_avail
593 maybe_export_avail = filterAvail ie avail
594 enough_avail = maybeToBool maybe_export_avail
595 Just export_avail = maybe_export_avail
597 ok_item (IEThingAll _) (AvailTC _ [n]) = False
598 -- This occurs when you import T(..), but
599 -- only export T abstractly. The single [n]
600 -- in the AvailTC is the type or class itself
603 check_occs :: RdrNameIE -> ExportOccMap -> AvailInfo -> RnMG ExportOccMap
604 check_occs ie occs avail
605 = foldlRn check occs (availNames avail)
608 = case lookupFM occs name_occ of
609 Nothing -> returnRn (addToFM occs name_occ (name, ie))
611 | name == name' -> -- Duplicate export
612 warnCheckRn opt_WarnDuplicateExports
613 (dupExportWarn name_occ ie ie')
614 `thenRn_` returnRn occs
616 | otherwise -> -- Same occ name but different names: an error
617 failWithRn occs (exportClashErr name_occ ie ie')
619 name_occ = nameOccName name
621 mk_export_fn :: NameSet -> (Name -> ExportFlag)
622 mk_export_fn exported_names
623 = \name -> if name `elemNameSet` exported_names
628 %************************************************************************
632 %************************************************************************
635 badImportItemErr mod ie
636 = sep [ptext SLIT("Module"), quotes (pprModuleName mod),
637 ptext SLIT("does not export"), quotes (ppr ie)]
639 dodgyImportWarn mod item = dodgyMsg (ptext SLIT("import")) item
640 dodgyExportWarn item = dodgyMsg (ptext SLIT("export")) item
642 dodgyMsg kind item@(IEThingAll tc)
643 = sep [ ptext SLIT("The") <+> kind <+> ptext SLIT("item") <+> quotes (ppr item),
644 ptext SLIT("suggests that") <+> quotes (ppr tc) <+> ptext SLIT("has constructor or class methods"),
645 ptext SLIT("but it has none; it is a type synonym or abstract type or class") ]
648 = hsep [ ptext SLIT("Unknown module in export list: module"), quotes (pprModuleName mod)]
650 exportItemErr export_item
651 = sep [ ptext SLIT("The export item") <+> quotes (ppr export_item),
652 ptext SLIT("attempts to export constructors or class methods that are not visible here") ]
654 exportClashErr occ_name ie1 ie2
655 = hsep [ptext SLIT("The export items"), quotes (ppr ie1)
656 ,ptext SLIT("and"), quotes (ppr ie2)
657 ,ptext SLIT("create conflicting exports for"), quotes (ppr occ_name)]
660 = vcat [ptext SLIT("Multiple declarations of") <+> quotes (ppr n),
661 nest 4 (vcat (map ppr sorted_locs))]
663 sorted_locs = sortLt occ'ed_before (map nameSrcLoc (n:ns))
664 occ'ed_before a b = LT == compare a b
666 dupExportWarn occ_name ie1 ie2
667 = hsep [quotes (ppr occ_name),
668 ptext SLIT("is exported by"), quotes (ppr ie1),
669 ptext SLIT("and"), quotes (ppr ie2)]
672 = hsep [ptext SLIT("Duplicate"),
673 quotes (ptext SLIT("Module") <+> pprModuleName mod),
674 ptext SLIT("in export list")]