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 UniqFM ( lookupUFM )
35 import Bag ( bagToList )
36 import Maybes ( maybeToBool )
39 import RdrName ( RdrName, rdrNameOcc, mkRdrQual, mkRdrUnqual )
40 import SrcLoc ( SrcLoc )
41 import NameSet ( elemNameSet, emptyNameSet )
43 import Unique ( getUnique )
44 import Util ( removeDups, equivClassesByUniq, sortLt )
49 %************************************************************************
51 \subsection{Get global names}
53 %************************************************************************
56 getGlobalNames :: RdrNameHsModule
57 -> RnMG (Maybe (ExportEnv,
59 NameEnv AvailInfo -- Maps a name to its parent AvailInfo
60 -- Just for in-scope things only
62 -- Nothing => no need to recompile
64 getGlobalNames (HsModule this_mod _ exports imports decls mod_loc)
65 = -- These two fix-loops are to get the right
66 -- provenance information into a Name
67 fixRn (\ ~(rec_exported_avails, _) ->
69 fixRn (\ ~(rec_rn_env, _) ->
71 rec_unqual_fn :: Name -> Bool -- Is this chap in scope unqualified?
72 rec_unqual_fn = unQualInScope rec_rn_env
74 rec_exp_fn :: Name -> ExportFlag
75 rec_exp_fn = mk_export_fn (availsToNameSet rec_exported_avails)
77 setOmitQualFn rec_unqual_fn $
78 setModuleRn this_mod $
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 `thenRn` \ (local_gbl_env, local_mod_avails) ->
85 -- PROCESS IMPORT DECLS
86 mapAndUnzipRn importsFromImportDecl all_imports `thenRn` \ (imp_gbl_envs, imp_avails_s) ->
89 -- We put the local env second, so that a local provenance
90 -- "wins", even if a module imports itself.
92 gbl_env :: GlobalRdrEnv
93 imp_gbl_env = foldr plusGlobalRdrEnv emptyRdrEnv imp_gbl_envs
94 gbl_env = imp_gbl_env `plusGlobalRdrEnv` local_gbl_env
96 all_avails :: ExportAvails
97 all_avails = foldr plusExportAvails local_mod_avails imp_avails_s
99 returnRn (gbl_env, all_avails)
100 ) `thenRn` \ (gbl_env, all_avails) ->
102 -- TRY FOR EARLY EXIT
103 -- We can't go for an early exit before this because we have to check
104 -- for name clashes. Consider:
106 -- module A where module B where
110 -- Suppose I've compiled everything up, and then I add a
111 -- new definition to module B, that defines "f".
113 -- Then I must detect the name clash in A before going for an early
114 -- exit. The early-exit code checks what's actually needed from B
115 -- to compile A, and of course that doesn't include B.f. That's
116 -- why we wait till after the plusRnEnv stuff to do the early-exit.
117 checkEarlyExit this_mod `thenRn` \ up_to_date ->
119 returnRn (junk_exp_fn, Nothing)
122 -- PROCESS EXPORT LISTS
123 exportsFromAvail this_mod exports all_avails gbl_env `thenRn` \ exported_avails ->
126 returnRn (exported_avails, Just (all_avails, gbl_env))
127 ) `thenRn` \ (exported_avails, maybe_stuff) ->
129 case maybe_stuff of {
130 Nothing -> returnRn Nothing ;
131 Just (all_avails, gbl_env) ->
134 -- DEAL WITH FIXITIES
135 fixitiesFromLocalDecls gbl_env decls `thenRn` \ local_fixity_env ->
136 getImportedFixities gbl_env `thenRn` \ imp_fixity_env ->
138 -- Export only those fixities that are for names that are
139 -- (a) defined in this module
141 exported_fixities :: [(Name,Fixity)]
142 exported_fixities = [(name,fixity) | FixitySig name fixity _ <- nameEnvElts local_fixity_env,
143 isLocallyDefined name
146 fixity_env = imp_fixity_env `plusNameEnv` local_fixity_env
148 traceRn (text "fixity env" <+> vcat (map ppr (nameEnvElts fixity_env))) `thenRn_`
152 export_env = ExportEnv exported_avails exported_fixities
153 rn_env = RnEnv gbl_env fixity_env
154 (_, global_avail_env) = all_avails
156 returnRn (Just (export_env, rn_env, global_avail_env))
159 junk_exp_fn = error "RnNames:export_fn"
161 all_imports = prel_imports ++ imports
163 -- NB: opt_NoImplicitPrelude is slightly different to import Prelude ();
164 -- because the former doesn't even look at Prelude.hi for instance declarations,
165 -- whereas the latter does.
166 prel_imports | this_mod == pRELUDE ||
167 explicit_prelude_import ||
168 opt_NoImplicitPrelude
171 | otherwise = [ImportDecl pRELUDE
172 False {- Not qualified -}
173 Nothing {- No "as" -}
174 Nothing {- No import list -}
177 explicit_prelude_import
178 = not (null [ () | (ImportDecl mod qual _ _ _) <- imports, mod == pRELUDE ])
183 = checkErrsRn `thenRn` \ no_errs_so_far ->
184 if not no_errs_so_far then
185 -- Found errors already, so exit now
189 traceRn (text "Considering whether compilation is required...") `thenRn_`
190 if not opt_SourceUnchanged then
191 -- Source code changed and no errors yet... carry on
192 traceRn (nest 4 (text "source file changed or recompilation check turned off")) `thenRn_`
196 -- Unchanged source, and no errors yet; see if usage info
197 -- up to date, and exit if so
198 checkUpToDate mod `thenRn` \ up_to_date ->
199 putDocRn (text "Compilation" <+>
200 text (if up_to_date then "IS NOT" else "IS") <+>
201 text "required") `thenRn_`
206 importsFromImportDecl :: RdrNameImportDecl
207 -> RnMG (GlobalRdrEnv,
210 importsFromImportDecl (ImportDecl imp_mod qual_only as_mod import_spec iloc)
211 = pushSrcLocRn iloc $
212 getInterfaceExports imp_mod `thenRn` \ avails ->
215 -- If there's an error in getInterfaceExports, (e.g. interface
216 -- file not found) we get lots of spurious errors from 'filterImports'
217 returnRn (emptyRdrEnv, mkEmptyExportAvails imp_mod)
220 filterImports imp_mod import_spec avails `thenRn` \ (filtered_avails, hides, explicits) ->
222 -- We 'improve' the provenance by setting
223 -- (a) the import-reason field, so that the Name says how it came into scope
224 -- including whether it's explicitly imported
225 -- (b) the print-unqualified field
226 -- But don't fiddle with wired-in things or we get in a twist
228 improve_prov name = setNameImportReason name (UserImport imp_mod iloc (is_explicit name))
229 is_explicit name = name `elemNameSet` explicits
231 qualifyImports imp_mod
232 (not qual_only) -- Maybe want unqualified names
234 filtered_avails improve_prov `thenRn` \ (rdr_name_env, mod_avails) ->
236 returnRn (rdr_name_env, mod_avails)
241 importsFromLocalDecls mod rec_exp_fn decls
242 = mapRn (getLocalDeclBinders newLocalName) decls `thenRn` \ avails_s ->
245 avails = concat avails_s
247 all_names :: [Name] -- All the defns; no dups eliminated
248 all_names = [name | avail <- avails, name <- availNames avail]
251 dups = filter non_singleton (equivClassesByUniq getUnique all_names)
253 non_singleton (x1:x2:xs) = True
254 non_singleton other = False
256 -- Check for duplicate definitions
257 mapRn (addErrRn . dupDeclErr) dups `thenRn_`
259 -- Record that locally-defined things are available
260 mapRn (recordSlurp Nothing Compulsory) avails `thenRn_`
262 -- Build the environment
264 True -- Want unqualified names
271 newLocalName rdr_name loc = newLocallyDefinedGlobalName mod (rdrNameOcc rdr_name)
274 getLocalDeclBinders :: (RdrName -> SrcLoc -> RnMG Name) -- New-name function
277 getLocalDeclBinders new_name (ValD binds)
278 = mapRn do_one (bagToList (collectTopBinders binds))
280 do_one (rdr_name, loc) = new_name rdr_name loc `thenRn` \ name ->
281 returnRn (Avail name)
283 -- foreign declarations
284 getLocalDeclBinders new_name (ForD (ForeignDecl nm kind _ dyn _ loc))
285 | binds_haskell_name kind dyn
286 = new_name nm loc `thenRn` \ name ->
287 returnRn [Avail name]
292 getLocalDeclBinders new_name decl
293 = getDeclBinders new_name decl `thenRn` \ maybe_avail ->
295 Nothing -> returnRn [] -- Instance decls and suchlike
296 Just avail -> returnRn [avail]
298 binds_haskell_name (FoImport _) _ = True
299 binds_haskell_name FoLabel _ = True
300 binds_haskell_name FoExport ext_nm = isDynamic ext_nm
302 fixitiesFromLocalDecls :: GlobalRdrEnv -> [RdrNameHsDecl] -> RnMG FixityEnv
303 fixitiesFromLocalDecls gbl_env decls
304 = foldlRn getFixities emptyNameEnv decls
306 getFixities :: FixityEnv -> RdrNameHsDecl -> RnMG FixityEnv
307 getFixities acc (FixD fix)
310 getFixities acc (TyClD (ClassDecl _ _ _ sigs _ _ _ _ _))
311 = foldlRn fix_decl acc [sig | FixSig sig <- sigs]
312 -- Get fixities from class decl sigs too
314 getFixities acc other_decl
317 fix_decl acc (FixitySig rdr_name fixity loc)
318 = -- Check for fixity decl for something not declared
319 case lookupRdrEnv gbl_env rdr_name of {
320 Nothing | opt_WarnUnusedBinds
321 -> pushSrcLocRn loc (addWarnRn (unusedFixityDecl rdr_name fixity)) `thenRn_`
323 | otherwise -> returnRn acc ;
327 -- Check for duplicate fixity decl
328 case lookupNameEnv acc name of {
329 Just (FixitySig _ _ loc') -> addErrRn (dupFixityDecl rdr_name loc loc') `thenRn_`
333 Nothing -> returnRn (addToNameEnv acc name (FixitySig name fixity loc))
337 %************************************************************************
339 \subsection{Filtering imports}
341 %************************************************************************
343 @filterImports@ takes the @ExportEnv@ telling what the imported module makes
344 available, and filters it through the import spec (if any).
347 filterImports :: Module -- The module being imported
348 -> Maybe (Bool, [RdrNameIE]) -- Import spec; True => hiding
349 -> [AvailInfo] -- What's available
350 -> RnMG ([AvailInfo], -- What's actually imported
351 [AvailInfo], -- What's to be hidden (the unqualified version, that is)
352 NameSet) -- What was imported explicitly
354 -- Complains if import spec mentions things that the module doesn't export
355 -- Warns/informs if import spec contains duplicates.
356 filterImports mod Nothing imports
357 = returnRn (imports, [], emptyNameSet)
359 filterImports mod (Just (want_hiding, import_items)) avails
360 = mapMaybeRn check_item import_items `thenRn` \ avails_w_explicits ->
362 (item_avails, explicits_s) = unzip avails_w_explicits
363 explicits = foldl addListToNameSet emptyNameSet explicits_s
367 -- All imported; item_avails to be hidden
368 returnRn (avails, item_avails, emptyNameSet)
370 -- Just item_avails imported; nothing to be hidden
371 returnRn (item_avails, [], explicits)
373 import_fm :: FiniteMap OccName AvailInfo
374 import_fm = listToFM [ (nameOccName name, avail)
376 name <- availNames avail]
377 -- Even though availNames returns data constructors too,
378 -- they won't make any difference because naked entities like T
379 -- in an import list map to TcOccs, not VarOccs.
381 check_item item@(IEModuleContents _)
382 = addErrRn (badImportItemErr mod item) `thenRn_`
386 | not (maybeToBool maybe_in_import_avails) ||
387 not (maybeToBool maybe_filtered_avail)
388 = addErrRn (badImportItemErr mod item) `thenRn_`
391 | dodgy_import = addWarnRn (dodgyImportWarn mod item) `thenRn_`
392 returnRn (Just (filtered_avail, explicits))
394 | otherwise = returnRn (Just (filtered_avail, explicits))
397 wanted_occ = rdrNameOcc (ieName item)
398 maybe_in_import_avails = lookupFM import_fm wanted_occ
400 Just avail = maybe_in_import_avails
401 maybe_filtered_avail = filterAvail item avail
402 Just filtered_avail = maybe_filtered_avail
403 explicits | dot_dot = [availName filtered_avail]
404 | otherwise = availNames filtered_avail
406 dot_dot = case item of
410 dodgy_import = case (item, avail) of
411 (IEThingAll _, AvailTC _ [n]) -> True
412 -- This occurs when you import T(..), but
413 -- only export T abstractly. The single [n]
414 -- in the AvailTC is the type or class itself
421 %************************************************************************
423 \subsection{Qualifiying imports}
425 %************************************************************************
427 @qualifyImports@ takes the @ExportEnv@ after filtering through the import spec
428 of an import decl, and deals with producing an @RnEnv@ with the
429 right qualified names. It also turns the @Names@ in the @ExportEnv@ into
430 fully fledged @Names@.
433 qualifyImports :: Module -- Imported module
434 -> Bool -- True <=> want unqualified import
435 -> Maybe Module -- Optional "as M" part
436 -> [AvailInfo] -- What's to be hidden
437 -> Avails -- Whats imported and how
438 -> (Name -> Name) -- Improves the provenance on imported things
439 -> RnMG (GlobalRdrEnv, ExportAvails)
440 -- NB: the Names in ExportAvails don't have the improve-provenance
441 -- function applied to them
442 -- We could fix that, but I don't think it matters
444 qualifyImports this_mod unqual_imp as_mod hides
447 -- Make the name environment. We're talking about a
448 -- single module here, so there must be no name clashes.
449 -- In practice there only ever will be if it's the module
452 -- Add the things that are available
453 name_env1 = foldl add_avail emptyRdrEnv avails
455 -- Delete things that are hidden
456 name_env2 = foldl del_avail name_env1 hides
458 -- Create the export-availability info
459 export_avails = mkExportAvails qual_mod unqual_imp name_env2 avails
461 returnRn (name_env2, export_avails)
464 qual_mod = case as_mod of
466 Just another_name -> another_name
468 add_avail :: GlobalRdrEnv -> AvailInfo -> GlobalRdrEnv
469 add_avail env avail = foldl add_name env (availNames avail)
475 env1 = addOneToGlobalRdrEnv env (mkRdrQual qual_mod occ) better_name
476 env2 = addOneToGlobalRdrEnv env1 (mkRdrUnqual occ) better_name
477 occ = nameOccName name
478 better_name = improve_prov name
480 del_avail env avail = foldl delOneFromGlobalRdrEnv env rdr_names
482 rdr_names = map (mkRdrUnqual . nameOccName) (availNames avail)
486 %************************************************************************
488 \subsection{Export list processing
490 %************************************************************************
492 Processing the export list.
494 You might think that we should record things that appear in the export list as
495 ``occurrences'' (using addOccurrenceName), but you'd be wrong. We do check (here)
496 that they are in scope, but there is no need to slurp in their actual declaration
497 (which is what addOccurrenceName forces). Indeed, doing so would big trouble when
498 compiling PrelBase, because it re-exports GHC, which includes takeMVar#, whose type
499 includes ConcBase.StateAndSynchVar#, and so on...
502 type ExportAccum -- The type of the accumulating parameter of
503 -- the main worker function in exportsFromAvail
504 = ([Module], -- 'module M's seen so far
505 ExportOccMap, -- Tracks exported occurrence names
506 NameEnv AvailInfo) -- 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 :: Module
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 (Just [IEModuleContents this_mod])
526 export_avails global_name_env
528 exportsFromAvail this_mod (Just export_items)
529 (mod_avail_env, entity_avail_env)
531 = foldlRn exports_from_item
532 ([], emptyFM, emptyNameEnv) export_items `thenRn` \ (_, _, export_avail_map) ->
534 export_avails :: [AvailInfo]
535 export_avails = nameEnvElts export_avail_map
537 returnRn export_avails
540 exports_from_item :: ExportAccum -> RdrNameIE -> RnMG ExportAccum
542 exports_from_item acc@(mods, occs, avails) ie@(IEModuleContents mod)
543 | mod `elem` mods -- Duplicate export of M
544 = warnCheckRn opt_WarnDuplicateExports
545 (dupModuleExport mod) `thenRn_`
549 = case lookupFM mod_avail_env mod of
550 Nothing -> failWithRn acc (modExportErr mod)
551 Just mod_avails -> foldlRn (check_occs ie) occs mod_avails `thenRn` \ occs' ->
553 avails' = foldl add_avail avails mod_avails
555 returnRn (mod:mods, occs', avails')
557 exports_from_item acc@(mods, occs, avails) ie
558 | not (maybeToBool maybe_in_scope)
559 = failWithRn acc (unknownNameErr (ieName ie))
561 | not (null dup_names)
562 = addNameClashErrRn rdr_name (name:dup_names) `thenRn_`
566 -- I can't see why this should ever happen; if the thing is in scope
567 -- at all it ought to have some availability
568 | not (maybeToBool maybe_avail)
569 = pprTrace "exportsFromAvail: curious Nothing:" (ppr name)
574 = failWithRn acc (exportItemErr ie)
576 | otherwise -- Phew! It's OK! Now to check the occurrence stuff!
577 = check_occs ie occs export_avail `thenRn` \ occs' ->
578 returnRn (mods, occs', add_avail avails export_avail)
582 maybe_in_scope = lookupFM global_name_env rdr_name
583 Just (name:dup_names) = maybe_in_scope
584 maybe_avail = lookupUFM entity_avail_env name
585 Just avail = maybe_avail
586 maybe_export_avail = filterAvail ie avail
587 enough_avail = maybeToBool maybe_export_avail
588 Just export_avail = maybe_export_avail
590 add_avail avails avail = addToNameEnv_C plusAvail avails (availName avail) avail
592 check_occs :: RdrNameIE -> ExportOccMap -> AvailInfo -> RnMG ExportOccMap
593 check_occs ie occs avail
594 = foldlRn check occs (availNames avail)
597 = case lookupFM occs name_occ of
598 Nothing -> returnRn (addToFM occs name_occ (name, ie))
600 | name == name' -> -- Duplicate export
601 warnCheckRn opt_WarnDuplicateExports
602 (dupExportWarn name_occ ie ie') `thenRn_`
605 | otherwise -> -- Same occ name but different names: an error
606 failWithRn occs (exportClashErr name_occ ie ie')
608 name_occ = nameOccName name
610 mk_export_fn :: NameSet -> (Name -> ExportFlag)
611 mk_export_fn exported_names
612 = \name -> if name `elemNameSet` exported_names
617 %************************************************************************
621 %************************************************************************
624 badImportItemErr mod ie
625 = sep [ptext SLIT("Module"), quotes (pprModule mod),
626 ptext SLIT("does not export"), quotes (ppr ie)]
628 dodgyImportWarn mod (IEThingAll tc)
629 = sep [ptext SLIT("Module") <+> quotes (pprModule mod) <+> ptext SLIT("exports") <+> quotes (ppr tc),
630 ptext SLIT("with no constructors/class operations;"),
631 ptext SLIT("yet it is imported with a (..)")]
634 = hsep [ ptext SLIT("Unknown module in export list: module"), quotes (pprModule mod)]
636 exportItemErr export_item
637 = sep [ ptext SLIT("Bad export item"), quotes (ppr export_item)]
639 exportClashErr occ_name ie1 ie2
640 = hsep [ptext SLIT("The export items"), quotes (ppr ie1), 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 pp sorted_ns))]
647 sorted_ns = sortLt occ'ed_before (n:ns)
649 occ'ed_before a b = LT == compare (getSrcLoc a) (getSrcLoc b)
651 pp n = pprProvenance (getNameProvenance n)
653 dupExportWarn occ_name ie1 ie2
654 = hsep [quotes (ppr occ_name),
655 ptext SLIT("is exported by"), quotes (ppr ie1),
656 ptext SLIT("and"), quotes (ppr ie2)]
659 = hsep [ptext SLIT("Duplicate"),
660 quotes (ptext SLIT("Module") <+> pprModule mod),
661 ptext SLIT("in export list")]
663 unusedFixityDecl rdr_name fixity
664 = hsep [ptext SLIT("Unused fixity declaration for"), quotes (ppr rdr_name)]
666 dupFixityDecl rdr_name loc1 loc2
667 = vcat [ptext SLIT("Multiple fixity declarations for") <+> quotes (ppr rdr_name),
668 ptext SLIT("at ") <+> ppr loc1,
669 ptext SLIT("and") <+> ppr loc2]