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(..), HsDecl(..), TyClDecl(..),
19 ForeignDecl(..), ForKind(..), isDynamic,
20 FixitySig(..), Sig(..), ImportDecl(..),
23 import RdrHsSyn ( RdrNameIE, RdrNameImportDecl,
24 RdrNameHsModule, RdrNameHsDecl
26 import RnIfaces ( getInterfaceExports, getDeclBinders, getDeclSysBinders,
27 recordSlurp, checkUpToDate
34 import PrelInfo ( main_RDR )
35 import UniqFM ( lookupUFM )
36 import Bag ( bagToList )
37 import Maybes ( maybeToBool )
38 import Module ( ModuleName, mkThisModule, pprModuleName, WhereFrom(..) )
40 import Name ( Name, ExportFlag(..), ImportReason(..), Provenance(..),
41 isLocallyDefined, setNameProvenance,
42 nameOccName, getSrcLoc, pprProvenance, getNameProvenance
44 import RdrName ( RdrName, rdrNameOcc, mkRdrQual, mkRdrUnqual, isQual )
45 import SrcLoc ( SrcLoc )
46 import NameSet ( elemNameSet, emptyNameSet )
48 import Unique ( getUnique )
49 import Util ( removeDups, equivClassesByUniq, sortLt )
50 import List ( partition )
55 %************************************************************************
57 \subsection{Get global names}
59 %************************************************************************
62 getGlobalNames :: RdrNameHsModule
63 -> RnMG (Maybe (ExportEnv,
65 FixityEnv, -- Fixities for local decls only
66 NameEnv AvailInfo -- Maps a name to its parent AvailInfo
67 -- Just for in-scope things only
69 -- Nothing => no need to recompile
71 getGlobalNames (HsModule this_mod _ exports imports decls mod_loc)
72 = -- These two fix-loops are to get the right
73 -- provenance information into a Name
74 fixRn (\ ~(rec_gbl_env, rec_exported_avails, _) ->
77 rec_unqual_fn :: Name -> Bool -- Is this chap in scope unqualified?
78 rec_unqual_fn = unQualInScope rec_gbl_env
80 rec_exp_fn :: Name -> ExportFlag
81 rec_exp_fn = mk_export_fn (availsToNameSet rec_exported_avails)
83 setModuleRn this_mod $
85 -- PROCESS LOCAL DECLS
86 -- Do these *first* so that the correct provenance gets
87 -- into the global name cache.
88 importsFromLocalDecls this_mod rec_exp_fn decls
89 `thenRn` \ (local_gbl_env, local_mod_avails) ->
91 -- PROCESS IMPORT DECLS
92 -- Do the non {- SOURCE -} ones first, so that we get a helpful
93 -- warning for {- SOURCE -} ones that are unnecessary
95 (source, ordinary) = partition is_source_import all_imports
96 is_source_import (ImportDecl _ ImportByUserSource _ _ _ _) = True
97 is_source_import other = False
99 mapAndUnzipRn (importsFromImportDecl rec_unqual_fn) ordinary
100 `thenRn` \ (imp_gbl_envs1, imp_avails_s1) ->
101 mapAndUnzipRn (importsFromImportDecl rec_unqual_fn) source
102 `thenRn` \ (imp_gbl_envs2, imp_avails_s2) ->
105 -- We put the local env second, so that a local provenance
106 -- "wins", even if a module imports itself.
108 gbl_env :: GlobalRdrEnv
109 imp_gbl_env = foldr plusGlobalRdrEnv emptyRdrEnv (imp_gbl_envs2 ++ imp_gbl_envs1)
110 gbl_env = imp_gbl_env `plusGlobalRdrEnv` local_gbl_env
112 all_avails :: ExportAvails
113 all_avails = foldr plusExportAvails local_mod_avails (imp_avails_s2 ++ imp_avails_s1)
116 -- TRY FOR EARLY EXIT
117 -- We can't go for an early exit before this because we have to check
118 -- for name clashes. Consider:
120 -- module A where module B where
124 -- Suppose I've compiled everything up, and then I add a
125 -- new definition to module B, that defines "f".
127 -- Then I must detect the name clash in A before going for an early
128 -- exit. The early-exit code checks what's actually needed from B
129 -- to compile A, and of course that doesn't include B.f. That's
130 -- why we wait till after the plusEnv stuff to do the early-exit.
131 checkEarlyExit this_mod `thenRn` \ up_to_date ->
133 returnRn (gbl_env, junk_exp_fn, Nothing)
136 -- RECORD BETTER PROVENANCES IN THE CACHE
137 -- The names in the envirnoment have better provenances (e.g. imported on line x)
138 -- than the names in the name cache. We update the latter now, so that we
139 -- we start renaming declarations we'll get the good names
140 -- The isQual is because the qualified name is always in scope
141 updateProvenances (concat [names | (rdr_name, names) <- rdrEnvToList imp_gbl_env,
142 isQual rdr_name]) `thenRn_`
144 -- PROCESS EXPORT LISTS
145 exportsFromAvail this_mod exports all_avails gbl_env
146 `thenRn` \ exported_avails ->
149 returnRn (gbl_env, exported_avails, Just all_avails)
150 ) `thenRn` \ (gbl_env, exported_avails, maybe_stuff) ->
152 case maybe_stuff of {
153 Nothing -> returnRn Nothing ;
156 -- DEAL WITH FIXITIES
157 fixitiesFromLocalDecls gbl_env decls `thenRn` \ local_fixity_env ->
159 -- Export only those fixities that are for names that are
160 -- (a) defined in this module
162 exported_fixities :: [(Name,Fixity)]
163 exported_fixities = [(name,fixity)
164 | FixitySig name fixity _ <- nameEnvElts local_fixity_env,
165 isLocallyDefined name
168 traceRn (text "fixity env" <+> vcat (map ppr (nameEnvElts local_fixity_env))) `thenRn_`
172 export_env = ExportEnv exported_avails exported_fixities
173 (_, global_avail_env) = all_avails
175 returnRn (Just (export_env, gbl_env, local_fixity_env, global_avail_env))
178 junk_exp_fn = error "RnNames:export_fn"
180 all_imports = prel_imports ++ imports
182 -- NB: opt_NoImplicitPrelude is slightly different to import Prelude ();
183 -- because the former doesn't even look at Prelude.hi for instance declarations,
184 -- whereas the latter does.
185 prel_imports | this_mod == pRELUDE_Name ||
186 explicit_prelude_import ||
187 opt_NoImplicitPrelude
190 | otherwise = [ImportDecl pRELUDE_Name
192 False {- Not qualified -}
193 Nothing {- No "as" -}
194 Nothing {- No import list -}
197 explicit_prelude_import
198 = not (null [ () | (ImportDecl mod _ _ _ _ _) <- imports, mod == pRELUDE_Name ])
203 = checkErrsRn `thenRn` \ no_errs_so_far ->
204 if not no_errs_so_far then
205 -- Found errors already, so exit now
209 traceRn (text "Considering whether compilation is required...") `thenRn_`
210 if not opt_SourceUnchanged then
211 -- Source code changed and no errors yet... carry on
212 traceRn (nest 4 (text "source file changed or recompilation check turned off")) `thenRn_`
216 -- Unchanged source, and no errors yet; see if usage info
217 -- up to date, and exit if so
218 checkUpToDate mod `thenRn` \ up_to_date ->
220 then putDocRn (text "Compilation IS NOT required")
221 else returnRn ()) `thenRn_`
226 importsFromImportDecl :: (Name -> Bool) -- OK to omit qualifier
228 -> RnMG (GlobalRdrEnv,
231 importsFromImportDecl is_unqual (ImportDecl imp_mod_name from qual_only as_mod import_spec iloc)
232 = pushSrcLocRn iloc $
233 getInterfaceExports imp_mod_name from `thenRn` \ (imp_mod, avails) ->
236 -- If there's an error in getInterfaceExports, (e.g. interface
237 -- file not found) we get lots of spurious errors from 'filterImports'
238 returnRn (emptyRdrEnv, mkEmptyExportAvails imp_mod_name)
241 filterImports imp_mod_name import_spec avails
242 `thenRn` \ (filtered_avails, hides, explicits) ->
244 -- We 'improve' the provenance by setting
245 -- (a) the import-reason field, so that the Name says how it came into scope
246 -- including whether it's explicitly imported
247 -- (b) the print-unqualified field
248 -- But don't fiddle with wired-in things or we get in a twist
251 setNameProvenance name (NonLocalDef (UserImport imp_mod iloc (is_explicit name))
253 is_explicit name = name `elemNameSet` explicits
255 qualifyImports imp_mod_name
256 (not qual_only) -- Maybe want unqualified names
258 filtered_avails improve_prov
259 `thenRn` \ (rdr_name_env, mod_avails) ->
261 returnRn (rdr_name_env, mod_avails)
266 importsFromLocalDecls mod_name rec_exp_fn decls
267 = mapRn (getLocalDeclBinders newLocalName) decls `thenRn` \ avails_s ->
270 avails = concat avails_s
272 all_names :: [Name] -- All the defns; no dups eliminated
273 all_names = [name | avail <- avails, name <- availNames avail]
276 (_, dups) = removeDups compare all_names
278 -- Check for duplicate definitions
279 mapRn_ (addErrRn . dupDeclErr) dups `thenRn_`
281 -- Record that locally-defined things are available
282 mapRn_ (recordSlurp Nothing) avails `thenRn_`
284 -- Build the environment
285 qualifyImports mod_name
286 True -- Want unqualified names
293 mod = mkThisModule mod_name
295 newLocalName rdr_name loc
296 = (if isQual rdr_name then
297 qualNameErr (text "the binding for" <+> quotes (ppr rdr_name)) (rdr_name,loc)
298 -- There should never be a qualified name in a binding position (except in instance decls)
299 -- The parser doesn't check this because the same parser parses instance decls
301 returnRn ()) `thenRn_`
303 newLocalTopBinder mod (rdrNameOcc rdr_name) rec_exp_fn loc
306 getLocalDeclBinders :: (RdrName -> SrcLoc -> RnMG Name) -- New-name function
309 getLocalDeclBinders new_name (ValD binds)
310 = mapRn do_one (bagToList (collectTopBinders binds))
312 do_one (rdr_name, loc) = new_name rdr_name loc `thenRn` \ name ->
313 returnRn (Avail name)
315 getLocalDeclBinders new_name decl
316 = getDeclBinders new_name decl `thenRn` \ maybe_avail ->
318 Nothing -> returnRn [] -- Instance decls and suchlike
319 Just avail -> getDeclSysBinders new_sys_name decl `thenRn_`
322 -- The getDeclSysBinders is just to get the names of superclass selectors
323 -- etc, into the cache
324 new_sys_name rdr_name loc = newImplicitBinder (rdrNameOcc rdr_name) loc
326 fixitiesFromLocalDecls :: GlobalRdrEnv -> [RdrNameHsDecl] -> RnMG FixityEnv
327 fixitiesFromLocalDecls gbl_env decls
328 = foldlRn getFixities emptyNameEnv decls
330 getFixities :: FixityEnv -> RdrNameHsDecl -> RnMG FixityEnv
331 getFixities acc (FixD fix)
334 getFixities acc (TyClD (ClassDecl _ _ _ _ sigs _ _ _ _ _ _))
335 = foldlRn fix_decl acc [sig | FixSig sig <- sigs]
336 -- Get fixities from class decl sigs too.
337 getFixities acc other_decl
340 fix_decl acc sig@(FixitySig rdr_name fixity loc)
341 = -- Check for fixity decl for something not declared
342 case lookupRdrEnv gbl_env rdr_name of {
343 Nothing | opt_WarnUnusedBinds
344 -> pushSrcLocRn loc (addWarnRn (unusedFixityDecl rdr_name fixity))
345 `thenRn_` returnRn acc
346 | otherwise -> returnRn acc ;
350 -- Check for duplicate fixity decl
351 case lookupNameEnv acc name of {
352 Just (FixitySig _ _ loc') -> addErrRn (dupFixityDecl rdr_name loc loc')
353 `thenRn_` returnRn acc ;
355 Nothing -> returnRn (addToNameEnv acc name (FixitySig name fixity loc))
359 %************************************************************************
361 \subsection{Filtering imports}
363 %************************************************************************
365 @filterImports@ takes the @ExportEnv@ telling what the imported module makes
366 available, and filters it through the import spec (if any).
369 filterImports :: ModuleName -- The module being imported
370 -> Maybe (Bool, [RdrNameIE]) -- Import spec; True => hiding
371 -> [AvailInfo] -- What's available
372 -> RnMG ([AvailInfo], -- What's actually imported
373 [AvailInfo], -- What's to be hidden
374 -- (the unqualified version, that is)
375 NameSet) -- What was imported explicitly
377 -- Complains if import spec mentions things that the module doesn't export
378 -- Warns/informs if import spec contains duplicates.
379 filterImports mod Nothing imports
380 = returnRn (imports, [], emptyNameSet)
382 filterImports mod (Just (want_hiding, import_items)) avails
383 = mapMaybeRn check_item import_items `thenRn` \ avails_w_explicits ->
385 (item_avails, explicits_s) = unzip avails_w_explicits
386 explicits = foldl addListToNameSet emptyNameSet explicits_s
390 -- All imported; item_avails to be hidden
391 returnRn (avails, item_avails, emptyNameSet)
393 -- Just item_avails imported; nothing to be hidden
394 returnRn (item_avails, [], explicits)
396 import_fm :: FiniteMap OccName AvailInfo
397 import_fm = listToFM [ (nameOccName name, avail)
399 name <- availNames avail]
400 -- Even though availNames returns data constructors too,
401 -- they won't make any difference because naked entities like T
402 -- in an import list map to TcOccs, not VarOccs.
404 check_item item@(IEModuleContents _)
405 = addErrRn (badImportItemErr mod item) `thenRn_`
409 | not (maybeToBool maybe_in_import_avails) ||
410 not (maybeToBool maybe_filtered_avail)
411 = addErrRn (badImportItemErr mod item) `thenRn_`
414 | dodgy_import = addWarnRn (dodgyImportWarn mod item) `thenRn_`
415 returnRn (Just (filtered_avail, explicits))
417 | otherwise = returnRn (Just (filtered_avail, explicits))
420 wanted_occ = rdrNameOcc (ieName item)
421 maybe_in_import_avails = lookupFM import_fm wanted_occ
423 Just avail = maybe_in_import_avails
424 maybe_filtered_avail = filterAvail item avail
425 Just filtered_avail = maybe_filtered_avail
426 explicits | dot_dot = [availName filtered_avail]
427 | otherwise = availNames filtered_avail
429 dot_dot = case item of
433 dodgy_import = case (item, avail) of
434 (IEThingAll _, AvailTC _ [n]) -> True
435 -- This occurs when you import T(..), but
436 -- only export T abstractly. The single [n]
437 -- in the AvailTC is the type or class itself
444 %************************************************************************
446 \subsection{Qualifiying imports}
448 %************************************************************************
450 @qualifyImports@ takes the @ExportEnv@ after filtering through the import spec
451 of an import decl, and deals with producing an @RnEnv@ with the
452 right qualified names. It also turns the @Names@ in the @ExportEnv@ into
453 fully fledged @Names@.
456 qualifyImports :: ModuleName -- Imported module
457 -> Bool -- True <=> want unqualified import
458 -> Maybe ModuleName -- Optional "as M" part
459 -> [AvailInfo] -- What's to be hidden
460 -> Avails -- Whats imported and how
461 -> (Name -> Name) -- Improves the provenance on imported things
462 -> RnMG (GlobalRdrEnv, ExportAvails)
463 -- NB: the Names in ExportAvails don't have the improve-provenance
464 -- function applied to them
465 -- We could fix that, but I don't think it matters
467 qualifyImports this_mod unqual_imp as_mod hides
470 -- Make the name environment. We're talking about a
471 -- single module here, so there must be no name clashes.
472 -- In practice there only ever will be if it's the module
475 -- Add the things that are available
476 name_env1 = foldl add_avail emptyRdrEnv avails
478 -- Delete things that are hidden
479 name_env2 = foldl del_avail name_env1 hides
481 -- Create the export-availability info
482 export_avails = mkExportAvails qual_mod unqual_imp name_env2 avails
484 returnRn (name_env2, export_avails)
487 qual_mod = case as_mod of
489 Just another_name -> another_name
491 add_avail :: GlobalRdrEnv -> AvailInfo -> GlobalRdrEnv
492 add_avail env avail = foldl add_name env (availNames avail)
498 env1 = addOneToGlobalRdrEnv env (mkRdrQual qual_mod occ) better_name
499 env2 = addOneToGlobalRdrEnv env1 (mkRdrUnqual occ) better_name
500 occ = nameOccName name
501 better_name = improve_prov name
503 del_avail env avail = foldl delOneFromGlobalRdrEnv env rdr_names
505 rdr_names = map (mkRdrUnqual . nameOccName) (availNames avail)
509 %************************************************************************
511 \subsection{Export list processing}
513 %************************************************************************
515 Processing the export list.
517 You might think that we should record things that appear in the export list
518 as ``occurrences'' (using @addOccurrenceName@), but you'd be wrong.
519 We do check (here) that they are in scope,
520 but there is no need to slurp in their actual declaration
521 (which is what @addOccurrenceName@ forces).
523 Indeed, doing so would big trouble when
524 compiling @PrelBase@, because it re-exports @GHC@, which includes @takeMVar#@,
525 whose type includes @ConcBase.StateAndSynchVar#@, and so on...
528 type ExportAccum -- The type of the accumulating parameter of
529 -- the main worker function in exportsFromAvail
530 = ([ModuleName], -- 'module M's seen so far
531 ExportOccMap, -- Tracks exported occurrence names
532 NameEnv AvailInfo) -- The accumulated exported stuff, kept in an env
533 -- so we can common-up related AvailInfos
535 type ExportOccMap = FiniteMap OccName (Name, RdrNameIE)
536 -- Tracks what a particular exported OccName
537 -- in an export list refers to, and which item
538 -- it came from. It's illegal to export two distinct things
539 -- that have the same occurrence name
542 exportsFromAvail :: ModuleName
543 -> Maybe [RdrNameIE] -- Export spec
547 -- Complains if two distinct exports have same OccName
548 -- Warns about identical exports.
549 -- Complains about exports items not in scope
550 exportsFromAvail this_mod Nothing export_avails global_name_env
551 = exportsFromAvail this_mod true_exports export_avails global_name_env
553 true_exports = Just $ if this_mod == mAIN_Name
554 then [IEVar main_RDR]
555 -- export Main.main *only* unless otherwise specified,
556 else [IEModuleContents this_mod]
557 -- but for all other modules export everything.
559 exportsFromAvail this_mod (Just export_items)
560 (mod_avail_env, entity_avail_env)
562 = foldlRn exports_from_item
563 ([], emptyFM, emptyNameEnv) export_items `thenRn` \ (_, _, export_avail_map) ->
565 export_avails :: [AvailInfo]
566 export_avails = nameEnvElts export_avail_map
568 returnRn export_avails
571 exports_from_item :: ExportAccum -> RdrNameIE -> RnMG ExportAccum
573 exports_from_item acc@(mods, occs, avails) ie@(IEModuleContents mod)
574 | mod `elem` mods -- Duplicate export of M
575 = warnCheckRn opt_WarnDuplicateExports
576 (dupModuleExport mod) `thenRn_`
580 = case lookupFM mod_avail_env mod of
581 Nothing -> failWithRn acc (modExportErr mod)
582 Just mod_avails -> foldlRn (check_occs ie) occs mod_avails
585 avails' = foldl add_avail avails mod_avails
587 returnRn (mod:mods, occs', avails')
589 exports_from_item acc@(mods, occs, avails) ie
590 | not (maybeToBool maybe_in_scope)
591 = failWithRn acc (unknownNameErr (ieName ie))
593 | not (null dup_names)
594 = addNameClashErrRn rdr_name (name:dup_names) `thenRn_`
598 -- I can't see why this should ever happen; if the thing is in scope
599 -- at all it ought to have some availability
600 | not (maybeToBool maybe_avail)
601 = pprTrace "exportsFromAvail: curious Nothing:" (ppr name)
606 = failWithRn acc (exportItemErr ie)
608 | otherwise -- Phew! It's OK! Now to check the occurrence stuff!
609 = check_occs ie occs export_avail `thenRn` \ occs' ->
610 returnRn (mods, occs', add_avail avails export_avail)
614 maybe_in_scope = lookupFM global_name_env rdr_name
615 Just (name:dup_names) = maybe_in_scope
616 maybe_avail = lookupUFM entity_avail_env name
617 Just avail = maybe_avail
618 maybe_export_avail = filterAvail ie avail
619 enough_avail = maybeToBool maybe_export_avail
620 Just export_avail = maybe_export_avail
622 add_avail avails avail = addToNameEnv_C plusAvail avails (availName avail) avail
624 check_occs :: RdrNameIE -> ExportOccMap -> AvailInfo -> RnMG ExportOccMap
625 check_occs ie occs avail
626 = foldlRn check occs (availNames avail)
629 = case lookupFM occs name_occ of
630 Nothing -> returnRn (addToFM occs name_occ (name, ie))
632 | name == name' -> -- Duplicate export
633 warnCheckRn opt_WarnDuplicateExports
634 (dupExportWarn name_occ ie ie')
635 `thenRn_` returnRn occs
637 | otherwise -> -- Same occ name but different names: an error
638 failWithRn occs (exportClashErr name_occ ie ie')
640 name_occ = nameOccName name
642 mk_export_fn :: NameSet -> (Name -> ExportFlag)
643 mk_export_fn exported_names
644 = \name -> if name `elemNameSet` exported_names
649 %************************************************************************
653 %************************************************************************
656 badImportItemErr mod ie
657 = sep [ptext SLIT("Module"), quotes (pprModuleName mod),
658 ptext SLIT("does not export"), quotes (ppr ie)]
660 dodgyImportWarn mod (IEThingAll tc)
661 = sep [ptext SLIT("Module") <+> quotes (pprModuleName mod)
662 <+> ptext SLIT("exports") <+> quotes (ppr tc),
663 ptext SLIT("with no constructors/class operations;"),
664 ptext SLIT("yet it is imported with a (..)")]
667 = hsep [ ptext SLIT("Unknown module in export list: module"), quotes (pprModuleName mod)]
669 exportItemErr export_item
670 = sep [ ptext SLIT("Bad export item"), quotes (ppr export_item)]
672 exportClashErr occ_name ie1 ie2
673 = hsep [ptext SLIT("The export items"), quotes (ppr ie1)
674 ,ptext SLIT("and"), quotes (ppr ie2)
675 ,ptext SLIT("create conflicting exports for"), quotes (ppr occ_name)]
678 = vcat [ptext SLIT("Multiple declarations of") <+> quotes (ppr n),
679 nest 4 (vcat (map pp sorted_ns))]
681 sorted_ns = sortLt occ'ed_before (n:ns)
683 occ'ed_before a b = LT == compare (getSrcLoc a) (getSrcLoc b)
685 pp n = pprProvenance (getNameProvenance n)
687 dupExportWarn occ_name ie1 ie2
688 = hsep [quotes (ppr occ_name),
689 ptext SLIT("is exported by"), quotes (ppr ie1),
690 ptext SLIT("and"), quotes (ppr ie2)]
693 = hsep [ptext SLIT("Duplicate"),
694 quotes (ptext SLIT("Module") <+> pprModuleName mod),
695 ptext SLIT("in export list")]
697 unusedFixityDecl rdr_name fixity
698 = hsep [ptext SLIT("Unused fixity declaration for"), quotes (ppr rdr_name)]
700 dupFixityDecl rdr_name loc1 loc2
701 = vcat [ptext SLIT("Multiple fixity declarations for") <+> quotes (ppr rdr_name),
702 ptext SLIT("at ") <+> ppr loc1,
703 ptext SLIT("and") <+> ppr loc2]