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 getLocalDeclBinders, extendRdrEnvRn,
10 reportUnusedNames, reportDeprecations,
11 mkModDeps, exportsFromAvail
14 #include "HsVersions.h"
16 import DynFlags ( DynFlag(..), GhcMode(..) )
17 import HsSyn ( IE(..), ieName, ImportDecl(..), LImportDecl,
18 ForeignDecl(..), HsGroup(..), HsBindGroup(..),
19 Sig(..), collectGroupBinders, tyClDeclNames
22 import IfaceEnv ( ifaceExportNames )
23 import LoadIface ( loadSrcInterface )
27 import PrelNames ( pRELUDE, isUnboundName, main_RDR_Unqual )
28 import Module ( Module, moduleUserString, unitModuleEnv,
29 lookupModuleEnv, moduleEnvElts, foldModuleEnv )
30 import Name ( Name, nameSrcLoc, nameOccName, nameModule, isWiredInName,
31 nameParent, nameParent_maybe, isExternalName,
35 import OccName ( srcDataName, isTcOcc, occNameFlavour, OccEnv,
36 mkOccEnv, lookupOccEnv, emptyOccEnv, extendOccEnv )
37 import HscTypes ( GenAvailInfo(..), AvailInfo,
38 HomePackageTable, PackageIfaceTable,
40 Deprecs(..), ModIface(..), Dependencies(..),
41 lookupIface, ExternalPackageState(..)
43 import Packages ( PackageIdH(..) )
44 import RdrName ( RdrName, rdrNameOcc, setRdrNameSpace,
45 GlobalRdrEnv, mkGlobalRdrEnv, GlobalRdrElt(..),
46 emptyGlobalRdrEnv, plusGlobalRdrEnv, globalRdrEnvElts,
47 extendGlobalRdrEnv, lookupGlobalRdrEnv, unQualOK, lookupGRE_Name,
48 Provenance(..), ImportSpec(..),
49 isLocalGRE, pprNameProvenance )
51 import Maybes ( isNothing, catMaybes, mapCatMaybes, seqMaybe, orElse )
52 import SrcLoc ( Located(..), mkGeneralSrcSpan,
53 unLoc, noLoc, srcLocSpan, SrcSpan )
54 import BasicTypes ( DeprecTxt )
55 import DriverPhases ( isHsBoot )
56 import Util ( notNull, isSingleton, thenCmp )
57 import ListSetOps ( equivClasses )
58 import List ( partition )
59 import IO ( openFile, IOMode(..) )
64 %************************************************************************
68 %************************************************************************
71 rnImports :: [LImportDecl RdrName]
72 -> RnM (GlobalRdrEnv, ImportAvails)
75 = do { -- PROCESS IMPORT DECLS
76 -- Do the non {- SOURCE -} ones first, so that we get a helpful
77 -- warning for {- SOURCE -} ones that are unnecessary
79 ; implicit_prelude <- doptM Opt_ImplicitPrelude
81 all_imports = mk_prel_imports this_mod implicit_prelude ++ imports
82 (source, ordinary) = partition is_source_import all_imports
83 is_source_import (L _ (ImportDecl _ is_boot _ _ _)) = is_boot
85 get_imports = importsFromImportDecl this_mod
87 ; stuff1 <- mappM get_imports ordinary
88 ; stuff2 <- mappM get_imports source
92 (imp_gbl_envs, imp_avails) = unzip (stuff1 ++ stuff2)
93 gbl_env :: GlobalRdrEnv
94 gbl_env = foldr plusGlobalRdrEnv emptyGlobalRdrEnv imp_gbl_envs
96 all_avails :: ImportAvails
97 all_avails = foldr plusImportAvails emptyImportAvails imp_avails
100 ; return (gbl_env, all_avails) }
102 -- NB: opt_NoImplicitPrelude is slightly different to import Prelude ();
103 -- because the former doesn't even look at Prelude.hi for instance
104 -- declarations, whereas the latter does.
105 mk_prel_imports this_mod implicit_prelude
106 | this_mod == pRELUDE
107 || explicit_prelude_import
108 || not implicit_prelude
111 | otherwise = [preludeImportDecl]
113 explicit_prelude_import
114 = notNull [ () | L _ (ImportDecl mod _ _ _ _) <- imports,
115 unLoc mod == pRELUDE ]
119 ImportDecl (L loc pRELUDE)
120 False {- Not a boot interface -}
121 False {- Not qualified -}
122 Nothing {- No "as" -}
123 Nothing {- No import list -}
125 loc = mkGeneralSrcSpan FSLIT("Implicit import declaration")
129 importsFromImportDecl :: Module
130 -> LImportDecl RdrName
131 -> RnM (GlobalRdrEnv, ImportAvails)
133 importsFromImportDecl this_mod
134 (L loc (ImportDecl loc_imp_mod_name want_boot qual_only as_mod imp_details))
138 -- If there's an error in loadInterface, (e.g. interface
139 -- file not found) we get lots of spurious errors from 'filterImports'
141 imp_mod_name = unLoc loc_imp_mod_name
142 doc = ppr imp_mod_name <+> ptext SLIT("is directly imported")
144 loadSrcInterface doc imp_mod_name want_boot `thenM` \ iface ->
146 -- Compiler sanity check: if the import didn't say
147 -- {-# SOURCE #-} we should not get a hi-boot file
148 WARN( not want_boot && mi_boot iface, ppr imp_mod_name )
150 -- Issue a user warning for a redundant {- SOURCE -} import
151 -- NB that we arrange to read all the ordinary imports before
152 -- any of the {- SOURCE -} imports
153 warnIf (want_boot && not (mi_boot iface))
154 (warnRedundantSourceImport imp_mod_name) `thenM_`
157 imp_mod = mi_module iface
158 deprecs = mi_deprecs iface
159 is_orph = mi_orphan iface
162 filtered_exports = filter not_this_mod (mi_exports iface)
163 not_this_mod (mod,_) = mod /= this_mod
164 -- If the module exports anything defined in this module, just ignore it.
165 -- Reason: otherwise it looks as if there are two local definition sites
166 -- for the thing, and an error gets reported. Easiest thing is just to
167 -- filter them out up front. This situation only arises if a module
168 -- imports itself, or another module that imported it. (Necessarily,
169 -- this invoves a loop.)
171 -- Tiresome consequence: if you say
176 -- module B( AType ) where
177 -- import {-# SOURCE #-} A( AType )
179 -- then you'll get a 'B does not export AType' message. Oh well.
181 qual_mod_name = case as_mod of
182 Nothing -> imp_mod_name
183 Just another_name -> another_name
184 imp_spec = ImportSpec { is_mod = imp_mod_name, is_qual = qual_only,
185 is_loc = loc, is_as = qual_mod_name, is_explicit = False }
187 -- Get the total imports, and filter them according to the import list
188 ifaceExportNames filtered_exports `thenM` \ total_avails ->
189 filterImports iface imp_spec
190 imp_details total_avails `thenM` \ (avail_env, gbl_env) ->
192 getDOpts `thenM` \ dflags ->
195 -- Compute new transitive dependencies
197 orphans | is_orph = ASSERT( not (imp_mod_name `elem` dep_orphs deps) )
198 imp_mod_name : dep_orphs deps
199 | otherwise = dep_orphs deps
201 (dependent_mods, dependent_pkgs)
202 = case mi_package iface of
204 -- Imported module is from the home package
205 -- Take its dependent modules and add imp_mod itself
206 -- Take its dependent packages unchanged
208 -- NB: (dep_mods deps) might include a hi-boot file
209 -- for the module being compiled, CM. Do *not* filter
210 -- this out (as we used to), because when we've
211 -- finished dealing with the direct imports we want to
212 -- know if any of them depended on CM.hi-boot, in
213 -- which case we should do the hi-boot consistency
214 -- check. See LoadIface.loadHiBootInterface
215 ((imp_mod_name, want_boot) : dep_mods deps, dep_pkgs deps)
218 -- Imported module is from another package
219 -- Dump the dependent modules
220 -- Add the package imp_mod comes from to the dependent packages
221 ASSERT2( not (pkg `elem` dep_pkgs deps), ppr pkg <+> ppr (dep_pkgs deps) )
222 ([], pkg : dep_pkgs deps)
224 import_all = case imp_details of
225 Just (is_hiding, ls) -- Imports are spec'd explicitly
226 | not is_hiding -> Just (not (null ls))
227 _ -> Nothing -- Everything is imported,
228 -- (or almost everything [hiding])
230 -- unqual_avails is the Avails that are visible in *unqualified* form
231 -- We need to know this so we know what to export when we see
232 -- module M ( module P ) where ...
233 -- Then we must export whatever came from P unqualified.
234 imports = ImportAvails {
235 imp_env = unitModuleEnv qual_mod_name avail_env,
236 imp_mods = unitModuleEnv imp_mod (imp_mod, import_all, loc),
238 imp_dep_mods = mkModDeps dependent_mods,
239 imp_dep_pkgs = dependent_pkgs }
242 -- Complain if we import a deprecated module
243 ifOptM Opt_WarnDeprecations (
245 DeprecAll txt -> addWarn (moduleDeprec imp_mod_name txt)
249 returnM (gbl_env, imports)
251 warnRedundantSourceImport mod_name
252 = ptext SLIT("Unnecessary {- SOURCE -} in the import of module")
253 <+> quotes (ppr mod_name)
257 %************************************************************************
259 importsFromLocalDecls
261 %************************************************************************
263 From the top-level declarations of this module produce
264 * the lexical environment
266 created by its bindings.
268 Complain about duplicate bindings
271 importsFromLocalDecls :: HsGroup RdrName -> RnM TcGblEnv
272 importsFromLocalDecls group
273 = do { gbl_env <- getGblEnv
275 ; names <- getLocalDeclBinders gbl_env group
277 ; implicit_prelude <- doptM Opt_ImplicitPrelude
279 -- Optimisation: filter out names for built-in syntax
280 -- They just clutter up the environment (esp tuples), and the parser
281 -- will generate Exact RdrNames for them, so the cluttered
282 -- envt is no use. To avoid doing this filter all the time,
283 -- we use -fno-implicit-prelude as a clue that the filter is
284 -- worth while. Really, it's only useful for GHC.Base and GHC.Tuple.
286 -- It's worth doing because it makes the environment smaller for
287 -- every module that imports the Prelude
289 -- Note: don't filter the gbl_env (hence all_names, not filered_all_names
290 -- in defn of gres above). Stupid reason: when parsing
291 -- data type decls, the constructors start as Exact tycon-names,
292 -- and then get turned into data con names by zapping the name space;
293 -- but that stops them being Exact, so they get looked up.
294 -- Ditto in fixity decls; e.g. infix 5 :
295 -- Sigh. It doesn't matter because it only affects the Data.Tuple really.
296 -- The important thing is to trim down the exports.
298 | implicit_prelude = names
299 | otherwise = filter (not . isBuiltInSyntax) names ;
301 ; this_mod = tcg_mod gbl_env
302 ; imports = emptyImportAvails {
303 imp_env = unitModuleEnv this_mod $
304 mkNameSet filtered_names
308 ; rdr_env' <- extendRdrEnvRn this_mod (tcg_rdr_env gbl_env) names
310 ; returnM (gbl_env { tcg_rdr_env = rdr_env',
311 tcg_imports = imports `plusImportAvails` tcg_imports gbl_env })
314 extendRdrEnvRn :: Module -> GlobalRdrEnv -> [Name] -> RnM GlobalRdrEnv
315 -- Add the new locally-bound names one by one, checking for duplicates as
316 -- we do so. Remember that in Template Haskell the duplicates
317 -- might *already be* in the GlobalRdrEnv from higher up the module
318 extendRdrEnvRn mod rdr_env names
319 = foldlM add_local rdr_env names
321 add_local rdr_env name
322 | gres <- lookupGlobalRdrEnv rdr_env (nameOccName name)
323 , (dup_gre:_) <- filter isLocalGRE gres -- Check for existing *local* defns
324 = do { addDupDeclErr (gre_name dup_gre) name
327 = return (extendGlobalRdrEnv rdr_env new_gre)
329 new_gre = GRE {gre_name = name, gre_prov = prov}
334 @getLocalDeclBinders@ returns the names for an @HsDecl@. It's
335 used for source code.
337 *** See "THE NAMING STORY" in HsDecls ****
340 getLocalDeclBinders :: TcGblEnv -> HsGroup RdrName -> RnM [Name]
341 getLocalDeclBinders gbl_env (HsGroup {hs_valds = val_decls,
342 hs_tyclds = tycl_decls,
343 hs_fords = foreign_decls })
344 = do { tc_names_s <- mappM new_tc tycl_decls
345 ; val_names <- mappM new_simple val_bndrs
346 ; return (foldr (++) val_names tc_names_s) }
348 mod = tcg_mod gbl_env
349 is_hs_boot = isHsBoot (tcg_src gbl_env) ;
350 val_bndrs | is_hs_boot = sig_hs_bndrs
351 | otherwise = for_hs_bndrs ++ val_hs_bndrs
352 -- In a hs-boot file, the value binders come from the
353 -- *signatures*, and there should be no foreign binders
355 new_simple rdr_name = newTopSrcBinder mod Nothing rdr_name
357 sig_hs_bndrs = [nm | HsBindGroup _ lsigs _ <- val_decls,
358 L _ (Sig nm _) <- lsigs]
359 val_hs_bndrs = collectGroupBinders val_decls
360 for_hs_bndrs = [nm | L _ (ForeignImport nm _ _ _) <- foreign_decls]
363 = do { main_name <- newTopSrcBinder mod Nothing main_rdr
364 ; sub_names <- mappM (newTopSrcBinder mod (Just main_name)) sub_rdrs
365 ; return (main_name : sub_names) }
367 (main_rdr : sub_rdrs) = tyClDeclNames (unLoc tc_decl)
371 %************************************************************************
373 \subsection{Filtering imports}
375 %************************************************************************
377 @filterImports@ takes the @ExportEnv@ telling what the imported module makes
378 available, and filters it through the import spec (if any).
381 filterImports :: ModIface
382 -> ImportSpec -- The span for the entire import decl
383 -> Maybe (Bool, [Located (IE RdrName)]) -- Import spec; True => hiding
384 -> NameSet -- What's available
385 -> RnM (NameSet, -- What's imported (qualified or unqualified)
386 GlobalRdrEnv) -- Same again, but in GRE form
388 -- Complains if import spec mentions things that the module doesn't export
389 -- Warns/informs if import spec contains duplicates.
391 mkGenericRdrEnv imp_spec names
392 = mkGlobalRdrEnv [ GRE { gre_name = name, gre_prov = Imported [imp_spec] }
393 | name <- nameSetToList names ]
395 filterImports iface imp_spec Nothing all_names
396 = returnM (all_names, mkGenericRdrEnv imp_spec all_names)
398 filterImports iface imp_spec (Just (want_hiding, import_items)) all_names
399 = mappM (addLocM get_item) import_items `thenM` \ gres_s ->
402 specified_names = mkNameSet (map gre_name gres)
404 if not want_hiding then
405 return (specified_names, mkGlobalRdrEnv gres)
408 keep n = not (n `elemNameSet` specified_names)
409 pruned_avails = filterNameSet keep all_names
411 return (pruned_avails, mkGenericRdrEnv imp_spec pruned_avails)
414 occ_env :: OccEnv Name -- Maps OccName to corresponding Name
415 occ_env = mkOccEnv [(nameOccName n, n) | n <- nameSetToList all_names]
416 -- This env will have entries for data constructors too,
417 -- they won't make any difference because naked entities like T
418 -- in an import list map to TcOccs, not VarOccs.
420 sub_env :: NameEnv [Name]
421 sub_env = mkSubNameEnv all_names
423 bale_out item = addErr (badImportItemErr iface imp_spec item) `thenM_`
426 succeed_with :: Bool -> [Name] -> RnM [GlobalRdrElt]
427 succeed_with all_explicit names
428 = do { loc <- getSrcSpanM
429 ; returnM (map (mk_gre loc) names) }
431 mk_gre loc name = GRE { gre_name = name,
432 gre_prov = Imported [imp_spec'] }
434 imp_spec' = imp_spec { is_loc = loc, is_explicit = explicit }
435 explicit = all_explicit || isNothing (nameParent_maybe name)
437 get_item :: IE RdrName -> RnM [GlobalRdrElt]
438 -- Empty result for a bad item.
439 -- Singleton result is typical case.
440 -- Can have two when we are hiding, and mention C which might be
441 -- both a class and a data constructor.
442 get_item item@(IEModuleContents _)
445 get_item item@(IEThingAll tc)
446 = case check_item item of
449 [n] -> -- This occurs when you import T(..), but
450 -- only export T abstractly. The single [n]
451 -- in the AvailTC is the type or class itself
452 ifOptM Opt_WarnDodgyImports (addWarn (dodgyImportWarn tc)) `thenM_`
453 succeed_with False [n]
455 names -> succeed_with False names
457 get_item item@(IEThingAbs n)
458 | want_hiding -- hiding( C )
459 -- Here the 'C' can be a data constructor
460 -- *or* a type/class, or even both
461 = case concat [check_item item, check_item (IEVar data_n)] of
463 names -> succeed_with True names
465 data_n = setRdrNameSpace n srcDataName
468 = case check_item item of
470 names -> succeed_with True names
472 check_item :: IE RdrName -> [Name]
474 = case lookupOccEnv occ_env (rdrNameOcc (ieName item)) of
476 Just name -> filterAvail item name sub_env
480 %************************************************************************
482 \subsection{Export list processing}
484 %************************************************************************
486 Processing the export list.
488 You might think that we should record things that appear in the export
489 list as ``occurrences'' (using @addOccurrenceName@), but you'd be
490 wrong. We do check (here) that they are in scope, but there is no
491 need to slurp in their actual declaration (which is what
492 @addOccurrenceName@ forces).
494 Indeed, doing so would big trouble when compiling @PrelBase@, because
495 it re-exports @GHC@, which includes @takeMVar#@, whose type includes
496 @ConcBase.StateAndSynchVar#@, and so on...
499 type ExportAccum -- The type of the accumulating parameter of
500 -- the main worker function in exportsFromAvail
501 = ([Module], -- 'module M's seen so far
502 ExportOccMap, -- Tracks exported occurrence names
503 NameSet) -- The accumulated exported stuff
504 emptyExportAccum = ([], emptyOccEnv, emptyNameSet)
506 type ExportOccMap = OccEnv (Name, IE RdrName)
507 -- Tracks what a particular exported OccName
508 -- in an export list refers to, and which item
509 -- it came from. It's illegal to export two distinct things
510 -- that have the same occurrence name
513 exportsFromAvail :: Bool -- False => no 'module M(..) where' header at all
514 -> Maybe [Located (IE RdrName)] -- Nothing => no explicit export list
516 -- Complains if two distinct exports have same OccName
517 -- Warns about identical exports.
518 -- Complains about exports items not in scope
520 exportsFromAvail explicit_mod exports
521 = do { TcGblEnv { tcg_rdr_env = rdr_env,
522 tcg_imports = imports } <- getGblEnv ;
524 -- If the module header is omitted altogether, then behave
525 -- as if the user had written "module Main(main) where..."
526 -- EXCEPT in interactive mode, when we behave as if he had
527 -- written "module Main where ..."
528 -- Reason: don't want to complain about 'main' not in scope
529 -- in interactive mode
530 ghci_mode <- getGhciMode ;
532 | explicit_mod = exports
533 | ghci_mode == Interactive = Nothing
534 | otherwise = Just [noLoc (IEVar main_RDR_Unqual)] } ;
535 exports_from_avail real_exports rdr_env imports }
538 exports_from_avail Nothing rdr_env imports
539 = -- Export all locally-defined things
540 -- We do this by filtering the global RdrEnv,
541 -- keeping only things that are locally-defined
542 return (mkNameSet [ gre_name gre
543 | gre <- globalRdrEnvElts rdr_env,
546 exports_from_avail (Just items) rdr_env (ImportAvails { imp_env = imp_env })
547 = foldlM do_litem emptyExportAccum items `thenM` \ (_, _, exports) ->
550 sub_env :: NameEnv [Name] -- Classify each name by its parent
551 sub_env = mkSubNameEnv (foldModuleEnv unionNameSets emptyNameSet imp_env)
553 do_litem :: ExportAccum -> Located (IE RdrName) -> RnM ExportAccum
554 do_litem acc = addLocM (exports_from_item acc)
556 exports_from_item :: ExportAccum -> IE RdrName -> RnM ExportAccum
557 exports_from_item acc@(mods, occs, exports) ie@(IEModuleContents mod)
558 | mod `elem` mods -- Duplicate export of M
559 = do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
560 warnIf warn_dup_exports (dupModuleExport mod) ;
564 = case lookupModuleEnv imp_env mod of
565 Nothing -> addErr (modExportErr mod) `thenM_`
569 new_exports = filterNameSet (inScopeUnqual rdr_env) names
572 -- This check_occs not only finds conflicts between this item
573 -- and others, but also internally within this item. That is,
574 -- if 'M.x' is in scope in several ways, we'll have several
575 -- members of mod_avails with the same OccName.
576 check_occs ie occs (nameSetToList new_exports) `thenM` \ occs' ->
577 returnM (mod:mods, occs', exports `unionNameSets` new_exports)
579 exports_from_item acc@(mods, occs, exports) ie
580 = lookupGlobalOccRn (ieName ie) `thenM` \ name ->
581 if isUnboundName name then
582 returnM acc -- Avoid error cascade
584 new_exports = filterAvail ie name sub_env
586 checkErr (not (null new_exports)) (exportItemErr ie) `thenM_`
587 checkForDodgyExport ie new_exports `thenM_`
588 check_occs ie occs new_exports `thenM` \ occs' ->
589 returnM (mods, occs', addListToNameSet exports new_exports)
591 -------------------------------
592 filterAvail :: IE RdrName -- Wanted
593 -> Name -- The Name of the ieName of the item
594 -> NameEnv [Name] -- Maps type/class names to their sub-names
595 -> [Name] -- Empty if even one thing reqd is missing
597 filterAvail (IEVar _) n subs = [n]
598 filterAvail (IEThingAbs _) n subs = [n]
599 filterAvail (IEThingAll _) n subs = n : subNames subs n
600 filterAvail (IEThingWith _ rdrs) n subs
601 | any isNothing mb_names = []
602 | otherwise = n : catMaybes mb_names
604 env = mkOccEnv [(nameOccName s, s) | s <- subNames subs n]
605 mb_names = map (lookupOccEnv env . rdrNameOcc) rdrs
606 filterAvail (IEModuleContents _) _ _ = panic "filterAvail"
608 subNames :: NameEnv [Name] -> Name -> [Name]
609 subNames env n = lookupNameEnv env n `orElse` []
611 mkSubNameEnv :: NameSet -> NameEnv [Name]
612 -- Maps types and classes to their constructors/classops respectively
613 -- This mapping just makes it easier to deal with A(..) export items
615 = foldNameSet add_name emptyNameEnv names
618 | Just parent <- nameParent_maybe name
619 = extendNameEnv_C (\ns _ -> name:ns) env parent [name]
622 -------------------------------
623 inScopeUnqual :: GlobalRdrEnv -> Name -> Bool
624 -- Checks whether the Name is in scope unqualified,
625 -- regardless of whether it's ambiguous or not
626 inScopeUnqual env n = any unQualOK (lookupGRE_Name env n)
628 -------------------------------
629 checkForDodgyExport :: IE RdrName -> [Name] -> RnM ()
630 checkForDodgyExport ie@(IEThingAll tc) [n]
631 | isTcOcc (nameOccName n) = addWarn (dodgyExportWarn tc)
632 -- This occurs when you export T(..), but
633 -- only import T abstractly, or T is a synonym.
634 -- The single [n] is the type or class itself
635 | otherwise = addErr (exportItemErr ie)
636 -- This happes if you export x(..), which is bogus
637 checkForDodgyExport _ _ = return ()
639 -------------------------------
640 check_occs :: IE RdrName -> ExportOccMap -> [Name] -> RnM ExportOccMap
641 check_occs ie occs names
642 = foldlM check occs names
645 = case lookupOccEnv occs name_occ of
646 Nothing -> returnM (extendOccEnv occs name_occ (name, ie))
649 | name == name' -- Duplicate export
650 -> do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
651 warnIf warn_dup_exports (dupExportWarn name_occ ie ie') ;
654 | otherwise -- Same occ name but different names: an error
655 -> do { global_env <- getGlobalRdrEnv ;
656 addErr (exportClashErr global_env name name' ie ie') ;
659 name_occ = nameOccName name
662 %*********************************************************
666 %*********************************************************
669 reportDeprecations :: TcGblEnv -> RnM ()
670 reportDeprecations tcg_env
671 = ifOptM Opt_WarnDeprecations $
672 do { (eps,hpt) <- getEpsAndHpt
673 ; mapM_ (check hpt (eps_PIT eps)) all_gres }
675 used_names = findUses (tcg_dus tcg_env) emptyNameSet
676 all_gres = globalRdrEnvElts (tcg_rdr_env tcg_env)
678 check hpt pit (GRE {gre_name = name, gre_prov = Imported (imp_spec:_)})
679 | name `elemNameSet` used_names
680 , Just deprec_txt <- lookupDeprec hpt pit name
681 = setSrcSpan (is_loc imp_spec) $
682 addWarn (sep [ptext SLIT("Deprecated use of") <+>
683 occNameFlavour (nameOccName name) <+>
688 name_mod = nameModule name
689 imp_mod = is_mod imp_spec
690 imp_msg = ptext SLIT("imported from") <+> ppr imp_mod <> extra
691 extra | imp_mod == name_mod = empty
692 | otherwise = ptext SLIT(", but defined in") <+> ppr name_mod
694 check hpt pit ok_gre = returnM () -- Local, or not used, or not deprectated
695 -- The Imported pattern-match: don't deprecate locally defined names
696 -- For a start, we may be exporting a deprecated thing
697 -- Also we may use a deprecated thing in the defn of another
698 -- deprecated things. We may even use a deprecated thing in
699 -- the defn of a non-deprecated thing, when changing a module's
702 lookupDeprec :: HomePackageTable -> PackageIfaceTable
703 -> Name -> Maybe DeprecTxt
704 lookupDeprec hpt pit n
705 = case lookupIface hpt pit (nameModule n) of
706 Just iface -> mi_dep_fn iface n `seqMaybe` -- Bleat if the thing, *or
707 mi_dep_fn iface (nameParent n) -- its parent*, is deprec'd
709 | isWiredInName n -> Nothing
710 -- We have not necessarily loaded the .hi file for a
711 -- wired-in name (yet), although we *could*.
712 -- And we never deprecate them
714 | otherwise -> pprPanic "lookupDeprec" (ppr n)
715 -- By now all the interfaces should have been loaded
717 gre_is_used :: NameSet -> GlobalRdrElt -> Bool
718 gre_is_used used_names gre = gre_name gre `elemNameSet` used_names
721 %*********************************************************
725 %*********************************************************
728 reportUnusedNames :: Maybe [Located (IE RdrName)] -- Export list
729 -> TcGblEnv -> RnM ()
730 reportUnusedNames export_decls gbl_env
731 = do { warnUnusedTopBinds unused_locals
732 ; warnUnusedModules unused_imp_mods
733 ; warnUnusedImports unused_imports
734 ; warnDuplicateImports defined_and_used
735 ; printMinimalImports minimal_imports }
737 used_names, all_used_names :: NameSet
738 used_names = findUses (tcg_dus gbl_env) emptyNameSet
739 all_used_names = used_names `unionNameSets`
740 mkNameSet (mapCatMaybes nameParent_maybe (nameSetToList used_names))
741 -- A use of C implies a use of T,
742 -- if C was brought into scope by T(..) or T(C)
744 -- Collect the defined names from the in-scope environment
745 defined_names :: [GlobalRdrElt]
746 defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)
748 -- Note that defined_and_used, defined_but_not_used
749 -- are both [GRE]; that's why we need defined_and_used
750 -- rather than just all_used_names
751 defined_and_used, defined_but_not_used :: [GlobalRdrElt]
752 (defined_and_used, defined_but_not_used)
753 = partition (gre_is_used all_used_names) defined_names
755 -- Filter out the ones that are
756 -- (a) defined in this module, and
757 -- (b) not defined by a 'deriving' clause
758 -- The latter have an Internal Name, so we can filter them out easily
759 unused_locals :: [GlobalRdrElt]
760 unused_locals = filter is_unused_local defined_but_not_used
761 is_unused_local :: GlobalRdrElt -> Bool
762 is_unused_local gre = isLocalGRE gre && isExternalName (gre_name gre)
764 unused_imports :: [GlobalRdrElt]
765 unused_imports = filter unused_imp defined_but_not_used
766 unused_imp (GRE {gre_prov = Imported imp_specs})
767 = not (all (module_unused . is_mod) imp_specs)
768 && any is_explicit imp_specs
769 -- Don't complain about unused imports if we've already said the
770 -- entire import is unused
771 unused_imp other = False
773 -- To figure out the minimal set of imports, start with the things
774 -- that are in scope (i.e. in gbl_env). Then just combine them
775 -- into a bunch of avails, so they are properly grouped
777 -- BUG WARNING: this does not deal properly with qualified imports!
778 minimal_imports :: FiniteMap Module AvailEnv
779 minimal_imports0 = foldr add_expall emptyFM expall_mods
780 minimal_imports1 = foldr add_name minimal_imports0 defined_and_used
781 minimal_imports = foldr add_inst_mod minimal_imports1 direct_import_mods
782 -- The last line makes sure that we retain all direct imports
783 -- even if we import nothing explicitly.
784 -- It's not necessarily redundant to import such modules. Consider
788 -- The import M() is not *necessarily* redundant, even if
789 -- we suck in no instance decls from M (e.g. it contains
790 -- no instance decls, or This contains no code). It may be
791 -- that we import M solely to ensure that M's orphan instance
792 -- decls (or those in its imports) are visible to people who
793 -- import This. Sigh.
794 -- There's really no good way to detect this, so the error message
795 -- in RnEnv.warnUnusedModules is weakened instead
797 -- We've carefully preserved the provenance so that we can
798 -- construct minimal imports that import the name by (one of)
799 -- the same route(s) as the programmer originally did.
800 add_name (GRE {gre_name = n, gre_prov = Imported imp_specs}) acc
801 = addToFM_C plusAvailEnv acc (is_mod (head imp_specs))
802 (unitAvailEnv (mk_avail n (nameParent_maybe n)))
806 -- Modules mentioned as 'module M' in the export list
807 expall_mods = case export_decls of
809 Just es -> [m | L _ (IEModuleContents m) <- es]
811 -- This is really bogus. The idea is that if we see 'module M' in
812 -- the export list we must retain the import decls that drive it
813 -- If we aren't careful we might see
814 -- module A( module M ) where
817 -- and suppose that N exports everything that M does. Then we
818 -- must not drop the import of M even though N brings it all into
821 -- BUG WARNING: 'module M' exports aside, what if M.x is mentioned?!
823 -- The reason that add_expall is bogus is that it doesn't take
824 -- qualified imports into account. But it's an improvement.
825 add_expall mod acc = addToFM_C plusAvailEnv acc mod emptyAvailEnv
827 -- n is the name of the thing, p is the name of its parent
828 mk_avail n (Just p) = AvailTC p [p,n]
829 mk_avail n Nothing | isTcOcc (nameOccName n) = AvailTC n [n]
830 | otherwise = Avail n
832 add_inst_mod (mod,_,_) acc
833 | mod `elemFM` acc = acc -- We import something already
834 | otherwise = addToFM acc mod emptyAvailEnv
836 -- Add an empty collection of imports for a module
837 -- from which we have sucked only instance decls
839 imports = tcg_imports gbl_env
841 direct_import_mods :: [(Module, Maybe Bool, SrcSpan)]
842 -- See the type of the imp_mods for this triple
843 direct_import_mods = moduleEnvElts (imp_mods imports)
845 -- unused_imp_mods are the directly-imported modules
846 -- that are not mentioned in minimal_imports1
847 -- [Note: not 'minimal_imports', because that includes directly-imported
848 -- modules even if we use nothing from them; see notes above]
850 -- BUG WARNING: does not deal correctly with multiple imports of the same module
851 -- becuase direct_import_mods has only one entry per module
852 unused_imp_mods = [(mod,loc) | (mod,imp,loc) <- direct_import_mods,
853 not (mod `elemFM` minimal_imports1),
856 -- The Just False part is not to complain about
857 -- import M (), which is an idiom for importing
858 -- instance declarations
860 module_unused :: Module -> Bool
861 module_unused mod = any (((==) mod) . fst) unused_imp_mods
863 ---------------------
864 warnDuplicateImports :: [GlobalRdrElt] -> RnM ()
865 -- Given the GREs for names that are used, figure out which imports
866 -- could be omitted without changing the top-level environment.
868 -- NB: Given import Foo( T )
869 -- import qualified Foo
870 -- we do not report a duplicate import, even though Foo.T is brought
871 -- into scope by both, because there's nothing you can *omit* without
872 -- changing the top-level environment. So we complain only if it's
873 -- explicitly named in both imports or neither.
875 -- Furthermore, we complain about Foo.T only if
876 -- there is no complaint about (unqualified) T
878 warnDuplicateImports gres
879 = ifOptM Opt_WarnUnusedImports $
880 sequenceM_ [ warn name (head dup_imps)
881 -- The 'head' picks the first offending group
882 -- for this particular name
883 | GRE { gre_name = name, gre_prov = Imported imps } <- gres
884 , let dup_imps = dups imps
885 , not (null dup_imps) ]
888 = panic "warnDuplicateImports" -- equivClasses never returns empty lists
889 warn name dup_imps@(imp1:_)
890 = addWarnAt (is_loc imp1)
891 ((quotes pp_name <+> ptext SLIT("is imported more than once:"))
892 $$ nest 2 (vcat (map ppr dup_imps)))
894 pp_name | is_qual imp1 = ppr (is_as imp1) <> dot <> ppr occ
895 | otherwise = ppr occ
896 occ = nameOccName name
898 dups :: [ImportSpec] -> [[ImportSpec]]
899 dups [imp] = [] -- Very common case
900 dups imps = filter (not . isSingleton) (unqual_dups ++ qual_dups)
902 unqual_dups = equivClasses cmp_unqual (filter (not . is_qual) imps)
903 qual_dups = equivClasses cmp_qual imps
905 cmp_unqual imp1 imp2 -- Make explicit come first
906 = not (is_explicit imp1) `compare` not (is_explicit imp2)
908 cmp_qual imp1 imp2 -- Group by explicit-ness, then by module qualifier
909 = (imp1 `cmp_unqual` imp2) `thenCmp`
910 (is_as imp1 `compare` is_as imp2)
912 -- ToDo: deal with original imports with 'qualified' and 'as M' clauses
913 printMinimalImports :: FiniteMap Module AvailEnv -- Minimal imports
915 printMinimalImports imps
916 = ifOptM Opt_D_dump_minimal_imports $ do {
918 mod_ies <- mappM to_ies (fmToList imps) ;
919 this_mod <- getModule ;
920 rdr_env <- getGlobalRdrEnv ;
921 ioToTcRn (do { h <- openFile (mkFilename this_mod) WriteMode ;
922 printForUser h (unQualInScope rdr_env)
923 (vcat (map ppr_mod_ie mod_ies)) })
926 mkFilename this_mod = moduleUserString this_mod ++ ".imports"
927 ppr_mod_ie (mod_name, ies)
928 | mod_name == pRELUDE
930 | null ies -- Nothing except instances comes from here
931 = ptext SLIT("import") <+> ppr mod_name <> ptext SLIT("() -- Instances only")
933 = ptext SLIT("import") <+> ppr mod_name <>
934 parens (fsep (punctuate comma (map ppr ies)))
936 to_ies (mod, avail_env) = mappM to_ie (availEnvElts avail_env) `thenM` \ ies ->
939 to_ie :: AvailInfo -> RnM (IE Name)
940 -- The main trick here is that if we're importing all the constructors
941 -- we want to say "T(..)", but if we're importing only a subset we want
942 -- to say "T(A,B,C)". So we have to find out what the module exports.
943 to_ie (Avail n) = returnM (IEVar n)
944 to_ie (AvailTC n [m]) = ASSERT( n==m )
945 returnM (IEThingAbs n)
947 = loadSrcInterface doc n_mod False `thenM` \ iface ->
948 case [xs | (m,as) <- mi_exports iface,
951 x == nameOccName n] of
952 [xs] | all_used xs -> returnM (IEThingAll n)
953 | otherwise -> returnM (IEThingWith n (filter (/= n) ns))
954 other -> pprTrace "to_ie" (ppr n <+> ppr n_mod <+> ppr other) $
957 all_used avail_occs = all (`elem` map nameOccName ns) avail_occs
958 doc = text "Compute minimal imports from" <+> ppr n
963 %************************************************************************
967 %************************************************************************
970 badImportItemErr iface imp_spec ie
971 = sep [ptext SLIT("Module"), quotes (ppr (is_mod imp_spec)), source_import,
972 ptext SLIT("does not export"), quotes (ppr ie)]
974 source_import | mi_boot iface = ptext SLIT("(hi-boot interface)")
977 dodgyImportWarn item = dodgyMsg (ptext SLIT("import")) item
978 dodgyExportWarn item = dodgyMsg (ptext SLIT("export")) item
981 = sep [ ptext SLIT("The") <+> kind <+> ptext SLIT("item") <+> quotes (ppr (IEThingAll tc)),
982 ptext SLIT("suggests that") <+> quotes (ppr tc) <+> ptext SLIT("has constructor or class methods"),
983 ptext SLIT("but it has none; it is a type synonym or abstract type or class") ]
986 = hsep [ ptext SLIT("Unknown module in export list: module"), quotes (ppr mod)]
988 exportItemErr export_item
989 = sep [ ptext SLIT("The export item") <+> quotes (ppr export_item),
990 ptext SLIT("attempts to export constructors or class methods that are not visible here") ]
992 exportClashErr global_env name1 name2 ie1 ie2
993 = vcat [ ptext SLIT("Conflicting exports for") <+> quotes (ppr occ) <> colon
994 , ppr_export ie1 name1
995 , ppr_export ie2 name2 ]
997 occ = nameOccName name1
998 ppr_export ie name = nest 2 (quotes (ppr ie) <+> ptext SLIT("exports") <+>
999 quotes (ppr name) <+> pprNameProvenance (get_gre name))
1001 -- get_gre finds a GRE for the Name, so that we can show its provenance
1003 = case lookupGRE_Name global_env name of
1005 [] -> pprPanic "exportClashErr" (ppr name)
1007 addDupDeclErr :: Name -> Name -> TcRn ()
1008 addDupDeclErr name1 name2
1009 = addErrAt (srcLocSpan loc2) $
1010 vcat [ptext SLIT("Multiple declarations of") <+> quotes (ppr name1),
1011 ptext SLIT("Declared at:") <+> vcat [ppr (nameSrcLoc name1), ppr loc2]]
1013 loc2 = nameSrcLoc name2
1015 dupExportWarn occ_name ie1 ie2
1016 = hsep [quotes (ppr occ_name),
1017 ptext SLIT("is exported by"), quotes (ppr ie1),
1018 ptext SLIT("and"), quotes (ppr ie2)]
1021 = hsep [ptext SLIT("Duplicate"),
1022 quotes (ptext SLIT("Module") <+> ppr mod),
1023 ptext SLIT("in export list")]
1025 moduleDeprec mod txt
1026 = sep [ ptext SLIT("Module") <+> quotes (ppr mod) <+> ptext SLIT("is deprecated:"),