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 )
37 import Module ( pprModule )
40 import RdrName ( RdrName, rdrNameOcc, mkRdrQual, mkRdrUnqual )
41 import SrcLoc ( SrcLoc )
42 import NameSet ( elemNameSet, emptyNameSet )
44 import Unique ( getUnique )
45 import Util ( removeDups, equivClassesByUniq, sortLt )
50 %************************************************************************
52 \subsection{Get global names}
54 %************************************************************************
57 getGlobalNames :: RdrNameHsModule
58 -> RnMG (Maybe (ExportEnv,
60 NameEnv AvailInfo -- Maps a name to its parent AvailInfo
61 -- Just for in-scope things only
63 -- Nothing => no need to recompile
65 getGlobalNames (HsModule this_mod _ exports imports decls mod_loc)
66 = -- These two fix-loops are to get the right
67 -- provenance information into a Name
68 fixRn (\ ~(rec_exported_avails, _) ->
70 fixRn (\ ~(rec_rn_env, _) ->
72 rec_unqual_fn :: Name -> Bool -- Is this chap in scope unqualified?
73 rec_unqual_fn = unQualInScope rec_rn_env
75 rec_exp_fn :: Name -> ExportFlag
76 rec_exp_fn = mk_export_fn (availsToNameSet rec_exported_avails)
78 setOmitQualFn rec_unqual_fn $
79 setModuleRn this_mod $
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 `thenRn` \ (local_gbl_env, local_mod_avails) ->
86 -- PROCESS IMPORT DECLS
87 mapAndUnzipRn importsFromImportDecl all_imports `thenRn` \ (imp_gbl_envs, imp_avails_s) ->
90 -- We put the local env second, so that a local provenance
91 -- "wins", even if a module imports itself.
93 gbl_env :: GlobalRdrEnv
94 imp_gbl_env = foldr plusGlobalRdrEnv emptyRdrEnv imp_gbl_envs
95 gbl_env = imp_gbl_env `plusGlobalRdrEnv` local_gbl_env
97 all_avails :: ExportAvails
98 all_avails = foldr plusExportAvails local_mod_avails imp_avails_s
100 returnRn (gbl_env, all_avails)
101 ) `thenRn` \ (gbl_env, all_avails) ->
103 -- TRY FOR EARLY EXIT
104 -- We can't go for an early exit before this because we have to check
105 -- for name clashes. Consider:
107 -- module A where module B where
111 -- Suppose I've compiled everything up, and then I add a
112 -- new definition to module B, that defines "f".
114 -- Then I must detect the name clash in A before going for an early
115 -- exit. The early-exit code checks what's actually needed from B
116 -- to compile A, and of course that doesn't include B.f. That's
117 -- why we wait till after the plusRnEnv stuff to do the early-exit.
118 checkEarlyExit this_mod `thenRn` \ up_to_date ->
120 returnRn (junk_exp_fn, Nothing)
123 -- PROCESS EXPORT LISTS
124 exportsFromAvail this_mod exports all_avails gbl_env `thenRn` \ exported_avails ->
127 returnRn (exported_avails, Just (all_avails, gbl_env))
128 ) `thenRn` \ (exported_avails, maybe_stuff) ->
130 case maybe_stuff of {
131 Nothing -> returnRn Nothing ;
132 Just (all_avails, gbl_env) ->
135 -- DEAL WITH FIXITIES
136 fixitiesFromLocalDecls gbl_env decls `thenRn` \ local_fixity_env ->
137 getImportedFixities gbl_env `thenRn` \ imp_fixity_env ->
139 -- Export only those fixities that are for names that are
140 -- (a) defined in this module
142 exported_fixities :: [(Name,Fixity)]
143 exported_fixities = [(name,fixity) | FixitySig name fixity _ <- nameEnvElts local_fixity_env,
144 isLocallyDefined name
147 fixity_env = imp_fixity_env `plusNameEnv` local_fixity_env
149 traceRn (text "fixity env" <+> vcat (map ppr (nameEnvElts fixity_env))) `thenRn_`
153 export_env = ExportEnv exported_avails exported_fixities
154 rn_env = RnEnv gbl_env fixity_env
155 (_, global_avail_env) = all_avails
157 returnRn (Just (export_env, rn_env, global_avail_env))
160 junk_exp_fn = error "RnNames:export_fn"
162 all_imports = prel_imports ++ imports
164 -- NB: opt_NoImplicitPrelude is slightly different to import Prelude ();
165 -- because the former doesn't even look at Prelude.hi for instance declarations,
166 -- whereas the latter does.
167 prel_imports | this_mod == pRELUDE ||
168 explicit_prelude_import ||
169 opt_NoImplicitPrelude
172 | otherwise = [ImportDecl pRELUDE
173 False {- Not qualified -}
174 Nothing {- No "as" -}
175 Nothing {- No import list -}
178 explicit_prelude_import
179 = not (null [ () | (ImportDecl mod qual _ _ _) <- imports, mod == pRELUDE ])
184 = checkErrsRn `thenRn` \ no_errs_so_far ->
185 if not no_errs_so_far then
186 -- Found errors already, so exit now
190 traceRn (text "Considering whether compilation is required...") `thenRn_`
191 if not opt_SourceUnchanged then
192 -- Source code changed and no errors yet... carry on
193 traceRn (nest 4 (text "source file changed or recompilation check turned off")) `thenRn_`
197 -- Unchanged source, and no errors yet; see if usage info
198 -- up to date, and exit if so
199 checkUpToDate mod `thenRn` \ up_to_date ->
200 putDocRn (text "Compilation" <+>
201 text (if up_to_date then "IS NOT" else "IS") <+>
202 text "required") `thenRn_`
207 importsFromImportDecl :: RdrNameImportDecl
208 -> RnMG (GlobalRdrEnv,
211 importsFromImportDecl (ImportDecl imp_mod qual_only as_mod import_spec iloc)
212 = pushSrcLocRn iloc $
213 getInterfaceExports imp_mod `thenRn` \ (imp_mod, avails) ->
216 -- If there's an error in getInterfaceExports, (e.g. interface
217 -- file not found) we get lots of spurious errors from 'filterImports'
218 returnRn (emptyRdrEnv, mkEmptyExportAvails imp_mod)
221 filterImports imp_mod import_spec avails `thenRn` \ (filtered_avails, hides, explicits) ->
223 -- We 'improve' the provenance by setting
224 -- (a) the import-reason field, so that the Name says how it came into scope
225 -- including whether it's explicitly imported
226 -- (b) the print-unqualified field
227 -- But don't fiddle with wired-in things or we get in a twist
229 improve_prov name = setNameImportReason name (UserImport imp_mod iloc (is_explicit name))
230 is_explicit name = name `elemNameSet` explicits
232 qualifyImports imp_mod
233 (not qual_only) -- Maybe want unqualified names
235 filtered_avails improve_prov `thenRn` \ (rdr_name_env, mod_avails) ->
237 returnRn (rdr_name_env, mod_avails)
242 importsFromLocalDecls mod rec_exp_fn decls
243 = mapRn (getLocalDeclBinders newLocalName) decls `thenRn` \ avails_s ->
246 avails = concat avails_s
248 all_names :: [Name] -- All the defns; no dups eliminated
249 all_names = [name | avail <- avails, name <- availNames avail]
252 dups = filter non_singleton (equivClassesByUniq getUnique all_names)
254 non_singleton (x1:x2:xs) = True
255 non_singleton other = False
257 -- Check for duplicate definitions
258 mapRn_ (addErrRn . dupDeclErr) dups `thenRn_`
260 -- Record that locally-defined things are available
261 mapRn_ (recordSlurp Nothing Compulsory) avails `thenRn_`
263 -- Build the environment
265 True -- Want unqualified names
272 newLocalName rdr_name loc = newLocallyDefinedGlobalName mod (rdrNameOcc rdr_name)
275 getLocalDeclBinders :: (RdrName -> SrcLoc -> RnMG Name) -- New-name function
278 getLocalDeclBinders new_name (ValD binds)
279 = mapRn do_one (bagToList (collectTopBinders binds))
281 do_one (rdr_name, loc) = new_name rdr_name loc `thenRn` \ name ->
282 returnRn (Avail name)
284 -- foreign declarations
285 getLocalDeclBinders new_name (ForD (ForeignDecl nm kind _ dyn _ loc))
286 | binds_haskell_name kind dyn
287 = new_name nm loc `thenRn` \ name ->
288 returnRn [Avail name]
293 getLocalDeclBinders new_name decl
294 = getDeclBinders new_name decl `thenRn` \ maybe_avail ->
296 Nothing -> returnRn [] -- Instance decls and suchlike
297 Just avail -> returnRn [avail]
299 binds_haskell_name (FoImport _) _ = True
300 binds_haskell_name FoLabel _ = True
301 binds_haskell_name FoExport ext_nm = isDynamic ext_nm
303 fixitiesFromLocalDecls :: GlobalRdrEnv -> [RdrNameHsDecl] -> RnMG FixityEnv
304 fixitiesFromLocalDecls gbl_env decls
305 = foldlRn getFixities emptyNameEnv decls
307 getFixities :: FixityEnv -> RdrNameHsDecl -> RnMG FixityEnv
308 getFixities acc (FixD fix)
312 getFixities acc (TyClD (ClassDecl _ _ _ sigs _ _ _ _ _))
313 = foldlRn fix_decl acc [sig | FixSig sig <- sigs]
314 -- Get fixities from class decl sigs too.
315 getFixities acc other_decl
318 fix_decl acc (FixitySig rdr_name fixity loc)
319 = -- Check for fixity decl for something not declared
320 case lookupRdrEnv gbl_env rdr_name of {
321 Nothing | opt_WarnUnusedBinds
322 -> pushSrcLocRn loc (addWarnRn (unusedFixityDecl rdr_name fixity)) `thenRn_`
324 | otherwise -> returnRn acc ;
328 -- Check for duplicate fixity decl
329 case lookupNameEnv acc name of {
330 Just (FixitySig _ _ loc') -> addErrRn (dupFixityDecl rdr_name loc loc') `thenRn_`
334 Nothing -> returnRn (addToNameEnv acc name (FixitySig name fixity loc))
338 %************************************************************************
340 \subsection{Filtering imports}
342 %************************************************************************
344 @filterImports@ takes the @ExportEnv@ telling what the imported module makes
345 available, and filters it through the import spec (if any).
348 filterImports :: Module -- The module being imported
349 -> Maybe (Bool, [RdrNameIE]) -- Import spec; True => hiding
350 -> [AvailInfo] -- What's available
351 -> RnMG ([AvailInfo], -- What's actually imported
352 [AvailInfo], -- What's to be hidden (the unqualified version, that is)
353 NameSet) -- What was imported explicitly
355 -- Complains if import spec mentions things that the module doesn't export
356 -- Warns/informs if import spec contains duplicates.
357 filterImports mod Nothing imports
358 = returnRn (imports, [], emptyNameSet)
360 filterImports mod (Just (want_hiding, import_items)) avails
361 = mapMaybeRn check_item import_items `thenRn` \ avails_w_explicits ->
363 (item_avails, explicits_s) = unzip avails_w_explicits
364 explicits = foldl addListToNameSet emptyNameSet explicits_s
368 -- All imported; item_avails to be hidden
369 returnRn (avails, item_avails, emptyNameSet)
371 -- Just item_avails imported; nothing to be hidden
372 returnRn (item_avails, [], explicits)
374 import_fm :: FiniteMap OccName AvailInfo
375 import_fm = listToFM [ (nameOccName name, avail)
377 name <- availNames avail]
378 -- Even though availNames returns data constructors too,
379 -- they won't make any difference because naked entities like T
380 -- in an import list map to TcOccs, not VarOccs.
382 check_item item@(IEModuleContents _)
383 = addErrRn (badImportItemErr mod item) `thenRn_`
387 | not (maybeToBool maybe_in_import_avails) ||
388 not (maybeToBool maybe_filtered_avail)
389 = addErrRn (badImportItemErr mod item) `thenRn_`
392 | dodgy_import = addWarnRn (dodgyImportWarn mod item) `thenRn_`
393 returnRn (Just (filtered_avail, explicits))
395 | otherwise = returnRn (Just (filtered_avail, explicits))
398 wanted_occ = rdrNameOcc (ieName item)
399 maybe_in_import_avails = lookupFM import_fm wanted_occ
401 Just avail = maybe_in_import_avails
402 maybe_filtered_avail = filterAvail item avail
403 Just filtered_avail = maybe_filtered_avail
404 explicits | dot_dot = [availName filtered_avail]
405 | otherwise = availNames filtered_avail
407 dot_dot = case item of
411 dodgy_import = case (item, avail) of
412 (IEThingAll _, AvailTC _ [n]) -> True
413 -- This occurs when you import T(..), but
414 -- only export T abstractly. The single [n]
415 -- in the AvailTC is the type or class itself
422 %************************************************************************
424 \subsection{Qualifiying imports}
426 %************************************************************************
428 @qualifyImports@ takes the @ExportEnv@ after filtering through the import spec
429 of an import decl, and deals with producing an @RnEnv@ with the
430 right qualified names. It also turns the @Names@ in the @ExportEnv@ into
431 fully fledged @Names@.
434 qualifyImports :: Module -- Imported module
435 -> Bool -- True <=> want unqualified import
436 -> Maybe Module -- Optional "as M" part
437 -> [AvailInfo] -- What's to be hidden
438 -> Avails -- Whats imported and how
439 -> (Name -> Name) -- Improves the provenance on imported things
440 -> RnMG (GlobalRdrEnv, ExportAvails)
441 -- NB: the Names in ExportAvails don't have the improve-provenance
442 -- function applied to them
443 -- We could fix that, but I don't think it matters
445 qualifyImports this_mod unqual_imp as_mod hides
448 -- Make the name environment. We're talking about a
449 -- single module here, so there must be no name clashes.
450 -- In practice there only ever will be if it's the module
453 -- Add the things that are available
454 name_env1 = foldl add_avail emptyRdrEnv avails
456 -- Delete things that are hidden
457 name_env2 = foldl del_avail name_env1 hides
459 -- Create the export-availability info
460 export_avails = mkExportAvails qual_mod unqual_imp name_env2 avails
462 returnRn (name_env2, export_avails)
465 qual_mod = case as_mod of
467 Just another_name -> another_name
469 add_avail :: GlobalRdrEnv -> AvailInfo -> GlobalRdrEnv
470 add_avail env avail = foldl add_name env (availNames avail)
476 env1 = addOneToGlobalRdrEnv env (mkRdrQual qual_mod occ) better_name
477 env2 = addOneToGlobalRdrEnv env1 (mkRdrUnqual occ) better_name
478 occ = nameOccName name
479 better_name = improve_prov name
481 del_avail env avail = foldl delOneFromGlobalRdrEnv env rdr_names
483 rdr_names = map (mkRdrUnqual . nameOccName) (availNames avail)
487 %************************************************************************
489 \subsection{Export list processing
491 %************************************************************************
493 Processing the export list.
495 You might think that we should record things that appear in the export list as
496 ``occurrences'' (using addOccurrenceName), but you'd be wrong. We do check (here)
497 that they are in scope, but there is no need to slurp in their actual declaration
498 (which is what addOccurrenceName forces). Indeed, doing so would big trouble when
499 compiling PrelBase, because it re-exports GHC, which includes takeMVar#, whose type
500 includes ConcBase.StateAndSynchVar#, and so on...
503 type ExportAccum -- The type of the accumulating parameter of
504 -- the main worker function in exportsFromAvail
505 = ([Module], -- 'module M's seen so far
506 ExportOccMap, -- Tracks exported occurrence names
507 NameEnv AvailInfo) -- The accumulated exported stuff, kept in an env
508 -- so we can common-up related AvailInfos
510 type ExportOccMap = FiniteMap OccName (Name, RdrNameIE)
511 -- Tracks what a particular exported OccName
512 -- in an export list refers to, and which item
513 -- it came from. It's illegal to export two distinct things
514 -- that have the same occurrence name
517 exportsFromAvail :: Module
518 -> Maybe [RdrNameIE] -- Export spec
522 -- Complains if two distinct exports have same OccName
523 -- Warns about identical exports.
524 -- Complains about exports items not in scope
525 exportsFromAvail this_mod Nothing export_avails global_name_env
526 = exportsFromAvail this_mod (Just [IEModuleContents this_mod])
527 export_avails global_name_env
529 exportsFromAvail this_mod (Just export_items)
530 (mod_avail_env, entity_avail_env)
532 = foldlRn exports_from_item
533 ([], emptyFM, emptyNameEnv) export_items `thenRn` \ (_, _, export_avail_map) ->
535 export_avails :: [AvailInfo]
536 export_avails = nameEnvElts export_avail_map
538 returnRn export_avails
541 exports_from_item :: ExportAccum -> RdrNameIE -> RnMG ExportAccum
543 exports_from_item acc@(mods, occs, avails) ie@(IEModuleContents mod)
544 | mod `elem` mods -- Duplicate export of M
545 = warnCheckRn opt_WarnDuplicateExports
546 (dupModuleExport mod) `thenRn_`
550 = case lookupFM mod_avail_env mod of
551 Nothing -> failWithRn acc (modExportErr mod)
552 Just mod_avails -> foldlRn (check_occs ie) occs mod_avails `thenRn` \ occs' ->
554 avails' = foldl add_avail avails mod_avails
556 returnRn (mod:mods, occs', avails')
558 exports_from_item acc@(mods, occs, avails) ie
559 | not (maybeToBool maybe_in_scope)
560 = failWithRn acc (unknownNameErr (ieName ie))
562 | not (null dup_names)
563 = addNameClashErrRn rdr_name (name:dup_names) `thenRn_`
567 -- I can't see why this should ever happen; if the thing is in scope
568 -- at all it ought to have some availability
569 | not (maybeToBool maybe_avail)
570 = pprTrace "exportsFromAvail: curious Nothing:" (ppr name)
575 = failWithRn acc (exportItemErr ie)
577 | otherwise -- Phew! It's OK! Now to check the occurrence stuff!
578 = check_occs ie occs export_avail `thenRn` \ occs' ->
579 returnRn (mods, occs', add_avail avails export_avail)
583 maybe_in_scope = lookupFM global_name_env rdr_name
584 Just (name:dup_names) = maybe_in_scope
585 maybe_avail = lookupUFM entity_avail_env name
586 Just avail = maybe_avail
587 maybe_export_avail = filterAvail ie avail
588 enough_avail = maybeToBool maybe_export_avail
589 Just export_avail = maybe_export_avail
591 add_avail avails avail = addToNameEnv_C plusAvail avails (availName avail) avail
593 check_occs :: RdrNameIE -> ExportOccMap -> AvailInfo -> RnMG ExportOccMap
594 check_occs ie occs avail
595 = foldlRn check occs (availNames avail)
598 = case lookupFM occs name_occ of
599 Nothing -> returnRn (addToFM occs name_occ (name, ie))
601 | name == name' -> -- Duplicate export
602 warnCheckRn opt_WarnDuplicateExports
603 (dupExportWarn name_occ ie ie') `thenRn_`
606 | otherwise -> -- Same occ name but different names: an error
607 failWithRn occs (exportClashErr name_occ ie ie')
609 name_occ = nameOccName name
611 mk_export_fn :: NameSet -> (Name -> ExportFlag)
612 mk_export_fn exported_names
613 = \name -> if name `elemNameSet` exported_names
618 %************************************************************************
622 %************************************************************************
625 badImportItemErr mod ie
626 = sep [ptext SLIT("Module"), quotes (pprModule mod),
627 ptext SLIT("does not export"), quotes (ppr ie)]
629 dodgyImportWarn mod (IEThingAll tc)
630 = sep [ptext SLIT("Module") <+> quotes (pprModule mod) <+> ptext SLIT("exports") <+> quotes (ppr tc),
631 ptext SLIT("with no constructors/class operations;"),
632 ptext SLIT("yet it is imported with a (..)")]
635 = hsep [ ptext SLIT("Unknown module in export list: module"), quotes (pprModule mod)]
637 exportItemErr export_item
638 = sep [ ptext SLIT("Bad export item"), quotes (ppr export_item)]
640 exportClashErr occ_name ie1 ie2
641 = hsep [ptext SLIT("The export items"), quotes (ppr ie1), ptext SLIT("and"), quotes (ppr ie2),
642 ptext SLIT("create conflicting exports for"), quotes (ppr occ_name)]
645 = vcat [ptext SLIT("Multiple declarations of") <+> quotes (ppr n),
646 nest 4 (vcat (map pp sorted_ns))]
648 sorted_ns = sortLt occ'ed_before (n:ns)
650 occ'ed_before a b = LT == compare (getSrcLoc a) (getSrcLoc b)
652 pp n = pprProvenance (getNameProvenance n)
654 dupExportWarn occ_name ie1 ie2
655 = hsep [quotes (ppr occ_name),
656 ptext SLIT("is exported by"), quotes (ppr ie1),
657 ptext SLIT("and"), quotes (ppr ie2)]
660 = hsep [ptext SLIT("Duplicate"),
661 quotes (ptext SLIT("Module") <+> pprModule mod),
662 ptext SLIT("in export list")]
664 unusedFixityDecl rdr_name fixity
665 = hsep [ptext SLIT("Unused fixity declaration for"), quotes (ppr rdr_name)]
667 dupFixityDecl rdr_name loc1 loc2
668 = vcat [ptext SLIT("Multiple fixity declarations for") <+> quotes (ppr rdr_name),
669 ptext SLIT("at ") <+> ppr loc1,
670 ptext SLIT("and") <+> ppr loc2]