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 )
57 import List ( partition )
58 import IO ( openFile, IOMode(..) )
63 %************************************************************************
67 %************************************************************************
70 rnImports :: [LImportDecl RdrName]
71 -> RnM (GlobalRdrEnv, ImportAvails)
74 = do { -- PROCESS IMPORT DECLS
75 -- Do the non {- SOURCE -} ones first, so that we get a helpful
76 -- warning for {- SOURCE -} ones that are unnecessary
78 ; implicit_prelude <- doptM Opt_ImplicitPrelude
80 all_imports = mk_prel_imports this_mod implicit_prelude ++ imports
81 (source, ordinary) = partition is_source_import all_imports
82 is_source_import (L _ (ImportDecl _ is_boot _ _ _)) = is_boot
84 get_imports = importsFromImportDecl this_mod
86 ; stuff1 <- mappM get_imports ordinary
87 ; stuff2 <- mappM get_imports source
91 (imp_gbl_envs, imp_avails) = unzip (stuff1 ++ stuff2)
92 gbl_env :: GlobalRdrEnv
93 gbl_env = foldr plusGlobalRdrEnv emptyGlobalRdrEnv imp_gbl_envs
95 all_avails :: ImportAvails
96 all_avails = foldr plusImportAvails emptyImportAvails imp_avails
99 ; return (gbl_env, all_avails) }
101 -- NB: opt_NoImplicitPrelude is slightly different to import Prelude ();
102 -- because the former doesn't even look at Prelude.hi for instance
103 -- declarations, whereas the latter does.
104 mk_prel_imports this_mod implicit_prelude
105 | this_mod == pRELUDE
106 || explicit_prelude_import
107 || not implicit_prelude
110 | otherwise = [preludeImportDecl]
112 explicit_prelude_import
113 = notNull [ () | L _ (ImportDecl mod _ _ _ _) <- imports,
114 unLoc mod == pRELUDE ]
118 ImportDecl (L loc pRELUDE)
119 False {- Not a boot interface -}
120 False {- Not qualified -}
121 Nothing {- No "as" -}
122 Nothing {- No import list -}
124 loc = mkGeneralSrcSpan FSLIT("Implicit import declaration")
128 importsFromImportDecl :: Module
129 -> LImportDecl RdrName
130 -> RnM (GlobalRdrEnv, ImportAvails)
132 importsFromImportDecl this_mod
133 (L loc (ImportDecl loc_imp_mod_name want_boot qual_only as_mod imp_details))
137 -- If there's an error in loadInterface, (e.g. interface
138 -- file not found) we get lots of spurious errors from 'filterImports'
140 imp_mod_name = unLoc loc_imp_mod_name
141 doc = ppr imp_mod_name <+> ptext SLIT("is directly imported")
143 loadSrcInterface doc imp_mod_name want_boot `thenM` \ iface ->
145 -- Compiler sanity check: if the import didn't say
146 -- {-# SOURCE #-} we should not get a hi-boot file
147 WARN( not want_boot && mi_boot iface, ppr imp_mod_name )
149 -- Issue a user warning for a redundant {- SOURCE -} import
150 -- NB that we arrange to read all the ordinary imports before
151 -- any of the {- SOURCE -} imports
152 warnIf (want_boot && not (mi_boot iface))
153 (warnRedundantSourceImport imp_mod_name) `thenM_`
156 imp_mod = mi_module iface
157 deprecs = mi_deprecs iface
158 is_orph = mi_orphan iface
161 filtered_exports = filter not_this_mod (mi_exports iface)
162 not_this_mod (mod,_) = mod /= this_mod
163 -- If the module exports anything defined in this module, just ignore it.
164 -- Reason: otherwise it looks as if there are two local definition sites
165 -- for the thing, and an error gets reported. Easiest thing is just to
166 -- filter them out up front. This situation only arises if a module
167 -- imports itself, or another module that imported it. (Necessarily,
168 -- this invoves a loop.)
170 -- Tiresome consequence: if you say
175 -- module B( AType ) where
176 -- import {-# SOURCE #-} A( AType )
178 -- then you'll get a 'B does not export AType' message. Oh well.
180 qual_mod_name = case as_mod of
181 Nothing -> imp_mod_name
182 Just another_name -> another_name
183 imp_spec = ImportSpec { is_mod = imp_mod_name, is_qual = qual_only,
184 is_loc = loc, is_as = qual_mod_name, is_explicit = False }
186 -- Get the total imports, and filter them according to the import list
187 ifaceExportNames filtered_exports `thenM` \ total_avails ->
188 filterImports iface imp_spec
189 imp_details total_avails `thenM` \ (avail_env, gbl_env) ->
191 getDOpts `thenM` \ dflags ->
194 -- Compute new transitive dependencies
196 orphans | is_orph = ASSERT( not (imp_mod_name `elem` dep_orphs deps) )
197 imp_mod_name : dep_orphs deps
198 | otherwise = dep_orphs deps
200 (dependent_mods, dependent_pkgs)
201 = case mi_package iface of
203 -- Imported module is from the home package
204 -- Take its dependent modules and add imp_mod itself
205 -- Take its dependent packages unchanged
207 -- NB: (dep_mods deps) might include a hi-boot file
208 -- for the module being compiled, CM. Do *not* filter
209 -- this out (as we used to), because when we've
210 -- finished dealing with the direct imports we want to
211 -- know if any of them depended on CM.hi-boot, in
212 -- which case we should do the hi-boot consistency
213 -- check. See LoadIface.loadHiBootInterface
214 ((imp_mod_name, want_boot) : dep_mods deps, dep_pkgs deps)
217 -- Imported module is from another package
218 -- Dump the dependent modules
219 -- Add the package imp_mod comes from to the dependent packages
220 ASSERT2( not (pkg `elem` dep_pkgs deps), ppr pkg <+> ppr (dep_pkgs deps) )
221 ([], pkg : dep_pkgs deps)
223 import_all = case imp_details of
224 Just (is_hiding, ls) -- Imports are spec'd explicitly
225 | not is_hiding -> Just (not (null ls))
226 _ -> Nothing -- Everything is imported,
227 -- (or almost everything [hiding])
229 -- unqual_avails is the Avails that are visible in *unqualified* form
230 -- We need to know this so we know what to export when we see
231 -- module M ( module P ) where ...
232 -- Then we must export whatever came from P unqualified.
233 imports = ImportAvails {
234 imp_env = unitModuleEnv qual_mod_name avail_env,
235 imp_mods = unitModuleEnv imp_mod (imp_mod, import_all, loc),
237 imp_dep_mods = mkModDeps dependent_mods,
238 imp_dep_pkgs = dependent_pkgs }
241 -- Complain if we import a deprecated module
242 ifOptM Opt_WarnDeprecations (
244 DeprecAll txt -> addWarn (moduleDeprec imp_mod_name txt)
248 returnM (gbl_env, imports)
250 warnRedundantSourceImport mod_name
251 = ptext SLIT("Unnecessary {- SOURCE -} in the import of module")
252 <+> quotes (ppr mod_name)
256 %************************************************************************
258 importsFromLocalDecls
260 %************************************************************************
262 From the top-level declarations of this module produce
263 * the lexical environment
265 created by its bindings.
267 Complain about duplicate bindings
270 importsFromLocalDecls :: HsGroup RdrName -> RnM TcGblEnv
271 importsFromLocalDecls group
272 = do { gbl_env <- getGblEnv
274 ; names <- getLocalDeclBinders gbl_env group
276 ; implicit_prelude <- doptM Opt_ImplicitPrelude
278 -- Optimisation: filter out names for built-in syntax
279 -- They just clutter up the environment (esp tuples), and the parser
280 -- will generate Exact RdrNames for them, so the cluttered
281 -- envt is no use. To avoid doing this filter all the time,
282 -- we use -fno-implicit-prelude as a clue that the filter is
283 -- worth while. Really, it's only useful for GHC.Base and GHC.Tuple.
285 -- It's worth doing because it makes the environment smaller for
286 -- every module that imports the Prelude
288 -- Note: don't filter the gbl_env (hence all_names, not filered_all_names
289 -- in defn of gres above). Stupid reason: when parsing
290 -- data type decls, the constructors start as Exact tycon-names,
291 -- and then get turned into data con names by zapping the name space;
292 -- but that stops them being Exact, so they get looked up.
293 -- Ditto in fixity decls; e.g. infix 5 :
294 -- Sigh. It doesn't matter because it only affects the Data.Tuple really.
295 -- The important thing is to trim down the exports.
297 | implicit_prelude = names
298 | otherwise = filter (not . isBuiltInSyntax) names ;
300 ; this_mod = tcg_mod gbl_env
301 ; imports = emptyImportAvails {
302 imp_env = unitModuleEnv this_mod $
303 mkNameSet filtered_names
307 ; rdr_env' <- extendRdrEnvRn this_mod (tcg_rdr_env gbl_env) names
309 ; returnM (gbl_env { tcg_rdr_env = rdr_env',
310 tcg_imports = imports `plusImportAvails` tcg_imports gbl_env })
313 extendRdrEnvRn :: Module -> GlobalRdrEnv -> [Name] -> RnM GlobalRdrEnv
314 -- Add the new locally-bound names one by one, checking for duplicates as
315 -- we do so. Remember that in Template Haskell the duplicates
316 -- might *already be* in the GlobalRdrEnv from higher up the module
317 extendRdrEnvRn mod rdr_env names
318 = foldlM add_local rdr_env names
320 add_local rdr_env name
321 | gres <- lookupGlobalRdrEnv rdr_env (nameOccName name)
322 , (dup_gre:_) <- filter isLocalGRE gres -- Check for existing *local* defns
323 = do { addDupDeclErr (gre_name dup_gre) name
326 = return (extendGlobalRdrEnv rdr_env new_gre)
328 new_gre = GRE {gre_name = name, gre_prov = prov}
333 @getLocalDeclBinders@ returns the names for an @HsDecl@. It's
334 used for source code.
336 *** See "THE NAMING STORY" in HsDecls ****
339 getLocalDeclBinders :: TcGblEnv -> HsGroup RdrName -> RnM [Name]
340 getLocalDeclBinders gbl_env (HsGroup {hs_valds = val_decls,
341 hs_tyclds = tycl_decls,
342 hs_fords = foreign_decls })
343 = do { tc_names_s <- mappM new_tc tycl_decls
344 ; val_names <- mappM new_simple val_bndrs
345 ; return (foldr (++) val_names tc_names_s) }
347 mod = tcg_mod gbl_env
348 is_hs_boot = isHsBoot (tcg_src gbl_env) ;
349 val_bndrs | is_hs_boot = sig_hs_bndrs
350 | otherwise = for_hs_bndrs ++ val_hs_bndrs
351 -- In a hs-boot file, the value binders come from the
352 -- *signatures*, and there should be no foreign binders
354 new_simple rdr_name = newTopSrcBinder mod Nothing rdr_name
356 sig_hs_bndrs = [nm | HsBindGroup _ lsigs _ <- val_decls,
357 L _ (Sig nm _) <- lsigs]
358 val_hs_bndrs = collectGroupBinders val_decls
359 for_hs_bndrs = [nm | L _ (ForeignImport nm _ _ _) <- foreign_decls]
362 = do { main_name <- newTopSrcBinder mod Nothing main_rdr
363 ; sub_names <- mappM (newTopSrcBinder mod (Just main_name)) sub_rdrs
364 ; return (main_name : sub_names) }
366 (main_rdr : sub_rdrs) = tyClDeclNames (unLoc tc_decl)
370 %************************************************************************
372 \subsection{Filtering imports}
374 %************************************************************************
376 @filterImports@ takes the @ExportEnv@ telling what the imported module makes
377 available, and filters it through the import spec (if any).
380 filterImports :: ModIface
381 -> ImportSpec -- The span for the entire import decl
382 -> Maybe (Bool, [Located (IE RdrName)]) -- Import spec; True => hiding
383 -> NameSet -- What's available
384 -> RnM (NameSet, -- What's imported (qualified or unqualified)
385 GlobalRdrEnv) -- Same again, but in GRE form
387 -- Complains if import spec mentions things that the module doesn't export
388 -- Warns/informs if import spec contains duplicates.
390 mkGenericRdrEnv imp_spec names
391 = mkGlobalRdrEnv [ GRE { gre_name = name, gre_prov = Imported [imp_spec] }
392 | name <- nameSetToList names ]
394 filterImports iface imp_spec Nothing all_names
395 = returnM (all_names, mkGenericRdrEnv imp_spec all_names)
397 filterImports iface imp_spec (Just (want_hiding, import_items)) all_names
398 = mappM (addLocM get_item) import_items `thenM` \ gres_s ->
401 specified_names = mkNameSet (map gre_name gres)
403 if not want_hiding then
404 return (specified_names, mkGlobalRdrEnv gres)
407 keep n = not (n `elemNameSet` specified_names)
408 pruned_avails = filterNameSet keep all_names
410 return (pruned_avails, mkGenericRdrEnv imp_spec pruned_avails)
413 occ_env :: OccEnv Name -- Maps OccName to corresponding Name
414 occ_env = mkOccEnv [(nameOccName n, n) | n <- nameSetToList all_names]
415 -- This env will have entries for data constructors too,
416 -- they won't make any difference because naked entities like T
417 -- in an import list map to TcOccs, not VarOccs.
419 sub_env :: NameEnv [Name]
420 sub_env = mkSubNameEnv all_names
422 bale_out item = addErr (badImportItemErr iface imp_spec item) `thenM_`
425 succeed_with :: Bool -> [Name] -> RnM [GlobalRdrElt]
426 succeed_with all_explicit names
427 = do { loc <- getSrcSpanM
428 ; returnM (map (mk_gre loc) names) }
430 mk_gre loc name = GRE { gre_name = name,
431 gre_prov = Imported [imp_spec'] }
433 imp_spec' = imp_spec { is_loc = loc, is_explicit = explicit }
434 explicit = all_explicit || isNothing (nameParent_maybe name)
436 get_item :: IE RdrName -> RnM [GlobalRdrElt]
437 -- Empty result for a bad item.
438 -- Singleton result is typical case.
439 -- Can have two when we are hiding, and mention C which might be
440 -- both a class and a data constructor.
441 get_item item@(IEModuleContents _)
444 get_item item@(IEThingAll tc)
445 = case check_item item of
448 [n] -> -- This occurs when you import T(..), but
449 -- only export T abstractly. The single [n]
450 -- in the AvailTC is the type or class itself
451 ifOptM Opt_WarnDodgyImports (addWarn (dodgyImportWarn tc)) `thenM_`
452 succeed_with False [n]
454 names -> succeed_with False names
456 get_item item@(IEThingAbs n)
457 | want_hiding -- hiding( C )
458 -- Here the 'C' can be a data constructor
459 -- *or* a type/class, or even both
460 = case concat [check_item item, check_item (IEVar data_n)] of
462 names -> succeed_with True names
464 data_n = setRdrNameSpace n srcDataName
467 = case check_item item of
469 names -> succeed_with True names
471 check_item :: IE RdrName -> [Name]
473 = case lookupOccEnv occ_env (rdrNameOcc (ieName item)) of
475 Just name -> filterAvail item name sub_env
479 %************************************************************************
481 \subsection{Export list processing}
483 %************************************************************************
485 Processing the export list.
487 You might think that we should record things that appear in the export
488 list as ``occurrences'' (using @addOccurrenceName@), but you'd be
489 wrong. We do check (here) that they are in scope, but there is no
490 need to slurp in their actual declaration (which is what
491 @addOccurrenceName@ forces).
493 Indeed, doing so would big trouble when compiling @PrelBase@, because
494 it re-exports @GHC@, which includes @takeMVar#@, whose type includes
495 @ConcBase.StateAndSynchVar#@, and so on...
498 type ExportAccum -- The type of the accumulating parameter of
499 -- the main worker function in exportsFromAvail
500 = ([Module], -- 'module M's seen so far
501 ExportOccMap, -- Tracks exported occurrence names
502 NameSet) -- The accumulated exported stuff
503 emptyExportAccum = ([], emptyOccEnv, emptyNameSet)
505 type ExportOccMap = OccEnv (Name, IE RdrName)
506 -- Tracks what a particular exported OccName
507 -- in an export list refers to, and which item
508 -- it came from. It's illegal to export two distinct things
509 -- that have the same occurrence name
512 exportsFromAvail :: Bool -- False => no 'module M(..) where' header at all
513 -> Maybe [Located (IE RdrName)] -- Nothing => no explicit export list
515 -- Complains if two distinct exports have same OccName
516 -- Warns about identical exports.
517 -- Complains about exports items not in scope
519 exportsFromAvail explicit_mod exports
520 = do { TcGblEnv { tcg_rdr_env = rdr_env,
521 tcg_imports = imports } <- getGblEnv ;
523 -- If the module header is omitted altogether, then behave
524 -- as if the user had written "module Main(main) where..."
525 -- EXCEPT in interactive mode, when we behave as if he had
526 -- written "module Main where ..."
527 -- Reason: don't want to complain about 'main' not in scope
528 -- in interactive mode
529 ghci_mode <- getGhciMode ;
531 | explicit_mod = exports
532 | ghci_mode == Interactive = Nothing
533 | otherwise = Just [noLoc (IEVar main_RDR_Unqual)] } ;
534 exports_from_avail real_exports rdr_env imports }
537 exports_from_avail Nothing rdr_env imports
538 = -- Export all locally-defined things
539 -- We do this by filtering the global RdrEnv,
540 -- keeping only things that are locally-defined
541 return (mkNameSet [ gre_name gre
542 | gre <- globalRdrEnvElts rdr_env,
545 exports_from_avail (Just items) rdr_env (ImportAvails { imp_env = imp_env })
546 = foldlM do_litem emptyExportAccum items `thenM` \ (_, _, exports) ->
549 sub_env :: NameEnv [Name] -- Classify each name by its parent
550 sub_env = mkSubNameEnv (foldModuleEnv unionNameSets emptyNameSet imp_env)
552 do_litem :: ExportAccum -> Located (IE RdrName) -> RnM ExportAccum
553 do_litem acc = addLocM (exports_from_item acc)
555 exports_from_item :: ExportAccum -> IE RdrName -> RnM ExportAccum
556 exports_from_item acc@(mods, occs, exports) ie@(IEModuleContents mod)
557 | mod `elem` mods -- Duplicate export of M
558 = do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
559 warnIf warn_dup_exports (dupModuleExport mod) ;
563 = case lookupModuleEnv imp_env mod of
564 Nothing -> addErr (modExportErr mod) `thenM_`
568 new_exports = filterNameSet (inScopeUnqual rdr_env) names
571 -- This check_occs not only finds conflicts between this item
572 -- and others, but also internally within this item. That is,
573 -- if 'M.x' is in scope in several ways, we'll have several
574 -- members of mod_avails with the same OccName.
575 check_occs ie occs (nameSetToList new_exports) `thenM` \ occs' ->
576 returnM (mod:mods, occs', exports `unionNameSets` new_exports)
578 exports_from_item acc@(mods, occs, exports) ie
579 = lookupGlobalOccRn (ieName ie) `thenM` \ name ->
580 if isUnboundName name then
581 returnM acc -- Avoid error cascade
583 new_exports = filterAvail ie name sub_env
585 checkErr (not (null new_exports)) (exportItemErr ie) `thenM_`
586 checkForDodgyExport ie new_exports `thenM_`
587 check_occs ie occs new_exports `thenM` \ occs' ->
588 returnM (mods, occs', addListToNameSet exports new_exports)
590 -------------------------------
591 filterAvail :: IE RdrName -- Wanted
592 -> Name -- The Name of the ieName of the item
593 -> NameEnv [Name] -- Maps type/class names to their sub-names
594 -> [Name] -- Empty if even one thing reqd is missing
596 filterAvail (IEVar _) n subs = [n]
597 filterAvail (IEThingAbs _) n subs = [n]
598 filterAvail (IEThingAll _) n subs = n : subNames subs n
599 filterAvail (IEThingWith _ rdrs) n subs
600 | any isNothing mb_names = []
601 | otherwise = n : catMaybes mb_names
603 env = mkOccEnv [(nameOccName s, s) | s <- subNames subs n]
604 mb_names = map (lookupOccEnv env . rdrNameOcc) rdrs
605 filterAvail (IEModuleContents _) _ _ = panic "filterAvail"
607 subNames :: NameEnv [Name] -> Name -> [Name]
608 subNames env n = lookupNameEnv env n `orElse` []
610 mkSubNameEnv :: NameSet -> NameEnv [Name]
611 -- Maps types and classes to their constructors/classops respectively
612 -- This mapping just makes it easier to deal with A(..) export items
614 = foldNameSet add_name emptyNameEnv names
617 | Just parent <- nameParent_maybe name
618 = extendNameEnv_C (\ns _ -> name:ns) env parent [name]
621 -------------------------------
622 inScopeUnqual :: GlobalRdrEnv -> Name -> Bool
623 -- Checks whether the Name is in scope unqualified,
624 -- regardless of whether it's ambiguous or not
625 inScopeUnqual env n = any unQualOK (lookupGRE_Name env n)
627 -------------------------------
628 checkForDodgyExport :: IE RdrName -> [Name] -> RnM ()
629 checkForDodgyExport ie@(IEThingAll tc) [n]
630 | isTcOcc (nameOccName n) = addWarn (dodgyExportWarn tc)
631 -- This occurs when you export T(..), but
632 -- only import T abstractly, or T is a synonym.
633 -- The single [n] is the type or class itself
634 | otherwise = addErr (exportItemErr ie)
635 -- This happes if you export x(..), which is bogus
636 checkForDodgyExport _ _ = return ()
638 -------------------------------
639 check_occs :: IE RdrName -> ExportOccMap -> [Name] -> RnM ExportOccMap
640 check_occs ie occs names
641 = foldlM check occs names
644 = case lookupOccEnv occs name_occ of
645 Nothing -> returnM (extendOccEnv occs name_occ (name, ie))
648 | name == name' -- Duplicate export
649 -> do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
650 warnIf warn_dup_exports (dupExportWarn name_occ ie ie') ;
653 | otherwise -- Same occ name but different names: an error
654 -> do { global_env <- getGlobalRdrEnv ;
655 addErr (exportClashErr global_env name name' ie ie') ;
658 name_occ = nameOccName name
661 %*********************************************************
665 %*********************************************************
668 reportDeprecations :: TcGblEnv -> RnM ()
669 reportDeprecations tcg_env
670 = ifOptM Opt_WarnDeprecations $
671 do { (eps,hpt) <- getEpsAndHpt
672 ; mapM_ (check hpt (eps_PIT eps)) all_gres }
674 used_names = allUses (tcg_dus tcg_env)
675 -- Report on all deprecated uses; hence allUses
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) <+>
685 (parens imp_msg) <> colon,
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 -- NB: currently, if f x = g, we only treat 'g' as used if 'f' is used
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 -- Filter out the ones that are
759 -- (a) defined in this module, and
760 -- (b) not defined by a 'deriving' clause
761 -- The latter have an Internal Name, so we can filter them out easily
762 unused_locals :: [GlobalRdrElt]
763 unused_locals = filter is_unused_local defined_but_not_used
764 is_unused_local :: GlobalRdrElt -> Bool
765 is_unused_local gre = isLocalGRE gre && isExternalName (gre_name gre)
767 unused_imports :: [GlobalRdrElt]
768 unused_imports = filter unused_imp defined_but_not_used
769 unused_imp (GRE {gre_prov = Imported imp_specs})
770 = not (all (module_unused . is_mod) imp_specs)
771 && any is_explicit imp_specs
772 -- Don't complain about unused imports if we've already said the
773 -- entire import is unused
774 unused_imp other = False
776 -- To figure out the minimal set of imports, start with the things
777 -- that are in scope (i.e. in gbl_env). Then just combine them
778 -- into a bunch of avails, so they are properly grouped
780 -- BUG WARNING: this does not deal properly with qualified imports!
781 minimal_imports :: FiniteMap Module AvailEnv
782 minimal_imports0 = foldr add_expall emptyFM expall_mods
783 minimal_imports1 = foldr add_name minimal_imports0 defined_and_used
784 minimal_imports = foldr add_inst_mod minimal_imports1 direct_import_mods
785 -- The last line makes sure that we retain all direct imports
786 -- even if we import nothing explicitly.
787 -- It's not necessarily redundant to import such modules. Consider
791 -- The import M() is not *necessarily* redundant, even if
792 -- we suck in no instance decls from M (e.g. it contains
793 -- no instance decls, or This contains no code). It may be
794 -- that we import M solely to ensure that M's orphan instance
795 -- decls (or those in its imports) are visible to people who
796 -- import This. Sigh.
797 -- There's really no good way to detect this, so the error message
798 -- in RnEnv.warnUnusedModules is weakened instead
800 -- We've carefully preserved the provenance so that we can
801 -- construct minimal imports that import the name by (one of)
802 -- the same route(s) as the programmer originally did.
803 add_name (GRE {gre_name = n, gre_prov = Imported imp_specs}) acc
804 = addToFM_C plusAvailEnv acc (is_mod (head imp_specs))
805 (unitAvailEnv (mk_avail n (nameParent_maybe n)))
809 -- Modules mentioned as 'module M' in the export list
810 expall_mods = case export_decls of
812 Just es -> [m | L _ (IEModuleContents m) <- es]
814 -- This is really bogus. The idea is that if we see 'module M' in
815 -- the export list we must retain the import decls that drive it
816 -- If we aren't careful we might see
817 -- module A( module M ) where
820 -- and suppose that N exports everything that M does. Then we
821 -- must not drop the import of M even though N brings it all into
824 -- BUG WARNING: 'module M' exports aside, what if M.x is mentioned?!
826 -- The reason that add_expall is bogus is that it doesn't take
827 -- qualified imports into account. But it's an improvement.
828 add_expall mod acc = addToFM_C plusAvailEnv acc mod emptyAvailEnv
830 -- n is the name of the thing, p is the name of its parent
831 mk_avail n (Just p) = AvailTC p [p,n]
832 mk_avail n Nothing | isTcOcc (nameOccName n) = AvailTC n [n]
833 | otherwise = Avail n
835 add_inst_mod (mod,_,_) acc
836 | mod `elemFM` acc = acc -- We import something already
837 | otherwise = addToFM acc mod emptyAvailEnv
839 -- Add an empty collection of imports for a module
840 -- from which we have sucked only instance decls
842 imports = tcg_imports gbl_env
844 direct_import_mods :: [(Module, Maybe Bool, SrcSpan)]
845 -- See the type of the imp_mods for this triple
846 direct_import_mods = moduleEnvElts (imp_mods imports)
848 -- unused_imp_mods are the directly-imported modules
849 -- that are not mentioned in minimal_imports1
850 -- [Note: not 'minimal_imports', because that includes directly-imported
851 -- modules even if we use nothing from them; see notes above]
853 -- BUG WARNING: does not deal correctly with multiple imports of the same module
854 -- becuase direct_import_mods has only one entry per module
855 unused_imp_mods = [(mod,loc) | (mod,imp,loc) <- direct_import_mods,
856 not (mod `elemFM` minimal_imports1),
859 -- The Just False part is not to complain about
860 -- import M (), which is an idiom for importing
861 -- instance declarations
863 module_unused :: Module -> Bool
864 module_unused mod = any (((==) mod) . fst) unused_imp_mods
866 ---------------------
867 warnDuplicateImports :: [GlobalRdrElt] -> RnM ()
868 -- Given the GREs for names that are used, figure out which imports
869 -- could be omitted without changing the top-level environment.
871 -- NB: Given import Foo( T )
872 -- import qualified Foo
873 -- we do not report a duplicate import, even though Foo.T is brought
874 -- into scope by both, because there's nothing you can *omit* without
875 -- changing the top-level environment. So we complain only if it's
876 -- explicitly named in both imports or neither.
878 -- Furthermore, we complain about Foo.T only if
879 -- there is no complaint about (unqualified) T
881 warnDuplicateImports gres
882 = ifOptM Opt_WarnUnusedImports $
883 sequenceM_ [ warn name pr
884 -- The 'head' picks the first offending group
885 -- for this particular name
886 | GRE { gre_name = name, gre_prov = Imported imps } <- gres
887 , pr <- redundants imps ]
889 warn name (red_imp, cov_imp)
890 = addWarnAt (is_loc red_imp)
891 (vcat [ptext SLIT("Redundant import of:") <+> quotes pp_name,
892 ptext SLIT("It is also") <+> ppr cov_imp])
894 pp_name | is_qual red_imp = ppr (is_as red_imp) <> dot <> ppr occ
895 | otherwise = ppr occ
896 occ = nameOccName name
898 redundants :: [ImportSpec] -> [(ImportSpec,ImportSpec)]
899 -- The returned pair is (redundant-import, covering-import)
901 = [ (red_imp, cov_imp)
903 , cov_imp <- take 1 (filter (covers red_imp) imps) ]
905 -- "red_imp" is a putative redundant import
906 -- "cov_imp" potentially covers it
908 covers red_imp cov_imp
910 = False -- Ignore diagonal elements
911 | not (is_as red_imp == is_as cov_imp)
912 = False -- They bring into scope different qualified names
913 | not (is_qual red_imp) && is_qual cov_imp
914 = False -- Covering one doesn't bring unqualified name into scope
915 | is_explicit red_imp
916 = not cov_explicit -- Redundant one is explicit and covering one isn't
917 || red_later -- Both are explicit; tie-break using red_later
919 = not cov_explicit -- Neither import is explicit
920 && (is_mod red_imp == is_mod cov_imp) -- They import the same module
921 && red_later -- Tie-break
923 cov_explicit = is_explicit cov_imp
924 red_loc = is_loc red_imp
925 cov_loc = is_loc cov_imp
926 red_later = red_loc > cov_loc
928 -- ToDo: deal with original imports with 'qualified' and 'as M' clauses
929 printMinimalImports :: FiniteMap Module AvailEnv -- Minimal imports
931 printMinimalImports imps
932 = ifOptM Opt_D_dump_minimal_imports $ do {
934 mod_ies <- mappM to_ies (fmToList imps) ;
935 this_mod <- getModule ;
936 rdr_env <- getGlobalRdrEnv ;
937 ioToTcRn (do { h <- openFile (mkFilename this_mod) WriteMode ;
938 printForUser h (unQualInScope rdr_env)
939 (vcat (map ppr_mod_ie mod_ies)) })
942 mkFilename this_mod = moduleUserString this_mod ++ ".imports"
943 ppr_mod_ie (mod_name, ies)
944 | mod_name == pRELUDE
946 | null ies -- Nothing except instances comes from here
947 = ptext SLIT("import") <+> ppr mod_name <> ptext SLIT("() -- Instances only")
949 = ptext SLIT("import") <+> ppr mod_name <>
950 parens (fsep (punctuate comma (map ppr ies)))
952 to_ies (mod, avail_env) = mappM to_ie (availEnvElts avail_env) `thenM` \ ies ->
955 to_ie :: AvailInfo -> RnM (IE Name)
956 -- The main trick here is that if we're importing all the constructors
957 -- we want to say "T(..)", but if we're importing only a subset we want
958 -- to say "T(A,B,C)". So we have to find out what the module exports.
959 to_ie (Avail n) = returnM (IEVar n)
960 to_ie (AvailTC n [m]) = ASSERT( n==m )
961 returnM (IEThingAbs n)
963 = loadSrcInterface doc n_mod False `thenM` \ iface ->
964 case [xs | (m,as) <- mi_exports iface,
967 x == nameOccName n] of
968 [xs] | all_used xs -> returnM (IEThingAll n)
969 | otherwise -> returnM (IEThingWith n (filter (/= n) ns))
970 other -> pprTrace "to_ie" (ppr n <+> ppr n_mod <+> ppr other) $
973 all_used avail_occs = all (`elem` map nameOccName ns) avail_occs
974 doc = text "Compute minimal imports from" <+> ppr n
979 %************************************************************************
983 %************************************************************************
986 badImportItemErr iface imp_spec ie
987 = sep [ptext SLIT("Module"), quotes (ppr (is_mod imp_spec)), source_import,
988 ptext SLIT("does not export"), quotes (ppr ie)]
990 source_import | mi_boot iface = ptext SLIT("(hi-boot interface)")
993 dodgyImportWarn item = dodgyMsg (ptext SLIT("import")) item
994 dodgyExportWarn item = dodgyMsg (ptext SLIT("export")) item
997 = sep [ ptext SLIT("The") <+> kind <+> ptext SLIT("item") <+> quotes (ppr (IEThingAll tc)),
998 ptext SLIT("suggests that") <+> quotes (ppr tc) <+> ptext SLIT("has constructor or class methods"),
999 ptext SLIT("but it has none; it is a type synonym or abstract type or class") ]
1002 = hsep [ ptext SLIT("Unknown module in export list: module"), quotes (ppr mod)]
1004 exportItemErr export_item
1005 = sep [ ptext SLIT("The export item") <+> quotes (ppr export_item),
1006 ptext SLIT("attempts to export constructors or class methods that are not visible here") ]
1008 exportClashErr global_env name1 name2 ie1 ie2
1009 = vcat [ ptext SLIT("Conflicting exports for") <+> quotes (ppr occ) <> colon
1010 , ppr_export ie1 name1
1011 , ppr_export ie2 name2 ]
1013 occ = nameOccName name1
1014 ppr_export ie name = nest 2 (quotes (ppr ie) <+> ptext SLIT("exports") <+>
1015 quotes (ppr name) <+> pprNameProvenance (get_gre name))
1017 -- get_gre finds a GRE for the Name, so that we can show its provenance
1019 = case lookupGRE_Name global_env name of
1021 [] -> pprPanic "exportClashErr" (ppr name)
1023 addDupDeclErr :: Name -> Name -> TcRn ()
1024 addDupDeclErr name_a name_b
1025 = addErrAt (srcLocSpan loc2) $
1026 vcat [ptext SLIT("Multiple declarations of") <+> quotes (ppr name1),
1027 ptext SLIT("Declared at:") <+> vcat [ppr (nameSrcLoc name1), ppr loc2]]
1029 loc2 = nameSrcLoc name2
1030 (name1,name2) | nameSrcLoc name_a > nameSrcLoc name_b = (name_b,name_a)
1031 | otherwise = (name_a,name_b)
1032 -- Report the error at the later location
1034 dupExportWarn occ_name ie1 ie2
1035 = hsep [quotes (ppr occ_name),
1036 ptext SLIT("is exported by"), quotes (ppr ie1),
1037 ptext SLIT("and"), quotes (ppr ie2)]
1040 = hsep [ptext SLIT("Duplicate"),
1041 quotes (ptext SLIT("Module") <+> ppr mod),
1042 ptext SLIT("in export list")]
1044 moduleDeprec mod txt
1045 = sep [ ptext SLIT("Module") <+> quotes (ppr mod) <+> ptext SLIT("is deprecated:"),