2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[RnNames]{Extracting imported and top-level names in scope}
8 rnImports, mkRdrEnvAndImports, importsFromLocalDecls,
9 rnExports, mkExportNameSet,
10 getLocalDeclBinders, extendRdrEnvRn,
11 reportUnusedNames, reportDeprecations
14 #include "HsVersions.h"
16 import DynFlags ( DynFlag(..), GhcMode(..) )
17 import HsSyn ( IE(..), ieName, ImportDecl(..), LImportDecl,
18 ForeignDecl(..), HsGroup(..), HsValBinds(..),
19 Sig(..), collectHsBindLocatedBinders, tyClDeclNames,
22 import IfaceEnv ( ifaceExportNames )
23 import LoadIface ( loadSrcInterface )
24 import TcRnMonad hiding (LIE)
27 import PrelNames ( pRELUDE, isUnboundName, main_RDR_Unqual )
28 import Module ( Module, moduleString, unitModuleEnv,
29 lookupModuleEnv, moduleEnvElts, foldModuleEnv )
30 import Name ( Name, nameSrcLoc, nameOccName, nameModule, isWiredInName,
31 nameParent, nameParent_maybe, isExternalName,
35 import OccName ( srcDataName, isTcOcc, pprNonVarNameSpace,
37 OccEnv, mkOccEnv, lookupOccEnv, emptyOccEnv,
39 import HscTypes ( GenAvailInfo(..), AvailInfo,
40 HomePackageTable, PackageIfaceTable,
42 Deprecs(..), ModIface(..), Dependencies(..),
43 lookupIface, ExternalPackageState(..)
45 import Packages ( PackageIdH(..) )
46 import RdrName ( RdrName, rdrNameOcc, setRdrNameSpace,
47 GlobalRdrEnv, mkGlobalRdrEnv, GlobalRdrElt(..),
48 emptyGlobalRdrEnv, plusGlobalRdrEnv, globalRdrEnvElts,
49 extendGlobalRdrEnv, lookupGlobalRdrEnv, unQualOK, lookupGRE_Name,
50 Provenance(..), ImportSpec(..), ImpDeclSpec(..), ImpItemSpec(..),
51 importSpecLoc, importSpecModule, isLocalGRE, pprNameProvenance )
53 import Maybes ( isNothing, catMaybes, mapCatMaybes, seqMaybe, orElse )
54 import SrcLoc ( Located(..), mkGeneralSrcSpan,
55 unLoc, noLoc, srcLocSpan, SrcSpan )
56 import BasicTypes ( DeprecTxt )
57 import DriverPhases ( isHsBoot )
58 import Util ( notNull )
59 import List ( partition )
60 import IO ( openFile, IOMode(..) )
65 %************************************************************************
69 %************************************************************************
72 rnImports :: [LImportDecl RdrName] -> RnM [LImportDecl Name]
74 -- PROCESS IMPORT DECLS
75 -- Do the non {- SOURCE -} ones first, so that we get a helpful
76 -- warning for {- SOURCE -} ones that are unnecessary
77 = do this_mod <- getModule
78 implicit_prelude <- doptM Opt_ImplicitPrelude
79 let 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
82 get_imports = rnImportDecl this_mod
84 stuff1 <- mapM get_imports ordinary
85 stuff2 <- mapM get_imports source
86 return (stuff1 ++ stuff2)
88 -- NB: opt_NoImplicitPrelude is slightly different to import Prelude ();
89 -- because the former doesn't even look at Prelude.hi for instance
90 -- declarations, whereas the latter does.
91 mk_prel_imports this_mod implicit_prelude
93 || explicit_prelude_import
94 || not implicit_prelude
96 | otherwise = [preludeImportDecl]
97 explicit_prelude_import
98 = notNull [ () | L _ (ImportDecl mod _ _ _ _) <- imports,
99 unLoc mod == pRELUDE ]
101 preludeImportDecl :: LImportDecl RdrName
104 ImportDecl (L loc pRELUDE)
105 False {- Not a boot interface -}
106 False {- Not qualified -}
107 Nothing {- No "as" -}
108 Nothing {- No import list -}
110 loc = mkGeneralSrcSpan FSLIT("Implicit import declaration")
112 mkRdrEnvAndImports :: [LImportDecl Name] -> RnM (GlobalRdrEnv, ImportAvails)
113 mkRdrEnvAndImports imports
114 = do this_mod <- getModule
115 let get_imports = importsFromImportDecl this_mod
116 stuff <- mapM get_imports imports
117 let (imp_gbl_envs, imp_avails) = unzip stuff
118 gbl_env :: GlobalRdrEnv
119 gbl_env = foldr plusGlobalRdrEnv emptyGlobalRdrEnv imp_gbl_envs
121 all_avails :: ImportAvails
122 all_avails = foldr plusImportAvails emptyImportAvails imp_avails
124 return (gbl_env, all_avails)
129 rnImportDecl :: Module
130 -> LImportDecl RdrName
131 -> RnM (LImportDecl Name)
132 rnImportDecl this_mod (L loc importDecl@(ImportDecl loc_imp_mod_name want_boot qual_only as_mod imp_details))
134 do iface <- loadSrcInterface doc imp_mod_name want_boot
135 let qual_mod_name = case as_mod of
136 Nothing -> imp_mod_name
137 Just another_name -> another_name
138 imp_spec = ImpDeclSpec { is_mod = imp_mod_name, is_qual = qual_only,
139 is_dloc = loc, is_as = qual_mod_name }
140 total_avails <- ifaceExportNames (mi_exports iface)
141 importDecl' <- rnImportDecl' iface imp_spec importDecl total_avails
142 return (L loc importDecl')
143 where imp_mod_name = unLoc loc_imp_mod_name
144 doc = ppr imp_mod_name <+> ptext SLIT("is directly imported")
146 rnImportDecl' :: ModIface -> ImpDeclSpec -> ImportDecl RdrName -> NameSet -> RnM (ImportDecl Name)
147 rnImportDecl' iface decl_spec (ImportDecl mod_name want_boot qual_only as_mod Nothing) all_names
148 = return $ ImportDecl mod_name want_boot qual_only as_mod Nothing
149 rnImportDecl' iface decl_spec (ImportDecl mod_name want_boot qual_only as_mod (Just (want_hiding,import_items))) all_names
150 = do import_items_mbs <- mapM (srcSpanWrapper) import_items
151 let rn_import_items = concat . catMaybes $ import_items_mbs
152 return $ ImportDecl mod_name want_boot qual_only as_mod (Just (want_hiding,rn_import_items))
154 srcSpanWrapper (L span ieRdr)
156 case get_item ieRdr of
158 -> do addErr (badImportItemErr iface decl_spec ieRdr)
161 -> return (Just [L span ie | ie <- ieNames])
162 occ_env :: OccEnv Name -- Maps OccName to corresponding Name
163 occ_env = mkOccEnv [(nameOccName n, n) | n <- nameSetToList all_names]
164 -- This env will have entries for data constructors too,
165 -- they won't make any difference because naked entities like T
166 -- in an import list map to TcOccs, not VarOccs.
168 sub_env :: NameEnv [Name]
169 sub_env = mkSubNameEnv all_names
171 get_item :: IE RdrName -> Maybe [IE Name]
172 -- Empty result for a bad item.
173 -- Singleton result is typical case.
174 -- Can have two when we are hiding, and mention C which might be
175 -- both a class and a data constructor.
176 get_item item@(IEModuleContents _)
178 get_item (IEThingAll tc)
179 = do name <- check_name tc
180 return [IEThingAll name]
181 get_item (IEThingAbs tc)
182 | want_hiding -- hiding ( C )
183 -- Here the 'C' can be a data constructor
184 -- *or* a type/class, or even both
185 = case catMaybes [check_name tc, check_name (setRdrNameSpace tc srcDataName)] of
187 names -> return [ IEThingAbs n | n <- names ]
189 = do name <- check_name tc
190 return [IEThingAbs name]
191 get_item (IEThingWith n ns) -- import (C (A,B))
192 = do name <- check_name n
193 let env = mkOccEnv [(nameOccName s, s) | s <- subNames sub_env name]
194 mb_names = map (lookupOccEnv env . rdrNameOcc) ns
195 names <- sequence mb_names
196 return [IEThingWith name names]
198 = do name <- check_name n
201 check_name :: RdrName -> Maybe Name
203 = lookupOccEnv occ_env (rdrNameOcc rdrName)
206 importsFromImportDecl :: Module
208 -> RnM (GlobalRdrEnv, ImportAvails)
210 importsFromImportDecl this_mod
211 (L loc (ImportDecl loc_imp_mod_name want_boot qual_only as_mod imp_details))
215 -- If there's an error in loadInterface, (e.g. interface
216 -- file not found) we get lots of spurious errors from 'filterImports'
218 imp_mod_name = unLoc loc_imp_mod_name
219 doc = ppr imp_mod_name <+> ptext SLIT("is directly imported")
221 loadSrcInterface doc imp_mod_name want_boot `thenM` \ iface ->
223 -- Compiler sanity check: if the import didn't say
224 -- {-# SOURCE #-} we should not get a hi-boot file
225 WARN( not want_boot && mi_boot iface, ppr imp_mod_name )
227 -- Issue a user warning for a redundant {- SOURCE -} import
228 -- NB that we arrange to read all the ordinary imports before
229 -- any of the {- SOURCE -} imports
230 warnIf (want_boot && not (mi_boot iface))
231 (warnRedundantSourceImport imp_mod_name) `thenM_`
234 imp_mod = mi_module iface
235 deprecs = mi_deprecs iface
236 is_orph = mi_orphan iface
239 filtered_exports = filter not_this_mod (mi_exports iface)
240 not_this_mod (mod,_) = mod /= this_mod
241 -- If the module exports anything defined in this module, just ignore it.
242 -- Reason: otherwise it looks as if there are two local definition sites
243 -- for the thing, and an error gets reported. Easiest thing is just to
244 -- filter them out up front. This situation only arises if a module
245 -- imports itself, or another module that imported it. (Necessarily,
246 -- this invoves a loop.)
248 -- Tiresome consequence: if you say
253 -- module B( AType ) where
254 -- import {-# SOURCE #-} A( AType )
256 -- then you'll get a 'B does not export AType' message. Oh well.
258 qual_mod_name = case as_mod of
259 Nothing -> imp_mod_name
260 Just another_name -> another_name
261 imp_spec = ImpDeclSpec { is_mod = imp_mod_name, is_qual = qual_only,
262 is_dloc = loc, is_as = qual_mod_name }
264 -- Get the total imports, and filter them according to the import list
265 ifaceExportNames filtered_exports `thenM` \ total_avails ->
266 filterImports iface imp_spec
267 imp_details total_avails `thenM` \ (avail_env, gbl_env) ->
269 getDOpts `thenM` \ dflags ->
272 -- Compute new transitive dependencies
274 orphans | is_orph = ASSERT( not (imp_mod_name `elem` dep_orphs deps) )
275 imp_mod_name : dep_orphs deps
276 | otherwise = dep_orphs deps
278 (dependent_mods, dependent_pkgs)
279 = case mi_package iface of
281 -- Imported module is from the home package
282 -- Take its dependent modules and add imp_mod itself
283 -- Take its dependent packages unchanged
285 -- NB: (dep_mods deps) might include a hi-boot file
286 -- for the module being compiled, CM. Do *not* filter
287 -- this out (as we used to), because when we've
288 -- finished dealing with the direct imports we want to
289 -- know if any of them depended on CM.hi-boot, in
290 -- which case we should do the hi-boot consistency
291 -- check. See LoadIface.loadHiBootInterface
292 ((imp_mod_name, want_boot) : dep_mods deps, dep_pkgs deps)
295 -- Imported module is from another package
296 -- Dump the dependent modules
297 -- Add the package imp_mod comes from to the dependent packages
298 ASSERT2( not (pkg `elem` dep_pkgs deps), ppr pkg <+> ppr (dep_pkgs deps) )
299 ([], pkg : dep_pkgs deps)
301 -- True <=> import M ()
302 import_all = case imp_details of
303 Just (is_hiding, ls) -> not is_hiding && null ls
306 -- unqual_avails is the Avails that are visible in *unqualified* form
307 -- We need to know this so we know what to export when we see
308 -- module M ( module P ) where ...
309 -- Then we must export whatever came from P unqualified.
310 imports = ImportAvails {
311 imp_env = unitModuleEnv qual_mod_name avail_env,
312 imp_mods = unitModuleEnv imp_mod (imp_mod, import_all, loc),
314 imp_dep_mods = mkModDeps dependent_mods,
315 imp_dep_pkgs = dependent_pkgs }
318 -- Complain if we import a deprecated module
319 ifOptM Opt_WarnDeprecations (
321 DeprecAll txt -> addWarn (moduleDeprec imp_mod_name txt)
325 returnM (gbl_env, imports)
327 warnRedundantSourceImport mod_name
328 = ptext SLIT("Unnecessary {- SOURCE -} in the import of module")
329 <+> quotes (ppr mod_name)
333 %************************************************************************
335 importsFromLocalDecls
337 %************************************************************************
339 From the top-level declarations of this module produce
340 * the lexical environment
342 created by its bindings.
344 Complain about duplicate bindings
347 importsFromLocalDecls :: HsGroup RdrName -> RnM TcGblEnv
348 importsFromLocalDecls group
349 = do { gbl_env <- getGblEnv
351 ; names <- getLocalDeclBinders gbl_env group
353 ; implicit_prelude <- doptM Opt_ImplicitPrelude
355 -- Optimisation: filter out names for built-in syntax
356 -- They just clutter up the environment (esp tuples), and the parser
357 -- will generate Exact RdrNames for them, so the cluttered
358 -- envt is no use. To avoid doing this filter all the time,
359 -- we use -fno-implicit-prelude as a clue that the filter is
360 -- worth while. Really, it's only useful for GHC.Base and GHC.Tuple.
362 -- It's worth doing because it makes the environment smaller for
363 -- every module that imports the Prelude
365 -- Note: don't filter the gbl_env (hence all_names, not filered_all_names
366 -- in defn of gres above). Stupid reason: when parsing
367 -- data type decls, the constructors start as Exact tycon-names,
368 -- and then get turned into data con names by zapping the name space;
369 -- but that stops them being Exact, so they get looked up.
370 -- Ditto in fixity decls; e.g. infix 5 :
371 -- Sigh. It doesn't matter because it only affects the Data.Tuple really.
372 -- The important thing is to trim down the exports.
374 | implicit_prelude = names
375 | otherwise = filter (not . isBuiltInSyntax) names ;
377 ; this_mod = tcg_mod gbl_env
378 ; imports = emptyImportAvails {
379 imp_env = unitModuleEnv this_mod $
380 mkNameSet filtered_names
384 ; rdr_env' <- extendRdrEnvRn (tcg_rdr_env gbl_env) names
386 ; returnM (gbl_env { tcg_rdr_env = rdr_env',
387 tcg_imports = imports `plusImportAvails` tcg_imports gbl_env })
390 extendRdrEnvRn :: GlobalRdrEnv -> [Name] -> RnM GlobalRdrEnv
391 -- Add the new locally-bound names one by one, checking for duplicates as
392 -- we do so. Remember that in Template Haskell the duplicates
393 -- might *already be* in the GlobalRdrEnv from higher up the module
394 extendRdrEnvRn rdr_env names
395 = foldlM add_local rdr_env names
397 add_local rdr_env name
398 | gres <- lookupGlobalRdrEnv rdr_env (nameOccName name)
399 , (dup_gre:_) <- filter isLocalGRE gres -- Check for existing *local* defns
400 = do { addDupDeclErr (gre_name dup_gre) name
403 = return (extendGlobalRdrEnv rdr_env new_gre)
405 new_gre = GRE {gre_name = name, gre_prov = LocalDef}
408 @getLocalDeclBinders@ returns the names for an @HsDecl@. It's
409 used for source code.
411 *** See "THE NAMING STORY" in HsDecls ****
414 getLocalDeclBinders :: TcGblEnv -> HsGroup RdrName -> RnM [Name]
415 getLocalDeclBinders gbl_env (HsGroup {hs_valds = ValBindsIn val_decls val_sigs,
416 hs_tyclds = tycl_decls,
417 hs_fords = foreign_decls })
418 = do { tc_names_s <- mappM new_tc tycl_decls
419 ; val_names <- mappM new_simple val_bndrs
420 ; return (foldr (++) val_names tc_names_s) }
422 mod = tcg_mod gbl_env
423 is_hs_boot = isHsBoot (tcg_src gbl_env) ;
424 val_bndrs | is_hs_boot = sig_hs_bndrs
425 | otherwise = for_hs_bndrs ++ val_hs_bndrs
426 -- In a hs-boot file, the value binders come from the
427 -- *signatures*, and there should be no foreign binders
429 new_simple rdr_name = newTopSrcBinder mod Nothing rdr_name
431 sig_hs_bndrs = [nm | L _ (TypeSig nm _) <- val_sigs]
432 val_hs_bndrs = collectHsBindLocatedBinders val_decls
433 for_hs_bndrs = [nm | L _ (ForeignImport nm _ _ _) <- foreign_decls]
436 = do { main_name <- newTopSrcBinder mod Nothing main_rdr
437 ; sub_names <- mappM (newTopSrcBinder mod (Just main_name)) sub_rdrs
438 ; return (main_name : sub_names) }
440 (main_rdr : sub_rdrs) = tyClDeclNames (unLoc tc_decl)
444 %************************************************************************
446 \subsection{Filtering imports}
448 %************************************************************************
450 @filterImports@ takes the @ExportEnv@ telling what the imported module makes
451 available, and filters it through the import spec (if any).
454 filterImports :: ModIface
455 -> ImpDeclSpec -- The span for the entire import decl
456 -> Maybe (Bool, [LIE Name]) -- Import spec; True => hiding
457 -> NameSet -- What's available
458 -> RnM (NameSet, -- What's imported (qualified or unqualified)
459 GlobalRdrEnv) -- Same again, but in GRE form
461 -- Complains if import spec mentions things that the module doesn't export
462 -- Warns/informs if import spec contains duplicates.
464 mkGenericRdrEnv decl_spec names
465 = mkGlobalRdrEnv [ GRE { gre_name = name, gre_prov = Imported [imp_spec] }
466 | name <- nameSetToList names ]
468 imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }
470 filterImports iface decl_spec Nothing all_names
471 = return (all_names, mkGenericRdrEnv decl_spec all_names)
473 filterImports iface decl_spec (Just (want_hiding, import_items)) all_names
474 = mapM (addLocM get_item) import_items >>= \gres_s ->
475 let gres = concat gres_s
476 specified_names = mkNameSet (map gre_name gres)
477 in if not want_hiding then
478 return (specified_names, mkGlobalRdrEnv gres)
479 else let keep n = not (n `elemNameSet` specified_names)
480 pruned_avails = filterNameSet keep all_names
481 in return (pruned_avails, mkGenericRdrEnv decl_spec pruned_avails)
483 sub_env :: NameEnv [Name] -- Classify each name by its parent
484 sub_env = mkSubNameEnv all_names
486 succeed_with :: Bool -> [Name] -> RnM [GlobalRdrElt]
487 succeed_with all_explicit names
488 = do { loc <- getSrcSpanM
489 ; returnM (map (mk_gre loc) names) }
491 mk_gre loc name = GRE { gre_name = name,
492 gre_prov = Imported [imp_spec] }
494 imp_spec = ImpSpec { is_decl = decl_spec, is_item = item_spec }
495 item_spec = ImpSome { is_explicit = explicit, is_iloc = loc }
496 explicit = all_explicit || isNothing (nameParent_maybe name)
498 get_item :: IE Name -> RnM [GlobalRdrElt]
499 -- Empty result for a bad item.
500 -- Singleton result is typical case.
501 -- Can have two when we are hiding, and mention C which might be
502 -- both a class and a data constructor.
503 get_item item@(IEModuleContents _)
504 -- This case should be filtered out by 'rnImports'.
505 = panic "filterImports: IEModuleContents?"
507 get_item (IEThingAll name)
508 = case subNames sub_env name of
509 [] -> -- This occurs when you import T(..), but
510 -- only export T abstractly.
511 do ifOptM Opt_WarnDodgyImports (addWarn (dodgyImportWarn name))
512 succeed_with False [name]
513 names -> succeed_with False (name:names)
515 get_item (IEThingAbs name)
516 = succeed_with True [name]
518 get_item (IEThingWith name names)
519 = succeed_with True (name:names)
520 get_item (IEVar name)
521 = succeed_with True [name]
526 %************************************************************************
528 \subsection{Export list processing}
530 %************************************************************************
532 Processing the export list.
534 You might think that we should record things that appear in the export
535 list as ``occurrences'' (using @addOccurrenceName@), but you'd be
536 wrong. We do check (here) that they are in scope, but there is no
537 need to slurp in their actual declaration (which is what
538 @addOccurrenceName@ forces).
540 Indeed, doing so would big trouble when compiling @PrelBase@, because
541 it re-exports @GHC@, which includes @takeMVar#@, whose type includes
542 @ConcBase.StateAndSynchVar#@, and so on...
545 type ExportAccum -- The type of the accumulating parameter of
546 -- the main worker function in rnExports
547 = ([Module], -- 'module M's seen so far
548 ExportOccMap, -- Tracks exported occurrence names
549 NameSet) -- The accumulated exported stuff
550 emptyExportAccum = ([], emptyOccEnv, emptyNameSet)
552 type ExportOccMap = OccEnv (Name, IE Name)
553 -- Tracks what a particular exported OccName
554 -- in an export list refers to, and which item
555 -- it came from. It's illegal to export two distinct things
556 -- that have the same occurrence name
558 rnExports :: Maybe [LIE RdrName]
559 -> RnM (Maybe [LIE Name])
560 rnExports Nothing = return Nothing
561 rnExports (Just exports)
562 = do TcGblEnv { tcg_imports = ImportAvails { imp_env = imp_env } } <- getGblEnv
563 let sub_env :: NameEnv [Name] -- Classify each name by its parent
564 sub_env = mkSubNameEnv (foldModuleEnv unionNameSets emptyNameSet imp_env)
568 rnExport (IEVar rdrName)
569 = do name <- lookupGlobalOccRn rdrName
571 rnExport (IEThingAbs rdrName)
572 = do name <- lookupGlobalOccRn rdrName
573 return (IEThingAbs name)
574 rnExport (IEThingAll rdrName)
575 = do name <- lookupGlobalOccRn rdrName
576 return (IEThingAll name)
577 rnExport (IEThingWith rdrName rdrNames)
578 = do name <- lookupGlobalOccRn rdrName
579 let env = mkOccEnv [(nameOccName s, s) | s <- subNames sub_env name]
580 mb_names = map (lookupOccEnv env . rdrNameOcc) rdrNames
581 if any isNothing mb_names
582 then -- The export error will be reporting in 'mkExportNameSet'
583 return (IEThingWith name [])
584 else return (IEThingWith name (catMaybes mb_names))
585 rnExport (IEModuleContents mod)
586 = return (IEModuleContents mod)
587 rn_exports <- mapM (inLoc rnExport) exports
588 return (Just rn_exports)
590 mkExportNameSet :: Bool -- False => no 'module M(..) where' header at all
591 -> Maybe [LIE Name] -- Nothing => no explicit export list
593 -- Complains if two distinct exports have same OccName
594 -- Warns about identical exports.
595 -- Complains about exports items not in scope
597 mkExportNameSet explicit_mod exports
598 = do TcGblEnv { tcg_rdr_env = rdr_env,
599 tcg_imports = imports } <- getGblEnv
601 -- If the module header is omitted altogether, then behave
602 -- as if the user had written "module Main(main) where..."
603 -- EXCEPT in interactive mode, when we behave as if he had
604 -- written "module Main where ..."
605 -- Reason: don't want to complain about 'main' not in scope
606 -- in interactive mode
607 ghc_mode <- getGhcMode
608 real_exports <- case () of
611 | ghc_mode == Interactive
614 -> do mainName <- lookupGlobalOccRn main_RDR_Unqual
615 return (Just [noLoc (IEVar mainName)])
616 -- ToDo: the 'noLoc' here is unhelpful if 'main' turns out to be out of scope
617 exports_from_avail real_exports rdr_env imports
620 exports_from_avail Nothing rdr_env imports
621 = -- Export all locally-defined things
622 -- We do this by filtering the global RdrEnv,
623 -- keeping only things that are locally-defined
624 return (mkNameSet [ gre_name gre
625 | gre <- globalRdrEnvElts rdr_env,
628 exports_from_avail (Just items) rdr_env (ImportAvails { imp_env = imp_env })
629 = do (_, _, exports) <- foldlM do_litem emptyExportAccum items
632 sub_env :: NameEnv [Name] -- Classify each name by its parent
633 sub_env = mkSubNameEnv (foldModuleEnv unionNameSets emptyNameSet imp_env)
635 do_litem :: ExportAccum -> LIE Name -> RnM ExportAccum
636 do_litem acc = addLocM (exports_from_item acc)
638 exports_from_item :: ExportAccum -> IE Name -> RnM ExportAccum
639 exports_from_item acc@(mods, occs, exports) ie@(IEModuleContents mod)
640 | mod `elem` mods -- Duplicate export of M
641 = do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
642 warnIf warn_dup_exports (dupModuleExport mod) ;
646 = case lookupModuleEnv imp_env mod of
647 Nothing -> do addErr (modExportErr mod)
650 -> do let new_exports = filterNameSet (inScopeUnqual rdr_env) names
651 -- This check_occs not only finds conflicts between this item
652 -- and others, but also internally within this item. That is,
653 -- if 'M.x' is in scope in several ways, we'll have several
654 -- members of mod_avails with the same OccName.
655 occs' <- check_occs ie occs (nameSetToList new_exports)
656 return (mod:mods, occs', exports `unionNameSets` new_exports)
658 exports_from_item acc@(mods, occs, exports) ie
659 = if isUnboundName (ieName ie)
660 then return acc -- Avoid error cascade
661 else let new_exports = filterAvail ie sub_env in
662 do checkErr (not (null new_exports)) (exportItemErr ie)
663 checkForDodgyExport ie new_exports
664 occs' <- check_occs ie occs new_exports
665 return (mods, occs', addListToNameSet exports new_exports)
667 -------------------------------
668 filterAvail :: IE Name -- Wanted
669 -> NameEnv [Name] -- Maps type/class names to their sub-names
672 filterAvail (IEVar n) subs = [n]
673 filterAvail (IEThingAbs n) subs = [n]
674 filterAvail (IEThingAll n) subs = n : subNames subs n
675 filterAvail (IEThingWith n ns) subs = n : ns
676 filterAvail (IEModuleContents _) _ = panic "filterAvail"
678 subNames :: NameEnv [Name] -> Name -> [Name]
679 subNames env n = lookupNameEnv env n `orElse` []
681 mkSubNameEnv :: NameSet -> NameEnv [Name]
682 -- Maps types and classes to their constructors/classops respectively
683 -- This mapping just makes it easier to deal with A(..) export items
685 = foldNameSet add_name emptyNameEnv names
688 | Just parent <- nameParent_maybe name
689 = extendNameEnv_C (\ns _ -> name:ns) env parent [name]
692 -------------------------------
693 inScopeUnqual :: GlobalRdrEnv -> Name -> Bool
694 -- Checks whether the Name is in scope unqualified,
695 -- regardless of whether it's ambiguous or not
696 inScopeUnqual env n = any unQualOK (lookupGRE_Name env n)
698 -------------------------------
699 checkForDodgyExport :: IE Name -> [Name] -> RnM ()
700 checkForDodgyExport ie@(IEThingAll tc) [n]
701 | isTcOcc (nameOccName n) = addWarn (dodgyExportWarn tc)
702 -- This occurs when you export T(..), but
703 -- only import T abstractly, or T is a synonym.
704 -- The single [n] is the type or class itself
705 | otherwise = addErr (exportItemErr ie)
706 -- This happes if you export x(..), which is bogus
707 checkForDodgyExport _ _ = return ()
709 -------------------------------
710 check_occs :: IE Name -> ExportOccMap -> [Name] -> RnM ExportOccMap
711 check_occs ie occs names
712 = foldlM check occs names
715 = case lookupOccEnv occs name_occ of
716 Nothing -> returnM (extendOccEnv occs name_occ (name, ie))
719 | name == name' -- Duplicate export
720 -> do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
721 warnIf warn_dup_exports (dupExportWarn name_occ ie ie') ;
724 | otherwise -- Same occ name but different names: an error
725 -> do { global_env <- getGlobalRdrEnv ;
726 addErr (exportClashErr global_env name name' ie ie') ;
729 name_occ = nameOccName name
732 %*********************************************************
736 %*********************************************************
739 reportDeprecations :: TcGblEnv -> RnM ()
740 reportDeprecations tcg_env
741 = ifOptM Opt_WarnDeprecations $
742 do { (eps,hpt) <- getEpsAndHpt
743 -- By this time, typechecking is complete,
744 -- so the PIT is fully populated
745 ; mapM_ (check hpt (eps_PIT eps)) all_gres }
747 used_names = allUses (tcg_dus tcg_env)
748 -- Report on all deprecated uses; hence allUses
749 all_gres = globalRdrEnvElts (tcg_rdr_env tcg_env)
751 check hpt pit (GRE {gre_name = name, gre_prov = Imported (imp_spec:_)})
752 | name `elemNameSet` used_names
753 , Just deprec_txt <- lookupDeprec hpt pit name
754 = setSrcSpan (importSpecLoc imp_spec) $
755 addWarn (sep [ptext SLIT("Deprecated use of") <+>
756 pprNonVarNameSpace (occNameSpace (nameOccName name)) <+>
758 (parens imp_msg) <> colon,
761 name_mod = nameModule name
762 imp_mod = importSpecModule imp_spec
763 imp_msg = ptext SLIT("imported from") <+> ppr imp_mod <> extra
764 extra | imp_mod == name_mod = empty
765 | otherwise = ptext SLIT(", but defined in") <+> ppr name_mod
767 check hpt pit ok_gre = returnM () -- Local, or not used, or not deprectated
768 -- The Imported pattern-match: don't deprecate locally defined names
769 -- For a start, we may be exporting a deprecated thing
770 -- Also we may use a deprecated thing in the defn of another
771 -- deprecated things. We may even use a deprecated thing in
772 -- the defn of a non-deprecated thing, when changing a module's
775 lookupDeprec :: HomePackageTable -> PackageIfaceTable
776 -> Name -> Maybe DeprecTxt
777 lookupDeprec hpt pit n
778 = case lookupIface hpt pit (nameModule n) of
779 Just iface -> mi_dep_fn iface n `seqMaybe` -- Bleat if the thing, *or
780 mi_dep_fn iface (nameParent n) -- its parent*, is deprec'd
782 | isWiredInName n -> Nothing
783 -- We have not necessarily loaded the .hi file for a
784 -- wired-in name (yet), although we *could*.
785 -- And we never deprecate them
787 | otherwise -> pprPanic "lookupDeprec" (ppr n)
788 -- By now all the interfaces should have been loaded
790 gre_is_used :: NameSet -> GlobalRdrElt -> Bool
791 gre_is_used used_names gre = gre_name gre `elemNameSet` used_names
794 %*********************************************************
798 %*********************************************************
801 reportUnusedNames :: Maybe [LIE RdrName] -- Export list
802 -> TcGblEnv -> RnM ()
803 reportUnusedNames export_decls gbl_env
804 = do { traceRn ((text "RUN") <+> (ppr (tcg_dus gbl_env)))
805 ; warnUnusedTopBinds unused_locals
806 ; warnUnusedModules unused_imp_mods
807 ; warnUnusedImports unused_imports
808 ; warnDuplicateImports defined_and_used
809 ; printMinimalImports minimal_imports }
811 used_names, all_used_names :: NameSet
812 used_names = findUses (tcg_dus gbl_env) emptyNameSet
813 -- NB: currently, if f x = g, we only treat 'g' as used if 'f' is used
816 all_used_names = used_names `unionNameSets`
817 mkNameSet (mapCatMaybes nameParent_maybe (nameSetToList used_names))
818 -- A use of C implies a use of T,
819 -- if C was brought into scope by T(..) or T(C)
821 -- Collect the defined names from the in-scope environment
822 defined_names :: [GlobalRdrElt]
823 defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)
825 -- Note that defined_and_used, defined_but_not_used
826 -- are both [GRE]; that's why we need defined_and_used
827 -- rather than just all_used_names
828 defined_and_used, defined_but_not_used :: [GlobalRdrElt]
829 (defined_and_used, defined_but_not_used)
830 = partition (gre_is_used all_used_names) defined_names
832 -- Filter out the ones that are
833 -- (a) defined in this module, and
834 -- (b) not defined by a 'deriving' clause
835 -- The latter have an Internal Name, so we can filter them out easily
836 unused_locals :: [GlobalRdrElt]
837 unused_locals = filter is_unused_local defined_but_not_used
838 is_unused_local :: GlobalRdrElt -> Bool
839 is_unused_local gre = isLocalGRE gre && isExternalName (gre_name gre)
841 unused_imports :: [GlobalRdrElt]
842 unused_imports = filter unused_imp defined_but_not_used
843 unused_imp (GRE {gre_prov = Imported imp_specs})
844 = not (all (module_unused . importSpecModule) imp_specs)
845 && or [exp | ImpSpec { is_item = ImpSome { is_explicit = exp } } <- imp_specs]
846 -- Don't complain about unused imports if we've already said the
847 -- entire import is unused
848 unused_imp other = False
850 -- To figure out the minimal set of imports, start with the things
851 -- that are in scope (i.e. in gbl_env). Then just combine them
852 -- into a bunch of avails, so they are properly grouped
854 -- BUG WARNING: this does not deal properly with qualified imports!
855 minimal_imports :: FiniteMap Module AvailEnv
856 minimal_imports0 = foldr add_expall emptyFM expall_mods
857 minimal_imports1 = foldr add_name minimal_imports0 defined_and_used
858 minimal_imports = foldr add_inst_mod minimal_imports1 direct_import_mods
859 -- The last line makes sure that we retain all direct imports
860 -- even if we import nothing explicitly.
861 -- It's not necessarily redundant to import such modules. Consider
865 -- The import M() is not *necessarily* redundant, even if
866 -- we suck in no instance decls from M (e.g. it contains
867 -- no instance decls, or This contains no code). It may be
868 -- that we import M solely to ensure that M's orphan instance
869 -- decls (or those in its imports) are visible to people who
870 -- import This. Sigh.
871 -- There's really no good way to detect this, so the error message
872 -- in RnEnv.warnUnusedModules is weakened instead
874 -- We've carefully preserved the provenance so that we can
875 -- construct minimal imports that import the name by (one of)
876 -- the same route(s) as the programmer originally did.
877 add_name (GRE {gre_name = n, gre_prov = Imported imp_specs}) acc
878 = addToFM_C plusAvailEnv acc (importSpecModule (head imp_specs))
879 (unitAvailEnv (mk_avail n (nameParent_maybe n)))
883 -- Modules mentioned as 'module M' in the export list
884 expall_mods = case export_decls of
886 Just es -> [m | L _ (IEModuleContents m) <- es]
888 -- This is really bogus. The idea is that if we see 'module M' in
889 -- the export list we must retain the import decls that drive it
890 -- If we aren't careful we might see
891 -- module A( module M ) where
894 -- and suppose that N exports everything that M does. Then we
895 -- must not drop the import of M even though N brings it all into
898 -- BUG WARNING: 'module M' exports aside, what if M.x is mentioned?!
900 -- The reason that add_expall is bogus is that it doesn't take
901 -- qualified imports into account. But it's an improvement.
902 add_expall mod acc = addToFM_C plusAvailEnv acc mod emptyAvailEnv
904 -- n is the name of the thing, p is the name of its parent
905 mk_avail n (Just p) = AvailTC p [p,n]
906 mk_avail n Nothing | isTcOcc (nameOccName n) = AvailTC n [n]
907 | otherwise = Avail n
909 add_inst_mod (mod,_,_) acc
910 | mod `elemFM` acc = acc -- We import something already
911 | otherwise = addToFM acc mod emptyAvailEnv
913 -- Add an empty collection of imports for a module
914 -- from which we have sucked only instance decls
916 imports = tcg_imports gbl_env
918 direct_import_mods :: [(Module, Bool, SrcSpan)]
919 -- See the type of the imp_mods for this triple
920 direct_import_mods = moduleEnvElts (imp_mods imports)
922 -- unused_imp_mods are the directly-imported modules
923 -- that are not mentioned in minimal_imports1
924 -- [Note: not 'minimal_imports', because that includes directly-imported
925 -- modules even if we use nothing from them; see notes above]
927 -- BUG WARNING: does not deal correctly with multiple imports of the same module
928 -- becuase direct_import_mods has only one entry per module
929 unused_imp_mods = [(mod,loc) | (mod,no_imp,loc) <- direct_import_mods,
930 not (mod `elemFM` minimal_imports1),
933 -- The not no_imp part is not to complain about
934 -- import M (), which is an idiom for importing
935 -- instance declarations
937 module_unused :: Module -> Bool
938 module_unused mod = any (((==) mod) . fst) unused_imp_mods
940 ---------------------
941 warnDuplicateImports :: [GlobalRdrElt] -> RnM ()
942 -- Given the GREs for names that are used, figure out which imports
943 -- could be omitted without changing the top-level environment.
945 -- NB: Given import Foo( T )
946 -- import qualified Foo
947 -- we do not report a duplicate import, even though Foo.T is brought
948 -- into scope by both, because there's nothing you can *omit* without
949 -- changing the top-level environment. So we complain only if it's
950 -- explicitly named in both imports or neither.
952 -- Furthermore, we complain about Foo.T only if
953 -- there is no complaint about (unqualified) T
955 warnDuplicateImports gres
956 = ifOptM Opt_WarnUnusedImports $
957 sequenceM_ [ warn name pr
958 -- The 'head' picks the first offending group
959 -- for this particular name
960 | GRE { gre_name = name, gre_prov = Imported imps } <- gres
961 , pr <- redundants imps ]
963 warn name (red_imp, cov_imp)
964 = addWarnAt (importSpecLoc red_imp)
965 (vcat [ptext SLIT("Redundant import of:") <+> quotes pp_name,
966 ptext SLIT("It is also") <+> ppr cov_imp])
968 pp_name | is_qual red_decl = ppr (is_as red_decl) <> dot <> ppr occ
969 | otherwise = ppr occ
970 occ = nameOccName name
971 red_decl = is_decl red_imp
973 redundants :: [ImportSpec] -> [(ImportSpec,ImportSpec)]
974 -- The returned pair is (redundant-import, covering-import)
976 = [ (red_imp, cov_imp)
978 , cov_imp <- take 1 (filter (covers red_imp) imps) ]
980 -- "red_imp" is a putative redundant import
981 -- "cov_imp" potentially covers it
982 -- This test decides whether red_imp could be dropped
984 -- NOTE: currently the test does not warn about
987 -- even if the same underlying 'x' is involved, because dropping
988 -- either import would change the qualified names in scope (M.x, N.x)
989 -- But if the qualified names aren't used, the import is indeed redundant
990 -- Sadly we don't know that. Oh well.
991 covers red_imp@(ImpSpec { is_decl = red_decl, is_item = red_item })
992 cov_imp@(ImpSpec { is_decl = cov_decl, is_item = cov_item })
994 = False -- Ignore diagonal elements
995 | not (is_as red_decl == is_as cov_decl)
996 = False -- They bring into scope different qualified names
997 | not (is_qual red_decl) && is_qual cov_decl
998 = False -- Covering one doesn't bring unqualified name into scope
1000 = not cov_selective -- Redundant one is selective and covering one isn't
1001 || red_later -- Both are explicit; tie-break using red_later
1003 = not cov_selective -- Neither import is selective
1004 && (is_mod red_decl == is_mod cov_decl) -- They import the same module
1005 && red_later -- Tie-break
1007 red_loc = importSpecLoc red_imp
1008 cov_loc = importSpecLoc cov_imp
1009 red_later = red_loc > cov_loc
1010 cov_selective = selectiveImpItem cov_item
1011 red_selective = selectiveImpItem red_item
1013 selectiveImpItem :: ImpItemSpec -> Bool
1014 selectiveImpItem ImpAll = False
1015 selectiveImpItem (ImpSome {}) = True
1017 -- ToDo: deal with original imports with 'qualified' and 'as M' clauses
1018 printMinimalImports :: FiniteMap Module AvailEnv -- Minimal imports
1020 printMinimalImports imps
1021 = ifOptM Opt_D_dump_minimal_imports $ do {
1023 mod_ies <- mappM to_ies (fmToList imps) ;
1024 this_mod <- getModule ;
1025 rdr_env <- getGlobalRdrEnv ;
1026 ioToTcRn (do { h <- openFile (mkFilename this_mod) WriteMode ;
1027 printForUser h (unQualInScope rdr_env)
1028 (vcat (map ppr_mod_ie mod_ies)) })
1031 mkFilename this_mod = moduleString this_mod ++ ".imports"
1032 ppr_mod_ie (mod_name, ies)
1033 | mod_name == pRELUDE
1035 | null ies -- Nothing except instances comes from here
1036 = ptext SLIT("import") <+> ppr mod_name <> ptext SLIT("() -- Instances only")
1038 = ptext SLIT("import") <+> ppr mod_name <>
1039 parens (fsep (punctuate comma (map ppr ies)))
1041 to_ies (mod, avail_env) = do ies <- mapM to_ie (availEnvElts avail_env)
1044 to_ie :: AvailInfo -> RnM (IE Name)
1045 -- The main trick here is that if we're importing all the constructors
1046 -- we want to say "T(..)", but if we're importing only a subset we want
1047 -- to say "T(A,B,C)". So we have to find out what the module exports.
1048 to_ie (Avail n) = returnM (IEVar n)
1049 to_ie (AvailTC n [m]) = ASSERT( n==m )
1050 returnM (IEThingAbs n)
1051 to_ie (AvailTC n ns)
1052 = loadSrcInterface doc n_mod False `thenM` \ iface ->
1053 case [xs | (m,as) <- mi_exports iface,
1056 x == nameOccName n] of
1057 [xs] | all_used xs -> returnM (IEThingAll n)
1058 | otherwise -> returnM (IEThingWith n (filter (/= n) ns))
1059 other -> pprTrace "to_ie" (ppr n <+> ppr n_mod <+> ppr other) $
1062 all_used avail_occs = all (`elem` map nameOccName ns) avail_occs
1063 doc = text "Compute minimal imports from" <+> ppr n
1064 n_mod = nameModule n
1068 %************************************************************************
1072 %************************************************************************
1075 badImportItemErr iface decl_spec ie
1076 = sep [ptext SLIT("Module"), quotes (ppr (is_mod decl_spec)), source_import,
1077 ptext SLIT("does not export"), quotes (ppr ie)]
1079 source_import | mi_boot iface = ptext SLIT("(hi-boot interface)")
1082 dodgyImportWarn item = dodgyMsg (ptext SLIT("import")) item
1083 dodgyExportWarn item = dodgyMsg (ptext SLIT("export")) item
1086 = sep [ ptext SLIT("The") <+> kind <+> ptext SLIT("item") <+> quotes (ppr (IEThingAll tc)),
1087 ptext SLIT("suggests that") <+> quotes (ppr tc) <+> ptext SLIT("has constructor or class methods"),
1088 ptext SLIT("but it has none; it is a type synonym or abstract type or class") ]
1091 = hsep [ ptext SLIT("Unknown module in export list: module"), quotes (ppr mod)]
1093 exportItemErr export_item
1094 = sep [ ptext SLIT("The export item") <+> quotes (ppr export_item),
1095 ptext SLIT("attempts to export constructors or class methods that are not visible here") ]
1097 exportClashErr global_env name1 name2 ie1 ie2
1098 = vcat [ ptext SLIT("Conflicting exports for") <+> quotes (ppr occ) <> colon
1099 , ppr_export ie1 name1
1100 , ppr_export ie2 name2 ]
1102 occ = nameOccName name1
1103 ppr_export ie name = nest 2 (quotes (ppr ie) <+> ptext SLIT("exports") <+>
1104 quotes (ppr name) <+> pprNameProvenance (get_gre name))
1106 -- get_gre finds a GRE for the Name, so that we can show its provenance
1108 = case lookupGRE_Name global_env name of
1110 [] -> pprPanic "exportClashErr" (ppr name)
1112 addDupDeclErr :: Name -> Name -> TcRn ()
1113 addDupDeclErr name_a name_b
1114 = addErrAt (srcLocSpan loc2) $
1115 vcat [ptext SLIT("Multiple declarations of") <+> quotes (ppr name1),
1116 ptext SLIT("Declared at:") <+> vcat [ppr (nameSrcLoc name1), ppr loc2]]
1118 loc2 = nameSrcLoc name2
1119 (name1,name2) | nameSrcLoc name_a > nameSrcLoc name_b = (name_b,name_a)
1120 | otherwise = (name_a,name_b)
1121 -- Report the error at the later location
1123 dupExportWarn occ_name ie1 ie2
1124 = hsep [quotes (ppr occ_name),
1125 ptext SLIT("is exported by"), quotes (ppr ie1),
1126 ptext SLIT("and"), quotes (ppr ie2)]
1129 = hsep [ptext SLIT("Duplicate"),
1130 quotes (ptext SLIT("Module") <+> ppr mod),
1131 ptext SLIT("in export list")]
1133 moduleDeprec mod txt
1134 = sep [ ptext SLIT("Module") <+> quotes (ppr mod) <+> ptext SLIT("is deprecated:"),