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,
15 #include "HsVersions.h"
17 import DynFlags ( DynFlag(..), GhcMode(..) )
18 import HsSyn ( IE(..), ieName, ImportDecl(..), LImportDecl,
19 ForeignDecl(..), HsGroup(..), HsValBinds(..),
20 Sig(..), collectHsBindLocatedBinders, tyClDeclNames,
23 import IfaceEnv ( ifaceExportNames )
24 import LoadIface ( loadSrcInterface )
25 import TcRnMonad hiding (LIE)
28 import PrelNames ( pRELUDE, isUnboundName, main_RDR_Unqual )
29 import Module ( Module, moduleString, unitModuleEnv,
30 lookupModuleEnv, moduleEnvElts, foldModuleEnv )
31 import Name ( Name, nameSrcLoc, nameOccName, nameModule, isWiredInName,
32 nameParent, nameParent_maybe, isExternalName,
36 import OccName ( srcDataName, isTcOcc, pprNonVarNameSpace,
38 OccEnv, mkOccEnv, lookupOccEnv, emptyOccEnv,
40 import HscTypes ( GenAvailInfo(..), AvailInfo,
41 HomePackageTable, PackageIfaceTable,
43 Deprecs(..), ModIface(..), Dependencies(..),
44 lookupIface, ExternalPackageState(..)
46 import Packages ( PackageIdH(..) )
47 import RdrName ( RdrName, rdrNameOcc, setRdrNameSpace,
48 GlobalRdrEnv, mkGlobalRdrEnv, GlobalRdrElt(..),
49 emptyGlobalRdrEnv, plusGlobalRdrEnv, globalRdrEnvElts,
50 extendGlobalRdrEnv, lookupGlobalRdrEnv, unQualOK, lookupGRE_Name,
51 Provenance(..), ImportSpec(..), ImpDeclSpec(..), ImpItemSpec(..),
52 importSpecLoc, importSpecModule, isLocalGRE, pprNameProvenance )
54 import Maybes ( isNothing, catMaybes, mapCatMaybes, seqMaybe, orElse )
55 import SrcLoc ( Located(..), mkGeneralSrcSpan,
56 unLoc, noLoc, srcLocSpan, SrcSpan )
57 import BasicTypes ( DeprecTxt )
58 import DriverPhases ( isHsBoot )
59 import Util ( notNull )
60 import List ( partition )
61 import IO ( openFile, IOMode(..) )
66 %************************************************************************
70 %************************************************************************
73 rnImports :: [LImportDecl RdrName] -> RnM [LImportDecl Name]
75 -- PROCESS IMPORT DECLS
76 -- Do the non {- SOURCE -} ones first, so that we get a helpful
77 -- warning for {- SOURCE -} ones that are unnecessary
78 = do this_mod <- getModule
79 implicit_prelude <- doptM Opt_ImplicitPrelude
80 let all_imports = mk_prel_imports this_mod implicit_prelude ++ imports
81 (source, ordinary) = partition is_source_import all_imports
82 is_source_import (L _ (ImportDecl _ is_boot _ _ _)) = is_boot
83 get_imports = importsFromImportDeclDirect this_mod
85 stuff1 <- mapM get_imports ordinary
86 stuff2 <- mapM get_imports source
87 return (stuff1 ++ stuff2)
89 -- NB: opt_NoImplicitPrelude is slightly different to import Prelude ();
90 -- because the former doesn't even look at Prelude.hi for instance
91 -- declarations, whereas the latter does.
92 mk_prel_imports this_mod implicit_prelude
94 || explicit_prelude_import
95 || not implicit_prelude
97 | otherwise = [preludeImportDecl]
98 explicit_prelude_import
99 = notNull [ () | L _ (ImportDecl mod _ _ _ _) <- imports,
100 unLoc mod == pRELUDE ]
102 preludeImportDecl :: LImportDecl RdrName
105 ImportDecl (L loc pRELUDE)
106 False {- Not a boot interface -}
107 False {- Not qualified -}
108 Nothing {- No "as" -}
109 Nothing {- No import list -}
111 loc = mkGeneralSrcSpan FSLIT("Implicit import declaration")
113 mkRdrEnvAndImports :: [LImportDecl Name] -> RnM (GlobalRdrEnv, ImportAvails)
114 mkRdrEnvAndImports imports
115 = do this_mod <- getModule
116 let get_imports = importsFromImportDecl this_mod
117 stuff <- mapM get_imports imports
118 let (imp_gbl_envs, imp_avails) = unzip stuff
119 gbl_env :: GlobalRdrEnv
120 gbl_env = foldr plusGlobalRdrEnv emptyGlobalRdrEnv imp_gbl_envs
122 all_avails :: ImportAvails
123 all_avails = foldr plusImportAvails emptyImportAvails imp_avails
125 return (gbl_env, all_avails)
130 rnImportDecl :: ModIface -> ImpDeclSpec -> ImportDecl RdrName -> NameSet -> RnM (ImportDecl Name)
131 rnImportDecl iface decl_spec (ImportDecl loc_imp_mod_name want_boot qual_only as_mod Nothing) all_names
132 = return $ ImportDecl loc_imp_mod_name want_boot qual_only as_mod Nothing
133 rnImportDecl iface decl_spec (ImportDecl loc_imp_mod_name want_boot qual_only as_mod (Just (want_hiding,import_items))) all_names
134 = do import_items_mbs <- mapM (srcSpanWrapper) import_items
135 let rn_import_items = concat . catMaybes $ import_items_mbs
136 return $ ImportDecl loc_imp_mod_name want_boot qual_only as_mod (Just (want_hiding,rn_import_items))
138 srcSpanWrapper (L span ieRdr)
140 case get_item ieRdr of
142 -> do addErr (badImportItemErr iface decl_spec ieRdr)
145 -> return (Just [L span ie | ie <- ieNames])
146 occ_env :: OccEnv Name -- Maps OccName to corresponding Name
147 occ_env = mkOccEnv [(nameOccName n, n) | n <- nameSetToList all_names]
148 -- This env will have entries for data constructors too,
149 -- they won't make any difference because naked entities like T
150 -- in an import list map to TcOccs, not VarOccs.
152 sub_env :: NameEnv [Name]
153 sub_env = mkSubNameEnv all_names
155 get_item :: IE RdrName -> Maybe [IE Name]
156 -- Empty result for a bad item.
157 -- Singleton result is typical case.
158 -- Can have two when we are hiding, and mention C which might be
159 -- both a class and a data constructor.
160 get_item item@(IEModuleContents _)
163 get_item (IEThingAll tc)
164 = do name <- check_name tc
165 return [IEThingAll name]
167 -> -- This occurs when you import T(..), but
168 -- only export T abstractly. The single [n]
169 -- in the AvailTC is the type or class itself
170 ifOptM Opt_WarnDodgyImports (addWarn (dodgyImportWarn tc)) `thenM_`
171 return [ IEThingAll n ]
173 names -> return [ IEThingAll n | n <- names ]
176 get_item (IEThingAbs tc)
177 | want_hiding -- hiding ( C )
178 -- Here the 'C' can be a data constructor
179 -- *or* a type/class, or even both
180 = case catMaybes [check_name tc, check_name (setRdrNameSpace tc srcDataName)] of
182 names -> return [ IEThingAbs n | n <- names ]
184 = do name <- check_name tc
185 return [IEThingAbs name]
186 get_item (IEThingWith n ns) -- import (C (A,B))
187 = do name <- check_name n
188 let env = mkOccEnv [(nameOccName s, s) | s <- subNames sub_env name]
189 mb_names = map (lookupOccEnv env . rdrNameOcc) ns
190 names <- sequence mb_names
191 return [IEThingWith name names]
194 = do name <- check_name n
197 check_name :: RdrName -> Maybe Name
199 = lookupOccEnv occ_env (rdrNameOcc rdrName)
202 importsFromImportDeclDirect :: Module
203 -> LImportDecl RdrName
204 -> RnM (LImportDecl Name)
205 importsFromImportDeclDirect this_mod
206 (L loc importDecl@(ImportDecl loc_imp_mod_name want_boot qual_only as_mod imp_details))
208 do iface <- loadSrcInterface doc imp_mod_name want_boot
209 -- Compiler sanity check: if the import didn't say
210 -- {-# SOURCE #-} we should not get a hi-boot file
211 WARN( not want_boot && mi_boot iface, ppr imp_mod_name ) $ do
212 -- Issue a user warning for a redundant {- SOURCE -} import
213 -- NB that we arrange to read all the ordinary imports before
214 -- any of the {- SOURCE -} imports
215 warnIf (want_boot && not (mi_boot iface))
216 (warnRedundantSourceImport imp_mod_name)
218 let deprecs = mi_deprecs iface
219 is_orph = mi_orphan iface
221 filtered_exports = filter not_this_mod (mi_exports iface)
222 not_this_mod (mod,_) = mod /= this_mod
223 imp_mod = mi_module iface
225 -- If the module exports anything defined in this module, just ignore it.
226 -- Reason: otherwise it looks as if there are two local definition sites
227 -- for the thing, and an error gets reported. Easiest thing is just to
228 -- filter them out up front. This situation only arises if a module
229 -- imports itself, or another module that imported it. (Necessarily,
230 -- this invoves a loop.)
232 -- Tiresome consequence: if you say
237 -- module B( AType ) where
238 -- import {-# SOURCE #-} A( AType )
240 -- then you'll get a 'B does not export AType' message. Oh well.
242 qual_mod_name = case as_mod of
243 Nothing -> imp_mod_name
244 Just another_name -> another_name
245 imp_spec = ImpDeclSpec { is_mod = imp_mod_name, is_qual = qual_only,
246 is_dloc = loc, is_as = qual_mod_name }
248 -- Get the total imports, and filter them according to the import list
249 total_avails <- ifaceExportNames filtered_exports
250 importDecl' <- rnImportDecl iface imp_spec importDecl total_avails
251 return (L loc importDecl')
252 where imp_mod_name = unLoc loc_imp_mod_name
253 doc = ppr imp_mod_name <+> ptext SLIT("is directly imported")
255 importsFromImportDecl :: Module
257 -> RnM (GlobalRdrEnv, ImportAvails)
259 importsFromImportDecl this_mod
260 (L loc (ImportDecl loc_imp_mod_name want_boot qual_only as_mod imp_details))
264 -- If there's an error in loadInterface, (e.g. interface
265 -- file not found) we get lots of spurious errors from 'filterImports'
267 imp_mod_name = unLoc loc_imp_mod_name
268 doc = ppr imp_mod_name <+> ptext SLIT("is directly imported")
270 loadSrcInterface doc imp_mod_name want_boot `thenM` \ iface ->
272 -- Compiler sanity check: if the import didn't say
273 -- {-# SOURCE #-} we should not get a hi-boot file
274 WARN( not want_boot && mi_boot iface, ppr imp_mod_name )
276 -- Issue a user warning for a redundant {- SOURCE -} import
277 -- NB that we arrange to read all the ordinary imports before
278 -- any of the {- SOURCE -} imports
279 warnIf (want_boot && not (mi_boot iface))
280 (warnRedundantSourceImport imp_mod_name) `thenM_`
283 imp_mod = mi_module iface
284 deprecs = mi_deprecs iface
285 is_orph = mi_orphan iface
288 filtered_exports = filter not_this_mod (mi_exports iface)
289 not_this_mod (mod,_) = mod /= this_mod
290 -- If the module exports anything defined in this module, just ignore it.
291 -- Reason: otherwise it looks as if there are two local definition sites
292 -- for the thing, and an error gets reported. Easiest thing is just to
293 -- filter them out up front. This situation only arises if a module
294 -- imports itself, or another module that imported it. (Necessarily,
295 -- this invoves a loop.)
297 -- Tiresome consequence: if you say
302 -- module B( AType ) where
303 -- import {-# SOURCE #-} A( AType )
305 -- then you'll get a 'B does not export AType' message. Oh well.
307 qual_mod_name = case as_mod of
308 Nothing -> imp_mod_name
309 Just another_name -> another_name
310 imp_spec = ImpDeclSpec { is_mod = imp_mod_name, is_qual = qual_only,
311 is_dloc = loc, is_as = qual_mod_name }
313 -- Get the total imports, and filter them according to the import list
314 ifaceExportNames filtered_exports `thenM` \ total_avails ->
315 filterImports iface imp_spec
316 imp_details total_avails `thenM` \ (avail_env, gbl_env) ->
318 getDOpts `thenM` \ dflags ->
321 -- Compute new transitive dependencies
323 orphans | is_orph = ASSERT( not (imp_mod_name `elem` dep_orphs deps) )
324 imp_mod_name : dep_orphs deps
325 | otherwise = dep_orphs deps
327 (dependent_mods, dependent_pkgs)
328 = case mi_package iface of
330 -- Imported module is from the home package
331 -- Take its dependent modules and add imp_mod itself
332 -- Take its dependent packages unchanged
334 -- NB: (dep_mods deps) might include a hi-boot file
335 -- for the module being compiled, CM. Do *not* filter
336 -- this out (as we used to), because when we've
337 -- finished dealing with the direct imports we want to
338 -- know if any of them depended on CM.hi-boot, in
339 -- which case we should do the hi-boot consistency
340 -- check. See LoadIface.loadHiBootInterface
341 ((imp_mod_name, want_boot) : dep_mods deps, dep_pkgs deps)
344 -- Imported module is from another package
345 -- Dump the dependent modules
346 -- Add the package imp_mod comes from to the dependent packages
347 ASSERT2( not (pkg `elem` dep_pkgs deps), ppr pkg <+> ppr (dep_pkgs deps) )
348 ([], pkg : dep_pkgs deps)
350 -- True <=> import M ()
351 import_all = case imp_details of
352 Just (is_hiding, ls) -> not is_hiding && null ls
355 -- unqual_avails is the Avails that are visible in *unqualified* form
356 -- We need to know this so we know what to export when we see
357 -- module M ( module P ) where ...
358 -- Then we must export whatever came from P unqualified.
359 imports = ImportAvails {
360 imp_env = unitModuleEnv qual_mod_name avail_env,
361 imp_mods = unitModuleEnv imp_mod (imp_mod, import_all, loc),
363 imp_dep_mods = mkModDeps dependent_mods,
364 imp_dep_pkgs = dependent_pkgs }
367 -- Complain if we import a deprecated module
368 ifOptM Opt_WarnDeprecations (
370 DeprecAll txt -> addWarn (moduleDeprec imp_mod_name txt)
374 returnM (gbl_env, imports)
376 warnRedundantSourceImport mod_name
377 = ptext SLIT("Unnecessary {- SOURCE -} in the import of module")
378 <+> quotes (ppr mod_name)
382 %************************************************************************
384 importsFromLocalDecls
386 %************************************************************************
388 From the top-level declarations of this module produce
389 * the lexical environment
391 created by its bindings.
393 Complain about duplicate bindings
396 importsFromLocalDecls :: HsGroup RdrName -> RnM TcGblEnv
397 importsFromLocalDecls group
398 = do { gbl_env <- getGblEnv
400 ; names <- getLocalDeclBinders gbl_env group
402 ; implicit_prelude <- doptM Opt_ImplicitPrelude
404 -- Optimisation: filter out names for built-in syntax
405 -- They just clutter up the environment (esp tuples), and the parser
406 -- will generate Exact RdrNames for them, so the cluttered
407 -- envt is no use. To avoid doing this filter all the time,
408 -- we use -fno-implicit-prelude as a clue that the filter is
409 -- worth while. Really, it's only useful for GHC.Base and GHC.Tuple.
411 -- It's worth doing because it makes the environment smaller for
412 -- every module that imports the Prelude
414 -- Note: don't filter the gbl_env (hence all_names, not filered_all_names
415 -- in defn of gres above). Stupid reason: when parsing
416 -- data type decls, the constructors start as Exact tycon-names,
417 -- and then get turned into data con names by zapping the name space;
418 -- but that stops them being Exact, so they get looked up.
419 -- Ditto in fixity decls; e.g. infix 5 :
420 -- Sigh. It doesn't matter because it only affects the Data.Tuple really.
421 -- The important thing is to trim down the exports.
423 | implicit_prelude = names
424 | otherwise = filter (not . isBuiltInSyntax) names ;
426 ; this_mod = tcg_mod gbl_env
427 ; imports = emptyImportAvails {
428 imp_env = unitModuleEnv this_mod $
429 mkNameSet filtered_names
433 ; rdr_env' <- extendRdrEnvRn (tcg_rdr_env gbl_env) names
435 ; returnM (gbl_env { tcg_rdr_env = rdr_env',
436 tcg_imports = imports `plusImportAvails` tcg_imports gbl_env })
439 extendRdrEnvRn :: GlobalRdrEnv -> [Name] -> RnM GlobalRdrEnv
440 -- Add the new locally-bound names one by one, checking for duplicates as
441 -- we do so. Remember that in Template Haskell the duplicates
442 -- might *already be* in the GlobalRdrEnv from higher up the module
443 extendRdrEnvRn rdr_env names
444 = foldlM add_local rdr_env names
446 add_local rdr_env name
447 | gres <- lookupGlobalRdrEnv rdr_env (nameOccName name)
448 , (dup_gre:_) <- filter isLocalGRE gres -- Check for existing *local* defns
449 = do { addDupDeclErr (gre_name dup_gre) name
452 = return (extendGlobalRdrEnv rdr_env new_gre)
454 new_gre = GRE {gre_name = name, gre_prov = LocalDef}
457 @getLocalDeclBinders@ returns the names for an @HsDecl@. It's
458 used for source code.
460 *** See "THE NAMING STORY" in HsDecls ****
463 getLocalDeclBinders :: TcGblEnv -> HsGroup RdrName -> RnM [Name]
464 getLocalDeclBinders gbl_env (HsGroup {hs_valds = ValBindsIn val_decls val_sigs,
465 hs_tyclds = tycl_decls,
466 hs_fords = foreign_decls })
467 = do { tc_names_s <- mappM new_tc tycl_decls
468 ; val_names <- mappM new_simple val_bndrs
469 ; return (foldr (++) val_names tc_names_s) }
471 mod = tcg_mod gbl_env
472 is_hs_boot = isHsBoot (tcg_src gbl_env) ;
473 val_bndrs | is_hs_boot = sig_hs_bndrs
474 | otherwise = for_hs_bndrs ++ val_hs_bndrs
475 -- In a hs-boot file, the value binders come from the
476 -- *signatures*, and there should be no foreign binders
478 new_simple rdr_name = newTopSrcBinder mod Nothing rdr_name
480 sig_hs_bndrs = [nm | L _ (TypeSig nm _) <- val_sigs]
481 val_hs_bndrs = collectHsBindLocatedBinders val_decls
482 for_hs_bndrs = [nm | L _ (ForeignImport nm _ _ _) <- foreign_decls]
485 = do { main_name <- newTopSrcBinder mod Nothing main_rdr
486 ; sub_names <- mappM (newTopSrcBinder mod (Just main_name)) sub_rdrs
487 ; return (main_name : sub_names) }
489 (main_rdr : sub_rdrs) = tyClDeclNames (unLoc tc_decl)
493 %************************************************************************
495 \subsection{Filtering imports}
497 %************************************************************************
499 @filterImports@ takes the @ExportEnv@ telling what the imported module makes
500 available, and filters it through the import spec (if any).
503 filterImports :: ModIface
504 -> ImpDeclSpec -- The span for the entire import decl
505 -> Maybe (Bool, [LIE Name]) -- Import spec; True => hiding
506 -> NameSet -- What's available
507 -> RnM (NameSet, -- What's imported (qualified or unqualified)
508 GlobalRdrEnv) -- Same again, but in GRE form
510 -- Complains if import spec mentions things that the module doesn't export
511 -- Warns/informs if import spec contains duplicates.
513 mkGenericRdrEnv decl_spec names
514 = mkGlobalRdrEnv [ GRE { gre_name = name, gre_prov = Imported [imp_spec] }
515 | name <- nameSetToList names ]
517 imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }
519 filterImports iface decl_spec Nothing all_names
520 = return (all_names, mkGenericRdrEnv decl_spec all_names)
522 filterImports iface decl_spec (Just (want_hiding, import_items)) all_names
523 = mapM (addLocM get_item) import_items >>= \gres_s ->
524 let gres = concat gres_s
525 specified_names = mkNameSet (map gre_name gres)
526 in if not want_hiding then
527 return (specified_names, mkGlobalRdrEnv gres)
528 else let keep n = not (n `elemNameSet` specified_names)
529 pruned_avails = filterNameSet keep all_names
530 in return (pruned_avails, mkGenericRdrEnv decl_spec pruned_avails)
532 sub_env :: NameEnv [Name] -- Classify each name by its parent
533 sub_env = mkSubNameEnv all_names
535 succeed_with :: Bool -> [Name] -> RnM [GlobalRdrElt]
536 succeed_with all_explicit names
537 = do { loc <- getSrcSpanM
538 ; returnM (map (mk_gre loc) names) }
540 mk_gre loc name = GRE { gre_name = name,
541 gre_prov = Imported [imp_spec] }
543 imp_spec = ImpSpec { is_decl = decl_spec, is_item = item_spec }
544 item_spec = ImpSome { is_explicit = explicit, is_iloc = loc }
545 explicit = all_explicit || isNothing (nameParent_maybe name)
547 get_item :: IE Name -> RnM [GlobalRdrElt]
548 -- Empty result for a bad item.
549 -- Singleton result is typical case.
550 -- Can have two when we are hiding, and mention C which might be
551 -- both a class and a data constructor.
552 get_item item@(IEModuleContents _)
553 -- This case should be filtered out by 'rnImports'.
554 = panic "filterImports: IEModuleContents?"
556 get_item (IEThingAll name)
557 = case subNames sub_env name of
558 [] -> do ifOptM Opt_WarnDodgyImports (addWarn (dodgyImportWarn name))
559 succeed_with False [name]
560 names -> succeed_with False (name:names)
562 get_item (IEThingAbs name)
563 = succeed_with True [name]
565 get_item (IEThingWith name names)
566 = succeed_with True (name:names)
567 get_item (IEVar name)
568 = succeed_with True [name]
573 %************************************************************************
575 \subsection{Export list processing}
577 %************************************************************************
579 Processing the export list.
581 You might think that we should record things that appear in the export
582 list as ``occurrences'' (using @addOccurrenceName@), but you'd be
583 wrong. We do check (here) that they are in scope, but there is no
584 need to slurp in their actual declaration (which is what
585 @addOccurrenceName@ forces).
587 Indeed, doing so would big trouble when compiling @PrelBase@, because
588 it re-exports @GHC@, which includes @takeMVar#@, whose type includes
589 @ConcBase.StateAndSynchVar#@, and so on...
592 type ExportAccum -- The type of the accumulating parameter of
593 -- the main worker function in rnExports
594 = ([Module], -- 'module M's seen so far
595 ExportOccMap, -- Tracks exported occurrence names
596 NameSet) -- The accumulated exported stuff
597 emptyExportAccum = ([], emptyOccEnv, emptyNameSet)
599 type ExportOccMap = OccEnv (Name, IE Name)
600 -- Tracks what a particular exported OccName
601 -- in an export list refers to, and which item
602 -- it came from. It's illegal to export two distinct things
603 -- that have the same occurrence name
605 rnExports :: Maybe [LIE RdrName]
606 -> RnM (Maybe [LIE Name])
607 rnExports Nothing = return Nothing
608 rnExports (Just exports)
609 = do TcGblEnv { tcg_imports = ImportAvails { imp_env = imp_env } } <- getGblEnv
610 let sub_env :: NameEnv [Name] -- Classify each name by its parent
611 sub_env = mkSubNameEnv (foldModuleEnv unionNameSets emptyNameSet imp_env)
615 rnExport (IEVar rdrName)
616 = do name <- lookupGlobalOccRn rdrName
618 rnExport (IEThingAbs rdrName)
619 = do name <- lookupGlobalOccRn rdrName
620 return (IEThingAbs name)
621 rnExport (IEThingAll rdrName)
622 = do name <- lookupGlobalOccRn rdrName
623 return (IEThingAll name)
624 rnExport (IEThingWith rdrName rdrNames)
625 = do name <- lookupGlobalOccRn rdrName
626 let env = mkOccEnv [(nameOccName s, s) | s <- subNames sub_env name]
627 mb_names = map (lookupOccEnv env . rdrNameOcc) rdrNames
628 if any isNothing mb_names
629 then -- The export error will be reporting in 'mkExportNameSet'
630 return (IEThingWith name [])
631 else return (IEThingWith name (catMaybes mb_names))
632 rnExport (IEModuleContents mod)
633 = return (IEModuleContents mod)
634 rn_exports <- mapM (inLoc rnExport) exports
635 return (Just rn_exports)
637 mkExportNameSet :: Bool -- False => no 'module M(..) where' header at all
638 -> Maybe [LIE Name] -- Nothing => no explicit export list
640 -- Complains if two distinct exports have same OccName
641 -- Warns about identical exports.
642 -- Complains about exports items not in scope
644 mkExportNameSet explicit_mod exports
645 = do TcGblEnv { tcg_rdr_env = rdr_env,
646 tcg_imports = imports } <- getGblEnv
648 -- If the module header is omitted altogether, then behave
649 -- as if the user had written "module Main(main) where..."
650 -- EXCEPT in interactive mode, when we behave as if he had
651 -- written "module Main where ..."
652 -- Reason: don't want to complain about 'main' not in scope
653 -- in interactive mode
654 ghci_mode <- getGhciMode
655 real_exports <- case () of
658 | ghci_mode == Interactive
661 -> do mainName <- lookupGlobalOccRn main_RDR_Unqual
662 return (Just [noLoc (IEVar mainName)])
663 -- ToDo: the 'noLoc' here is unhelpful if 'main' turns out to be out of scope
664 exports_from_avail real_exports rdr_env imports
667 exports_from_avail Nothing rdr_env imports
668 = -- Export all locally-defined things
669 -- We do this by filtering the global RdrEnv,
670 -- keeping only things that are locally-defined
671 return (mkNameSet [ gre_name gre
672 | gre <- globalRdrEnvElts rdr_env,
675 exports_from_avail (Just items) rdr_env (ImportAvails { imp_env = imp_env })
676 = do (_, _, exports) <- foldlM do_litem emptyExportAccum items
679 sub_env :: NameEnv [Name] -- Classify each name by its parent
680 sub_env = mkSubNameEnv (foldModuleEnv unionNameSets emptyNameSet imp_env)
682 do_litem :: ExportAccum -> LIE Name -> RnM ExportAccum
683 do_litem acc = addLocM (exports_from_item acc)
685 exports_from_item :: ExportAccum -> IE Name -> RnM ExportAccum
686 exports_from_item acc@(mods, occs, exports) ie@(IEModuleContents mod)
687 | mod `elem` mods -- Duplicate export of M
688 = do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
689 warnIf warn_dup_exports (dupModuleExport mod) ;
693 = case lookupModuleEnv imp_env mod of
694 Nothing -> do addErr (modExportErr mod)
697 -> do let new_exports = filterNameSet (inScopeUnqual rdr_env) names
698 -- This check_occs not only finds conflicts between this item
699 -- and others, but also internally within this item. That is,
700 -- if 'M.x' is in scope in several ways, we'll have several
701 -- members of mod_avails with the same OccName.
702 occs' <- check_occs ie occs (nameSetToList new_exports)
703 return (mod:mods, occs', exports `unionNameSets` new_exports)
705 exports_from_item acc@(mods, occs, exports) ie
706 = if isUnboundName (ieName ie)
707 then return acc -- Avoid error cascade
708 else let new_exports = filterAvail ie sub_env in
709 do checkErr (not (null new_exports)) (exportItemErr ie)
710 checkForDodgyExport ie new_exports
711 occs' <- check_occs ie occs new_exports
712 return (mods, occs', addListToNameSet exports new_exports)
714 -------------------------------
715 filterAvail :: IE Name -- Wanted
716 -> NameEnv [Name] -- Maps type/class names to their sub-names
719 filterAvail (IEVar n) subs = [n]
720 filterAvail (IEThingAbs n) subs = [n]
721 filterAvail (IEThingAll n) subs = n : subNames subs n
722 filterAvail (IEThingWith n ns) subs = n : ns
723 filterAvail (IEModuleContents _) _ = panic "filterAvail"
725 subNames :: NameEnv [Name] -> Name -> [Name]
726 subNames env n = lookupNameEnv env n `orElse` []
728 mkSubNameEnv :: NameSet -> NameEnv [Name]
729 -- Maps types and classes to their constructors/classops respectively
730 -- This mapping just makes it easier to deal with A(..) export items
732 = foldNameSet add_name emptyNameEnv names
735 | Just parent <- nameParent_maybe name
736 = extendNameEnv_C (\ns _ -> name:ns) env parent [name]
739 -------------------------------
740 inScopeUnqual :: GlobalRdrEnv -> Name -> Bool
741 -- Checks whether the Name is in scope unqualified,
742 -- regardless of whether it's ambiguous or not
743 inScopeUnqual env n = any unQualOK (lookupGRE_Name env n)
745 -------------------------------
746 checkForDodgyExport :: IE Name -> [Name] -> RnM ()
747 checkForDodgyExport ie@(IEThingAll tc) [n]
748 | isTcOcc (nameOccName n) = addWarn (dodgyExportWarn tc)
749 -- This occurs when you export T(..), but
750 -- only import T abstractly, or T is a synonym.
751 -- The single [n] is the type or class itself
752 | otherwise = addErr (exportItemErr ie)
753 -- This happes if you export x(..), which is bogus
754 checkForDodgyExport _ _ = return ()
756 -------------------------------
757 check_occs :: IE Name -> ExportOccMap -> [Name] -> RnM ExportOccMap
758 check_occs ie occs names
759 = foldlM check occs names
762 = case lookupOccEnv occs name_occ of
763 Nothing -> returnM (extendOccEnv occs name_occ (name, ie))
766 | name == name' -- Duplicate export
767 -> do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
768 warnIf warn_dup_exports (dupExportWarn name_occ ie ie') ;
771 | otherwise -- Same occ name but different names: an error
772 -> do { global_env <- getGlobalRdrEnv ;
773 addErr (exportClashErr global_env name name' ie ie') ;
776 name_occ = nameOccName name
779 %*********************************************************
783 %*********************************************************
786 reportDeprecations :: TcGblEnv -> RnM ()
787 reportDeprecations tcg_env
788 = ifOptM Opt_WarnDeprecations $
789 do { (eps,hpt) <- getEpsAndHpt
790 -- By this time, typechecking is complete,
791 -- so the PIT is fully populated
792 ; mapM_ (check hpt (eps_PIT eps)) all_gres }
794 used_names = allUses (tcg_dus tcg_env)
795 -- Report on all deprecated uses; hence allUses
796 all_gres = globalRdrEnvElts (tcg_rdr_env tcg_env)
798 check hpt pit (GRE {gre_name = name, gre_prov = Imported (imp_spec:_)})
799 | name `elemNameSet` used_names
800 , Just deprec_txt <- lookupDeprec hpt pit name
801 = setSrcSpan (importSpecLoc imp_spec) $
802 addWarn (sep [ptext SLIT("Deprecated use of") <+>
803 pprNonVarNameSpace (occNameSpace (nameOccName name)) <+>
805 (parens imp_msg) <> colon,
808 name_mod = nameModule name
809 imp_mod = importSpecModule imp_spec
810 imp_msg = ptext SLIT("imported from") <+> ppr imp_mod <> extra
811 extra | imp_mod == name_mod = empty
812 | otherwise = ptext SLIT(", but defined in") <+> ppr name_mod
814 check hpt pit ok_gre = returnM () -- Local, or not used, or not deprectated
815 -- The Imported pattern-match: don't deprecate locally defined names
816 -- For a start, we may be exporting a deprecated thing
817 -- Also we may use a deprecated thing in the defn of another
818 -- deprecated things. We may even use a deprecated thing in
819 -- the defn of a non-deprecated thing, when changing a module's
822 lookupDeprec :: HomePackageTable -> PackageIfaceTable
823 -> Name -> Maybe DeprecTxt
824 lookupDeprec hpt pit n
825 = case lookupIface hpt pit (nameModule n) of
826 Just iface -> mi_dep_fn iface n `seqMaybe` -- Bleat if the thing, *or
827 mi_dep_fn iface (nameParent n) -- its parent*, is deprec'd
829 | isWiredInName n -> Nothing
830 -- We have not necessarily loaded the .hi file for a
831 -- wired-in name (yet), although we *could*.
832 -- And we never deprecate them
834 | otherwise -> pprPanic "lookupDeprec" (ppr n)
835 -- By now all the interfaces should have been loaded
837 gre_is_used :: NameSet -> GlobalRdrElt -> Bool
838 gre_is_used used_names gre = gre_name gre `elemNameSet` used_names
841 %*********************************************************
845 %*********************************************************
848 reportUnusedNames :: Maybe [LIE RdrName] -- Export list
849 -> TcGblEnv -> RnM ()
850 reportUnusedNames export_decls gbl_env
851 = do { traceRn ((text "RUN") <+> (ppr (tcg_dus gbl_env)))
852 ; warnUnusedTopBinds unused_locals
853 ; warnUnusedModules unused_imp_mods
854 ; warnUnusedImports unused_imports
855 ; warnDuplicateImports defined_and_used
856 ; printMinimalImports minimal_imports }
858 used_names, all_used_names :: NameSet
859 used_names = findUses (tcg_dus gbl_env) emptyNameSet
860 -- NB: currently, if f x = g, we only treat 'g' as used if 'f' is used
863 all_used_names = used_names `unionNameSets`
864 mkNameSet (mapCatMaybes nameParent_maybe (nameSetToList used_names))
865 -- A use of C implies a use of T,
866 -- if C was brought into scope by T(..) or T(C)
868 -- Collect the defined names from the in-scope environment
869 defined_names :: [GlobalRdrElt]
870 defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)
872 -- Note that defined_and_used, defined_but_not_used
873 -- are both [GRE]; that's why we need defined_and_used
874 -- rather than just all_used_names
875 defined_and_used, defined_but_not_used :: [GlobalRdrElt]
876 (defined_and_used, defined_but_not_used)
877 = partition (gre_is_used all_used_names) defined_names
879 -- Filter out the ones that are
880 -- (a) defined in this module, and
881 -- (b) not defined by a 'deriving' clause
882 -- The latter have an Internal Name, so we can filter them out easily
883 unused_locals :: [GlobalRdrElt]
884 unused_locals = filter is_unused_local defined_but_not_used
885 is_unused_local :: GlobalRdrElt -> Bool
886 is_unused_local gre = isLocalGRE gre && isExternalName (gre_name gre)
888 unused_imports :: [GlobalRdrElt]
889 unused_imports = filter unused_imp defined_but_not_used
890 unused_imp (GRE {gre_prov = Imported imp_specs})
891 = not (all (module_unused . importSpecModule) imp_specs)
892 && or [exp | ImpSpec { is_item = ImpSome { is_explicit = exp } } <- imp_specs]
893 -- Don't complain about unused imports if we've already said the
894 -- entire import is unused
895 unused_imp other = False
897 -- To figure out the minimal set of imports, start with the things
898 -- that are in scope (i.e. in gbl_env). Then just combine them
899 -- into a bunch of avails, so they are properly grouped
901 -- BUG WARNING: this does not deal properly with qualified imports!
902 minimal_imports :: FiniteMap Module AvailEnv
903 minimal_imports0 = foldr add_expall emptyFM expall_mods
904 minimal_imports1 = foldr add_name minimal_imports0 defined_and_used
905 minimal_imports = foldr add_inst_mod minimal_imports1 direct_import_mods
906 -- The last line makes sure that we retain all direct imports
907 -- even if we import nothing explicitly.
908 -- It's not necessarily redundant to import such modules. Consider
912 -- The import M() is not *necessarily* redundant, even if
913 -- we suck in no instance decls from M (e.g. it contains
914 -- no instance decls, or This contains no code). It may be
915 -- that we import M solely to ensure that M's orphan instance
916 -- decls (or those in its imports) are visible to people who
917 -- import This. Sigh.
918 -- There's really no good way to detect this, so the error message
919 -- in RnEnv.warnUnusedModules is weakened instead
921 -- We've carefully preserved the provenance so that we can
922 -- construct minimal imports that import the name by (one of)
923 -- the same route(s) as the programmer originally did.
924 add_name (GRE {gre_name = n, gre_prov = Imported imp_specs}) acc
925 = addToFM_C plusAvailEnv acc (importSpecModule (head imp_specs))
926 (unitAvailEnv (mk_avail n (nameParent_maybe n)))
930 -- Modules mentioned as 'module M' in the export list
931 expall_mods = case export_decls of
933 Just es -> [m | L _ (IEModuleContents m) <- es]
935 -- This is really bogus. The idea is that if we see 'module M' in
936 -- the export list we must retain the import decls that drive it
937 -- If we aren't careful we might see
938 -- module A( module M ) where
941 -- and suppose that N exports everything that M does. Then we
942 -- must not drop the import of M even though N brings it all into
945 -- BUG WARNING: 'module M' exports aside, what if M.x is mentioned?!
947 -- The reason that add_expall is bogus is that it doesn't take
948 -- qualified imports into account. But it's an improvement.
949 add_expall mod acc = addToFM_C plusAvailEnv acc mod emptyAvailEnv
951 -- n is the name of the thing, p is the name of its parent
952 mk_avail n (Just p) = AvailTC p [p,n]
953 mk_avail n Nothing | isTcOcc (nameOccName n) = AvailTC n [n]
954 | otherwise = Avail n
956 add_inst_mod (mod,_,_) acc
957 | mod `elemFM` acc = acc -- We import something already
958 | otherwise = addToFM acc mod emptyAvailEnv
960 -- Add an empty collection of imports for a module
961 -- from which we have sucked only instance decls
963 imports = tcg_imports gbl_env
965 direct_import_mods :: [(Module, Bool, SrcSpan)]
966 -- See the type of the imp_mods for this triple
967 direct_import_mods = moduleEnvElts (imp_mods imports)
969 -- unused_imp_mods are the directly-imported modules
970 -- that are not mentioned in minimal_imports1
971 -- [Note: not 'minimal_imports', because that includes directly-imported
972 -- modules even if we use nothing from them; see notes above]
974 -- BUG WARNING: does not deal correctly with multiple imports of the same module
975 -- becuase direct_import_mods has only one entry per module
976 unused_imp_mods = [(mod,loc) | (mod,no_imp,loc) <- direct_import_mods,
977 not (mod `elemFM` minimal_imports1),
980 -- The not no_imp part is not to complain about
981 -- import M (), which is an idiom for importing
982 -- instance declarations
984 module_unused :: Module -> Bool
985 module_unused mod = any (((==) mod) . fst) unused_imp_mods
987 ---------------------
988 warnDuplicateImports :: [GlobalRdrElt] -> RnM ()
989 -- Given the GREs for names that are used, figure out which imports
990 -- could be omitted without changing the top-level environment.
992 -- NB: Given import Foo( T )
993 -- import qualified Foo
994 -- we do not report a duplicate import, even though Foo.T is brought
995 -- into scope by both, because there's nothing you can *omit* without
996 -- changing the top-level environment. So we complain only if it's
997 -- explicitly named in both imports or neither.
999 -- Furthermore, we complain about Foo.T only if
1000 -- there is no complaint about (unqualified) T
1002 warnDuplicateImports gres
1003 = ifOptM Opt_WarnUnusedImports $
1004 sequenceM_ [ warn name pr
1005 -- The 'head' picks the first offending group
1006 -- for this particular name
1007 | GRE { gre_name = name, gre_prov = Imported imps } <- gres
1008 , pr <- redundants imps ]
1010 warn name (red_imp, cov_imp)
1011 = addWarnAt (importSpecLoc red_imp)
1012 (vcat [ptext SLIT("Redundant import of:") <+> quotes pp_name,
1013 ptext SLIT("It is also") <+> ppr cov_imp])
1015 pp_name | is_qual red_decl = ppr (is_as red_decl) <> dot <> ppr occ
1016 | otherwise = ppr occ
1017 occ = nameOccName name
1018 red_decl = is_decl red_imp
1020 redundants :: [ImportSpec] -> [(ImportSpec,ImportSpec)]
1021 -- The returned pair is (redundant-import, covering-import)
1023 = [ (red_imp, cov_imp)
1025 , cov_imp <- take 1 (filter (covers red_imp) imps) ]
1027 -- "red_imp" is a putative redundant import
1028 -- "cov_imp" potentially covers it
1029 -- This test decides whether red_imp could be dropped
1031 -- NOTE: currently the test does not warn about
1034 -- even if the same underlying 'x' is involved, because dropping
1035 -- either import would change the qualified names in scope (M.x, N.x)
1036 -- But if the qualified names aren't used, the import is indeed redundant
1037 -- Sadly we don't know that. Oh well.
1038 covers red_imp@(ImpSpec { is_decl = red_decl, is_item = red_item })
1039 cov_imp@(ImpSpec { is_decl = cov_decl, is_item = cov_item })
1040 | red_loc == cov_loc
1041 = False -- Ignore diagonal elements
1042 | not (is_as red_decl == is_as cov_decl)
1043 = False -- They bring into scope different qualified names
1044 | not (is_qual red_decl) && is_qual cov_decl
1045 = False -- Covering one doesn't bring unqualified name into scope
1047 = not cov_selective -- Redundant one is selective and covering one isn't
1048 || red_later -- Both are explicit; tie-break using red_later
1050 = not cov_selective -- Neither import is selective
1051 && (is_mod red_decl == is_mod cov_decl) -- They import the same module
1052 && red_later -- Tie-break
1054 red_loc = importSpecLoc red_imp
1055 cov_loc = importSpecLoc cov_imp
1056 red_later = red_loc > cov_loc
1057 cov_selective = selectiveImpItem cov_item
1058 red_selective = selectiveImpItem red_item
1060 selectiveImpItem :: ImpItemSpec -> Bool
1061 selectiveImpItem ImpAll = False
1062 selectiveImpItem (ImpSome {}) = True
1064 -- ToDo: deal with original imports with 'qualified' and 'as M' clauses
1065 printMinimalImports :: FiniteMap Module AvailEnv -- Minimal imports
1067 printMinimalImports imps
1068 = ifOptM Opt_D_dump_minimal_imports $ do {
1070 mod_ies <- mappM to_ies (fmToList imps) ;
1071 this_mod <- getModule ;
1072 rdr_env <- getGlobalRdrEnv ;
1073 ioToTcRn (do { h <- openFile (mkFilename this_mod) WriteMode ;
1074 printForUser h (unQualInScope rdr_env)
1075 (vcat (map ppr_mod_ie mod_ies)) })
1078 mkFilename this_mod = moduleString this_mod ++ ".imports"
1079 ppr_mod_ie (mod_name, ies)
1080 | mod_name == pRELUDE
1082 | null ies -- Nothing except instances comes from here
1083 = ptext SLIT("import") <+> ppr mod_name <> ptext SLIT("() -- Instances only")
1085 = ptext SLIT("import") <+> ppr mod_name <>
1086 parens (fsep (punctuate comma (map ppr ies)))
1088 to_ies (mod, avail_env) = do ies <- mapM to_ie (availEnvElts avail_env)
1091 to_ie :: AvailInfo -> RnM (IE Name)
1092 -- The main trick here is that if we're importing all the constructors
1093 -- we want to say "T(..)", but if we're importing only a subset we want
1094 -- to say "T(A,B,C)". So we have to find out what the module exports.
1095 to_ie (Avail n) = returnM (IEVar n)
1096 to_ie (AvailTC n [m]) = ASSERT( n==m )
1097 returnM (IEThingAbs n)
1098 to_ie (AvailTC n ns)
1099 = loadSrcInterface doc n_mod False `thenM` \ iface ->
1100 case [xs | (m,as) <- mi_exports iface,
1103 x == nameOccName n] of
1104 [xs] | all_used xs -> returnM (IEThingAll n)
1105 | otherwise -> returnM (IEThingWith n (filter (/= n) ns))
1106 other -> pprTrace "to_ie" (ppr n <+> ppr n_mod <+> ppr other) $
1109 all_used avail_occs = all (`elem` map nameOccName ns) avail_occs
1110 doc = text "Compute minimal imports from" <+> ppr n
1111 n_mod = nameModule n
1115 %************************************************************************
1119 %************************************************************************
1122 badImportItemErr iface decl_spec ie
1123 = sep [ptext SLIT("Module"), quotes (ppr (is_mod decl_spec)), source_import,
1124 ptext SLIT("does not export"), quotes (ppr ie)]
1126 source_import | mi_boot iface = ptext SLIT("(hi-boot interface)")
1129 dodgyImportWarn item = dodgyMsg (ptext SLIT("import")) item
1130 dodgyExportWarn item = dodgyMsg (ptext SLIT("export")) item
1133 = sep [ ptext SLIT("The") <+> kind <+> ptext SLIT("item") <+> quotes (ppr (IEThingAll tc)),
1134 ptext SLIT("suggests that") <+> quotes (ppr tc) <+> ptext SLIT("has constructor or class methods"),
1135 ptext SLIT("but it has none; it is a type synonym or abstract type or class") ]
1138 = hsep [ ptext SLIT("Unknown module in export list: module"), quotes (ppr mod)]
1140 exportItemErr export_item
1141 = sep [ ptext SLIT("The export item") <+> quotes (ppr export_item),
1142 ptext SLIT("attempts to export constructors or class methods that are not visible here") ]
1144 exportClashErr global_env name1 name2 ie1 ie2
1145 = vcat [ ptext SLIT("Conflicting exports for") <+> quotes (ppr occ) <> colon
1146 , ppr_export ie1 name1
1147 , ppr_export ie2 name2 ]
1149 occ = nameOccName name1
1150 ppr_export ie name = nest 2 (quotes (ppr ie) <+> ptext SLIT("exports") <+>
1151 quotes (ppr name) <+> pprNameProvenance (get_gre name))
1153 -- get_gre finds a GRE for the Name, so that we can show its provenance
1155 = case lookupGRE_Name global_env name of
1157 [] -> pprPanic "exportClashErr" (ppr name)
1159 addDupDeclErr :: Name -> Name -> TcRn ()
1160 addDupDeclErr name_a name_b
1161 = addErrAt (srcLocSpan loc2) $
1162 vcat [ptext SLIT("Multiple declarations of") <+> quotes (ppr name1),
1163 ptext SLIT("Declared at:") <+> vcat [ppr (nameSrcLoc name1), ppr loc2]]
1165 loc2 = nameSrcLoc name2
1166 (name1,name2) | nameSrcLoc name_a > nameSrcLoc name_b = (name_b,name_a)
1167 | otherwise = (name_a,name_b)
1168 -- Report the error at the later location
1170 dupExportWarn occ_name ie1 ie2
1171 = hsep [quotes (ppr occ_name),
1172 ptext SLIT("is exported by"), quotes (ppr ie1),
1173 ptext SLIT("and"), quotes (ppr ie2)]
1176 = hsep [ptext SLIT("Duplicate"),
1177 quotes (ptext SLIT("Module") <+> ppr mod),
1178 ptext SLIT("in export list")]
1180 moduleDeprec mod txt
1181 = sep [ ptext SLIT("Module") <+> quotes (ppr mod) <+> ptext SLIT("is deprecated:"),