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(..), DynFlags(..) )
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)
29 import Name ( Name, nameSrcLoc, nameOccName, nameModule, isWiredInName,
30 nameParent, nameParent_maybe, isExternalName,
34 import OccName ( srcDataName, isTcOcc, pprNonVarNameSpace,
36 OccEnv, mkOccEnv, lookupOccEnv, emptyOccEnv,
38 import HscTypes ( GenAvailInfo(..), AvailInfo,
39 HomePackageTable, PackageIfaceTable,
41 Deprecs(..), ModIface(..), Dependencies(..),
42 lookupIfaceByModule, ExternalPackageState(..)
44 import RdrName ( RdrName, rdrNameOcc, setRdrNameSpace,
45 GlobalRdrEnv, mkGlobalRdrEnv, GlobalRdrElt(..),
46 emptyGlobalRdrEnv, plusGlobalRdrEnv, globalRdrEnvElts,
47 extendGlobalRdrEnv, lookupGlobalRdrEnv, unQualOK, lookupGRE_Name,
48 Provenance(..), ImportSpec(..), ImpDeclSpec(..), ImpItemSpec(..),
49 importSpecLoc, importSpecModule, isLocalGRE, pprNameProvenance )
52 import Maybes ( isNothing, catMaybes, mapCatMaybes, seqMaybe, orElse )
53 import SrcLoc ( Located(..), mkGeneralSrcSpan,
54 unLoc, noLoc, srcLocSpan, SrcSpan )
55 import BasicTypes ( DeprecTxt )
56 import DriverPhases ( isHsBoot )
57 import Util ( notNull )
58 import List ( partition )
59 import IO ( openFile, IOMode(..) )
64 %************************************************************************
68 %************************************************************************
71 rnImports :: [LImportDecl RdrName] -> RnM [LImportDecl Name]
73 -- PROCESS IMPORT DECLS
74 -- Do the non {- SOURCE -} ones first, so that we get a helpful
75 -- warning for {- SOURCE -} ones that are unnecessary
76 = do this_mod <- getModule
77 implicit_prelude <- doptM Opt_ImplicitPrelude
78 let all_imports = mk_prel_imports this_mod implicit_prelude ++ imports
79 (source, ordinary) = partition is_source_import all_imports
80 is_source_import (L _ (ImportDecl _ is_boot _ _ _)) = is_boot
81 get_imports = rnImportDecl this_mod
83 stuff1 <- mapM get_imports ordinary
84 stuff2 <- mapM get_imports source
85 return (stuff1 ++ stuff2)
87 -- NB: opt_NoImplicitPrelude is slightly different to import Prelude ();
88 -- because the former doesn't even look at Prelude.hi for instance
89 -- declarations, whereas the latter does.
90 mk_prel_imports this_mod implicit_prelude
92 || explicit_prelude_import
93 || not implicit_prelude
95 | otherwise = [preludeImportDecl]
96 explicit_prelude_import
97 = notNull [ () | L _ (ImportDecl mod _ _ _ _) <- imports,
98 unLoc mod == pRELUDE_NAME ]
100 preludeImportDecl :: LImportDecl RdrName
103 ImportDecl (L loc pRELUDE_NAME)
104 False {- Not a boot interface -}
105 False {- Not qualified -}
106 Nothing {- No "as" -}
107 Nothing {- No import list -}
109 loc = mkGeneralSrcSpan FSLIT("Implicit import declaration")
111 mkRdrEnvAndImports :: [LImportDecl Name] -> RnM (GlobalRdrEnv, ImportAvails)
112 mkRdrEnvAndImports imports
113 = do this_mod <- getModule
114 let get_imports = importsFromImportDecl this_mod
115 stuff <- mapM get_imports imports
116 let (imp_gbl_envs, imp_avails) = unzip stuff
117 gbl_env :: GlobalRdrEnv
118 gbl_env = foldr plusGlobalRdrEnv emptyGlobalRdrEnv imp_gbl_envs
120 all_avails :: ImportAvails
121 all_avails = foldr plusImportAvails emptyImportAvails imp_avails
123 return (gbl_env, all_avails)
128 rnImportDecl :: Module
129 -> LImportDecl RdrName
130 -> RnM (LImportDecl Name)
131 rnImportDecl this_mod (L loc importDecl@(ImportDecl loc_imp_mod_name want_boot qual_only as_mod imp_details))
133 do iface <- loadSrcInterface doc imp_mod_name want_boot
134 let qual_mod_name = case as_mod of
135 Nothing -> imp_mod_name
136 Just another_name -> another_name
137 imp_spec = ImpDeclSpec { is_mod = imp_mod_name, is_qual = qual_only,
138 is_dloc = loc, is_as = qual_mod_name }
139 total_avails <- ifaceExportNames (mi_exports iface)
140 importDecl' <- rnImportDecl' iface imp_spec importDecl total_avails
141 return (L loc importDecl')
142 where imp_mod_name = unLoc loc_imp_mod_name
143 doc = ppr imp_mod_name <+> ptext SLIT("is directly imported")
145 rnImportDecl' :: ModIface -> ImpDeclSpec -> ImportDecl RdrName -> NameSet -> RnM (ImportDecl Name)
146 rnImportDecl' iface decl_spec (ImportDecl mod_name want_boot qual_only as_mod Nothing) all_names
147 = return $ ImportDecl mod_name want_boot qual_only as_mod Nothing
148 rnImportDecl' iface decl_spec (ImportDecl mod_name want_boot qual_only as_mod (Just (want_hiding,import_items))) all_names
149 = do import_items_mbs <- mapM (srcSpanWrapper) import_items
150 let rn_import_items = concat . catMaybes $ import_items_mbs
151 return $ ImportDecl mod_name want_boot qual_only as_mod (Just (want_hiding,rn_import_items))
153 srcSpanWrapper (L span ieRdr)
154 = case get_item ieRdr of
156 -> do addErrAt span (badImportItemErr iface decl_spec ieRdr)
159 -> return (Just [L span ie | ie <- ieNames])
160 occ_env :: OccEnv Name -- Maps OccName to corresponding Name
161 occ_env = mkOccEnv [(nameOccName n, n) | n <- nameSetToList all_names]
162 -- This env will have entries for data constructors too,
163 -- they won't make any difference because naked entities like T
164 -- in an import list map to TcOccs, not VarOccs.
166 sub_env :: NameEnv [Name]
167 sub_env = mkSubNameEnv all_names
169 get_item :: IE RdrName -> Maybe [IE Name]
170 -- Empty result for a bad item.
171 -- Singleton result is typical case.
172 -- Can have two when we are hiding, and mention C which might be
173 -- both a class and a data constructor.
174 get_item item@(IEModuleContents _)
176 get_item (IEThingAll tc)
177 = do name <- check_name tc
178 return [IEThingAll name]
179 get_item (IEThingAbs tc)
180 | want_hiding -- hiding ( C )
181 -- Here the 'C' can be a data constructor
182 -- *or* a type/class, or even both
183 = case catMaybes [check_name tc, check_name (setRdrNameSpace tc srcDataName)] of
185 names -> return [ IEThingAbs n | n <- names ]
187 = do name <- check_name tc
188 return [IEThingAbs name]
189 get_item (IEThingWith n ns) -- import (C (A,B))
190 = do name <- check_name n
191 let env = mkOccEnv [(nameOccName s, s) | s <- subNames sub_env name]
192 mb_names = map (lookupOccEnv env . rdrNameOcc) ns
193 names <- sequence mb_names
194 return [IEThingWith name names]
196 = do name <- check_name n
199 check_name :: RdrName -> Maybe Name
201 = lookupOccEnv occ_env (rdrNameOcc rdrName)
204 importsFromImportDecl :: Module
206 -> RnM (GlobalRdrEnv, ImportAvails)
208 importsFromImportDecl this_mod
209 (L loc (ImportDecl loc_imp_mod_name want_boot qual_only as_mod imp_details))
213 -- If there's an error in loadInterface, (e.g. interface
214 -- file not found) we get lots of spurious errors from 'filterImports'
216 imp_mod_name = unLoc loc_imp_mod_name
217 doc = ppr imp_mod_name <+> ptext SLIT("is directly imported")
219 loadSrcInterface doc imp_mod_name want_boot `thenM` \ iface ->
221 -- Compiler sanity check: if the import didn't say
222 -- {-# SOURCE #-} we should not get a hi-boot file
223 WARN( not want_boot && mi_boot iface, ppr imp_mod_name )
225 -- Issue a user warning for a redundant {- SOURCE -} import
226 -- NB that we arrange to read all the ordinary imports before
227 -- any of the {- SOURCE -} imports
228 warnIf (want_boot && not (mi_boot iface))
229 (warnRedundantSourceImport imp_mod_name) `thenM_`
232 imp_mod = mi_module iface
233 deprecs = mi_deprecs iface
234 is_orph = mi_orphan iface
237 filtered_exports = filter not_this_mod (mi_exports iface)
238 not_this_mod (mod,_) = mod /= this_mod
239 -- If the module exports anything defined in this module, just ignore it.
240 -- Reason: otherwise it looks as if there are two local definition sites
241 -- for the thing, and an error gets reported. Easiest thing is just to
242 -- filter them out up front. This situation only arises if a module
243 -- imports itself, or another module that imported it. (Necessarily,
244 -- this invoves a loop.)
246 -- Tiresome consequence: if you say
251 -- module B( AType ) where
252 -- import {-# SOURCE #-} A( AType )
254 -- then you'll get a 'B does not export AType' message. Oh well.
256 qual_mod_name = case as_mod of
257 Nothing -> imp_mod_name
258 Just another_name -> another_name
259 imp_spec = ImpDeclSpec { is_mod = imp_mod_name, is_qual = qual_only,
260 is_dloc = loc, is_as = qual_mod_name }
262 -- Get the total imports, and filter them according to the import list
263 ifaceExportNames filtered_exports `thenM` \ total_avails ->
264 filterImports iface imp_spec
265 imp_details total_avails `thenM` \ (avail_env, gbl_env) ->
267 getDOpts `thenM` \ dflags ->
270 -- Compute new transitive dependencies
272 orphans | is_orph = ASSERT( not (imp_mod `elem` dep_orphs deps) )
273 imp_mod : dep_orphs deps
274 | otherwise = dep_orphs deps
276 pkg = modulePackageId (mi_module iface)
278 (dependent_mods, dependent_pkgs)
279 | pkg == thisPackage dflags =
280 -- Imported module is from the home package
281 -- Take its dependent modules and add imp_mod itself
282 -- Take its dependent packages unchanged
284 -- NB: (dep_mods deps) might include a hi-boot file
285 -- for the module being compiled, CM. Do *not* filter
286 -- this out (as we used to), because when we've
287 -- finished dealing with the direct imports we want to
288 -- know if any of them depended on CM.hi-boot, in
289 -- which case we should do the hi-boot consistency
290 -- check. See LoadIface.loadHiBootInterface
291 ((imp_mod_name, want_boot) : dep_mods deps, dep_pkgs deps)
294 -- Imported module is from another package
295 -- Dump the dependent modules
296 -- Add the package imp_mod comes from to the dependent packages
297 ASSERT2( not (pkg `elem` dep_pkgs deps), ppr pkg <+> ppr (dep_pkgs deps) )
298 ([], pkg : dep_pkgs deps)
300 -- True <=> import M ()
301 import_all = case imp_details of
302 Just (is_hiding, ls) -> not is_hiding && null ls
305 -- unqual_avails is the Avails that are visible in *unqualified* form
306 -- We need to know this so we know what to export when we see
307 -- module M ( module P ) where ...
308 -- Then we must export whatever came from P unqualified.
309 imports = ImportAvails {
310 imp_env = unitUFM qual_mod_name avail_env,
311 imp_mods = unitModuleEnv imp_mod (imp_mod, import_all, loc),
313 imp_dep_mods = mkModDeps dependent_mods,
314 imp_dep_pkgs = dependent_pkgs }
317 -- Complain if we import a deprecated module
318 ifOptM Opt_WarnDeprecations (
320 DeprecAll txt -> addWarn (moduleDeprec imp_mod_name txt)
324 returnM (gbl_env, imports)
326 warnRedundantSourceImport mod_name
327 = ptext SLIT("Unnecessary {-# SOURCE #-} in the import of module")
328 <+> quotes (ppr mod_name)
332 %************************************************************************
334 importsFromLocalDecls
336 %************************************************************************
338 From the top-level declarations of this module produce
339 * the lexical environment
341 created by its bindings.
343 Complain about duplicate bindings
346 importsFromLocalDecls :: HsGroup RdrName -> RnM TcGblEnv
347 importsFromLocalDecls group
348 = do { gbl_env <- getGblEnv
350 ; names <- getLocalDeclBinders gbl_env group
352 ; implicit_prelude <- doptM Opt_ImplicitPrelude
354 -- Optimisation: filter out names for built-in syntax
355 -- They just clutter up the environment (esp tuples), and the parser
356 -- will generate Exact RdrNames for them, so the cluttered
357 -- envt is no use. To avoid doing this filter all the time,
358 -- we use -fno-implicit-prelude as a clue that the filter is
359 -- worth while. Really, it's only useful for GHC.Base and GHC.Tuple.
361 -- It's worth doing because it makes the environment smaller for
362 -- every module that imports the Prelude
364 -- Note: don't filter the gbl_env (hence all_names, not filered_all_names
365 -- in defn of gres above). Stupid reason: when parsing
366 -- data type decls, the constructors start as Exact tycon-names,
367 -- and then get turned into data con names by zapping the name space;
368 -- but that stops them being Exact, so they get looked up.
369 -- Ditto in fixity decls; e.g. infix 5 :
370 -- Sigh. It doesn't matter because it only affects the Data.Tuple really.
371 -- The important thing is to trim down the exports.
373 | implicit_prelude = names
374 | otherwise = filter (not . isBuiltInSyntax) names ;
376 ; this_mod = tcg_mod gbl_env
377 ; imports = emptyImportAvails {
378 imp_env = unitUFM (moduleName this_mod) $
379 mkNameSet filtered_names
383 ; rdr_env' <- extendRdrEnvRn (tcg_rdr_env gbl_env) names
385 ; returnM (gbl_env { tcg_rdr_env = rdr_env',
386 tcg_imports = imports `plusImportAvails` tcg_imports gbl_env })
389 extendRdrEnvRn :: GlobalRdrEnv -> [Name] -> RnM GlobalRdrEnv
390 -- Add the new locally-bound names one by one, checking for duplicates as
391 -- we do so. Remember that in Template Haskell the duplicates
392 -- might *already be* in the GlobalRdrEnv from higher up the module
393 extendRdrEnvRn rdr_env names
394 = foldlM add_local rdr_env names
396 add_local rdr_env name
397 | gres <- lookupGlobalRdrEnv rdr_env (nameOccName name)
398 , (dup_gre:_) <- filter isLocalGRE gres -- Check for existing *local* defns
399 = do { addDupDeclErr (gre_name dup_gre) name
402 = return (extendGlobalRdrEnv rdr_env new_gre)
404 new_gre = GRE {gre_name = name, gre_prov = LocalDef}
407 @getLocalDeclBinders@ returns the names for an @HsDecl@. It's
408 used for source code.
410 *** See "THE NAMING STORY" in HsDecls ****
413 getLocalDeclBinders :: TcGblEnv -> HsGroup RdrName -> RnM [Name]
414 getLocalDeclBinders gbl_env (HsGroup {hs_valds = ValBindsIn val_decls val_sigs,
415 hs_tyclds = tycl_decls,
416 hs_fords = foreign_decls })
417 = do { tc_names_s <- mappM new_tc tycl_decls
418 ; val_names <- mappM new_simple val_bndrs
419 ; return (foldr (++) val_names tc_names_s) }
421 mod = tcg_mod gbl_env
422 is_hs_boot = isHsBoot (tcg_src gbl_env) ;
423 val_bndrs | is_hs_boot = sig_hs_bndrs
424 | otherwise = for_hs_bndrs ++ val_hs_bndrs
425 -- In a hs-boot file, the value binders come from the
426 -- *signatures*, and there should be no foreign binders
428 new_simple rdr_name = newTopSrcBinder mod Nothing rdr_name
430 sig_hs_bndrs = [nm | L _ (TypeSig nm _) <- val_sigs]
431 val_hs_bndrs = collectHsBindLocatedBinders val_decls
432 for_hs_bndrs = [nm | L _ (ForeignImport nm _ _) <- foreign_decls]
435 = do { main_name <- newTopSrcBinder mod Nothing main_rdr
436 ; sub_names <- mappM (newTopSrcBinder mod (Just main_name)) sub_rdrs
437 ; return (main_name : sub_names) }
439 (main_rdr : sub_rdrs) = tyClDeclNames (unLoc tc_decl)
443 %************************************************************************
445 \subsection{Filtering imports}
447 %************************************************************************
449 @filterImports@ takes the @ExportEnv@ telling what the imported module makes
450 available, and filters it through the import spec (if any).
453 filterImports :: ModIface
454 -> ImpDeclSpec -- The span for the entire import decl
455 -> Maybe (Bool, [LIE Name]) -- Import spec; True => hiding
456 -> NameSet -- What's available
457 -> RnM (NameSet, -- What's imported (qualified or unqualified)
458 GlobalRdrEnv) -- Same again, but in GRE form
460 -- Complains if import spec mentions things that the module doesn't export
461 -- Warns/informs if import spec contains duplicates.
463 mkGenericRdrEnv decl_spec names
464 = mkGlobalRdrEnv [ GRE { gre_name = name, gre_prov = Imported [imp_spec] }
465 | name <- nameSetToList names ]
467 imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }
469 filterImports iface decl_spec Nothing all_names
470 = return (all_names, mkGenericRdrEnv decl_spec all_names)
472 filterImports iface decl_spec (Just (want_hiding, import_items)) all_names
473 = mapM (addLocM get_item) import_items >>= \gres_s ->
474 let gres = concat gres_s
475 specified_names = mkNameSet (map gre_name gres)
476 in if not want_hiding then
477 return (specified_names, mkGlobalRdrEnv gres)
478 else let keep n = not (n `elemNameSet` specified_names)
479 pruned_avails = filterNameSet keep all_names
480 in return (pruned_avails, mkGenericRdrEnv decl_spec pruned_avails)
482 sub_env :: NameEnv [Name] -- Classify each name by its parent
483 sub_env = mkSubNameEnv all_names
485 succeed_with :: Bool -> [Name] -> RnM [GlobalRdrElt]
486 succeed_with all_explicit names
487 = do { loc <- getSrcSpanM
488 ; returnM (map (mk_gre loc) names) }
490 mk_gre loc name = GRE { gre_name = name,
491 gre_prov = Imported [imp_spec] }
493 imp_spec = ImpSpec { is_decl = decl_spec, is_item = item_spec }
494 item_spec = ImpSome { is_explicit = explicit, is_iloc = loc }
495 explicit = all_explicit || isNothing (nameParent_maybe name)
497 get_item :: IE Name -> RnM [GlobalRdrElt]
498 -- Empty result for a bad item.
499 -- Singleton result is typical case.
500 -- Can have two when we are hiding, and mention C which might be
501 -- both a class and a data constructor.
502 get_item item@(IEModuleContents _)
503 -- This case should be filtered out by 'rnImports'.
504 = panic "filterImports: IEModuleContents?"
506 get_item (IEThingAll name)
507 = case subNames sub_env name of
508 [] -> -- This occurs when you import T(..), but
509 -- only export T abstractly.
510 do ifOptM Opt_WarnDodgyImports (addWarn (dodgyImportWarn name))
511 succeed_with False [name]
512 names -> succeed_with False (name:names)
514 get_item (IEThingAbs name)
515 = succeed_with True [name]
517 get_item (IEThingWith name names)
518 = succeed_with True (name:names)
519 get_item (IEVar name)
520 = succeed_with True [name]
525 %************************************************************************
527 \subsection{Export list processing}
529 %************************************************************************
531 Processing the export list.
533 You might think that we should record things that appear in the export
534 list as ``occurrences'' (using @addOccurrenceName@), but you'd be
535 wrong. We do check (here) that they are in scope, but there is no
536 need to slurp in their actual declaration (which is what
537 @addOccurrenceName@ forces).
539 Indeed, doing so would big trouble when compiling @PrelBase@, because
540 it re-exports @GHC@, which includes @takeMVar#@, whose type includes
541 @ConcBase.StateAndSynchVar#@, and so on...
544 type ExportAccum -- The type of the accumulating parameter of
545 -- the main worker function in rnExports
546 = ([ModuleName], -- 'module M's seen so far
547 ExportOccMap, -- Tracks exported occurrence names
548 NameSet) -- The accumulated exported stuff
549 emptyExportAccum = ([], emptyOccEnv, emptyNameSet)
551 type ExportOccMap = OccEnv (Name, IE RdrName)
552 -- Tracks what a particular exported OccName
553 -- in an export list refers to, and which item
554 -- it came from. It's illegal to export two distinct things
555 -- that have the same occurrence name
557 rnExports :: Maybe [LIE RdrName]
558 -> RnM (Maybe [LIE Name])
559 rnExports Nothing = return Nothing
560 rnExports (Just exports)
561 = do TcGblEnv { tcg_imports = ImportAvails { imp_env = imp_env } } <- getGblEnv
562 let sub_env :: NameEnv [Name] -- Classify each name by its parent
563 sub_env = mkSubNameEnv (foldUFM unionNameSets emptyNameSet imp_env)
564 rnExport (IEVar rdrName)
565 = do name <- lookupGlobalOccRn rdrName
567 rnExport (IEThingAbs rdrName)
568 = do name <- lookupGlobalOccRn rdrName
569 return (IEThingAbs name)
570 rnExport (IEThingAll rdrName)
571 = do name <- lookupGlobalOccRn rdrName
572 return (IEThingAll name)
573 rnExport ie@(IEThingWith rdrName rdrNames)
574 = do name <- lookupGlobalOccRn rdrName
575 if isUnboundName name
576 then return (IEThingWith name [])
578 let env = mkOccEnv [(nameOccName s, s) | s <- subNames sub_env name]
579 mb_names = map (lookupOccEnv env . rdrNameOcc) rdrNames
580 if any isNothing mb_names
581 then do addErr (exportItemErr ie)
582 return (IEThingWith name [])
583 else return (IEThingWith name (catMaybes mb_names))
584 rnExport (IEModuleContents mod)
585 = return (IEModuleContents mod)
586 rn_exports <- mapM (wrapLocM rnExport) exports
587 return (Just rn_exports)
589 mkExportNameSet :: Bool -- False => no 'module M(..) where' header at all
590 -> Maybe ([LIE Name], [LIE RdrName]) -- Nothing => no explicit export list
592 -- Complains if two distinct exports have same OccName
593 -- Warns about identical exports.
594 -- Complains about exports items not in scope
596 mkExportNameSet explicit_mod exports
597 = do TcGblEnv { tcg_rdr_env = rdr_env,
598 tcg_imports = imports } <- getGblEnv
600 -- If the module header is omitted altogether, then behave
601 -- as if the user had written "module Main(main) where..."
602 -- EXCEPT in interactive mode, when we behave as if he had
603 -- written "module Main where ..."
604 -- Reason: don't want to complain about 'main' not in scope
605 -- in interactive mode
606 ghc_mode <- getGhcMode
607 real_exports <- case () of
610 | ghc_mode == Interactive
613 -> do mainName <- lookupGlobalOccRn main_RDR_Unqual
614 return (Just ([noLoc (IEVar mainName)]
615 ,[noLoc (IEVar main_RDR_Unqual)]))
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,origItems)) rdr_env (ImportAvails { imp_env = imp_env })
629 = do (_, _, exports) <- foldlM do_litem emptyExportAccum (zip items origItems)
632 sub_env :: NameEnv [Name] -- Classify each name by its parent
633 sub_env = mkSubNameEnv (foldUFM unionNameSets emptyNameSet imp_env)
635 do_litem :: ExportAccum -> (LIE Name, LIE RdrName) -> RnM ExportAccum
636 do_litem acc (ieName, ieRdr)
637 = addLocM (exports_from_item acc (unLoc ieRdr)) ieName
639 exports_from_item :: ExportAccum -> IE RdrName -> IE Name -> RnM ExportAccum
640 exports_from_item acc@(mods, occs, exports) ieRdr@(IEModuleContents mod) ie
641 | mod `elem` mods -- Duplicate export of M
642 = do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
643 warnIf warn_dup_exports (dupModuleExport mod) ;
647 = case lookupUFM imp_env mod of
648 Nothing -> do addErr (modExportErr mod)
651 -> do let new_exports = filterNameSet (inScopeUnqual rdr_env) names
652 -- This check_occs not only finds conflicts between this item
653 -- and others, but also internally within this item. That is,
654 -- if 'M.x' is in scope in several ways, we'll have several
655 -- members of mod_avails with the same OccName.
656 occs' <- check_occs ieRdr occs (nameSetToList new_exports)
657 return (mod:mods, occs', exports `unionNameSets` new_exports)
659 exports_from_item acc@(mods, occs, exports) ieRdr ie
660 = if isUnboundName (ieName ie)
661 then return acc -- Avoid error cascade
662 else let new_exports = filterAvail ie sub_env in
663 do -- checkErr (not (null (drop 1 new_exports))) (exportItemErr ie)
664 checkForDodgyExport ie new_exports
665 occs' <- check_occs ieRdr occs new_exports
666 return (mods, occs', addListToNameSet exports new_exports)
668 -------------------------------
669 filterAvail :: IE Name -- Wanted
670 -> NameEnv [Name] -- Maps type/class names to their sub-names
673 filterAvail (IEVar n) subs = [n]
674 filterAvail (IEThingAbs n) subs = [n]
675 filterAvail (IEThingAll n) subs = n : subNames subs n
676 filterAvail (IEThingWith n ns) subs = n : ns
677 filterAvail (IEModuleContents _) _ = panic "filterAvail"
679 subNames :: NameEnv [Name] -> Name -> [Name]
680 subNames env n = lookupNameEnv env n `orElse` []
682 mkSubNameEnv :: NameSet -> NameEnv [Name]
683 -- Maps types and classes to their constructors/classops respectively
684 -- This mapping just makes it easier to deal with A(..) export items
686 = foldNameSet add_name emptyNameEnv names
689 | Just parent <- nameParent_maybe name
690 = extendNameEnv_C (\ns _ -> name:ns) env parent [name]
693 -------------------------------
694 inScopeUnqual :: GlobalRdrEnv -> Name -> Bool
695 -- Checks whether the Name is in scope unqualified,
696 -- regardless of whether it's ambiguous or not
697 inScopeUnqual env n = any unQualOK (lookupGRE_Name env n)
699 -------------------------------
700 checkForDodgyExport :: IE Name -> [Name] -> RnM ()
701 checkForDodgyExport ie@(IEThingAll tc) [n]
702 | isTcOcc (nameOccName n) = addWarn (dodgyExportWarn tc)
703 -- This occurs when you export T(..), but
704 -- only import T abstractly, or T is a synonym.
705 -- The single [n] is the type or class itself
706 | otherwise = addErr (exportItemErr ie)
707 -- This happes if you export x(..), which is bogus
708 checkForDodgyExport _ _ = return ()
710 -------------------------------
711 check_occs :: IE RdrName -> ExportOccMap -> [Name] -> RnM ExportOccMap
712 check_occs ie occs names
713 = foldlM check occs names
716 = case lookupOccEnv occs name_occ of
717 Nothing -> returnM (extendOccEnv occs name_occ (name, ie))
720 | name == name' -- Duplicate export
721 -> do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
722 warnIf warn_dup_exports (dupExportWarn name_occ ie ie') ;
725 | otherwise -- Same occ name but different names: an error
726 -> do { global_env <- getGlobalRdrEnv ;
727 addErr (exportClashErr global_env name' name ie' ie) ;
730 name_occ = nameOccName name
733 %*********************************************************
737 %*********************************************************
740 reportDeprecations :: DynFlags -> TcGblEnv -> RnM ()
741 reportDeprecations dflags tcg_env
742 = ifOptM Opt_WarnDeprecations $
743 do { (eps,hpt) <- getEpsAndHpt
744 -- By this time, typechecking is complete,
745 -- so the PIT is fully populated
746 ; mapM_ (check hpt (eps_PIT eps)) all_gres }
748 used_names = allUses (tcg_dus tcg_env)
749 -- Report on all deprecated uses; hence allUses
750 all_gres = globalRdrEnvElts (tcg_rdr_env tcg_env)
752 check hpt pit (GRE {gre_name = name, gre_prov = Imported (imp_spec:_)})
753 | name `elemNameSet` used_names
754 , Just deprec_txt <- lookupDeprec dflags hpt pit name
755 = addWarnAt (importSpecLoc imp_spec)
756 (sep [ptext SLIT("Deprecated use of") <+>
757 pprNonVarNameSpace (occNameSpace (nameOccName name)) <+>
759 (parens imp_msg) <> colon,
762 name_mod = nameModule name
763 imp_mod = importSpecModule imp_spec
764 imp_msg = ptext SLIT("imported from") <+> ppr imp_mod <> extra
765 extra | imp_mod == moduleName name_mod = empty
766 | otherwise = ptext SLIT(", but defined in") <+> ppr name_mod
768 check hpt pit ok_gre = returnM () -- Local, or not used, or not deprectated
769 -- The Imported pattern-match: don't deprecate locally defined names
770 -- For a start, we may be exporting a deprecated thing
771 -- Also we may use a deprecated thing in the defn of another
772 -- deprecated things. We may even use a deprecated thing in
773 -- the defn of a non-deprecated thing, when changing a module's
776 lookupDeprec :: DynFlags -> HomePackageTable -> PackageIfaceTable
777 -> Name -> Maybe DeprecTxt
778 lookupDeprec dflags hpt pit n
779 = case lookupIfaceByModule dflags hpt pit (nameModule n) of
780 Just iface -> mi_dep_fn iface n `seqMaybe` -- Bleat if the thing, *or
781 mi_dep_fn iface (nameParent n) -- its parent*, is deprec'd
783 | isWiredInName n -> Nothing
784 -- We have not necessarily loaded the .hi file for a
785 -- wired-in name (yet), although we *could*.
786 -- And we never deprecate them
788 | otherwise -> pprPanic "lookupDeprec" (ppr n)
789 -- By now all the interfaces should have been loaded
791 gre_is_used :: NameSet -> GlobalRdrElt -> Bool
792 gre_is_used used_names gre = gre_name gre `elemNameSet` used_names
795 %*********************************************************
799 %*********************************************************
802 reportUnusedNames :: Maybe [LIE RdrName] -- Export list
803 -> TcGblEnv -> RnM ()
804 reportUnusedNames export_decls gbl_env
805 = do { traceRn ((text "RUN") <+> (ppr (tcg_dus gbl_env)))
806 ; warnUnusedTopBinds unused_locals
807 ; warnUnusedModules unused_imp_mods
808 ; warnUnusedImports unused_imports
809 ; warnDuplicateImports defined_and_used
810 ; printMinimalImports minimal_imports }
812 used_names, all_used_names :: NameSet
813 used_names = findUses (tcg_dus gbl_env) emptyNameSet
814 -- NB: currently, if f x = g, we only treat 'g' as used if 'f' is used
817 all_used_names = used_names `unionNameSets`
818 mkNameSet (mapCatMaybes nameParent_maybe (nameSetToList used_names))
819 -- A use of C implies a use of T,
820 -- if C was brought into scope by T(..) or T(C)
822 -- Collect the defined names from the in-scope environment
823 defined_names :: [GlobalRdrElt]
824 defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)
826 -- Note that defined_and_used, defined_but_not_used
827 -- are both [GRE]; that's why we need defined_and_used
828 -- rather than just all_used_names
829 defined_and_used, defined_but_not_used :: [GlobalRdrElt]
830 (defined_and_used, defined_but_not_used)
831 = partition (gre_is_used all_used_names) defined_names
833 -- Filter out the ones that are
834 -- (a) defined in this module, and
835 -- (b) not defined by a 'deriving' clause
836 -- The latter have an Internal Name, so we can filter them out easily
837 unused_locals :: [GlobalRdrElt]
838 unused_locals = filter is_unused_local defined_but_not_used
839 is_unused_local :: GlobalRdrElt -> Bool
840 is_unused_local gre = isLocalGRE gre && isExternalName (gre_name gre)
842 unused_imports :: [GlobalRdrElt]
843 unused_imports = filter unused_imp defined_but_not_used
844 unused_imp (GRE {gre_prov = Imported imp_specs})
845 = not (all (module_unused . importSpecModule) imp_specs)
846 && or [exp | ImpSpec { is_item = ImpSome { is_explicit = exp } } <- imp_specs]
847 -- Don't complain about unused imports if we've already said the
848 -- entire import is unused
849 unused_imp other = False
851 -- To figure out the minimal set of imports, start with the things
852 -- that are in scope (i.e. in gbl_env). Then just combine them
853 -- into a bunch of avails, so they are properly grouped
855 -- BUG WARNING: this does not deal properly with qualified imports!
856 minimal_imports :: FiniteMap ModuleName AvailEnv
857 minimal_imports0 = foldr add_expall emptyFM expall_mods
858 minimal_imports1 = foldr add_name minimal_imports0 defined_and_used
859 minimal_imports = foldr add_inst_mod minimal_imports1 direct_import_mods
860 -- The last line makes sure that we retain all direct imports
861 -- even if we import nothing explicitly.
862 -- It's not necessarily redundant to import such modules. Consider
866 -- The import M() is not *necessarily* redundant, even if
867 -- we suck in no instance decls from M (e.g. it contains
868 -- no instance decls, or This contains no code). It may be
869 -- that we import M solely to ensure that M's orphan instance
870 -- decls (or those in its imports) are visible to people who
871 -- import This. Sigh.
872 -- There's really no good way to detect this, so the error message
873 -- in RnEnv.warnUnusedModules is weakened instead
875 -- We've carefully preserved the provenance so that we can
876 -- construct minimal imports that import the name by (one of)
877 -- the same route(s) as the programmer originally did.
878 add_name (GRE {gre_name = n, gre_prov = Imported imp_specs}) acc
879 = addToFM_C plusAvailEnv acc (importSpecModule (head imp_specs))
880 (unitAvailEnv (mk_avail n (nameParent_maybe n)))
884 -- Modules mentioned as 'module M' in the export list
885 expall_mods = case export_decls of
887 Just es -> [m | L _ (IEModuleContents m) <- es]
889 -- This is really bogus. The idea is that if we see 'module M' in
890 -- the export list we must retain the import decls that drive it
891 -- If we aren't careful we might see
892 -- module A( module M ) where
895 -- and suppose that N exports everything that M does. Then we
896 -- must not drop the import of M even though N brings it all into
899 -- BUG WARNING: 'module M' exports aside, what if M.x is mentioned?!
901 -- The reason that add_expall is bogus is that it doesn't take
902 -- qualified imports into account. But it's an improvement.
903 add_expall mod acc = addToFM_C plusAvailEnv acc mod emptyAvailEnv
905 -- n is the name of the thing, p is the name of its parent
906 mk_avail n (Just p) = AvailTC p [p,n]
907 mk_avail n Nothing | isTcOcc (nameOccName n) = AvailTC n [n]
908 | otherwise = Avail n
910 add_inst_mod (mod,_,_) acc
911 | mod_name `elemFM` acc = acc -- We import something already
912 | otherwise = addToFM acc mod_name emptyAvailEnv
914 mod_name = moduleName mod
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_name,loc) | (mod,no_imp,loc) <- direct_import_mods,
932 let mod_name = moduleName mod,
933 not (mod_name `elemFM` minimal_imports1),
936 -- The not no_imp part is not to complain about
937 -- import M (), which is an idiom for importing
938 -- instance declarations
940 module_unused :: ModuleName -> Bool
941 module_unused mod = any (((==) mod) . fst) unused_imp_mods
943 ---------------------
944 warnDuplicateImports :: [GlobalRdrElt] -> RnM ()
945 -- Given the GREs for names that are used, figure out which imports
946 -- could be omitted without changing the top-level environment.
948 -- NB: Given import Foo( T )
949 -- import qualified Foo
950 -- we do not report a duplicate import, even though Foo.T is brought
951 -- into scope by both, because there's nothing you can *omit* without
952 -- changing the top-level environment. So we complain only if it's
953 -- explicitly named in both imports or neither.
955 -- Furthermore, we complain about Foo.T only if
956 -- there is no complaint about (unqualified) T
958 warnDuplicateImports gres
959 = ifOptM Opt_WarnUnusedImports $
960 sequenceM_ [ warn name pr
961 -- The 'head' picks the first offending group
962 -- for this particular name
963 | GRE { gre_name = name, gre_prov = Imported imps } <- gres
964 , pr <- redundants imps ]
966 warn name (red_imp, cov_imp)
967 = addWarnAt (importSpecLoc red_imp)
968 (vcat [ptext SLIT("Redundant import of:") <+> quotes pp_name,
969 ptext SLIT("It is also") <+> ppr cov_imp])
971 pp_name | is_qual red_decl = ppr (is_as red_decl) <> dot <> ppr occ
972 | otherwise = ppr occ
973 occ = nameOccName name
974 red_decl = is_decl red_imp
976 redundants :: [ImportSpec] -> [(ImportSpec,ImportSpec)]
977 -- The returned pair is (redundant-import, covering-import)
979 = [ (red_imp, cov_imp)
981 , cov_imp <- take 1 (filter (covers red_imp) imps) ]
983 -- "red_imp" is a putative redundant import
984 -- "cov_imp" potentially covers it
985 -- This test decides whether red_imp could be dropped
987 -- NOTE: currently the test does not warn about
990 -- even if the same underlying 'x' is involved, because dropping
991 -- either import would change the qualified names in scope (M.x, N.x)
992 -- But if the qualified names aren't used, the import is indeed redundant
993 -- Sadly we don't know that. Oh well.
994 covers red_imp@(ImpSpec { is_decl = red_decl, is_item = red_item })
995 cov_imp@(ImpSpec { is_decl = cov_decl, is_item = cov_item })
997 = False -- Ignore diagonal elements
998 | not (is_as red_decl == is_as cov_decl)
999 = False -- They bring into scope different qualified names
1000 | not (is_qual red_decl) && is_qual cov_decl
1001 = False -- Covering one doesn't bring unqualified name into scope
1003 = not cov_selective -- Redundant one is selective and covering one isn't
1004 || red_later -- Both are explicit; tie-break using red_later
1006 = not cov_selective -- Neither import is selective
1007 && (is_mod red_decl == is_mod cov_decl) -- They import the same module
1008 && red_later -- Tie-break
1010 red_loc = importSpecLoc red_imp
1011 cov_loc = importSpecLoc cov_imp
1012 red_later = red_loc > cov_loc
1013 cov_selective = selectiveImpItem cov_item
1014 red_selective = selectiveImpItem red_item
1016 selectiveImpItem :: ImpItemSpec -> Bool
1017 selectiveImpItem ImpAll = False
1018 selectiveImpItem (ImpSome {}) = True
1020 -- ToDo: deal with original imports with 'qualified' and 'as M' clauses
1021 printMinimalImports :: FiniteMap ModuleName AvailEnv -- Minimal imports
1023 printMinimalImports imps
1024 = ifOptM Opt_D_dump_minimal_imports $ do {
1026 mod_ies <- mappM to_ies (fmToList imps) ;
1027 this_mod <- getModule ;
1028 rdr_env <- getGlobalRdrEnv ;
1029 ioToTcRn (do { h <- openFile (mkFilename this_mod) WriteMode ;
1030 printForUser h (mkPrintUnqualified rdr_env)
1031 (vcat (map ppr_mod_ie mod_ies)) })
1034 mkFilename this_mod = moduleNameString (moduleName this_mod) ++ ".imports"
1035 ppr_mod_ie (mod_name, ies)
1036 | mod_name == moduleName pRELUDE
1038 | null ies -- Nothing except instances comes from here
1039 = ptext SLIT("import") <+> ppr mod_name <> ptext SLIT("() -- Instances only")
1041 = ptext SLIT("import") <+> ppr mod_name <>
1042 parens (fsep (punctuate comma (map ppr ies)))
1044 to_ies (mod, avail_env) = do ies <- mapM to_ie (availEnvElts avail_env)
1047 to_ie :: AvailInfo -> RnM (IE Name)
1048 -- The main trick here is that if we're importing all the constructors
1049 -- we want to say "T(..)", but if we're importing only a subset we want
1050 -- to say "T(A,B,C)". So we have to find out what the module exports.
1051 to_ie (Avail n) = returnM (IEVar n)
1052 to_ie (AvailTC n [m]) = ASSERT( n==m )
1053 returnM (IEThingAbs n)
1054 to_ie (AvailTC n ns)
1055 = loadSrcInterface doc n_mod False `thenM` \ iface ->
1056 case [xs | (m,as) <- mi_exports iface,
1057 moduleName m == n_mod,
1059 x == nameOccName n] of
1060 [xs] | all_used xs -> returnM (IEThingAll n)
1061 | otherwise -> returnM (IEThingWith n (filter (/= n) ns))
1062 other -> pprTrace "to_ie" (ppr n <+> ppr n_mod <+> ppr other) $
1065 all_used avail_occs = all (`elem` map nameOccName ns) avail_occs
1066 doc = text "Compute minimal imports from" <+> ppr n
1067 n_mod = moduleName (nameModule n)
1071 %************************************************************************
1075 %************************************************************************
1078 badImportItemErr iface decl_spec ie
1079 = sep [ptext SLIT("Module"), quotes (ppr (is_mod decl_spec)), source_import,
1080 ptext SLIT("does not export"), quotes (ppr ie)]
1082 source_import | mi_boot iface = ptext SLIT("(hi-boot interface)")
1085 dodgyImportWarn item = dodgyMsg (ptext SLIT("import")) item
1086 dodgyExportWarn item = dodgyMsg (ptext SLIT("export")) item
1089 = sep [ ptext SLIT("The") <+> kind <+> ptext SLIT("item") <+> quotes (ppr (IEThingAll tc)),
1090 ptext SLIT("suggests that") <+> quotes (ppr tc) <+> ptext SLIT("has constructor or class methods"),
1091 ptext SLIT("but it has none; it is a type synonym or abstract type or class") ]
1094 = hsep [ ptext SLIT("Unknown module in export list: module"), quotes (ppr mod)]
1096 exportItemErr export_item
1097 = sep [ ptext SLIT("The export item") <+> quotes (ppr export_item),
1098 ptext SLIT("attempts to export constructors or class methods that are not visible here") ]
1100 exportClashErr global_env name1 name2 ie1 ie2
1101 = vcat [ ptext SLIT("Conflicting exports for") <+> quotes (ppr occ) <> colon
1102 , ppr_export ie1 name1
1103 , ppr_export ie2 name2 ]
1105 occ = nameOccName name1
1106 ppr_export ie name = nest 2 (quotes (ppr ie) <+> ptext SLIT("exports") <+>
1107 quotes (ppr name) <+> pprNameProvenance (get_gre name))
1109 -- get_gre finds a GRE for the Name, so that we can show its provenance
1111 = case lookupGRE_Name global_env name of
1113 [] -> pprPanic "exportClashErr" (ppr name)
1115 addDupDeclErr :: Name -> Name -> TcRn ()
1116 addDupDeclErr name_a name_b
1117 = addErrAt (srcLocSpan loc2) $
1118 vcat [ptext SLIT("Multiple declarations of") <+> quotes (ppr name1),
1119 ptext SLIT("Declared at:") <+> vcat [ppr (nameSrcLoc name1), ppr loc2]]
1121 loc2 = nameSrcLoc name2
1122 (name1,name2) | nameSrcLoc name_a > nameSrcLoc name_b = (name_b,name_a)
1123 | otherwise = (name_a,name_b)
1124 -- Report the error at the later location
1126 dupExportWarn occ_name ie1 ie2
1127 = hsep [quotes (ppr occ_name),
1128 ptext SLIT("is exported by"), quotes (ppr ie1),
1129 ptext SLIT("and"), quotes (ppr ie2)]
1132 = hsep [ptext SLIT("Duplicate"),
1133 quotes (ptext SLIT("Module") <+> ppr mod),
1134 ptext SLIT("in export list")]
1136 moduleDeprec mod txt
1137 = sep [ ptext SLIT("Module") <+> quotes (ppr mod) <+> ptext SLIT("is deprecated:"),