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 = importsFromImportDeclDirect 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 :: ModIface -> ImpDeclSpec -> ImportDecl RdrName -> NameSet -> RnM (ImportDecl Name)
130 rnImportDecl iface decl_spec (ImportDecl loc_imp_mod_name want_boot qual_only as_mod Nothing) all_names
131 = return $ ImportDecl loc_imp_mod_name want_boot qual_only as_mod Nothing
132 rnImportDecl iface decl_spec (ImportDecl loc_imp_mod_name want_boot qual_only as_mod (Just (want_hiding,import_items))) all_names
133 = do import_items_mbs <- mapM (srcSpanWrapper) import_items
134 let rn_import_items = concat . catMaybes $ import_items_mbs
135 return $ ImportDecl loc_imp_mod_name want_boot qual_only as_mod (Just (want_hiding,rn_import_items))
137 srcSpanWrapper (L span ieRdr)
139 case get_item ieRdr of
141 -> do addErr (badImportItemErr iface decl_spec ieRdr)
144 -> return (Just [L span ie | ie <- ieNames])
145 occ_env :: OccEnv Name -- Maps OccName to corresponding Name
146 occ_env = mkOccEnv [(nameOccName n, n) | n <- nameSetToList all_names]
147 -- This env will have entries for data constructors too,
148 -- they won't make any difference because naked entities like T
149 -- in an import list map to TcOccs, not VarOccs.
151 sub_env :: NameEnv [Name]
152 sub_env = mkSubNameEnv all_names
154 get_item :: IE RdrName -> Maybe [IE Name]
155 -- Empty result for a bad item.
156 -- Singleton result is typical case.
157 -- Can have two when we are hiding, and mention C which might be
158 -- both a class and a data constructor.
159 get_item item@(IEModuleContents _)
162 get_item (IEThingAll tc)
163 = do name <- check_name tc
164 return [IEThingAll name]
166 -> -- This occurs when you import T(..), but
167 -- only export T abstractly. The single [n]
168 -- in the AvailTC is the type or class itself
169 ifOptM Opt_WarnDodgyImports (addWarn (dodgyImportWarn tc)) `thenM_`
170 return [ IEThingAll n ]
172 names -> return [ IEThingAll n | n <- names ]
175 get_item (IEThingAbs tc)
176 | want_hiding -- hiding ( C )
177 -- Here the 'C' can be a data constructor
178 -- *or* a type/class, or even both
179 = case catMaybes [check_name tc, check_name (setRdrNameSpace tc srcDataName)] of
181 names -> return [ IEThingAbs n | n <- names ]
183 = do name <- check_name tc
184 return [IEThingAbs name]
185 get_item (IEThingWith n ns) -- import (C (A,B))
186 = do name <- check_name n
187 let env = mkOccEnv [(nameOccName s, s) | s <- subNames sub_env name]
188 mb_names = map (lookupOccEnv env . rdrNameOcc) ns
189 names <- sequence mb_names
190 return [IEThingWith name names]
193 = do name <- check_name n
196 check_name :: RdrName -> Maybe Name
198 = lookupOccEnv occ_env (rdrNameOcc rdrName)
201 importsFromImportDeclDirect :: Module
202 -> LImportDecl RdrName
203 -> RnM (LImportDecl Name)
204 importsFromImportDeclDirect this_mod
205 (L loc importDecl@(ImportDecl loc_imp_mod_name want_boot qual_only as_mod imp_details))
207 do iface <- loadSrcInterface doc imp_mod_name want_boot
208 -- Compiler sanity check: if the import didn't say
209 -- {-# SOURCE #-} we should not get a hi-boot file
210 WARN( not want_boot && mi_boot iface, ppr imp_mod_name ) $ do
211 -- Issue a user warning for a redundant {- SOURCE -} import
212 -- NB that we arrange to read all the ordinary imports before
213 -- any of the {- SOURCE -} imports
214 warnIf (want_boot && not (mi_boot iface))
215 (warnRedundantSourceImport imp_mod_name)
217 let filtered_exports = filter not_this_mod (mi_exports iface)
218 not_this_mod (mod,_) = mod /= this_mod
220 -- If the module exports anything defined in this module, just ignore it.
221 -- Reason: otherwise it looks as if there are two local definition sites
222 -- for the thing, and an error gets reported. Easiest thing is just to
223 -- filter them out up front. This situation only arises if a module
224 -- imports itself, or another module that imported it. (Necessarily,
225 -- this invoves a loop.)
227 -- Tiresome consequence: if you say
232 -- module B( AType ) where
233 -- import {-# SOURCE #-} A( AType )
235 -- then you'll get a 'B does not export AType' message. Oh well.
237 qual_mod_name = case as_mod of
238 Nothing -> imp_mod_name
239 Just another_name -> another_name
240 imp_spec = ImpDeclSpec { is_mod = imp_mod_name, is_qual = qual_only,
241 is_dloc = loc, is_as = qual_mod_name }
243 -- Get the total imports, and filter them according to the import list
244 total_avails <- ifaceExportNames filtered_exports
245 importDecl' <- rnImportDecl iface imp_spec importDecl total_avails
246 return (L loc importDecl')
247 where imp_mod_name = unLoc loc_imp_mod_name
248 doc = ppr imp_mod_name <+> ptext SLIT("is directly imported")
250 importsFromImportDecl :: Module
252 -> RnM (GlobalRdrEnv, ImportAvails)
254 importsFromImportDecl this_mod
255 (L loc (ImportDecl loc_imp_mod_name want_boot qual_only as_mod imp_details))
259 -- If there's an error in loadInterface, (e.g. interface
260 -- file not found) we get lots of spurious errors from 'filterImports'
262 imp_mod_name = unLoc loc_imp_mod_name
263 doc = ppr imp_mod_name <+> ptext SLIT("is directly imported")
265 loadSrcInterface doc imp_mod_name want_boot `thenM` \ iface ->
267 -- Compiler sanity check: if the import didn't say
268 -- {-# SOURCE #-} we should not get a hi-boot file
269 WARN( not want_boot && mi_boot iface, ppr imp_mod_name )
271 -- Issue a user warning for a redundant {- SOURCE -} import
272 -- NB that we arrange to read all the ordinary imports before
273 -- any of the {- SOURCE -} imports
274 warnIf (want_boot && not (mi_boot iface))
275 (warnRedundantSourceImport imp_mod_name) `thenM_`
278 imp_mod = mi_module iface
279 deprecs = mi_deprecs iface
280 is_orph = mi_orphan iface
283 filtered_exports = filter not_this_mod (mi_exports iface)
284 not_this_mod (mod,_) = mod /= this_mod
285 -- If the module exports anything defined in this module, just ignore it.
286 -- Reason: otherwise it looks as if there are two local definition sites
287 -- for the thing, and an error gets reported. Easiest thing is just to
288 -- filter them out up front. This situation only arises if a module
289 -- imports itself, or another module that imported it. (Necessarily,
290 -- this invoves a loop.)
292 -- Tiresome consequence: if you say
297 -- module B( AType ) where
298 -- import {-# SOURCE #-} A( AType )
300 -- then you'll get a 'B does not export AType' message. Oh well.
302 qual_mod_name = case as_mod of
303 Nothing -> imp_mod_name
304 Just another_name -> another_name
305 imp_spec = ImpDeclSpec { is_mod = imp_mod_name, is_qual = qual_only,
306 is_dloc = loc, is_as = qual_mod_name }
308 -- Get the total imports, and filter them according to the import list
309 ifaceExportNames filtered_exports `thenM` \ total_avails ->
310 filterImports iface imp_spec
311 imp_details total_avails `thenM` \ (avail_env, gbl_env) ->
313 getDOpts `thenM` \ dflags ->
316 -- Compute new transitive dependencies
318 orphans | is_orph = ASSERT( not (imp_mod_name `elem` dep_orphs deps) )
319 imp_mod_name : dep_orphs deps
320 | otherwise = dep_orphs deps
322 (dependent_mods, dependent_pkgs)
323 = case mi_package iface of
325 -- Imported module is from the home package
326 -- Take its dependent modules and add imp_mod itself
327 -- Take its dependent packages unchanged
329 -- NB: (dep_mods deps) might include a hi-boot file
330 -- for the module being compiled, CM. Do *not* filter
331 -- this out (as we used to), because when we've
332 -- finished dealing with the direct imports we want to
333 -- know if any of them depended on CM.hi-boot, in
334 -- which case we should do the hi-boot consistency
335 -- check. See LoadIface.loadHiBootInterface
336 ((imp_mod_name, want_boot) : dep_mods deps, dep_pkgs deps)
339 -- Imported module is from another package
340 -- Dump the dependent modules
341 -- Add the package imp_mod comes from to the dependent packages
342 ASSERT2( not (pkg `elem` dep_pkgs deps), ppr pkg <+> ppr (dep_pkgs deps) )
343 ([], pkg : dep_pkgs deps)
345 -- True <=> import M ()
346 import_all = case imp_details of
347 Just (is_hiding, ls) -> not is_hiding && null ls
350 -- unqual_avails is the Avails that are visible in *unqualified* form
351 -- We need to know this so we know what to export when we see
352 -- module M ( module P ) where ...
353 -- Then we must export whatever came from P unqualified.
354 imports = ImportAvails {
355 imp_env = unitModuleEnv qual_mod_name avail_env,
356 imp_mods = unitModuleEnv imp_mod (imp_mod, import_all, loc),
358 imp_dep_mods = mkModDeps dependent_mods,
359 imp_dep_pkgs = dependent_pkgs }
362 -- Complain if we import a deprecated module
363 ifOptM Opt_WarnDeprecations (
365 DeprecAll txt -> addWarn (moduleDeprec imp_mod_name txt)
369 returnM (gbl_env, imports)
371 warnRedundantSourceImport mod_name
372 = ptext SLIT("Unnecessary {- SOURCE -} in the import of module")
373 <+> quotes (ppr mod_name)
377 %************************************************************************
379 importsFromLocalDecls
381 %************************************************************************
383 From the top-level declarations of this module produce
384 * the lexical environment
386 created by its bindings.
388 Complain about duplicate bindings
391 importsFromLocalDecls :: HsGroup RdrName -> RnM TcGblEnv
392 importsFromLocalDecls group
393 = do { gbl_env <- getGblEnv
395 ; names <- getLocalDeclBinders gbl_env group
397 ; implicit_prelude <- doptM Opt_ImplicitPrelude
399 -- Optimisation: filter out names for built-in syntax
400 -- They just clutter up the environment (esp tuples), and the parser
401 -- will generate Exact RdrNames for them, so the cluttered
402 -- envt is no use. To avoid doing this filter all the time,
403 -- we use -fno-implicit-prelude as a clue that the filter is
404 -- worth while. Really, it's only useful for GHC.Base and GHC.Tuple.
406 -- It's worth doing because it makes the environment smaller for
407 -- every module that imports the Prelude
409 -- Note: don't filter the gbl_env (hence all_names, not filered_all_names
410 -- in defn of gres above). Stupid reason: when parsing
411 -- data type decls, the constructors start as Exact tycon-names,
412 -- and then get turned into data con names by zapping the name space;
413 -- but that stops them being Exact, so they get looked up.
414 -- Ditto in fixity decls; e.g. infix 5 :
415 -- Sigh. It doesn't matter because it only affects the Data.Tuple really.
416 -- The important thing is to trim down the exports.
418 | implicit_prelude = names
419 | otherwise = filter (not . isBuiltInSyntax) names ;
421 ; this_mod = tcg_mod gbl_env
422 ; imports = emptyImportAvails {
423 imp_env = unitModuleEnv this_mod $
424 mkNameSet filtered_names
428 ; rdr_env' <- extendRdrEnvRn (tcg_rdr_env gbl_env) names
430 ; returnM (gbl_env { tcg_rdr_env = rdr_env',
431 tcg_imports = imports `plusImportAvails` tcg_imports gbl_env })
434 extendRdrEnvRn :: GlobalRdrEnv -> [Name] -> RnM GlobalRdrEnv
435 -- Add the new locally-bound names one by one, checking for duplicates as
436 -- we do so. Remember that in Template Haskell the duplicates
437 -- might *already be* in the GlobalRdrEnv from higher up the module
438 extendRdrEnvRn rdr_env names
439 = foldlM add_local rdr_env names
441 add_local rdr_env name
442 | gres <- lookupGlobalRdrEnv rdr_env (nameOccName name)
443 , (dup_gre:_) <- filter isLocalGRE gres -- Check for existing *local* defns
444 = do { addDupDeclErr (gre_name dup_gre) name
447 = return (extendGlobalRdrEnv rdr_env new_gre)
449 new_gre = GRE {gre_name = name, gre_prov = LocalDef}
452 @getLocalDeclBinders@ returns the names for an @HsDecl@. It's
453 used for source code.
455 *** See "THE NAMING STORY" in HsDecls ****
458 getLocalDeclBinders :: TcGblEnv -> HsGroup RdrName -> RnM [Name]
459 getLocalDeclBinders gbl_env (HsGroup {hs_valds = ValBindsIn val_decls val_sigs,
460 hs_tyclds = tycl_decls,
461 hs_fords = foreign_decls })
462 = do { tc_names_s <- mappM new_tc tycl_decls
463 ; val_names <- mappM new_simple val_bndrs
464 ; return (foldr (++) val_names tc_names_s) }
466 mod = tcg_mod gbl_env
467 is_hs_boot = isHsBoot (tcg_src gbl_env) ;
468 val_bndrs | is_hs_boot = sig_hs_bndrs
469 | otherwise = for_hs_bndrs ++ val_hs_bndrs
470 -- In a hs-boot file, the value binders come from the
471 -- *signatures*, and there should be no foreign binders
473 new_simple rdr_name = newTopSrcBinder mod Nothing rdr_name
475 sig_hs_bndrs = [nm | L _ (TypeSig nm _) <- val_sigs]
476 val_hs_bndrs = collectHsBindLocatedBinders val_decls
477 for_hs_bndrs = [nm | L _ (ForeignImport nm _ _ _) <- foreign_decls]
480 = do { main_name <- newTopSrcBinder mod Nothing main_rdr
481 ; sub_names <- mappM (newTopSrcBinder mod (Just main_name)) sub_rdrs
482 ; return (main_name : sub_names) }
484 (main_rdr : sub_rdrs) = tyClDeclNames (unLoc tc_decl)
488 %************************************************************************
490 \subsection{Filtering imports}
492 %************************************************************************
494 @filterImports@ takes the @ExportEnv@ telling what the imported module makes
495 available, and filters it through the import spec (if any).
498 filterImports :: ModIface
499 -> ImpDeclSpec -- The span for the entire import decl
500 -> Maybe (Bool, [LIE Name]) -- Import spec; True => hiding
501 -> NameSet -- What's available
502 -> RnM (NameSet, -- What's imported (qualified or unqualified)
503 GlobalRdrEnv) -- Same again, but in GRE form
505 -- Complains if import spec mentions things that the module doesn't export
506 -- Warns/informs if import spec contains duplicates.
508 mkGenericRdrEnv decl_spec names
509 = mkGlobalRdrEnv [ GRE { gre_name = name, gre_prov = Imported [imp_spec] }
510 | name <- nameSetToList names ]
512 imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }
514 filterImports iface decl_spec Nothing all_names
515 = return (all_names, mkGenericRdrEnv decl_spec all_names)
517 filterImports iface decl_spec (Just (want_hiding, import_items)) all_names
518 = mapM (addLocM get_item) import_items >>= \gres_s ->
519 let gres = concat gres_s
520 specified_names = mkNameSet (map gre_name gres)
521 in if not want_hiding then
522 return (specified_names, mkGlobalRdrEnv gres)
523 else let keep n = not (n `elemNameSet` specified_names)
524 pruned_avails = filterNameSet keep all_names
525 in return (pruned_avails, mkGenericRdrEnv decl_spec pruned_avails)
527 sub_env :: NameEnv [Name] -- Classify each name by its parent
528 sub_env = mkSubNameEnv all_names
530 succeed_with :: Bool -> [Name] -> RnM [GlobalRdrElt]
531 succeed_with all_explicit names
532 = do { loc <- getSrcSpanM
533 ; returnM (map (mk_gre loc) names) }
535 mk_gre loc name = GRE { gre_name = name,
536 gre_prov = Imported [imp_spec] }
538 imp_spec = ImpSpec { is_decl = decl_spec, is_item = item_spec }
539 item_spec = ImpSome { is_explicit = explicit, is_iloc = loc }
540 explicit = all_explicit || isNothing (nameParent_maybe name)
542 get_item :: IE Name -> RnM [GlobalRdrElt]
543 -- Empty result for a bad item.
544 -- Singleton result is typical case.
545 -- Can have two when we are hiding, and mention C which might be
546 -- both a class and a data constructor.
547 get_item item@(IEModuleContents _)
548 -- This case should be filtered out by 'rnImports'.
549 = panic "filterImports: IEModuleContents?"
551 get_item (IEThingAll name)
552 = case subNames sub_env name of
553 [] -> do ifOptM Opt_WarnDodgyImports (addWarn (dodgyImportWarn name))
554 succeed_with False [name]
555 names -> succeed_with False (name:names)
557 get_item (IEThingAbs name)
558 = succeed_with True [name]
560 get_item (IEThingWith name names)
561 = succeed_with True (name:names)
562 get_item (IEVar name)
563 = succeed_with True [name]
568 %************************************************************************
570 \subsection{Export list processing}
572 %************************************************************************
574 Processing the export list.
576 You might think that we should record things that appear in the export
577 list as ``occurrences'' (using @addOccurrenceName@), but you'd be
578 wrong. We do check (here) that they are in scope, but there is no
579 need to slurp in their actual declaration (which is what
580 @addOccurrenceName@ forces).
582 Indeed, doing so would big trouble when compiling @PrelBase@, because
583 it re-exports @GHC@, which includes @takeMVar#@, whose type includes
584 @ConcBase.StateAndSynchVar#@, and so on...
587 type ExportAccum -- The type of the accumulating parameter of
588 -- the main worker function in rnExports
589 = ([Module], -- 'module M's seen so far
590 ExportOccMap, -- Tracks exported occurrence names
591 NameSet) -- The accumulated exported stuff
592 emptyExportAccum = ([], emptyOccEnv, emptyNameSet)
594 type ExportOccMap = OccEnv (Name, IE Name)
595 -- Tracks what a particular exported OccName
596 -- in an export list refers to, and which item
597 -- it came from. It's illegal to export two distinct things
598 -- that have the same occurrence name
600 rnExports :: Maybe [LIE RdrName]
601 -> RnM (Maybe [LIE Name])
602 rnExports Nothing = return Nothing
603 rnExports (Just exports)
604 = do TcGblEnv { tcg_imports = ImportAvails { imp_env = imp_env } } <- getGblEnv
605 let sub_env :: NameEnv [Name] -- Classify each name by its parent
606 sub_env = mkSubNameEnv (foldModuleEnv unionNameSets emptyNameSet imp_env)
610 rnExport (IEVar rdrName)
611 = do name <- lookupGlobalOccRn rdrName
613 rnExport (IEThingAbs rdrName)
614 = do name <- lookupGlobalOccRn rdrName
615 return (IEThingAbs name)
616 rnExport (IEThingAll rdrName)
617 = do name <- lookupGlobalOccRn rdrName
618 return (IEThingAll name)
619 rnExport (IEThingWith rdrName rdrNames)
620 = do name <- lookupGlobalOccRn rdrName
621 let env = mkOccEnv [(nameOccName s, s) | s <- subNames sub_env name]
622 mb_names = map (lookupOccEnv env . rdrNameOcc) rdrNames
623 if any isNothing mb_names
624 then -- The export error will be reporting in 'mkExportNameSet'
625 return (IEThingWith name [])
626 else return (IEThingWith name (catMaybes mb_names))
627 rnExport (IEModuleContents mod)
628 = return (IEModuleContents mod)
629 rn_exports <- mapM (inLoc rnExport) exports
630 return (Just rn_exports)
632 mkExportNameSet :: Bool -- False => no 'module M(..) where' header at all
633 -> Maybe [LIE Name] -- Nothing => no explicit export list
635 -- Complains if two distinct exports have same OccName
636 -- Warns about identical exports.
637 -- Complains about exports items not in scope
639 mkExportNameSet explicit_mod exports
640 = do TcGblEnv { tcg_rdr_env = rdr_env,
641 tcg_imports = imports } <- getGblEnv
643 -- If the module header is omitted altogether, then behave
644 -- as if the user had written "module Main(main) where..."
645 -- EXCEPT in interactive mode, when we behave as if he had
646 -- written "module Main where ..."
647 -- Reason: don't want to complain about 'main' not in scope
648 -- in interactive mode
649 ghci_mode <- getGhciMode
650 real_exports <- case () of
653 | ghci_mode == Interactive
656 -> do mainName <- lookupGlobalOccRn main_RDR_Unqual
657 return (Just [noLoc (IEVar mainName)])
658 -- ToDo: the 'noLoc' here is unhelpful if 'main' turns out to be out of scope
659 exports_from_avail real_exports rdr_env imports
662 exports_from_avail Nothing rdr_env imports
663 = -- Export all locally-defined things
664 -- We do this by filtering the global RdrEnv,
665 -- keeping only things that are locally-defined
666 return (mkNameSet [ gre_name gre
667 | gre <- globalRdrEnvElts rdr_env,
670 exports_from_avail (Just items) rdr_env (ImportAvails { imp_env = imp_env })
671 = do (_, _, exports) <- foldlM do_litem emptyExportAccum items
674 sub_env :: NameEnv [Name] -- Classify each name by its parent
675 sub_env = mkSubNameEnv (foldModuleEnv unionNameSets emptyNameSet imp_env)
677 do_litem :: ExportAccum -> LIE Name -> RnM ExportAccum
678 do_litem acc = addLocM (exports_from_item acc)
680 exports_from_item :: ExportAccum -> IE Name -> RnM ExportAccum
681 exports_from_item acc@(mods, occs, exports) ie@(IEModuleContents mod)
682 | mod `elem` mods -- Duplicate export of M
683 = do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
684 warnIf warn_dup_exports (dupModuleExport mod) ;
688 = case lookupModuleEnv imp_env mod of
689 Nothing -> do addErr (modExportErr mod)
692 -> do let new_exports = filterNameSet (inScopeUnqual rdr_env) names
693 -- This check_occs not only finds conflicts between this item
694 -- and others, but also internally within this item. That is,
695 -- if 'M.x' is in scope in several ways, we'll have several
696 -- members of mod_avails with the same OccName.
697 occs' <- check_occs ie occs (nameSetToList new_exports)
698 return (mod:mods, occs', exports `unionNameSets` new_exports)
700 exports_from_item acc@(mods, occs, exports) ie
701 = if isUnboundName (ieName ie)
702 then return acc -- Avoid error cascade
703 else let new_exports = filterAvail ie sub_env in
704 do checkErr (not (null new_exports)) (exportItemErr ie)
705 checkForDodgyExport ie new_exports
706 occs' <- check_occs ie occs new_exports
707 return (mods, occs', addListToNameSet exports new_exports)
709 -------------------------------
710 filterAvail :: IE Name -- Wanted
711 -> NameEnv [Name] -- Maps type/class names to their sub-names
714 filterAvail (IEVar n) subs = [n]
715 filterAvail (IEThingAbs n) subs = [n]
716 filterAvail (IEThingAll n) subs = n : subNames subs n
717 filterAvail (IEThingWith n ns) subs = n : ns
718 filterAvail (IEModuleContents _) _ = panic "filterAvail"
720 subNames :: NameEnv [Name] -> Name -> [Name]
721 subNames env n = lookupNameEnv env n `orElse` []
723 mkSubNameEnv :: NameSet -> NameEnv [Name]
724 -- Maps types and classes to their constructors/classops respectively
725 -- This mapping just makes it easier to deal with A(..) export items
727 = foldNameSet add_name emptyNameEnv names
730 | Just parent <- nameParent_maybe name
731 = extendNameEnv_C (\ns _ -> name:ns) env parent [name]
734 -------------------------------
735 inScopeUnqual :: GlobalRdrEnv -> Name -> Bool
736 -- Checks whether the Name is in scope unqualified,
737 -- regardless of whether it's ambiguous or not
738 inScopeUnqual env n = any unQualOK (lookupGRE_Name env n)
740 -------------------------------
741 checkForDodgyExport :: IE Name -> [Name] -> RnM ()
742 checkForDodgyExport ie@(IEThingAll tc) [n]
743 | isTcOcc (nameOccName n) = addWarn (dodgyExportWarn tc)
744 -- This occurs when you export T(..), but
745 -- only import T abstractly, or T is a synonym.
746 -- The single [n] is the type or class itself
747 | otherwise = addErr (exportItemErr ie)
748 -- This happes if you export x(..), which is bogus
749 checkForDodgyExport _ _ = return ()
751 -------------------------------
752 check_occs :: IE Name -> ExportOccMap -> [Name] -> RnM ExportOccMap
753 check_occs ie occs names
754 = foldlM check occs names
757 = case lookupOccEnv occs name_occ of
758 Nothing -> returnM (extendOccEnv occs name_occ (name, ie))
761 | name == name' -- Duplicate export
762 -> do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
763 warnIf warn_dup_exports (dupExportWarn name_occ ie ie') ;
766 | otherwise -- Same occ name but different names: an error
767 -> do { global_env <- getGlobalRdrEnv ;
768 addErr (exportClashErr global_env name name' ie ie') ;
771 name_occ = nameOccName name
774 %*********************************************************
778 %*********************************************************
781 reportDeprecations :: TcGblEnv -> RnM ()
782 reportDeprecations tcg_env
783 = ifOptM Opt_WarnDeprecations $
784 do { (eps,hpt) <- getEpsAndHpt
785 -- By this time, typechecking is complete,
786 -- so the PIT is fully populated
787 ; mapM_ (check hpt (eps_PIT eps)) all_gres }
789 used_names = allUses (tcg_dus tcg_env)
790 -- Report on all deprecated uses; hence allUses
791 all_gres = globalRdrEnvElts (tcg_rdr_env tcg_env)
793 check hpt pit (GRE {gre_name = name, gre_prov = Imported (imp_spec:_)})
794 | name `elemNameSet` used_names
795 , Just deprec_txt <- lookupDeprec hpt pit name
796 = setSrcSpan (importSpecLoc imp_spec) $
797 addWarn (sep [ptext SLIT("Deprecated use of") <+>
798 pprNonVarNameSpace (occNameSpace (nameOccName name)) <+>
800 (parens imp_msg) <> colon,
803 name_mod = nameModule name
804 imp_mod = importSpecModule imp_spec
805 imp_msg = ptext SLIT("imported from") <+> ppr imp_mod <> extra
806 extra | imp_mod == name_mod = empty
807 | otherwise = ptext SLIT(", but defined in") <+> ppr name_mod
809 check hpt pit ok_gre = returnM () -- Local, or not used, or not deprectated
810 -- The Imported pattern-match: don't deprecate locally defined names
811 -- For a start, we may be exporting a deprecated thing
812 -- Also we may use a deprecated thing in the defn of another
813 -- deprecated things. We may even use a deprecated thing in
814 -- the defn of a non-deprecated thing, when changing a module's
817 lookupDeprec :: HomePackageTable -> PackageIfaceTable
818 -> Name -> Maybe DeprecTxt
819 lookupDeprec hpt pit n
820 = case lookupIface hpt pit (nameModule n) of
821 Just iface -> mi_dep_fn iface n `seqMaybe` -- Bleat if the thing, *or
822 mi_dep_fn iface (nameParent n) -- its parent*, is deprec'd
824 | isWiredInName n -> Nothing
825 -- We have not necessarily loaded the .hi file for a
826 -- wired-in name (yet), although we *could*.
827 -- And we never deprecate them
829 | otherwise -> pprPanic "lookupDeprec" (ppr n)
830 -- By now all the interfaces should have been loaded
832 gre_is_used :: NameSet -> GlobalRdrElt -> Bool
833 gre_is_used used_names gre = gre_name gre `elemNameSet` used_names
836 %*********************************************************
840 %*********************************************************
843 reportUnusedNames :: Maybe [LIE RdrName] -- Export list
844 -> TcGblEnv -> RnM ()
845 reportUnusedNames export_decls gbl_env
846 = do { traceRn ((text "RUN") <+> (ppr (tcg_dus gbl_env)))
847 ; warnUnusedTopBinds unused_locals
848 ; warnUnusedModules unused_imp_mods
849 ; warnUnusedImports unused_imports
850 ; warnDuplicateImports defined_and_used
851 ; printMinimalImports minimal_imports }
853 used_names, all_used_names :: NameSet
854 used_names = findUses (tcg_dus gbl_env) emptyNameSet
855 -- NB: currently, if f x = g, we only treat 'g' as used if 'f' is used
858 all_used_names = used_names `unionNameSets`
859 mkNameSet (mapCatMaybes nameParent_maybe (nameSetToList used_names))
860 -- A use of C implies a use of T,
861 -- if C was brought into scope by T(..) or T(C)
863 -- Collect the defined names from the in-scope environment
864 defined_names :: [GlobalRdrElt]
865 defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)
867 -- Note that defined_and_used, defined_but_not_used
868 -- are both [GRE]; that's why we need defined_and_used
869 -- rather than just all_used_names
870 defined_and_used, defined_but_not_used :: [GlobalRdrElt]
871 (defined_and_used, defined_but_not_used)
872 = partition (gre_is_used all_used_names) defined_names
874 -- Filter out the ones that are
875 -- (a) defined in this module, and
876 -- (b) not defined by a 'deriving' clause
877 -- The latter have an Internal Name, so we can filter them out easily
878 unused_locals :: [GlobalRdrElt]
879 unused_locals = filter is_unused_local defined_but_not_used
880 is_unused_local :: GlobalRdrElt -> Bool
881 is_unused_local gre = isLocalGRE gre && isExternalName (gre_name gre)
883 unused_imports :: [GlobalRdrElt]
884 unused_imports = filter unused_imp defined_but_not_used
885 unused_imp (GRE {gre_prov = Imported imp_specs})
886 = not (all (module_unused . importSpecModule) imp_specs)
887 && or [exp | ImpSpec { is_item = ImpSome { is_explicit = exp } } <- imp_specs]
888 -- Don't complain about unused imports if we've already said the
889 -- entire import is unused
890 unused_imp other = False
892 -- To figure out the minimal set of imports, start with the things
893 -- that are in scope (i.e. in gbl_env). Then just combine them
894 -- into a bunch of avails, so they are properly grouped
896 -- BUG WARNING: this does not deal properly with qualified imports!
897 minimal_imports :: FiniteMap Module AvailEnv
898 minimal_imports0 = foldr add_expall emptyFM expall_mods
899 minimal_imports1 = foldr add_name minimal_imports0 defined_and_used
900 minimal_imports = foldr add_inst_mod minimal_imports1 direct_import_mods
901 -- The last line makes sure that we retain all direct imports
902 -- even if we import nothing explicitly.
903 -- It's not necessarily redundant to import such modules. Consider
907 -- The import M() is not *necessarily* redundant, even if
908 -- we suck in no instance decls from M (e.g. it contains
909 -- no instance decls, or This contains no code). It may be
910 -- that we import M solely to ensure that M's orphan instance
911 -- decls (or those in its imports) are visible to people who
912 -- import This. Sigh.
913 -- There's really no good way to detect this, so the error message
914 -- in RnEnv.warnUnusedModules is weakened instead
916 -- We've carefully preserved the provenance so that we can
917 -- construct minimal imports that import the name by (one of)
918 -- the same route(s) as the programmer originally did.
919 add_name (GRE {gre_name = n, gre_prov = Imported imp_specs}) acc
920 = addToFM_C plusAvailEnv acc (importSpecModule (head imp_specs))
921 (unitAvailEnv (mk_avail n (nameParent_maybe n)))
925 -- Modules mentioned as 'module M' in the export list
926 expall_mods = case export_decls of
928 Just es -> [m | L _ (IEModuleContents m) <- es]
930 -- This is really bogus. The idea is that if we see 'module M' in
931 -- the export list we must retain the import decls that drive it
932 -- If we aren't careful we might see
933 -- module A( module M ) where
936 -- and suppose that N exports everything that M does. Then we
937 -- must not drop the import of M even though N brings it all into
940 -- BUG WARNING: 'module M' exports aside, what if M.x is mentioned?!
942 -- The reason that add_expall is bogus is that it doesn't take
943 -- qualified imports into account. But it's an improvement.
944 add_expall mod acc = addToFM_C plusAvailEnv acc mod emptyAvailEnv
946 -- n is the name of the thing, p is the name of its parent
947 mk_avail n (Just p) = AvailTC p [p,n]
948 mk_avail n Nothing | isTcOcc (nameOccName n) = AvailTC n [n]
949 | otherwise = Avail n
951 add_inst_mod (mod,_,_) acc
952 | mod `elemFM` acc = acc -- We import something already
953 | otherwise = addToFM acc mod emptyAvailEnv
955 -- Add an empty collection of imports for a module
956 -- from which we have sucked only instance decls
958 imports = tcg_imports gbl_env
960 direct_import_mods :: [(Module, Bool, SrcSpan)]
961 -- See the type of the imp_mods for this triple
962 direct_import_mods = moduleEnvElts (imp_mods imports)
964 -- unused_imp_mods are the directly-imported modules
965 -- that are not mentioned in minimal_imports1
966 -- [Note: not 'minimal_imports', because that includes directly-imported
967 -- modules even if we use nothing from them; see notes above]
969 -- BUG WARNING: does not deal correctly with multiple imports of the same module
970 -- becuase direct_import_mods has only one entry per module
971 unused_imp_mods = [(mod,loc) | (mod,no_imp,loc) <- direct_import_mods,
972 not (mod `elemFM` minimal_imports1),
975 -- The not no_imp part is not to complain about
976 -- import M (), which is an idiom for importing
977 -- instance declarations
979 module_unused :: Module -> Bool
980 module_unused mod = any (((==) mod) . fst) unused_imp_mods
982 ---------------------
983 warnDuplicateImports :: [GlobalRdrElt] -> RnM ()
984 -- Given the GREs for names that are used, figure out which imports
985 -- could be omitted without changing the top-level environment.
987 -- NB: Given import Foo( T )
988 -- import qualified Foo
989 -- we do not report a duplicate import, even though Foo.T is brought
990 -- into scope by both, because there's nothing you can *omit* without
991 -- changing the top-level environment. So we complain only if it's
992 -- explicitly named in both imports or neither.
994 -- Furthermore, we complain about Foo.T only if
995 -- there is no complaint about (unqualified) T
997 warnDuplicateImports gres
998 = ifOptM Opt_WarnUnusedImports $
999 sequenceM_ [ warn name pr
1000 -- The 'head' picks the first offending group
1001 -- for this particular name
1002 | GRE { gre_name = name, gre_prov = Imported imps } <- gres
1003 , pr <- redundants imps ]
1005 warn name (red_imp, cov_imp)
1006 = addWarnAt (importSpecLoc red_imp)
1007 (vcat [ptext SLIT("Redundant import of:") <+> quotes pp_name,
1008 ptext SLIT("It is also") <+> ppr cov_imp])
1010 pp_name | is_qual red_decl = ppr (is_as red_decl) <> dot <> ppr occ
1011 | otherwise = ppr occ
1012 occ = nameOccName name
1013 red_decl = is_decl red_imp
1015 redundants :: [ImportSpec] -> [(ImportSpec,ImportSpec)]
1016 -- The returned pair is (redundant-import, covering-import)
1018 = [ (red_imp, cov_imp)
1020 , cov_imp <- take 1 (filter (covers red_imp) imps) ]
1022 -- "red_imp" is a putative redundant import
1023 -- "cov_imp" potentially covers it
1024 -- This test decides whether red_imp could be dropped
1026 -- NOTE: currently the test does not warn about
1029 -- even if the same underlying 'x' is involved, because dropping
1030 -- either import would change the qualified names in scope (M.x, N.x)
1031 -- But if the qualified names aren't used, the import is indeed redundant
1032 -- Sadly we don't know that. Oh well.
1033 covers red_imp@(ImpSpec { is_decl = red_decl, is_item = red_item })
1034 cov_imp@(ImpSpec { is_decl = cov_decl, is_item = cov_item })
1035 | red_loc == cov_loc
1036 = False -- Ignore diagonal elements
1037 | not (is_as red_decl == is_as cov_decl)
1038 = False -- They bring into scope different qualified names
1039 | not (is_qual red_decl) && is_qual cov_decl
1040 = False -- Covering one doesn't bring unqualified name into scope
1042 = not cov_selective -- Redundant one is selective and covering one isn't
1043 || red_later -- Both are explicit; tie-break using red_later
1045 = not cov_selective -- Neither import is selective
1046 && (is_mod red_decl == is_mod cov_decl) -- They import the same module
1047 && red_later -- Tie-break
1049 red_loc = importSpecLoc red_imp
1050 cov_loc = importSpecLoc cov_imp
1051 red_later = red_loc > cov_loc
1052 cov_selective = selectiveImpItem cov_item
1053 red_selective = selectiveImpItem red_item
1055 selectiveImpItem :: ImpItemSpec -> Bool
1056 selectiveImpItem ImpAll = False
1057 selectiveImpItem (ImpSome {}) = True
1059 -- ToDo: deal with original imports with 'qualified' and 'as M' clauses
1060 printMinimalImports :: FiniteMap Module AvailEnv -- Minimal imports
1062 printMinimalImports imps
1063 = ifOptM Opt_D_dump_minimal_imports $ do {
1065 mod_ies <- mappM to_ies (fmToList imps) ;
1066 this_mod <- getModule ;
1067 rdr_env <- getGlobalRdrEnv ;
1068 ioToTcRn (do { h <- openFile (mkFilename this_mod) WriteMode ;
1069 printForUser h (unQualInScope rdr_env)
1070 (vcat (map ppr_mod_ie mod_ies)) })
1073 mkFilename this_mod = moduleString this_mod ++ ".imports"
1074 ppr_mod_ie (mod_name, ies)
1075 | mod_name == pRELUDE
1077 | null ies -- Nothing except instances comes from here
1078 = ptext SLIT("import") <+> ppr mod_name <> ptext SLIT("() -- Instances only")
1080 = ptext SLIT("import") <+> ppr mod_name <>
1081 parens (fsep (punctuate comma (map ppr ies)))
1083 to_ies (mod, avail_env) = do ies <- mapM to_ie (availEnvElts avail_env)
1086 to_ie :: AvailInfo -> RnM (IE Name)
1087 -- The main trick here is that if we're importing all the constructors
1088 -- we want to say "T(..)", but if we're importing only a subset we want
1089 -- to say "T(A,B,C)". So we have to find out what the module exports.
1090 to_ie (Avail n) = returnM (IEVar n)
1091 to_ie (AvailTC n [m]) = ASSERT( n==m )
1092 returnM (IEThingAbs n)
1093 to_ie (AvailTC n ns)
1094 = loadSrcInterface doc n_mod False `thenM` \ iface ->
1095 case [xs | (m,as) <- mi_exports iface,
1098 x == nameOccName n] of
1099 [xs] | all_used xs -> returnM (IEThingAll n)
1100 | otherwise -> returnM (IEThingWith n (filter (/= n) ns))
1101 other -> pprTrace "to_ie" (ppr n <+> ppr n_mod <+> ppr other) $
1104 all_used avail_occs = all (`elem` map nameOccName ns) avail_occs
1105 doc = text "Compute minimal imports from" <+> ppr n
1106 n_mod = nameModule n
1110 %************************************************************************
1114 %************************************************************************
1117 badImportItemErr iface decl_spec ie
1118 = sep [ptext SLIT("Module"), quotes (ppr (is_mod decl_spec)), source_import,
1119 ptext SLIT("does not export"), quotes (ppr ie)]
1121 source_import | mi_boot iface = ptext SLIT("(hi-boot interface)")
1124 dodgyImportWarn item = dodgyMsg (ptext SLIT("import")) item
1125 dodgyExportWarn item = dodgyMsg (ptext SLIT("export")) item
1128 = sep [ ptext SLIT("The") <+> kind <+> ptext SLIT("item") <+> quotes (ppr (IEThingAll tc)),
1129 ptext SLIT("suggests that") <+> quotes (ppr tc) <+> ptext SLIT("has constructor or class methods"),
1130 ptext SLIT("but it has none; it is a type synonym or abstract type or class") ]
1133 = hsep [ ptext SLIT("Unknown module in export list: module"), quotes (ppr mod)]
1135 exportItemErr export_item
1136 = sep [ ptext SLIT("The export item") <+> quotes (ppr export_item),
1137 ptext SLIT("attempts to export constructors or class methods that are not visible here") ]
1139 exportClashErr global_env name1 name2 ie1 ie2
1140 = vcat [ ptext SLIT("Conflicting exports for") <+> quotes (ppr occ) <> colon
1141 , ppr_export ie1 name1
1142 , ppr_export ie2 name2 ]
1144 occ = nameOccName name1
1145 ppr_export ie name = nest 2 (quotes (ppr ie) <+> ptext SLIT("exports") <+>
1146 quotes (ppr name) <+> pprNameProvenance (get_gre name))
1148 -- get_gre finds a GRE for the Name, so that we can show its provenance
1150 = case lookupGRE_Name global_env name of
1152 [] -> pprPanic "exportClashErr" (ppr name)
1154 addDupDeclErr :: Name -> Name -> TcRn ()
1155 addDupDeclErr name_a name_b
1156 = addErrAt (srcLocSpan loc2) $
1157 vcat [ptext SLIT("Multiple declarations of") <+> quotes (ppr name1),
1158 ptext SLIT("Declared at:") <+> vcat [ppr (nameSrcLoc name1), ppr loc2]]
1160 loc2 = nameSrcLoc name2
1161 (name1,name2) | nameSrcLoc name_a > nameSrcLoc name_b = (name_b,name_a)
1162 | otherwise = (name_a,name_b)
1163 -- Report the error at the later location
1165 dupExportWarn occ_name ie1 ie2
1166 = hsep [quotes (ppr occ_name),
1167 ptext SLIT("is exported by"), quotes (ppr ie1),
1168 ptext SLIT("and"), quotes (ppr ie2)]
1171 = hsep [ptext SLIT("Duplicate"),
1172 quotes (ptext SLIT("Module") <+> ppr mod),
1173 ptext SLIT("in export list")]
1175 moduleDeprec mod txt
1176 = sep [ ptext SLIT("Module") <+> quotes (ppr mod) <+> ptext SLIT("is deprecated:"),