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,
14 opt_SourceUnchanged, opt_WarnUnusedBinds
17 import HsSyn ( HsModule(..), ImportDecl(..), HsDecl(..), TyClDecl(..),
19 ForeignDecl(..), ForKind(..), isDynamic,
20 FixitySig(..), Sig(..),
23 import RdrHsSyn ( RdrNameIE, RdrNameImportDecl,
24 RdrNameHsModule, RdrNameHsDecl
26 import RnIfaces ( getInterfaceExports, getDeclBinders, getImportedFixities,
27 recordSlurp, checkUpToDate
34 import PrelInfo ( main_RDR )
35 import UniqFM ( lookupUFM )
36 import Bag ( bagToList )
37 import Maybes ( maybeToBool )
38 import Module ( pprModule )
41 import RdrName ( RdrName, rdrNameOcc, mkRdrQual, mkRdrUnqual )
42 import SrcLoc ( SrcLoc )
43 import NameSet ( elemNameSet, emptyNameSet )
45 import Unique ( getUnique )
46 import Util ( removeDups, equivClassesByUniq, sortLt )
51 %************************************************************************
53 \subsection{Get global names}
55 %************************************************************************
58 getGlobalNames :: RdrNameHsModule
59 -> RnMG (Maybe (ExportEnv,
61 NameEnv AvailInfo -- 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 (\ ~(rec_exported_avails, _) ->
71 fixRn (\ ~(rec_rn_env, _) ->
73 rec_unqual_fn :: Name -> Bool -- Is this chap in scope unqualified?
74 rec_unqual_fn = unQualInScope rec_rn_env
76 rec_exp_fn :: Name -> ExportFlag
77 rec_exp_fn = mk_export_fn (availsToNameSet rec_exported_avails)
79 setOmitQualFn rec_unqual_fn $
80 setModuleRn this_mod $
82 -- PROCESS LOCAL DECLS
83 -- Do these *first* so that the correct provenance gets
84 -- into the global name cache.
85 importsFromLocalDecls this_mod rec_exp_fn decls `thenRn` \ (local_gbl_env, local_mod_avails) ->
87 -- PROCESS IMPORT DECLS
88 mapAndUnzipRn importsFromImportDecl all_imports `thenRn` \ (imp_gbl_envs, imp_avails_s) ->
91 -- We put the local env second, so that a local provenance
92 -- "wins", even if a module imports itself.
94 gbl_env :: GlobalRdrEnv
95 imp_gbl_env = foldr plusGlobalRdrEnv emptyRdrEnv imp_gbl_envs
96 gbl_env = imp_gbl_env `plusGlobalRdrEnv` local_gbl_env
98 all_avails :: ExportAvails
99 all_avails = foldr plusExportAvails local_mod_avails imp_avails_s
101 returnRn (gbl_env, all_avails)
102 ) `thenRn` \ (gbl_env, all_avails) ->
104 -- TRY FOR EARLY EXIT
105 -- We can't go for an early exit before this because we have to check
106 -- for name clashes. Consider:
108 -- module A where module B where
112 -- Suppose I've compiled everything up, and then I add a
113 -- new definition to module B, that defines "f".
115 -- Then I must detect the name clash in A before going for an early
116 -- exit. The early-exit code checks what's actually needed from B
117 -- to compile A, and of course that doesn't include B.f. That's
118 -- why we wait till after the plusRnEnv stuff to do the early-exit.
119 checkEarlyExit this_mod `thenRn` \ up_to_date ->
121 returnRn (junk_exp_fn, Nothing)
124 -- PROCESS EXPORT LISTS
125 exportsFromAvail this_mod exports all_avails gbl_env `thenRn` \ exported_avails ->
128 returnRn (exported_avails, Just (all_avails, gbl_env))
129 ) `thenRn` \ (exported_avails, maybe_stuff) ->
131 case maybe_stuff of {
132 Nothing -> returnRn Nothing ;
133 Just (all_avails, gbl_env) ->
136 -- DEAL WITH FIXITIES
137 fixitiesFromLocalDecls gbl_env decls `thenRn` \ local_fixity_env ->
138 getImportedFixities gbl_env `thenRn` \ imp_fixity_env ->
140 -- Export only those fixities that are for names that are
141 -- (a) defined in this module
143 exported_fixities :: [(Name,Fixity)]
144 exported_fixities = [(name,fixity) | FixitySig name fixity _ <- nameEnvElts local_fixity_env,
145 isLocallyDefined name
148 fixity_env = imp_fixity_env `plusNameEnv` local_fixity_env
150 traceRn (text "fixity env" <+> vcat (map ppr (nameEnvElts fixity_env))) `thenRn_`
154 export_env = ExportEnv exported_avails exported_fixities
155 rn_env = RnEnv gbl_env fixity_env
156 (_, global_avail_env) = all_avails
158 returnRn (Just (export_env, rn_env, global_avail_env))
161 junk_exp_fn = error "RnNames:export_fn"
163 all_imports = prel_imports ++ imports
165 -- NB: opt_NoImplicitPrelude is slightly different to import Prelude ();
166 -- because the former doesn't even look at Prelude.hi for instance declarations,
167 -- whereas the latter does.
168 prel_imports | this_mod == pRELUDE ||
169 explicit_prelude_import ||
170 opt_NoImplicitPrelude
173 | otherwise = [ImportDecl pRELUDE
174 False {- Not qualified -}
175 Nothing {- No "as" -}
176 Nothing {- No import list -}
179 explicit_prelude_import
180 = not (null [ () | (ImportDecl mod qual _ _ _) <- imports, mod == pRELUDE ])
185 = checkErrsRn `thenRn` \ no_errs_so_far ->
186 if not no_errs_so_far then
187 -- Found errors already, so exit now
191 traceRn (text "Considering whether compilation is required...") `thenRn_`
192 if not opt_SourceUnchanged then
193 -- Source code changed and no errors yet... carry on
194 traceRn (nest 4 (text "source file changed or recompilation check turned off")) `thenRn_`
198 -- Unchanged source, and no errors yet; see if usage info
199 -- up to date, and exit if so
200 checkUpToDate mod `thenRn` \ up_to_date ->
201 putDocRn (text "Compilation" <+>
202 text (if up_to_date then "IS NOT" else "IS") <+>
203 text "required") `thenRn_`
208 importsFromImportDecl :: RdrNameImportDecl
209 -> RnMG (GlobalRdrEnv,
212 importsFromImportDecl (ImportDecl imp_mod qual_only as_mod import_spec iloc)
213 = pushSrcLocRn iloc $
214 getInterfaceExports imp_mod `thenRn` \ (imp_mod, avails) ->
217 -- If there's an error in getInterfaceExports, (e.g. interface
218 -- file not found) we get lots of spurious errors from 'filterImports'
219 returnRn (emptyRdrEnv, mkEmptyExportAvails imp_mod)
222 filterImports imp_mod import_spec avails `thenRn` \ (filtered_avails, hides, explicits) ->
224 -- We 'improve' the provenance by setting
225 -- (a) the import-reason field, so that the Name says how it came into scope
226 -- including whether it's explicitly imported
227 -- (b) the print-unqualified field
228 -- But don't fiddle with wired-in things or we get in a twist
230 improve_prov name = setNameImportReason name (UserImport imp_mod iloc (is_explicit name))
231 is_explicit name = name `elemNameSet` explicits
233 qualifyImports imp_mod
234 (not qual_only) -- Maybe want unqualified names
236 filtered_avails improve_prov `thenRn` \ (rdr_name_env, mod_avails) ->
238 returnRn (rdr_name_env, mod_avails)
243 importsFromLocalDecls mod rec_exp_fn decls
244 = mapRn (getLocalDeclBinders newLocalName) decls `thenRn` \ avails_s ->
247 avails = concat avails_s
249 all_names :: [Name] -- All the defns; no dups eliminated
250 all_names = [name | avail <- avails, name <- availNames avail]
253 dups = filter non_singleton (equivClassesByUniq getUnique all_names)
255 non_singleton (x1:x2:xs) = True
256 non_singleton other = False
258 -- Check for duplicate definitions
259 mapRn_ (addErrRn . dupDeclErr) dups `thenRn_`
261 -- Record that locally-defined things are available
262 mapRn_ (recordSlurp Nothing Compulsory) avails `thenRn_`
264 -- Build the environment
266 True -- Want unqualified names
273 newLocalName rdr_name loc = newLocallyDefinedGlobalName mod (rdrNameOcc rdr_name)
276 getLocalDeclBinders :: (RdrName -> SrcLoc -> RnMG Name) -- New-name function
279 getLocalDeclBinders new_name (ValD binds)
280 = mapRn do_one (bagToList (collectTopBinders binds))
282 do_one (rdr_name, loc) = new_name rdr_name loc `thenRn` \ name ->
283 returnRn (Avail name)
285 -- foreign declarations
286 getLocalDeclBinders new_name (ForD (ForeignDecl nm kind _ dyn _ loc))
287 | binds_haskell_name kind dyn
288 = new_name nm loc `thenRn` \ name ->
289 returnRn [Avail name]
294 getLocalDeclBinders new_name decl
295 = getDeclBinders new_name decl `thenRn` \ maybe_avail ->
297 Nothing -> returnRn [] -- Instance decls and suchlike
298 Just avail -> returnRn [avail]
300 binds_haskell_name (FoImport _) _ = True
301 binds_haskell_name FoLabel _ = True
302 binds_haskell_name FoExport ext_nm = isDynamic ext_nm
304 fixitiesFromLocalDecls :: GlobalRdrEnv -> [RdrNameHsDecl] -> RnMG FixityEnv
305 fixitiesFromLocalDecls gbl_env decls
306 = foldlRn getFixities emptyNameEnv decls
308 getFixities :: FixityEnv -> RdrNameHsDecl -> RnMG FixityEnv
309 getFixities acc (FixD fix)
313 getFixities acc (TyClD (ClassDecl _ _ _ sigs _ _ _ _ _))
314 = foldlRn fix_decl acc [sig | FixSig sig <- sigs]
315 -- Get fixities from class decl sigs too.
316 getFixities acc other_decl
319 fix_decl acc (FixitySig rdr_name fixity loc)
320 = -- Check for fixity decl for something not declared
321 case lookupRdrEnv gbl_env rdr_name of {
322 Nothing | opt_WarnUnusedBinds
323 -> pushSrcLocRn loc (addWarnRn (unusedFixityDecl rdr_name fixity)) `thenRn_`
325 | otherwise -> returnRn acc ;
329 -- Check for duplicate fixity decl
330 case lookupNameEnv acc name of {
331 Just (FixitySig _ _ loc') -> addErrRn (dupFixityDecl rdr_name loc loc') `thenRn_`
335 Nothing -> returnRn (addToNameEnv acc name (FixitySig name fixity loc))
339 %************************************************************************
341 \subsection{Filtering imports}
343 %************************************************************************
345 @filterImports@ takes the @ExportEnv@ telling what the imported module makes
346 available, and filters it through the import spec (if any).
349 filterImports :: Module -- The module being imported
350 -> Maybe (Bool, [RdrNameIE]) -- Import spec; True => hiding
351 -> [AvailInfo] -- What's available
352 -> RnMG ([AvailInfo], -- What's actually imported
353 [AvailInfo], -- What's to be hidden (the unqualified version, that is)
354 NameSet) -- What was imported explicitly
356 -- Complains if import spec mentions things that the module doesn't export
357 -- Warns/informs if import spec contains duplicates.
358 filterImports mod Nothing imports
359 = returnRn (imports, [], emptyNameSet)
361 filterImports mod (Just (want_hiding, import_items)) avails
362 = mapMaybeRn check_item import_items `thenRn` \ avails_w_explicits ->
364 (item_avails, explicits_s) = unzip avails_w_explicits
365 explicits = foldl addListToNameSet emptyNameSet explicits_s
369 -- All imported; item_avails to be hidden
370 returnRn (avails, item_avails, emptyNameSet)
372 -- Just item_avails imported; nothing to be hidden
373 returnRn (item_avails, [], explicits)
375 import_fm :: FiniteMap OccName AvailInfo
376 import_fm = listToFM [ (nameOccName name, avail)
378 name <- availNames avail]
379 -- Even though availNames returns data constructors too,
380 -- they won't make any difference because naked entities like T
381 -- in an import list map to TcOccs, not VarOccs.
383 check_item item@(IEModuleContents _)
384 = addErrRn (badImportItemErr mod item) `thenRn_`
388 | not (maybeToBool maybe_in_import_avails) ||
389 not (maybeToBool maybe_filtered_avail)
390 = addErrRn (badImportItemErr mod item) `thenRn_`
393 | dodgy_import = addWarnRn (dodgyImportWarn mod item) `thenRn_`
394 returnRn (Just (filtered_avail, explicits))
396 | otherwise = returnRn (Just (filtered_avail, explicits))
399 wanted_occ = rdrNameOcc (ieName item)
400 maybe_in_import_avails = lookupFM import_fm wanted_occ
402 Just avail = maybe_in_import_avails
403 maybe_filtered_avail = filterAvail item avail
404 Just filtered_avail = maybe_filtered_avail
405 explicits | dot_dot = [availName filtered_avail]
406 | otherwise = availNames filtered_avail
408 dot_dot = case item of
412 dodgy_import = case (item, avail) of
413 (IEThingAll _, AvailTC _ [n]) -> True
414 -- This occurs when you import T(..), but
415 -- only export T abstractly. The single [n]
416 -- in the AvailTC is the type or class itself
423 %************************************************************************
425 \subsection{Qualifiying imports}
427 %************************************************************************
429 @qualifyImports@ takes the @ExportEnv@ after filtering through the import spec
430 of an import decl, and deals with producing an @RnEnv@ with the
431 right qualified names. It also turns the @Names@ in the @ExportEnv@ into
432 fully fledged @Names@.
435 qualifyImports :: Module -- Imported module
436 -> Bool -- True <=> want unqualified import
437 -> Maybe Module -- Optional "as M" part
438 -> [AvailInfo] -- What's to be hidden
439 -> Avails -- Whats imported and how
440 -> (Name -> Name) -- Improves the provenance on imported things
441 -> RnMG (GlobalRdrEnv, ExportAvails)
442 -- NB: the Names in ExportAvails don't have the improve-provenance
443 -- function applied to them
444 -- We could fix that, but I don't think it matters
446 qualifyImports this_mod unqual_imp as_mod hides
449 -- Make the name environment. We're talking about a
450 -- single module here, so there must be no name clashes.
451 -- In practice there only ever will be if it's the module
454 -- Add the things that are available
455 name_env1 = foldl add_avail emptyRdrEnv avails
457 -- Delete things that are hidden
458 name_env2 = foldl del_avail name_env1 hides
460 -- Create the export-availability info
461 export_avails = mkExportAvails qual_mod unqual_imp name_env2 avails
463 returnRn (name_env2, export_avails)
466 qual_mod = case as_mod of
468 Just another_name -> another_name
470 add_avail :: GlobalRdrEnv -> AvailInfo -> GlobalRdrEnv
471 add_avail env avail = foldl add_name env (availNames avail)
477 env1 = addOneToGlobalRdrEnv env (mkRdrQual qual_mod occ) better_name
478 env2 = addOneToGlobalRdrEnv env1 (mkRdrUnqual occ) better_name
479 occ = nameOccName name
480 better_name = improve_prov name
482 del_avail env avail = foldl delOneFromGlobalRdrEnv env rdr_names
484 rdr_names = map (mkRdrUnqual . nameOccName) (availNames avail)
488 %************************************************************************
490 \subsection{Export list processing
492 %************************************************************************
494 Processing the export list.
496 You might think that we should record things that appear in the export list as
497 ``occurrences'' (using addOccurrenceName), but you'd be wrong. We do check (here)
498 that they are in scope, but there is no need to slurp in their actual declaration
499 (which is what addOccurrenceName forces). Indeed, doing so would big trouble when
500 compiling PrelBase, because it re-exports GHC, which includes takeMVar#, whose type
501 includes ConcBase.StateAndSynchVar#, and so on...
504 type ExportAccum -- The type of the accumulating parameter of
505 -- the main worker function in exportsFromAvail
506 = ([Module], -- 'module M's seen so far
507 ExportOccMap, -- Tracks exported occurrence names
508 NameEnv AvailInfo) -- The accumulated exported stuff, kept in an env
509 -- so we can common-up related AvailInfos
511 type ExportOccMap = FiniteMap OccName (Name, RdrNameIE)
512 -- Tracks what a particular exported OccName
513 -- in an export list refers to, and which item
514 -- it came from. It's illegal to export two distinct things
515 -- that have the same occurrence name
518 exportsFromAvail :: Module
519 -> Maybe [RdrNameIE] -- Export spec
523 -- Complains if two distinct exports have same OccName
524 -- Warns about identical exports.
525 -- Complains about exports items not in scope
526 exportsFromAvail this_mod Nothing export_avails global_name_env
527 = exportsFromAvail this_mod true_exports export_avails global_name_env
529 true_exports = Just $ if this_mod == mAIN
530 then [IEVar main_RDR]
531 -- export Main.main *only* unless otherwise specified,
532 else [IEModuleContents this_mod]
533 -- but for all other modules export everything.
535 exportsFromAvail this_mod (Just export_items)
536 (mod_avail_env, entity_avail_env)
538 = foldlRn exports_from_item
539 ([], emptyFM, emptyNameEnv) export_items `thenRn` \ (_, _, export_avail_map) ->
541 export_avails :: [AvailInfo]
542 export_avails = nameEnvElts export_avail_map
544 returnRn export_avails
547 exports_from_item :: ExportAccum -> RdrNameIE -> RnMG ExportAccum
549 exports_from_item acc@(mods, occs, avails) ie@(IEModuleContents mod)
550 | mod `elem` mods -- Duplicate export of M
551 = warnCheckRn opt_WarnDuplicateExports
552 (dupModuleExport mod) `thenRn_`
556 = case lookupFM mod_avail_env mod of
557 Nothing -> failWithRn acc (modExportErr mod)
558 Just mod_avails -> foldlRn (check_occs ie) occs mod_avails `thenRn` \ occs' ->
560 avails' = foldl add_avail avails mod_avails
562 returnRn (mod:mods, occs', avails')
564 exports_from_item 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: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!
584 = check_occs ie occs export_avail `thenRn` \ occs' ->
585 returnRn (mods, occs', add_avail 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 add_avail avails avail = addToNameEnv_C plusAvail avails (availName avail) avail
599 check_occs :: RdrNameIE -> ExportOccMap -> AvailInfo -> RnMG ExportOccMap
600 check_occs ie occs avail
601 = foldlRn check occs (availNames avail)
604 = case lookupFM occs name_occ of
605 Nothing -> returnRn (addToFM occs name_occ (name, ie))
607 | name == name' -> -- Duplicate export
608 warnCheckRn opt_WarnDuplicateExports
609 (dupExportWarn name_occ ie ie') `thenRn_`
612 | otherwise -> -- Same occ name but different names: an error
613 failWithRn occs (exportClashErr name_occ ie ie')
615 name_occ = nameOccName name
617 mk_export_fn :: NameSet -> (Name -> ExportFlag)
618 mk_export_fn exported_names
619 = \name -> if name `elemNameSet` exported_names
624 %************************************************************************
628 %************************************************************************
631 badImportItemErr mod ie
632 = sep [ptext SLIT("Module"), quotes (pprModule mod),
633 ptext SLIT("does not export"), quotes (ppr ie)]
635 dodgyImportWarn mod (IEThingAll tc)
636 = sep [ptext SLIT("Module") <+> quotes (pprModule mod) <+> ptext SLIT("exports") <+> quotes (ppr tc),
637 ptext SLIT("with no constructors/class operations;"),
638 ptext SLIT("yet it is imported with a (..)")]
641 = hsep [ ptext SLIT("Unknown module in export list: module"), quotes (pprModule mod)]
643 exportItemErr export_item
644 = sep [ ptext SLIT("Bad export item"), quotes (ppr export_item)]
646 exportClashErr occ_name ie1 ie2
647 = hsep [ptext SLIT("The export items"), quotes (ppr ie1), ptext SLIT("and"), quotes (ppr ie2),
648 ptext SLIT("create conflicting exports for"), quotes (ppr occ_name)]
651 = vcat [ptext SLIT("Multiple declarations of") <+> quotes (ppr n),
652 nest 4 (vcat (map pp sorted_ns))]
654 sorted_ns = sortLt occ'ed_before (n:ns)
656 occ'ed_before a b = LT == compare (getSrcLoc a) (getSrcLoc b)
658 pp n = pprProvenance (getNameProvenance n)
660 dupExportWarn occ_name ie1 ie2
661 = hsep [quotes (ppr occ_name),
662 ptext SLIT("is exported by"), quotes (ppr ie1),
663 ptext SLIT("and"), quotes (ppr ie2)]
666 = hsep [ptext SLIT("Duplicate"),
667 quotes (ptext SLIT("Module") <+> pprModule mod),
668 ptext SLIT("in export list")]
670 unusedFixityDecl rdr_name fixity
671 = hsep [ptext SLIT("Unused fixity declaration for"), quotes (ppr rdr_name)]
673 dupFixityDecl rdr_name loc1 loc2
674 = vcat [ptext SLIT("Multiple fixity declarations for") <+> quotes (ppr rdr_name),
675 ptext SLIT("at ") <+> ppr loc1,
676 ptext SLIT("and") <+> ppr loc2]