2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[RnNames]{Extracting imported and top-level names in scope}
8 rnImports, importsFromLocalDecls,
9 reportUnusedNames, reportDeprecations,
10 mkModDeps, exportsFromAvail
13 #include "HsVersions.h"
15 import DynFlags ( DynFlag(..), GhcMode(..) )
16 import HsSyn ( IE(..), ieName, ImportDecl(..), LImportDecl,
17 ForeignDecl(..), HsGroup(..), HsBindGroup(..),
18 Sig(..), collectGroupBinders, tyClDeclNames
21 import IfaceEnv ( ifaceExportNames )
22 import LoadIface ( loadSrcInterface )
26 import PrelNames ( pRELUDE, isUnboundName, main_RDR_Unqual )
27 import Module ( Module, moduleUserString, unitModuleEnv,
28 lookupModuleEnv, moduleEnvElts, foldModuleEnv )
29 import Name ( Name, nameSrcLoc, nameOccName, nameModule, isWiredInName,
30 nameParent, nameParent_maybe, isExternalName,
34 import OccName ( srcDataName, isTcOcc, occNameFlavour, OccEnv,
35 mkOccEnv, lookupOccEnv, emptyOccEnv, extendOccEnv )
36 import HscTypes ( GenAvailInfo(..), AvailInfo,
37 HomePackageTable, PackageIfaceTable,
38 availNames, unQualInScope,
39 Deprecs(..), ModIface(..), Dependencies(..),
40 lookupIface, ExternalPackageState(..)
42 import Packages ( PackageIdH(..) )
43 import RdrName ( RdrName, rdrNameOcc, setRdrNameSpace,
44 GlobalRdrEnv, mkGlobalRdrEnv, GlobalRdrElt(..),
45 emptyGlobalRdrEnv, plusGlobalRdrEnv, globalRdrEnvElts,
46 unQualOK, lookupGRE_Name,
47 Provenance(..), ImportSpec(..),
48 isLocalGRE, pprNameProvenance )
50 import Maybes ( isNothing, catMaybes, mapCatMaybes, seqMaybe, orElse )
51 import SrcLoc ( Located(..), mkGeneralSrcSpan,
52 unLoc, noLoc, srcLocSpan, combineSrcSpans, SrcSpan )
53 import BasicTypes ( DeprecTxt )
54 import ListSetOps ( removeDups )
55 import Util ( sortLe, notNull, isSingleton )
56 import List ( partition )
57 import IO ( openFile, IOMode(..) )
62 %************************************************************************
66 %************************************************************************
69 rnImports :: [LImportDecl RdrName]
70 -> RnM (GlobalRdrEnv, ImportAvails)
73 = do { -- PROCESS IMPORT DECLS
74 -- Do the non {- SOURCE -} ones first, so that we get a helpful
75 -- warning for {- SOURCE -} ones that are unnecessary
77 ; implicit_prelude <- doptM Opt_ImplicitPrelude
79 all_imports = mk_prel_imports this_mod implicit_prelude ++ imports
80 (source, ordinary) = partition is_source_import all_imports
81 is_source_import (L _ (ImportDecl _ is_boot _ _ _)) = is_boot
83 get_imports = importsFromImportDecl this_mod
85 ; stuff1 <- mappM get_imports ordinary
86 ; stuff2 <- mappM get_imports source
90 (imp_gbl_envs, imp_avails) = unzip (stuff1 ++ stuff2)
91 gbl_env :: GlobalRdrEnv
92 gbl_env = foldr plusGlobalRdrEnv emptyGlobalRdrEnv imp_gbl_envs
94 all_avails :: ImportAvails
95 all_avails = foldr plusImportAvails emptyImportAvails imp_avails
98 ; return (gbl_env, all_avails) }
100 -- NB: opt_NoImplicitPrelude is slightly different to import Prelude ();
101 -- because the former doesn't even look at Prelude.hi for instance
102 -- declarations, whereas the latter does.
103 mk_prel_imports this_mod implicit_prelude
104 | this_mod == pRELUDE
105 || explicit_prelude_import
106 || not implicit_prelude
109 | otherwise = [preludeImportDecl]
111 explicit_prelude_import
112 = notNull [ () | L _ (ImportDecl mod _ _ _ _) <- imports,
113 unLoc mod == pRELUDE ]
117 ImportDecl (L loc pRELUDE)
118 False {- Not a boot interface -}
119 False {- Not qualified -}
120 Nothing {- No "as" -}
121 Nothing {- No import list -}
123 loc = mkGeneralSrcSpan FSLIT("Implicit import declaration")
127 importsFromImportDecl :: Module
128 -> LImportDecl RdrName
129 -> RnM (GlobalRdrEnv, ImportAvails)
131 importsFromImportDecl this_mod
132 (L loc (ImportDecl loc_imp_mod_name want_boot qual_only as_mod imp_details))
136 -- If there's an error in loadInterface, (e.g. interface
137 -- file not found) we get lots of spurious errors from 'filterImports'
139 imp_mod_name = unLoc loc_imp_mod_name
140 doc = ppr imp_mod_name <+> ptext SLIT("is directly imported")
142 loadSrcInterface doc imp_mod_name want_boot `thenM` \ iface ->
144 -- Compiler sanity check: if the import didn't say
145 -- {-# SOURCE #-} we should not get a hi-boot file
146 WARN( not want_boot && mi_boot iface, ppr imp_mod_name )
148 -- Issue a user warning for a redundant {- SOURCE -} import
149 -- NB that we arrange to read all the ordinary imports before
150 -- any of the {- SOURCE -} imports
151 warnIf (want_boot && not (mi_boot iface))
152 (warnRedundantSourceImport imp_mod_name) `thenM_`
155 imp_mod = mi_module iface
156 deprecs = mi_deprecs iface
157 is_orph = mi_orphan iface
160 filtered_exports = filter not_this_mod (mi_exports iface)
161 not_this_mod (mod,_) = mod /= this_mod
162 -- If the module exports anything defined in this module, just ignore it.
163 -- Reason: otherwise it looks as if there are two local definition sites
164 -- for the thing, and an error gets reported. Easiest thing is just to
165 -- filter them out up front. This situation only arises if a module
166 -- imports itself, or another module that imported it. (Necessarily,
167 -- this invoves a loop.)
169 -- Tiresome consequence: if you say
174 -- module B( AType ) where
175 -- import {-# SOURCE #-} A( AType )
177 -- then you'll get a 'B does not export AType' message. Oh well.
179 qual_mod_name = case as_mod of
180 Nothing -> imp_mod_name
181 Just another_name -> another_name
182 imp_spec = ImportSpec { is_mod = imp_mod_name, is_qual = qual_only,
183 is_loc = loc, is_as = qual_mod_name }
185 -- Get the total imports, and filter them according to the import list
186 ifaceExportNames filtered_exports `thenM` \ total_avails ->
187 filterImports iface imp_spec
188 imp_details total_avails `thenM` \ (avail_env, gbl_env) ->
190 getDOpts `thenM` \ dflags ->
193 -- Compute new transitive dependencies
195 orphans | is_orph = ASSERT( not (imp_mod_name `elem` dep_orphs deps) )
196 imp_mod_name : dep_orphs deps
197 | otherwise = dep_orphs deps
199 (dependent_mods, dependent_pkgs)
200 = case mi_package iface of
202 -- Imported module is from the home package
203 -- Take its dependent modules and add imp_mod itself
204 -- Take its dependent packages unchanged
206 -- NB: (dep_mods deps) might include a hi-boot file
207 -- for the module being compiled, CM. Do *not* filter
208 -- this out (as we used to), because when we've
209 -- finished dealing with the direct imports we want to
210 -- know if any of them depended on CM.hi-boot, in
211 -- which case we should do the hi-boot consistency
212 -- check. See LoadIface.loadHiBootInterface
213 ((imp_mod_name, want_boot) : dep_mods deps, dep_pkgs deps)
216 -- Imported module is from another package
217 -- Dump the dependent modules
218 -- Add the package imp_mod comes from to the dependent packages
219 ASSERT2( not (pkg `elem` dep_pkgs deps), ppr pkg <+> ppr (dep_pkgs deps) )
220 ([], pkg : dep_pkgs deps)
222 import_all = case imp_details of
223 Just (is_hiding, ls) -- Imports are spec'd explicitly
224 | not is_hiding -> Just (not (null ls))
225 _ -> Nothing -- Everything is imported,
226 -- (or almost everything [hiding])
228 -- unqual_avails is the Avails that are visible in *unqualified* form
229 -- We need to know this so we know what to export when we see
230 -- module M ( module P ) where ...
231 -- Then we must export whatever came from P unqualified.
232 imports = ImportAvails {
233 imp_env = unitModuleEnv qual_mod_name avail_env,
234 imp_mods = unitModuleEnv imp_mod (imp_mod, import_all, loc),
236 imp_dep_mods = mkModDeps dependent_mods,
237 imp_dep_pkgs = dependent_pkgs }
240 -- Complain if we import a deprecated module
241 ifOptM Opt_WarnDeprecations (
243 DeprecAll txt -> addWarn (moduleDeprec imp_mod_name txt)
247 returnM (gbl_env, imports)
249 warnRedundantSourceImport mod_name
250 = ptext SLIT("Unnecessary {- SOURCE -} in the import of module")
251 <+> quotes (ppr mod_name)
255 %************************************************************************
257 importsFromLocalDecls
259 %************************************************************************
261 From the top-level declarations of this module produce
262 * the lexical environment
264 created by its bindings.
266 Complain about duplicate bindings
269 importsFromLocalDecls :: HsGroup RdrName
270 -> RnM (GlobalRdrEnv, ImportAvails)
271 importsFromLocalDecls group
272 = getModule `thenM` \ this_mod ->
273 getLocalDeclBinders this_mod group `thenM` \ avails ->
274 -- The avails that are returned don't include the "system" names
276 all_names :: [Name] -- All the defns; no dups eliminated
277 all_names = [name | avail <- avails, name <- availNames avail]
280 (_, dups) = removeDups compare all_names
282 -- Check for duplicate definitions
283 -- The complaint will come out as "Multiple declarations of Foo.f" because
284 -- since 'f' is in the env twice, the unQualInScope used by the error-msg
285 -- printer returns False. It seems awkward to fix, unfortunately.
286 mappM_ addDupDeclErr dups `thenM_`
288 doptM Opt_ImplicitPrelude `thenM` \ implicit_prelude ->
290 prov = LocalDef this_mod
291 gbl_env = mkGlobalRdrEnv gres
292 gres = [ GRE { gre_name = name, gre_prov = prov}
295 -- Optimisation: filter out names for built-in syntax
296 -- They just clutter up the environment (esp tuples), and the parser
297 -- will generate Exact RdrNames for them, so the cluttered
298 -- envt is no use. To avoid doing this filter all the time,
299 -- we use -fno-implicit-prelude as a clue that the filter is
300 -- worth while. Really, it's only useful for GHC.Base and GHC.Tuple.
302 -- It's worth doing because it makes the environment smaller for
303 -- every module that imports the Prelude
305 -- Note: don't filter the gbl_env (hence all_names, not filered_all_names
306 -- in defn of gres above). Stupid reason: when parsing
307 -- data type decls, the constructors start as Exact tycon-names,
308 -- and then get turned into data con names by zapping the name space;
309 -- but that stops them being Exact, so they get looked up.
310 -- Ditto in fixity decls; e.g. infix 5 :
311 -- Sigh. It doesn't matter because it only affects the Data.Tuple really.
312 -- The important thing is to trim down the exports.
314 | implicit_prelude = all_names
315 | otherwise = filter (not . isBuiltInSyntax) all_names
317 imports = emptyImportAvails {
318 imp_env = unitModuleEnv this_mod $
319 mkNameSet filtered_names
322 returnM (gbl_env, imports)
326 %*********************************************************
328 \subsection{Getting binders out of a declaration}
330 %*********************************************************
332 @getLocalDeclBinders@ returns the names for an @HsDecl@. It's
333 used for source code.
335 *** See "THE NAMING STORY" in HsDecls ****
338 getLocalDeclBinders :: Module -> HsGroup RdrName -> RnM [AvailInfo]
339 getLocalDeclBinders mod (HsGroup {hs_valds = val_decls,
340 hs_tyclds = tycl_decls,
341 hs_fords = foreign_decls })
342 = -- For type and class decls, we generate Global names, with
343 -- no export indicator. They need to be global because they get
344 -- permanently bound into the TyCons and Classes. They don't need
345 -- an export indicator because they are all implicitly exported.
347 mappM new_tc tycl_decls `thenM` \ tc_avails ->
349 -- In a hs-boot file, the value binders come from the
350 -- *signatures*, and there should be no foreign binders
351 tcIsHsBoot `thenM` \ is_hs_boot ->
352 let val_bndrs | is_hs_boot = sig_hs_bndrs
353 | otherwise = for_hs_bndrs ++ val_hs_bndrs
355 mappM new_simple val_bndrs `thenM` \ names ->
357 returnM (tc_avails ++ map Avail names)
359 new_simple rdr_name = newTopSrcBinder mod Nothing rdr_name
361 sig_hs_bndrs = [nm | HsBindGroup _ lsigs _ <- val_decls,
362 L _ (Sig nm _) <- lsigs]
363 val_hs_bndrs = collectGroupBinders val_decls
364 for_hs_bndrs = [nm | L _ (ForeignImport nm _ _ _) <- foreign_decls]
367 = newTopSrcBinder mod Nothing main_rdr `thenM` \ main_name ->
368 mappM (newTopSrcBinder mod (Just main_name)) sub_rdrs `thenM` \ sub_names ->
369 returnM (AvailTC main_name (main_name : sub_names))
371 (main_rdr : sub_rdrs) = tyClDeclNames (unLoc tc_decl)
375 %************************************************************************
377 \subsection{Filtering imports}
379 %************************************************************************
381 @filterImports@ takes the @ExportEnv@ telling what the imported module makes
382 available, and filters it through the import spec (if any).
385 filterImports :: ModIface
386 -> ImportSpec -- The span for the entire import decl
387 -> Maybe (Bool, [Located (IE RdrName)]) -- Import spec; True => hiding
388 -> NameSet -- What's available
389 -> RnM (NameSet, -- What's imported (qualified or unqualified)
390 GlobalRdrEnv) -- Same again, but in GRE form
392 -- Complains if import spec mentions things that the module doesn't export
393 -- Warns/informs if import spec contains duplicates.
395 mkGenericRdrEnv imp_spec names
396 = mkGlobalRdrEnv [ GRE { gre_name = name, gre_prov = Imported [imp_spec] False }
397 | name <- nameSetToList names ]
399 filterImports iface imp_spec Nothing all_names
400 = returnM (all_names, mkGenericRdrEnv imp_spec all_names)
402 filterImports iface imp_spec (Just (want_hiding, import_items)) all_names
403 = mappM (addLocM get_item) import_items `thenM` \ gres_s ->
406 specified_names = mkNameSet (map gre_name gres)
408 if not want_hiding then
409 return (specified_names, mkGlobalRdrEnv gres)
412 keep n = not (n `elemNameSet` specified_names)
413 pruned_avails = filterNameSet keep all_names
415 return (pruned_avails, mkGenericRdrEnv imp_spec pruned_avails)
418 occ_env :: OccEnv Name -- Maps OccName to corresponding Name
419 occ_env = mkOccEnv [(nameOccName n, n) | n <- nameSetToList all_names]
420 -- This env will have entries for data constructors too,
421 -- they won't make any difference because naked entities like T
422 -- in an import list map to TcOccs, not VarOccs.
424 sub_env :: NameEnv [Name]
425 sub_env = mkSubNameEnv all_names
427 bale_out item = addErr (badImportItemErr iface imp_spec item) `thenM_`
430 succeed_with :: Bool -> [Name] -> RnM [GlobalRdrElt]
431 succeed_with all_explicit names
432 = do { loc <- getSrcSpanM
433 ; returnM (map (mk_gre loc) names) }
435 mk_gre loc name = GRE { gre_name = name,
436 gre_prov = Imported [this_imp_spec loc] (explicit name) }
437 this_imp_spec loc = imp_spec { is_loc = loc }
438 explicit name = all_explicit || isNothing (nameParent_maybe name)
440 get_item :: IE RdrName -> RnM [GlobalRdrElt]
441 -- Empty result for a bad item.
442 -- Singleton result is typical case.
443 -- Can have two when we are hiding, and mention C which might be
444 -- both a class and a data constructor.
445 get_item item@(IEModuleContents _)
448 get_item item@(IEThingAll tc)
449 = case check_item item of
452 [n] -> -- This occurs when you import T(..), but
453 -- only export T abstractly. The single [n]
454 -- in the AvailTC is the type or class itself
455 ifOptM Opt_WarnDodgyImports (addWarn (dodgyImportWarn tc)) `thenM_`
456 succeed_with False [n]
458 names -> succeed_with False names
460 get_item item@(IEThingAbs n)
461 | want_hiding -- hiding( C )
462 -- Here the 'C' can be a data constructor
463 -- *or* a type/class, or even both
464 = case concat [check_item item, check_item (IEVar data_n)] of
466 names -> succeed_with True names
468 data_n = setRdrNameSpace n srcDataName
471 = case check_item item of
473 names -> succeed_with True names
475 check_item :: IE RdrName -> [Name]
477 = case lookupOccEnv occ_env (rdrNameOcc (ieName item)) of
479 Just name -> filterAvail item name sub_env
483 %************************************************************************
485 \subsection{Export list processing}
487 %************************************************************************
489 Processing the export list.
491 You might think that we should record things that appear in the export
492 list as ``occurrences'' (using @addOccurrenceName@), but you'd be
493 wrong. We do check (here) that they are in scope, but there is no
494 need to slurp in their actual declaration (which is what
495 @addOccurrenceName@ forces).
497 Indeed, doing so would big trouble when compiling @PrelBase@, because
498 it re-exports @GHC@, which includes @takeMVar#@, whose type includes
499 @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 NameSet) -- The accumulated exported stuff
507 emptyExportAccum = ([], emptyOccEnv, emptyNameSet)
509 type ExportOccMap = OccEnv (Name, IE RdrName)
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 :: Bool -- False => no 'module M(..) where' header at all
517 -> Maybe [Located (IE RdrName)] -- Nothing => no explicit export list
519 -- Complains if two distinct exports have same OccName
520 -- Warns about identical exports.
521 -- Complains about exports items not in scope
523 exportsFromAvail explicit_mod exports
524 = do { TcGblEnv { tcg_rdr_env = rdr_env,
525 tcg_imports = imports } <- getGblEnv ;
527 -- If the module header is omitted altogether, then behave
528 -- as if the user had written "module Main(main) where..."
529 -- EXCEPT in interactive mode, when we behave as if he had
530 -- written "module Main where ..."
531 -- Reason: don't want to complain about 'main' not in scope
532 -- in interactive mode
533 ghci_mode <- getGhciMode ;
535 | explicit_mod = exports
536 | ghci_mode == Interactive = Nothing
537 | otherwise = Just [noLoc (IEVar main_RDR_Unqual)] } ;
538 exports_from_avail real_exports rdr_env imports }
541 exports_from_avail Nothing rdr_env imports
542 = -- Export all locally-defined things
543 -- We do this by filtering the global RdrEnv,
544 -- keeping only things that are locally-defined
545 return (mkNameSet [ gre_name gre
546 | gre <- globalRdrEnvElts rdr_env,
549 exports_from_avail (Just items) rdr_env (ImportAvails { imp_env = imp_env })
550 = foldlM do_litem emptyExportAccum items `thenM` \ (_, _, exports) ->
553 sub_env :: NameEnv [Name] -- Classify each name by its parent
554 sub_env = mkSubNameEnv (foldModuleEnv unionNameSets emptyNameSet imp_env)
556 do_litem :: ExportAccum -> Located (IE RdrName) -> RnM ExportAccum
557 do_litem acc = addLocM (exports_from_item acc)
559 exports_from_item :: ExportAccum -> IE RdrName -> RnM ExportAccum
560 exports_from_item acc@(mods, occs, exports) ie@(IEModuleContents mod)
561 | mod `elem` mods -- Duplicate export of M
562 = do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
563 warnIf warn_dup_exports (dupModuleExport mod) ;
567 = case lookupModuleEnv imp_env mod of
568 Nothing -> addErr (modExportErr mod) `thenM_`
572 new_exports = filterNameSet (inScopeUnqual rdr_env) names
575 -- This check_occs not only finds conflicts between this item
576 -- and others, but also internally within this item. That is,
577 -- if 'M.x' is in scope in several ways, we'll have several
578 -- members of mod_avails with the same OccName.
579 check_occs ie occs (nameSetToList new_exports) `thenM` \ occs' ->
580 returnM (mod:mods, occs', exports `unionNameSets` new_exports)
582 exports_from_item acc@(mods, occs, exports) ie
583 = lookupGlobalOccRn (ieName ie) `thenM` \ name ->
584 if isUnboundName name then
585 returnM acc -- Avoid error cascade
587 new_exports = filterAvail ie name sub_env
589 checkErr (not (null new_exports)) (exportItemErr ie) `thenM_`
590 checkForDodgyExport ie new_exports `thenM_`
591 check_occs ie occs new_exports `thenM` \ occs' ->
592 returnM (mods, occs', addListToNameSet exports new_exports)
594 -------------------------------
595 filterAvail :: IE RdrName -- Wanted
596 -> Name -- The Name of the ieName of the item
597 -> NameEnv [Name] -- Maps type/class names to their sub-names
598 -> [Name] -- Empty if even one thing reqd is missing
600 filterAvail (IEVar _) n subs = [n]
601 filterAvail (IEThingAbs _) n subs = [n]
602 filterAvail (IEThingAll _) n subs = n : subNames subs n
603 filterAvail (IEThingWith _ rdrs) n subs
604 | any isNothing mb_names = []
605 | otherwise = n : catMaybes mb_names
607 env = mkOccEnv [(nameOccName s, s) | s <- subNames subs n]
608 mb_names = map (lookupOccEnv env . rdrNameOcc) rdrs
609 filterAvail (IEModuleContents _) _ _ = panic "filterAvail"
611 subNames :: NameEnv [Name] -> Name -> [Name]
612 subNames env n = lookupNameEnv env n `orElse` []
614 mkSubNameEnv :: NameSet -> NameEnv [Name]
615 -- Maps types and classes to their constructors/classops respectively
616 -- This mapping just makes it easier to deal with A(..) export items
618 = foldNameSet add_name emptyNameEnv names
621 | Just parent <- nameParent_maybe name
622 = extendNameEnv_C (\ns _ -> name:ns) env parent [name]
625 -------------------------------
626 inScopeUnqual :: GlobalRdrEnv -> Name -> Bool
627 -- Checks whether the Name is in scope unqualified,
628 -- regardless of whether it's ambiguous or not
629 inScopeUnqual env n = any unQualOK (lookupGRE_Name env n)
631 -------------------------------
632 checkForDodgyExport :: IE RdrName -> [Name] -> RnM ()
633 checkForDodgyExport ie@(IEThingAll tc) [n]
634 | isTcOcc (nameOccName n) = addWarn (dodgyExportWarn tc)
635 -- This occurs when you export T(..), but
636 -- only import T abstractly, or T is a synonym.
637 -- The single [n] is the type or class itself
638 | otherwise = addErr (exportItemErr ie)
639 -- This happes if you export x(..), which is bogus
640 checkForDodgyExport _ _ = return ()
642 -------------------------------
643 check_occs :: IE RdrName -> ExportOccMap -> [Name] -> RnM ExportOccMap
644 check_occs ie occs names
645 = foldlM check occs names
648 = case lookupOccEnv occs name_occ of
649 Nothing -> returnM (extendOccEnv occs name_occ (name, ie))
652 | name == name' -- Duplicate export
653 -> do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
654 warnIf warn_dup_exports (dupExportWarn name_occ ie ie') ;
657 | otherwise -- Same occ name but different names: an error
658 -> do { global_env <- getGlobalRdrEnv ;
659 addErr (exportClashErr global_env name name' ie ie') ;
662 name_occ = nameOccName name
665 %*********************************************************
669 %*********************************************************
672 reportDeprecations :: TcGblEnv -> RnM ()
673 reportDeprecations tcg_env
674 = ifOptM Opt_WarnDeprecations $
675 do { (eps,hpt) <- getEpsAndHpt
676 ; mapM_ (check hpt (eps_PIT eps)) all_gres }
678 used_names = findUses (tcg_dus tcg_env) emptyNameSet
679 all_gres = globalRdrEnvElts (tcg_rdr_env tcg_env)
681 check hpt pit (GRE {gre_name = name, gre_prov = Imported (imp_spec:_) _})
682 | name `elemNameSet` used_names
683 , Just deprec_txt <- lookupDeprec hpt pit name
684 = setSrcSpan (is_loc imp_spec) $
685 addWarn (sep [ptext SLIT("Deprecated use of") <+>
686 occNameFlavour (nameOccName name) <+>
691 name_mod = nameModule name
692 imp_mod = is_mod imp_spec
693 imp_msg = ptext SLIT("imported from") <+> ppr imp_mod <> extra
694 extra | imp_mod == name_mod = empty
695 | otherwise = ptext SLIT(", but defined in") <+> ppr name_mod
697 check hpt pit ok_gre = returnM () -- Local, or not used, or not deprectated
698 -- The Imported pattern-match: don't deprecate locally defined names
699 -- For a start, we may be exporting a deprecated thing
700 -- Also we may use a deprecated thing in the defn of another
701 -- deprecated things. We may even use a deprecated thing in
702 -- the defn of a non-deprecated thing, when changing a module's
705 lookupDeprec :: HomePackageTable -> PackageIfaceTable
706 -> Name -> Maybe DeprecTxt
707 lookupDeprec hpt pit n
708 = case lookupIface hpt pit (nameModule n) of
709 Just iface -> mi_dep_fn iface n `seqMaybe` -- Bleat if the thing, *or
710 mi_dep_fn iface (nameParent n) -- its parent*, is deprec'd
712 | isWiredInName n -> Nothing
713 -- We have not necessarily loaded the .hi file for a
714 -- wired-in name (yet), although we *could*.
715 -- And we never deprecate them
717 | otherwise -> pprPanic "lookupDeprec" (ppr n)
718 -- By now all the interfaces should have been loaded
720 gre_is_used :: NameSet -> GlobalRdrElt -> Bool
721 gre_is_used used_names gre = gre_name gre `elemNameSet` used_names
724 %*********************************************************
728 %*********************************************************
731 reportUnusedNames :: Maybe [Located (IE RdrName)] -- Export list
732 -> TcGblEnv -> RnM ()
733 reportUnusedNames export_decls gbl_env
734 = do { warnUnusedTopBinds unused_locals
735 ; warnUnusedModules unused_imp_mods
736 ; warnUnusedImports unused_imports
737 ; warnDuplicateImports dup_imps
738 ; printMinimalImports minimal_imports }
740 used_names, all_used_names :: NameSet
741 used_names = findUses (tcg_dus gbl_env) emptyNameSet
742 all_used_names = used_names `unionNameSets`
743 mkNameSet (mapCatMaybes nameParent_maybe (nameSetToList used_names))
744 -- A use of C implies a use of T,
745 -- if C was brought into scope by T(..) or T(C)
747 -- Collect the defined names from the in-scope environment
748 defined_names :: [GlobalRdrElt]
749 defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)
751 -- Note that defined_and_used, defined_but_not_used
752 -- are both [GRE]; that's why we need defined_and_used
753 -- rather than just all_used_names
754 defined_and_used, defined_but_not_used :: [GlobalRdrElt]
755 (defined_and_used, defined_but_not_used)
756 = partition (gre_is_used all_used_names) defined_names
758 -- Find the duplicate imports
759 dup_imps = filter is_dup defined_and_used
760 is_dup (GRE {gre_prov = Imported imp_spec True}) = not (isSingleton imp_spec)
763 -- Filter out the ones that are
764 -- (a) defined in this module, and
765 -- (b) not defined by a 'deriving' clause
766 -- The latter have an Internal Name, so we can filter them out easily
767 unused_locals :: [GlobalRdrElt]
768 unused_locals = filter is_unused_local defined_but_not_used
769 is_unused_local :: GlobalRdrElt -> Bool
770 is_unused_local gre = isLocalGRE gre && isExternalName (gre_name gre)
772 unused_imports :: [GlobalRdrElt]
773 unused_imports = filter unused_imp defined_but_not_used
774 unused_imp (GRE {gre_prov = Imported imp_specs True})
775 = not (all (module_unused . is_mod) imp_specs)
776 -- Don't complain about unused imports if we've already said the
777 -- entire import is unused
778 unused_imp other = False
780 -- To figure out the minimal set of imports, start with the things
781 -- that are in scope (i.e. in gbl_env). Then just combine them
782 -- into a bunch of avails, so they are properly grouped
784 -- BUG WARNING: this does not deal properly with qualified imports!
785 minimal_imports :: FiniteMap Module AvailEnv
786 minimal_imports0 = foldr add_expall emptyFM expall_mods
787 minimal_imports1 = foldr add_name minimal_imports0 defined_and_used
788 minimal_imports = foldr add_inst_mod minimal_imports1 direct_import_mods
789 -- The last line makes sure that we retain all direct imports
790 -- even if we import nothing explicitly.
791 -- It's not necessarily redundant to import such modules. Consider
795 -- The import M() is not *necessarily* redundant, even if
796 -- we suck in no instance decls from M (e.g. it contains
797 -- no instance decls, or This contains no code). It may be
798 -- that we import M solely to ensure that M's orphan instance
799 -- decls (or those in its imports) are visible to people who
800 -- import This. Sigh.
801 -- There's really no good way to detect this, so the error message
802 -- in RnEnv.warnUnusedModules is weakened instead
804 -- We've carefully preserved the provenance so that we can
805 -- construct minimal imports that import the name by (one of)
806 -- the same route(s) as the programmer originally did.
807 add_name (GRE {gre_name = n, gre_prov = Imported imp_specs _}) acc
808 = addToFM_C plusAvailEnv acc (is_mod (head imp_specs))
809 (unitAvailEnv (mk_avail n (nameParent_maybe n)))
813 -- Modules mentioned as 'module M' in the export list
814 expall_mods = case export_decls of
816 Just es -> [m | L _ (IEModuleContents m) <- es]
818 -- This is really bogus. The idea is that if we see 'module M' in
819 -- the export list we must retain the import decls that drive it
820 -- If we aren't careful we might see
821 -- module A( module M ) where
824 -- and suppose that N exports everything that M does. Then we
825 -- must not drop the import of M even though N brings it all into
828 -- BUG WARNING: 'module M' exports aside, what if M.x is mentioned?!
830 -- The reason that add_expall is bogus is that it doesn't take
831 -- qualified imports into account. But it's an improvement.
832 add_expall mod acc = addToFM_C plusAvailEnv acc mod emptyAvailEnv
834 -- n is the name of the thing, p is the name of its parent
835 mk_avail n (Just p) = AvailTC p [p,n]
836 mk_avail n Nothing | isTcOcc (nameOccName n) = AvailTC n [n]
837 | otherwise = Avail n
839 add_inst_mod (mod,_,_) acc
840 | mod `elemFM` acc = acc -- We import something already
841 | otherwise = addToFM acc mod emptyAvailEnv
843 -- Add an empty collection of imports for a module
844 -- from which we have sucked only instance decls
846 imports = tcg_imports gbl_env
848 direct_import_mods :: [(Module, Maybe Bool, SrcSpan)]
849 -- See the type of the imp_mods for this triple
850 direct_import_mods = moduleEnvElts (imp_mods imports)
852 -- unused_imp_mods are the directly-imported modules
853 -- that are not mentioned in minimal_imports1
854 -- [Note: not 'minimal_imports', because that includes directly-imported
855 -- modules even if we use nothing from them; see notes above]
857 -- BUG WARNING: does not deal correctly with multiple imports of the same module
858 -- becuase direct_import_mods has only one entry per module
859 unused_imp_mods = [(mod,loc) | (mod,imp,loc) <- direct_import_mods,
860 not (mod `elemFM` minimal_imports1),
863 -- The Just False part is not to complain about
864 -- import M (), which is an idiom for importing
865 -- instance declarations
867 module_unused :: Module -> Bool
868 module_unused mod = any (((==) mod) . fst) unused_imp_mods
870 ---------------------
871 warnDuplicateImports :: [GlobalRdrElt] -> RnM ()
872 warnDuplicateImports gres
873 = ifOptM Opt_WarnUnusedImports (mapM_ warn gres)
875 warn (GRE { gre_name = name, gre_prov = Imported imps _ })
876 = addWarn ((quotes (ppr name) <+> ptext SLIT("is imported more than once:"))
877 $$ nest 2 (vcat (map ppr imps)))
878 warn gre = panic "warnDuplicateImports"
879 -- The GREs should all have Imported provenance
882 -- ToDo: deal with original imports with 'qualified' and 'as M' clauses
883 printMinimalImports :: FiniteMap Module AvailEnv -- Minimal imports
885 printMinimalImports imps
886 = ifOptM Opt_D_dump_minimal_imports $ do {
888 mod_ies <- mappM to_ies (fmToList imps) ;
889 this_mod <- getModule ;
890 rdr_env <- getGlobalRdrEnv ;
891 ioToTcRn (do { h <- openFile (mkFilename this_mod) WriteMode ;
892 printForUser h (unQualInScope rdr_env)
893 (vcat (map ppr_mod_ie mod_ies)) })
896 mkFilename this_mod = moduleUserString this_mod ++ ".imports"
897 ppr_mod_ie (mod_name, ies)
898 | mod_name == pRELUDE
900 | null ies -- Nothing except instances comes from here
901 = ptext SLIT("import") <+> ppr mod_name <> ptext SLIT("() -- Instances only")
903 = ptext SLIT("import") <+> ppr mod_name <>
904 parens (fsep (punctuate comma (map ppr ies)))
906 to_ies (mod, avail_env) = mappM to_ie (availEnvElts avail_env) `thenM` \ ies ->
909 to_ie :: AvailInfo -> RnM (IE Name)
910 -- The main trick here is that if we're importing all the constructors
911 -- we want to say "T(..)", but if we're importing only a subset we want
912 -- to say "T(A,B,C)". So we have to find out what the module exports.
913 to_ie (Avail n) = returnM (IEVar n)
914 to_ie (AvailTC n [m]) = ASSERT( n==m )
915 returnM (IEThingAbs n)
917 = loadSrcInterface doc n_mod False `thenM` \ iface ->
918 case [xs | (m,as) <- mi_exports iface,
921 x == nameOccName n] of
922 [xs] | all_used xs -> returnM (IEThingAll n)
923 | otherwise -> returnM (IEThingWith n (filter (/= n) ns))
924 other -> pprTrace "to_ie" (ppr n <+> ppr n_mod <+> ppr other) $
927 all_used avail_occs = all (`elem` map nameOccName ns) avail_occs
928 doc = text "Compute minimal imports from" <+> ppr n
933 %************************************************************************
937 %************************************************************************
940 badImportItemErr iface imp_spec ie
941 = sep [ptext SLIT("Module"), quotes (ppr (is_mod imp_spec)), source_import,
942 ptext SLIT("does not export"), quotes (ppr ie)]
944 source_import | mi_boot iface = ptext SLIT("(hi-boot interface)")
947 dodgyImportWarn item = dodgyMsg (ptext SLIT("import")) item
948 dodgyExportWarn item = dodgyMsg (ptext SLIT("export")) item
951 = sep [ ptext SLIT("The") <+> kind <+> ptext SLIT("item") <+> quotes (ppr (IEThingAll tc)),
952 ptext SLIT("suggests that") <+> quotes (ppr tc) <+> ptext SLIT("has constructor or class methods"),
953 ptext SLIT("but it has none; it is a type synonym or abstract type or class") ]
956 = hsep [ ptext SLIT("Unknown module in export list: module"), quotes (ppr mod)]
958 exportItemErr export_item
959 = sep [ ptext SLIT("The export item") <+> quotes (ppr export_item),
960 ptext SLIT("attempts to export constructors or class methods that are not visible here") ]
962 exportClashErr global_env name1 name2 ie1 ie2
963 = vcat [ ptext SLIT("Conflicting exports for") <+> quotes (ppr occ) <> colon
964 , ppr_export ie1 name1
965 , ppr_export ie2 name2 ]
967 occ = nameOccName name1
968 ppr_export ie name = nest 2 (quotes (ppr ie) <+> ptext SLIT("exports") <+>
969 quotes (ppr name) <+> pprNameProvenance (get_gre name))
971 -- get_gre finds a GRE for the Name, so that we can show its provenance
973 = case lookupGRE_Name global_env name of
975 [] -> pprPanic "exportClashErr" (ppr name)
977 addDupDeclErr :: [Name] -> TcRn ()
980 vcat [ptext SLIT("Multiple declarations of") <+> quotes (ppr name1),
981 ptext SLIT("Declared at:") <+> vcat (map ppr sorted_locs)]
983 locs = map nameSrcLoc names
984 big_loc = foldr1 combineSrcSpans (map srcLocSpan locs)
986 sorted_locs = sortLe (<=) (sortLe (<=) locs)
988 dupExportWarn occ_name ie1 ie2
989 = hsep [quotes (ppr occ_name),
990 ptext SLIT("is exported by"), quotes (ppr ie1),
991 ptext SLIT("and"), quotes (ppr ie2)]
994 = hsep [ptext SLIT("Duplicate"),
995 quotes (ptext SLIT("Module") <+> ppr mod),
996 ptext SLIT("in export list")]
999 = sep [ ptext SLIT("Module") <+> quotes (ppr mod) <+> ptext SLIT("is deprecated:"),