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 RdrName)
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)
565 rnExport (IEVar rdrName)
566 = do name <- lookupGlobalOccRn rdrName
568 rnExport (IEThingAbs rdrName)
569 = do name <- lookupGlobalOccRn rdrName
570 return (IEThingAbs name)
571 rnExport (IEThingAll rdrName)
572 = do name <- lookupGlobalOccRn rdrName
573 return (IEThingAll name)
574 rnExport ie@(IEThingWith rdrName rdrNames)
575 = do name <- lookupGlobalOccRn rdrName
576 if isUnboundName name
577 then return (IEThingWith name [])
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 do addErr (exportItemErr ie)
583 return (IEThingWith name [])
584 else return (IEThingWith name (catMaybes mb_names))
585 rnExport (IEModuleContents mod)
586 = return (IEModuleContents mod)
587 rn_exports <- mapM (wrapLocM rnExport) exports
588 return (Just rn_exports)
590 mkExportNameSet :: Bool -- False => no 'module M(..) where' header at all
591 -> Maybe ([LIE Name], [LIE RdrName]) -- 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 ,[noLoc (IEVar main_RDR_Unqual)]))
617 -- ToDo: the 'noLoc' here is unhelpful if 'main' turns out to be out of scope
618 exports_from_avail real_exports rdr_env imports
621 exports_from_avail Nothing rdr_env imports
622 = -- Export all locally-defined things
623 -- We do this by filtering the global RdrEnv,
624 -- keeping only things that are locally-defined
625 return (mkNameSet [ gre_name gre
626 | gre <- globalRdrEnvElts rdr_env,
629 exports_from_avail (Just (items,origItems)) rdr_env (ImportAvails { imp_env = imp_env })
630 = do (_, _, exports) <- foldlM do_litem emptyExportAccum (zip items origItems)
633 sub_env :: NameEnv [Name] -- Classify each name by its parent
634 sub_env = mkSubNameEnv (foldModuleEnv unionNameSets emptyNameSet imp_env)
636 do_litem :: ExportAccum -> (LIE Name, LIE RdrName) -> RnM ExportAccum
637 do_litem acc (ieName, ieRdr)
638 = addLocM (exports_from_item acc (unLoc ieRdr)) ieName
640 exports_from_item :: ExportAccum -> IE RdrName -> IE Name -> RnM ExportAccum
641 exports_from_item acc@(mods, occs, exports) ieRdr@(IEModuleContents mod) ie
642 | mod `elem` mods -- Duplicate export of M
643 = do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
644 warnIf warn_dup_exports (dupModuleExport mod) ;
648 = case lookupModuleEnv imp_env mod of
649 Nothing -> do addErr (modExportErr mod)
652 -> do let new_exports = filterNameSet (inScopeUnqual rdr_env) names
653 -- This check_occs not only finds conflicts between this item
654 -- and others, but also internally within this item. That is,
655 -- if 'M.x' is in scope in several ways, we'll have several
656 -- members of mod_avails with the same OccName.
657 occs' <- check_occs ieRdr occs (nameSetToList new_exports)
658 return (mod:mods, occs', exports `unionNameSets` new_exports)
660 exports_from_item acc@(mods, occs, exports) ieRdr ie
661 = if isUnboundName (ieName ie)
662 then return acc -- Avoid error cascade
663 else let new_exports = filterAvail ie sub_env in
664 do -- checkErr (not (null (drop 1 new_exports))) (exportItemErr ie)
665 checkForDodgyExport ie new_exports
666 occs' <- check_occs ieRdr occs new_exports
667 return (mods, occs', addListToNameSet exports new_exports)
669 -------------------------------
670 filterAvail :: IE Name -- Wanted
671 -> NameEnv [Name] -- Maps type/class names to their sub-names
674 filterAvail (IEVar n) subs = [n]
675 filterAvail (IEThingAbs n) subs = [n]
676 filterAvail (IEThingAll n) subs = n : subNames subs n
677 filterAvail (IEThingWith n ns) subs = n : ns
678 filterAvail (IEModuleContents _) _ = panic "filterAvail"
680 subNames :: NameEnv [Name] -> Name -> [Name]
681 subNames env n = lookupNameEnv env n `orElse` []
683 mkSubNameEnv :: NameSet -> NameEnv [Name]
684 -- Maps types and classes to their constructors/classops respectively
685 -- This mapping just makes it easier to deal with A(..) export items
687 = foldNameSet add_name emptyNameEnv names
690 | Just parent <- nameParent_maybe name
691 = extendNameEnv_C (\ns _ -> name:ns) env parent [name]
694 -------------------------------
695 inScopeUnqual :: GlobalRdrEnv -> Name -> Bool
696 -- Checks whether the Name is in scope unqualified,
697 -- regardless of whether it's ambiguous or not
698 inScopeUnqual env n = any unQualOK (lookupGRE_Name env n)
700 -------------------------------
701 checkForDodgyExport :: IE Name -> [Name] -> RnM ()
702 checkForDodgyExport ie@(IEThingAll tc) [n]
703 | isTcOcc (nameOccName n) = addWarn (dodgyExportWarn tc)
704 -- This occurs when you export T(..), but
705 -- only import T abstractly, or T is a synonym.
706 -- The single [n] is the type or class itself
707 | otherwise = addErr (exportItemErr ie)
708 -- This happes if you export x(..), which is bogus
709 checkForDodgyExport _ _ = return ()
711 -------------------------------
712 check_occs :: IE RdrName -> ExportOccMap -> [Name] -> RnM ExportOccMap
713 check_occs ie occs names
714 = foldlM check occs names
717 = case lookupOccEnv occs name_occ of
718 Nothing -> returnM (extendOccEnv occs name_occ (name, ie))
721 | name == name' -- Duplicate export
722 -> do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
723 warnIf warn_dup_exports (dupExportWarn name_occ ie ie') ;
726 | otherwise -- Same occ name but different names: an error
727 -> do { global_env <- getGlobalRdrEnv ;
728 addErr (exportClashErr global_env name name' ie ie') ;
731 name_occ = nameOccName name
734 %*********************************************************
738 %*********************************************************
741 reportDeprecations :: TcGblEnv -> RnM ()
742 reportDeprecations tcg_env
743 = ifOptM Opt_WarnDeprecations $
744 do { (eps,hpt) <- getEpsAndHpt
745 -- By this time, typechecking is complete,
746 -- so the PIT is fully populated
747 ; mapM_ (check hpt (eps_PIT eps)) all_gres }
749 used_names = allUses (tcg_dus tcg_env)
750 -- Report on all deprecated uses; hence allUses
751 all_gres = globalRdrEnvElts (tcg_rdr_env tcg_env)
753 check hpt pit (GRE {gre_name = name, gre_prov = Imported (imp_spec:_)})
754 | name `elemNameSet` used_names
755 , Just deprec_txt <- lookupDeprec hpt pit name
756 = setSrcSpan (importSpecLoc imp_spec) $
757 addWarn (sep [ptext SLIT("Deprecated use of") <+>
758 pprNonVarNameSpace (occNameSpace (nameOccName name)) <+>
760 (parens imp_msg) <> colon,
763 name_mod = nameModule name
764 imp_mod = importSpecModule imp_spec
765 imp_msg = ptext SLIT("imported from") <+> ppr imp_mod <> extra
766 extra | imp_mod == name_mod = empty
767 | otherwise = ptext SLIT(", but defined in") <+> ppr name_mod
769 check hpt pit ok_gre = returnM () -- Local, or not used, or not deprectated
770 -- The Imported pattern-match: don't deprecate locally defined names
771 -- For a start, we may be exporting a deprecated thing
772 -- Also we may use a deprecated thing in the defn of another
773 -- deprecated things. We may even use a deprecated thing in
774 -- the defn of a non-deprecated thing, when changing a module's
777 lookupDeprec :: HomePackageTable -> PackageIfaceTable
778 -> Name -> Maybe DeprecTxt
779 lookupDeprec hpt pit n
780 = case lookupIface hpt pit (nameModule n) of
781 Just iface -> mi_dep_fn iface n `seqMaybe` -- Bleat if the thing, *or
782 mi_dep_fn iface (nameParent n) -- its parent*, is deprec'd
784 | isWiredInName n -> Nothing
785 -- We have not necessarily loaded the .hi file for a
786 -- wired-in name (yet), although we *could*.
787 -- And we never deprecate them
789 | otherwise -> pprPanic "lookupDeprec" (ppr n)
790 -- By now all the interfaces should have been loaded
792 gre_is_used :: NameSet -> GlobalRdrElt -> Bool
793 gre_is_used used_names gre = gre_name gre `elemNameSet` used_names
796 %*********************************************************
800 %*********************************************************
803 reportUnusedNames :: Maybe [LIE RdrName] -- Export list
804 -> TcGblEnv -> RnM ()
805 reportUnusedNames export_decls gbl_env
806 = do { traceRn ((text "RUN") <+> (ppr (tcg_dus gbl_env)))
807 ; warnUnusedTopBinds unused_locals
808 ; warnUnusedModules unused_imp_mods
809 ; warnUnusedImports unused_imports
810 ; warnDuplicateImports defined_and_used
811 ; printMinimalImports minimal_imports }
813 used_names, all_used_names :: NameSet
814 used_names = findUses (tcg_dus gbl_env) emptyNameSet
815 -- NB: currently, if f x = g, we only treat 'g' as used if 'f' is used
818 all_used_names = used_names `unionNameSets`
819 mkNameSet (mapCatMaybes nameParent_maybe (nameSetToList used_names))
820 -- A use of C implies a use of T,
821 -- if C was brought into scope by T(..) or T(C)
823 -- Collect the defined names from the in-scope environment
824 defined_names :: [GlobalRdrElt]
825 defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)
827 -- Note that defined_and_used, defined_but_not_used
828 -- are both [GRE]; that's why we need defined_and_used
829 -- rather than just all_used_names
830 defined_and_used, defined_but_not_used :: [GlobalRdrElt]
831 (defined_and_used, defined_but_not_used)
832 = partition (gre_is_used all_used_names) defined_names
834 -- Filter out the ones that are
835 -- (a) defined in this module, and
836 -- (b) not defined by a 'deriving' clause
837 -- The latter have an Internal Name, so we can filter them out easily
838 unused_locals :: [GlobalRdrElt]
839 unused_locals = filter is_unused_local defined_but_not_used
840 is_unused_local :: GlobalRdrElt -> Bool
841 is_unused_local gre = isLocalGRE gre && isExternalName (gre_name gre)
843 unused_imports :: [GlobalRdrElt]
844 unused_imports = filter unused_imp defined_but_not_used
845 unused_imp (GRE {gre_prov = Imported imp_specs})
846 = not (all (module_unused . importSpecModule) imp_specs)
847 && or [exp | ImpSpec { is_item = ImpSome { is_explicit = exp } } <- imp_specs]
848 -- Don't complain about unused imports if we've already said the
849 -- entire import is unused
850 unused_imp other = False
852 -- To figure out the minimal set of imports, start with the things
853 -- that are in scope (i.e. in gbl_env). Then just combine them
854 -- into a bunch of avails, so they are properly grouped
856 -- BUG WARNING: this does not deal properly with qualified imports!
857 minimal_imports :: FiniteMap Module AvailEnv
858 minimal_imports0 = foldr add_expall emptyFM expall_mods
859 minimal_imports1 = foldr add_name minimal_imports0 defined_and_used
860 minimal_imports = foldr add_inst_mod minimal_imports1 direct_import_mods
861 -- The last line makes sure that we retain all direct imports
862 -- even if we import nothing explicitly.
863 -- It's not necessarily redundant to import such modules. Consider
867 -- The import M() is not *necessarily* redundant, even if
868 -- we suck in no instance decls from M (e.g. it contains
869 -- no instance decls, or This contains no code). It may be
870 -- that we import M solely to ensure that M's orphan instance
871 -- decls (or those in its imports) are visible to people who
872 -- import This. Sigh.
873 -- There's really no good way to detect this, so the error message
874 -- in RnEnv.warnUnusedModules is weakened instead
876 -- We've carefully preserved the provenance so that we can
877 -- construct minimal imports that import the name by (one of)
878 -- the same route(s) as the programmer originally did.
879 add_name (GRE {gre_name = n, gre_prov = Imported imp_specs}) acc
880 = addToFM_C plusAvailEnv acc (importSpecModule (head imp_specs))
881 (unitAvailEnv (mk_avail n (nameParent_maybe n)))
885 -- Modules mentioned as 'module M' in the export list
886 expall_mods = case export_decls of
888 Just es -> [m | L _ (IEModuleContents m) <- es]
890 -- This is really bogus. The idea is that if we see 'module M' in
891 -- the export list we must retain the import decls that drive it
892 -- If we aren't careful we might see
893 -- module A( module M ) where
896 -- and suppose that N exports everything that M does. Then we
897 -- must not drop the import of M even though N brings it all into
900 -- BUG WARNING: 'module M' exports aside, what if M.x is mentioned?!
902 -- The reason that add_expall is bogus is that it doesn't take
903 -- qualified imports into account. But it's an improvement.
904 add_expall mod acc = addToFM_C plusAvailEnv acc mod emptyAvailEnv
906 -- n is the name of the thing, p is the name of its parent
907 mk_avail n (Just p) = AvailTC p [p,n]
908 mk_avail n Nothing | isTcOcc (nameOccName n) = AvailTC n [n]
909 | otherwise = Avail n
911 add_inst_mod (mod,_,_) acc
912 | mod `elemFM` acc = acc -- We import something already
913 | otherwise = addToFM acc mod emptyAvailEnv
915 -- Add an empty collection of imports for a module
916 -- from which we have sucked only instance decls
918 imports = tcg_imports gbl_env
920 direct_import_mods :: [(Module, Bool, SrcSpan)]
921 -- See the type of the imp_mods for this triple
922 direct_import_mods = moduleEnvElts (imp_mods imports)
924 -- unused_imp_mods are the directly-imported modules
925 -- that are not mentioned in minimal_imports1
926 -- [Note: not 'minimal_imports', because that includes directly-imported
927 -- modules even if we use nothing from them; see notes above]
929 -- BUG WARNING: does not deal correctly with multiple imports of the same module
930 -- becuase direct_import_mods has only one entry per module
931 unused_imp_mods = [(mod,loc) | (mod,no_imp,loc) <- direct_import_mods,
932 not (mod `elemFM` minimal_imports1),
935 -- The not no_imp part is not to complain about
936 -- import M (), which is an idiom for importing
937 -- instance declarations
939 module_unused :: Module -> Bool
940 module_unused mod = any (((==) mod) . fst) unused_imp_mods
942 ---------------------
943 warnDuplicateImports :: [GlobalRdrElt] -> RnM ()
944 -- Given the GREs for names that are used, figure out which imports
945 -- could be omitted without changing the top-level environment.
947 -- NB: Given import Foo( T )
948 -- import qualified Foo
949 -- we do not report a duplicate import, even though Foo.T is brought
950 -- into scope by both, because there's nothing you can *omit* without
951 -- changing the top-level environment. So we complain only if it's
952 -- explicitly named in both imports or neither.
954 -- Furthermore, we complain about Foo.T only if
955 -- there is no complaint about (unqualified) T
957 warnDuplicateImports gres
958 = ifOptM Opt_WarnUnusedImports $
959 sequenceM_ [ warn name pr
960 -- The 'head' picks the first offending group
961 -- for this particular name
962 | GRE { gre_name = name, gre_prov = Imported imps } <- gres
963 , pr <- redundants imps ]
965 warn name (red_imp, cov_imp)
966 = addWarnAt (importSpecLoc red_imp)
967 (vcat [ptext SLIT("Redundant import of:") <+> quotes pp_name,
968 ptext SLIT("It is also") <+> ppr cov_imp])
970 pp_name | is_qual red_decl = ppr (is_as red_decl) <> dot <> ppr occ
971 | otherwise = ppr occ
972 occ = nameOccName name
973 red_decl = is_decl red_imp
975 redundants :: [ImportSpec] -> [(ImportSpec,ImportSpec)]
976 -- The returned pair is (redundant-import, covering-import)
978 = [ (red_imp, cov_imp)
980 , cov_imp <- take 1 (filter (covers red_imp) imps) ]
982 -- "red_imp" is a putative redundant import
983 -- "cov_imp" potentially covers it
984 -- This test decides whether red_imp could be dropped
986 -- NOTE: currently the test does not warn about
989 -- even if the same underlying 'x' is involved, because dropping
990 -- either import would change the qualified names in scope (M.x, N.x)
991 -- But if the qualified names aren't used, the import is indeed redundant
992 -- Sadly we don't know that. Oh well.
993 covers red_imp@(ImpSpec { is_decl = red_decl, is_item = red_item })
994 cov_imp@(ImpSpec { is_decl = cov_decl, is_item = cov_item })
996 = False -- Ignore diagonal elements
997 | not (is_as red_decl == is_as cov_decl)
998 = False -- They bring into scope different qualified names
999 | not (is_qual red_decl) && is_qual cov_decl
1000 = False -- Covering one doesn't bring unqualified name into scope
1002 = not cov_selective -- Redundant one is selective and covering one isn't
1003 || red_later -- Both are explicit; tie-break using red_later
1005 = not cov_selective -- Neither import is selective
1006 && (is_mod red_decl == is_mod cov_decl) -- They import the same module
1007 && red_later -- Tie-break
1009 red_loc = importSpecLoc red_imp
1010 cov_loc = importSpecLoc cov_imp
1011 red_later = red_loc > cov_loc
1012 cov_selective = selectiveImpItem cov_item
1013 red_selective = selectiveImpItem red_item
1015 selectiveImpItem :: ImpItemSpec -> Bool
1016 selectiveImpItem ImpAll = False
1017 selectiveImpItem (ImpSome {}) = True
1019 -- ToDo: deal with original imports with 'qualified' and 'as M' clauses
1020 printMinimalImports :: FiniteMap Module AvailEnv -- Minimal imports
1022 printMinimalImports imps
1023 = ifOptM Opt_D_dump_minimal_imports $ do {
1025 mod_ies <- mappM to_ies (fmToList imps) ;
1026 this_mod <- getModule ;
1027 rdr_env <- getGlobalRdrEnv ;
1028 ioToTcRn (do { h <- openFile (mkFilename this_mod) WriteMode ;
1029 printForUser h (unQualInScope rdr_env)
1030 (vcat (map ppr_mod_ie mod_ies)) })
1033 mkFilename this_mod = moduleString this_mod ++ ".imports"
1034 ppr_mod_ie (mod_name, ies)
1035 | mod_name == pRELUDE
1037 | null ies -- Nothing except instances comes from here
1038 = ptext SLIT("import") <+> ppr mod_name <> ptext SLIT("() -- Instances only")
1040 = ptext SLIT("import") <+> ppr mod_name <>
1041 parens (fsep (punctuate comma (map ppr ies)))
1043 to_ies (mod, avail_env) = do ies <- mapM to_ie (availEnvElts avail_env)
1046 to_ie :: AvailInfo -> RnM (IE Name)
1047 -- The main trick here is that if we're importing all the constructors
1048 -- we want to say "T(..)", but if we're importing only a subset we want
1049 -- to say "T(A,B,C)". So we have to find out what the module exports.
1050 to_ie (Avail n) = returnM (IEVar n)
1051 to_ie (AvailTC n [m]) = ASSERT( n==m )
1052 returnM (IEThingAbs n)
1053 to_ie (AvailTC n ns)
1054 = loadSrcInterface doc n_mod False `thenM` \ iface ->
1055 case [xs | (m,as) <- mi_exports iface,
1058 x == nameOccName n] of
1059 [xs] | all_used xs -> returnM (IEThingAll n)
1060 | otherwise -> returnM (IEThingWith n (filter (/= n) ns))
1061 other -> pprTrace "to_ie" (ppr n <+> ppr n_mod <+> ppr other) $
1064 all_used avail_occs = all (`elem` map nameOccName ns) avail_occs
1065 doc = text "Compute minimal imports from" <+> ppr n
1066 n_mod = nameModule n
1070 %************************************************************************
1074 %************************************************************************
1077 badImportItemErr iface decl_spec ie
1078 = sep [ptext SLIT("Module"), quotes (ppr (is_mod decl_spec)), source_import,
1079 ptext SLIT("does not export"), quotes (ppr ie)]
1081 source_import | mi_boot iface = ptext SLIT("(hi-boot interface)")
1084 dodgyImportWarn item = dodgyMsg (ptext SLIT("import")) item
1085 dodgyExportWarn item = dodgyMsg (ptext SLIT("export")) item
1088 = sep [ ptext SLIT("The") <+> kind <+> ptext SLIT("item") <+> quotes (ppr (IEThingAll tc)),
1089 ptext SLIT("suggests that") <+> quotes (ppr tc) <+> ptext SLIT("has constructor or class methods"),
1090 ptext SLIT("but it has none; it is a type synonym or abstract type or class") ]
1093 = hsep [ ptext SLIT("Unknown module in export list: module"), quotes (ppr mod)]
1095 exportItemErr export_item
1096 = sep [ ptext SLIT("The export item") <+> quotes (ppr export_item),
1097 ptext SLIT("attempts to export constructors or class methods that are not visible here") ]
1099 exportClashErr global_env name1 name2 ie1 ie2
1100 = vcat [ ptext SLIT("Conflicting exports for") <+> quotes (ppr occ) <> colon
1101 , ppr_export ie1 name1
1102 , ppr_export ie2 name2 ]
1104 occ = nameOccName name1
1105 ppr_export ie name = nest 2 (quotes (ppr ie) <+> ptext SLIT("exports") <+>
1106 quotes (ppr name) <+> pprNameProvenance (get_gre name))
1108 -- get_gre finds a GRE for the Name, so that we can show its provenance
1110 = case lookupGRE_Name global_env name of
1112 [] -> pprPanic "exportClashErr" (ppr name)
1114 addDupDeclErr :: Name -> Name -> TcRn ()
1115 addDupDeclErr name_a name_b
1116 = addErrAt (srcLocSpan loc2) $
1117 vcat [ptext SLIT("Multiple declarations of") <+> quotes (ppr name1),
1118 ptext SLIT("Declared at:") <+> vcat [ppr (nameSrcLoc name1), ppr loc2]]
1120 loc2 = nameSrcLoc name2
1121 (name1,name2) | nameSrcLoc name_a > nameSrcLoc name_b = (name_b,name_a)
1122 | otherwise = (name_a,name_b)
1123 -- Report the error at the later location
1125 dupExportWarn occ_name ie1 ie2
1126 = hsep [quotes (ppr occ_name),
1127 ptext SLIT("is exported by"), quotes (ppr ie1),
1128 ptext SLIT("and"), quotes (ppr ie2)]
1131 = hsep [ptext SLIT("Duplicate"),
1132 quotes (ptext SLIT("Module") <+> ppr mod),
1133 ptext SLIT("in export list")]
1135 moduleDeprec mod txt
1136 = sep [ ptext SLIT("Module") <+> quotes (ppr mod) <+> ptext SLIT("is deprecated:"),