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 `thenRn` \ exported_avails ->
148 returnRn (gbl_env, exported_avails, Just all_avails)
149 ) `thenRn` \ (gbl_env, exported_avails, maybe_stuff) ->
151 case maybe_stuff of {
152 Nothing -> returnRn Nothing ;
155 -- DEAL WITH FIXITIES
156 fixitiesFromLocalDecls gbl_env decls `thenRn` \ local_fixity_env ->
158 -- Export only those fixities that are for names that are
159 -- (a) defined in this module
161 exported_fixities :: [(Name,Fixity)]
162 exported_fixities = [(name,fixity)
163 | FixitySig name fixity _ <- nameEnvElts local_fixity_env,
164 isLocallyDefined name
168 export_mods = case exports of
170 Just es -> [mod | IEModuleContents mod <- es, mod /= this_mod]
172 export_env = ExportEnv exported_avails exported_fixities export_mods
173 (_, global_avail_env) = all_avails
175 traceRn (text "fixity env" <+> vcat (map ppr (nameEnvElts local_fixity_env))) `thenRn_`
177 returnRn (Just (export_env, gbl_env, local_fixity_env, global_avail_env))
180 junk_exp_fn = error "RnNames:export_fn"
182 all_imports = prel_imports ++ imports
184 -- NB: opt_NoImplicitPrelude is slightly different to import Prelude ();
185 -- because the former doesn't even look at Prelude.hi for instance declarations,
186 -- whereas the latter does.
187 prel_imports | this_mod == pRELUDE_Name ||
188 explicit_prelude_import ||
189 opt_NoImplicitPrelude
192 | otherwise = [ImportDecl pRELUDE_Name
194 False {- Not qualified -}
195 Nothing {- No "as" -}
196 Nothing {- No import list -}
199 explicit_prelude_import
200 = not (null [ () | (ImportDecl mod _ _ _ _ _) <- imports, mod == pRELUDE_Name ])
205 = checkErrsRn `thenRn` \ no_errs_so_far ->
206 if not no_errs_so_far then
207 -- Found errors already, so exit now
211 traceRn (text "Considering whether compilation is required...") `thenRn_`
212 if not opt_SourceUnchanged then
213 -- Source code changed and no errors yet... carry on
214 traceRn (nest 4 (text "source file changed or recompilation check turned off")) `thenRn_`
218 -- Unchanged source, and no errors yet; see if usage info
219 -- up to date, and exit if so
220 checkUpToDate mod `thenRn` \ up_to_date ->
222 then putDocRn (text "Compilation IS NOT required")
223 else returnRn ()) `thenRn_`
228 importsFromImportDecl :: (Name -> Bool) -- OK to omit qualifier
230 -> RnMG (GlobalRdrEnv,
233 importsFromImportDecl is_unqual (ImportDecl imp_mod_name from qual_only as_mod import_spec iloc)
234 = pushSrcLocRn iloc $
235 getInterfaceExports imp_mod_name from `thenRn` \ (imp_mod, avails) ->
238 -- If there's an error in getInterfaceExports, (e.g. interface
239 -- file not found) we get lots of spurious errors from 'filterImports'
240 returnRn (emptyRdrEnv, mkEmptyExportAvails imp_mod_name)
243 filterImports imp_mod_name import_spec avails
244 `thenRn` \ (filtered_avails, hides, explicits) ->
246 -- We 'improve' the provenance by setting
247 -- (a) the import-reason field, so that the Name says how it came into scope
248 -- including whether it's explicitly imported
249 -- (b) the print-unqualified field
250 -- But don't fiddle with wired-in things or we get in a twist
253 setNameProvenance name (NonLocalDef (UserImport imp_mod iloc (is_explicit name))
255 is_explicit name = name `elemNameSet` explicits
257 qualifyImports imp_mod_name
258 (not qual_only) -- Maybe want unqualified names
260 filtered_avails improve_prov
261 `thenRn` \ (rdr_name_env, mod_avails) ->
263 returnRn (rdr_name_env, mod_avails)
268 importsFromLocalDecls mod_name rec_exp_fn decls
269 = mapRn (getLocalDeclBinders newLocalName) decls `thenRn` \ avails_s ->
272 avails = concat avails_s
274 all_names :: [Name] -- All the defns; no dups eliminated
275 all_names = [name | avail <- avails, name <- availNames avail]
278 (_, dups) = removeDups compare all_names
280 -- Check for duplicate definitions
281 mapRn_ (addErrRn . dupDeclErr) dups `thenRn_`
283 -- Record that locally-defined things are available
284 mapRn_ (recordSlurp Nothing) avails `thenRn_`
286 -- Build the environment
287 qualifyImports mod_name
288 True -- Want unqualified names
295 mod = mkThisModule mod_name
297 newLocalName rdr_name loc
298 = (if isQual rdr_name then
299 qualNameErr (text "the binding for" <+> quotes (ppr rdr_name)) (rdr_name,loc)
300 -- There should never be a qualified name in a binding position (except in instance decls)
301 -- The parser doesn't check this because the same parser parses instance decls
303 returnRn ()) `thenRn_`
305 newLocalTopBinder mod (rdrNameOcc rdr_name) rec_exp_fn loc
308 getLocalDeclBinders :: (RdrName -> SrcLoc -> RnMG Name) -- New-name function
311 getLocalDeclBinders new_name (ValD binds)
312 = mapRn do_one (bagToList (collectTopBinders binds))
314 do_one (rdr_name, loc) = new_name rdr_name loc `thenRn` \ name ->
315 returnRn (Avail name)
317 getLocalDeclBinders new_name decl
318 = getDeclBinders new_name decl `thenRn` \ maybe_avail ->
320 Nothing -> returnRn [] -- Instance decls and suchlike
321 Just avail -> getDeclSysBinders new_sys_name decl `thenRn_`
324 -- The getDeclSysBinders is just to get the names of superclass selectors
325 -- etc, into the cache
326 new_sys_name rdr_name loc = newImplicitBinder (rdrNameOcc rdr_name) loc
328 fixitiesFromLocalDecls :: GlobalRdrEnv -> [RdrNameHsDecl] -> RnMG FixityEnv
329 fixitiesFromLocalDecls gbl_env decls
330 = foldlRn getFixities emptyNameEnv decls
332 getFixities :: FixityEnv -> RdrNameHsDecl -> RnMG FixityEnv
333 getFixities acc (FixD fix)
336 getFixities acc (TyClD (ClassDecl _ _ _ _ sigs _ _ _ _ _ _))
337 = foldlRn fix_decl acc [sig | FixSig sig <- sigs]
338 -- Get fixities from class decl sigs too.
339 getFixities acc other_decl
342 fix_decl acc sig@(FixitySig rdr_name fixity loc)
343 = -- Check for fixity decl for something not declared
344 case lookupRdrEnv gbl_env rdr_name of {
345 Nothing | opt_WarnUnusedBinds
346 -> pushSrcLocRn loc (addWarnRn (unusedFixityDecl rdr_name fixity))
347 `thenRn_` returnRn acc
348 | otherwise -> returnRn acc ;
352 -- Check for duplicate fixity decl
353 case lookupNameEnv acc name of {
354 Just (FixitySig _ _ loc') -> addErrRn (dupFixityDecl rdr_name loc loc')
355 `thenRn_` returnRn acc ;
357 Nothing -> returnRn (addToNameEnv acc name (FixitySig name fixity loc))
361 %************************************************************************
363 \subsection{Filtering imports}
365 %************************************************************************
367 @filterImports@ takes the @ExportEnv@ telling what the imported module makes
368 available, and filters it through the import spec (if any).
371 filterImports :: ModuleName -- The module being imported
372 -> Maybe (Bool, [RdrNameIE]) -- Import spec; True => hiding
373 -> [AvailInfo] -- What's available
374 -> RnMG ([AvailInfo], -- What's actually imported
375 [AvailInfo], -- What's to be hidden
376 -- (the unqualified version, that is)
377 NameSet) -- What was imported explicitly
379 -- Complains if import spec mentions things that the module doesn't export
380 -- Warns/informs if import spec contains duplicates.
381 filterImports mod Nothing imports
382 = returnRn (imports, [], emptyNameSet)
384 filterImports mod (Just (want_hiding, import_items)) avails
385 = mapMaybeRn check_item import_items `thenRn` \ avails_w_explicits ->
387 (item_avails, explicits_s) = unzip avails_w_explicits
388 explicits = foldl addListToNameSet emptyNameSet explicits_s
392 -- All imported; item_avails to be hidden
393 returnRn (avails, item_avails, emptyNameSet)
395 -- Just item_avails imported; nothing to be hidden
396 returnRn (item_avails, [], explicits)
398 import_fm :: FiniteMap OccName AvailInfo
399 import_fm = listToFM [ (nameOccName name, avail)
401 name <- availNames avail]
402 -- Even though availNames returns data constructors too,
403 -- they won't make any difference because naked entities like T
404 -- in an import list map to TcOccs, not VarOccs.
406 check_item item@(IEModuleContents _)
407 = addErrRn (badImportItemErr mod item) `thenRn_`
411 | not (maybeToBool maybe_in_import_avails) ||
412 not (maybeToBool maybe_filtered_avail)
413 = addErrRn (badImportItemErr mod item) `thenRn_`
416 | dodgy_import = addWarnRn (dodgyImportWarn mod item) `thenRn_`
417 returnRn (Just (filtered_avail, explicits))
419 | otherwise = returnRn (Just (filtered_avail, explicits))
422 wanted_occ = rdrNameOcc (ieName item)
423 maybe_in_import_avails = lookupFM import_fm wanted_occ
425 Just avail = maybe_in_import_avails
426 maybe_filtered_avail = filterAvail item avail
427 Just filtered_avail = maybe_filtered_avail
428 explicits | dot_dot = [availName filtered_avail]
429 | otherwise = availNames filtered_avail
431 dot_dot = case item of
435 dodgy_import = case (item, avail) of
436 (IEThingAll _, AvailTC _ [n]) -> True
437 -- This occurs when you import T(..), but
438 -- only export T abstractly. The single [n]
439 -- in the AvailTC is the type or class itself
446 %************************************************************************
448 \subsection{Qualifiying imports}
450 %************************************************************************
452 @qualifyImports@ takes the @ExportEnv@ after filtering through the import spec
453 of an import decl, and deals with producing an @RnEnv@ with the
454 right qualified names. It also turns the @Names@ in the @ExportEnv@ into
455 fully fledged @Names@.
458 qualifyImports :: ModuleName -- Imported module
459 -> Bool -- True <=> want unqualified import
460 -> Maybe ModuleName -- Optional "as M" part
461 -> [AvailInfo] -- What's to be hidden
462 -> Avails -- Whats imported and how
463 -> (Name -> Name) -- Improves the provenance on imported things
464 -> RnMG (GlobalRdrEnv, ExportAvails)
465 -- NB: the Names in ExportAvails don't have the improve-provenance
466 -- function applied to them
467 -- We could fix that, but I don't think it matters
469 qualifyImports this_mod unqual_imp as_mod hides
472 -- Make the name environment. We're talking about a
473 -- single module here, so there must be no name clashes.
474 -- In practice there only ever will be if it's the module
477 -- Add the things that are available
478 name_env1 = foldl add_avail emptyRdrEnv avails
480 -- Delete things that are hidden
481 name_env2 = foldl del_avail name_env1 hides
483 -- Create the export-availability info
484 export_avails = mkExportAvails qual_mod unqual_imp name_env2 avails
486 returnRn (name_env2, export_avails)
489 qual_mod = case as_mod of
491 Just another_name -> another_name
493 add_avail :: GlobalRdrEnv -> AvailInfo -> GlobalRdrEnv
494 add_avail env avail = foldl add_name env (availNames avail)
500 env1 = addOneToGlobalRdrEnv env (mkRdrQual qual_mod occ) better_name
501 env2 = addOneToGlobalRdrEnv env1 (mkRdrUnqual occ) better_name
502 occ = nameOccName name
503 better_name = improve_prov name
505 del_avail env avail = foldl delOneFromGlobalRdrEnv env rdr_names
507 rdr_names = map (mkRdrUnqual . nameOccName) (availNames avail)
511 %************************************************************************
513 \subsection{Export list processing}
515 %************************************************************************
517 Processing the export list.
519 You might think that we should record things that appear in the export list
520 as ``occurrences'' (using @addOccurrenceName@), but you'd be wrong.
521 We do check (here) that they are in scope,
522 but there is no need to slurp in their actual declaration
523 (which is what @addOccurrenceName@ forces).
525 Indeed, doing so would big trouble when
526 compiling @PrelBase@, because it re-exports @GHC@, which includes @takeMVar#@,
527 whose type includes @ConcBase.StateAndSynchVar#@, and so on...
530 type ExportAccum -- The type of the accumulating parameter of
531 -- the main worker function in exportsFromAvail
532 = ([ModuleName], -- 'module M's seen so far
533 ExportOccMap, -- Tracks exported occurrence names
534 NameEnv AvailInfo) -- The accumulated exported stuff, kept in an env
535 -- so we can common-up related AvailInfos
537 type ExportOccMap = FiniteMap OccName (Name, RdrNameIE)
538 -- Tracks what a particular exported OccName
539 -- in an export list refers to, and which item
540 -- it came from. It's illegal to export two distinct things
541 -- that have the same occurrence name
544 exportsFromAvail :: ModuleName
545 -> Maybe [RdrNameIE] -- Export spec
549 -- Complains if two distinct exports have same OccName
550 -- Warns about identical exports.
551 -- Complains about exports items not in scope
552 exportsFromAvail this_mod Nothing export_avails global_name_env
553 = exportsFromAvail this_mod true_exports export_avails global_name_env
555 true_exports = Just $ if this_mod == mAIN_Name
556 then [IEVar main_RDR]
557 -- export Main.main *only* unless otherwise specified,
558 else [IEModuleContents this_mod]
559 -- but for all other modules export everything.
561 exportsFromAvail this_mod (Just export_items)
562 (mod_avail_env, entity_avail_env)
564 = foldlRn exports_from_item
565 ([], emptyFM, emptyNameEnv) export_items `thenRn` \ (_, _, export_avail_map) ->
567 export_avails :: [AvailInfo]
568 export_avails = nameEnvElts export_avail_map
570 returnRn export_avails
573 exports_from_item :: ExportAccum -> RdrNameIE -> RnMG ExportAccum
575 exports_from_item acc@(mods, occs, avails) ie@(IEModuleContents mod)
576 | mod `elem` mods -- Duplicate export of M
577 = warnCheckRn opt_WarnDuplicateExports
578 (dupModuleExport mod) `thenRn_`
582 = case lookupFM mod_avail_env mod of
583 Nothing -> failWithRn acc (modExportErr mod)
584 Just mod_avails -> foldlRn (check_occs ie) occs mod_avails
587 avails' = foldl add_avail avails mod_avails
589 returnRn (mod:mods, occs', avails')
591 exports_from_item acc@(mods, occs, avails) ie
592 | not (maybeToBool maybe_in_scope)
593 = failWithRn acc (unknownNameErr (ieName ie))
595 | not (null dup_names)
596 = addNameClashErrRn rdr_name (name:dup_names) `thenRn_`
600 -- I can't see why this should ever happen; if the thing is in scope
601 -- at all it ought to have some availability
602 | not (maybeToBool maybe_avail)
603 = pprTrace "exportsFromAvail: curious Nothing:" (ppr name)
608 = failWithRn acc (exportItemErr ie)
610 | otherwise -- Phew! It's OK! Now to check the occurrence stuff!
611 = check_occs ie occs export_avail `thenRn` \ occs' ->
612 returnRn (mods, occs', add_avail avails export_avail)
616 maybe_in_scope = lookupFM global_name_env rdr_name
617 Just (name:dup_names) = maybe_in_scope
618 maybe_avail = lookupUFM entity_avail_env name
619 Just avail = maybe_avail
620 maybe_export_avail = filterAvail ie avail
621 enough_avail = maybeToBool maybe_export_avail
622 Just export_avail = maybe_export_avail
624 add_avail avails avail = addToNameEnv_C plusAvail avails (availName avail) avail
626 check_occs :: RdrNameIE -> ExportOccMap -> AvailInfo -> RnMG ExportOccMap
627 check_occs ie occs avail
628 = foldlRn check occs (availNames avail)
631 = case lookupFM occs name_occ of
632 Nothing -> returnRn (addToFM occs name_occ (name, ie))
634 | name == name' -> -- Duplicate export
635 warnCheckRn opt_WarnDuplicateExports
636 (dupExportWarn name_occ ie ie')
637 `thenRn_` returnRn occs
639 | otherwise -> -- Same occ name but different names: an error
640 failWithRn occs (exportClashErr name_occ ie ie')
642 name_occ = nameOccName name
644 mk_export_fn :: NameSet -> (Name -> ExportFlag)
645 mk_export_fn exported_names
646 = \name -> if name `elemNameSet` exported_names
651 %************************************************************************
655 %************************************************************************
658 badImportItemErr mod ie
659 = sep [ptext SLIT("Module"), quotes (pprModuleName mod),
660 ptext SLIT("does not export"), quotes (ppr ie)]
662 dodgyImportWarn mod (IEThingAll tc)
663 = sep [ptext SLIT("Module") <+> quotes (pprModuleName mod)
664 <+> ptext SLIT("exports") <+> quotes (ppr tc),
665 ptext SLIT("with no constructors/class operations;"),
666 ptext SLIT("yet it is imported with a (..)")]
669 = hsep [ ptext SLIT("Unknown module in export list: module"), quotes (pprModuleName mod)]
671 exportItemErr export_item
672 = sep [ ptext SLIT("Bad export item"), quotes (ppr export_item)]
674 exportClashErr occ_name ie1 ie2
675 = hsep [ptext SLIT("The export items"), quotes (ppr ie1)
676 ,ptext SLIT("and"), quotes (ppr ie2)
677 ,ptext SLIT("create conflicting exports for"), quotes (ppr occ_name)]
680 = vcat [ptext SLIT("Multiple declarations of") <+> quotes (ppr n),
681 nest 4 (vcat (map pp sorted_ns))]
683 sorted_ns = sortLt occ'ed_before (n:ns)
685 occ'ed_before a b = LT == compare (getSrcLoc a) (getSrcLoc b)
687 pp n = pprProvenance (getNameProvenance n)
689 dupExportWarn occ_name ie1 ie2
690 = hsep [quotes (ppr occ_name),
691 ptext SLIT("is exported by"), quotes (ppr ie1),
692 ptext SLIT("and"), quotes (ppr ie2)]
695 = hsep [ptext SLIT("Duplicate"),
696 quotes (ptext SLIT("Module") <+> pprModuleName mod),
697 ptext SLIT("in export list")]
699 unusedFixityDecl rdr_name fixity
700 = hsep [ptext SLIT("Unused fixity declaration for"), quotes (ppr rdr_name)]
702 dupFixityDecl rdr_name loc1 loc2
703 = vcat [ptext SLIT("Multiple fixity declarations for") <+> quotes (ppr rdr_name),
704 ptext SLIT("at ") <+> ppr loc1,
705 ptext SLIT("and") <+> ppr loc2]