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,
20 instDeclATs, isIdxTyDecl,
23 import RnHsDoc ( rnHsDoc )
24 import IfaceEnv ( ifaceExportNames )
25 import LoadIface ( loadSrcInterface )
26 import TcRnMonad hiding (LIE)
31 import Name ( Name, nameSrcLoc, nameOccName, nameModule, isWiredInName,
32 nameParent, nameParent_maybe, isExternalName,
33 isBuiltInSyntax, isTyConName )
36 import OccName ( srcDataName, isTcOcc, pprNonVarNameSpace,
38 OccEnv, mkOccEnv, lookupOccEnv, emptyOccEnv,
40 import HscTypes ( GenAvailInfo(..), AvailInfo,
41 HomePackageTable, PackageIfaceTable,
43 Deprecs(..), ModIface(..), Dependencies(..),
44 lookupIfaceByModule, ExternalPackageState(..)
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 )
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(..) )
67 %************************************************************************
71 %************************************************************************
74 rnImports :: [LImportDecl RdrName] -> RnM [LImportDecl Name]
76 -- PROCESS IMPORT DECLS
77 -- Do the non {- SOURCE -} ones first, so that we get a helpful
78 -- warning for {- SOURCE -} ones that are unnecessary
79 = do this_mod <- getModule
80 implicit_prelude <- doptM Opt_ImplicitPrelude
81 let all_imports = mk_prel_imports this_mod implicit_prelude ++ imports
82 (source, ordinary) = partition is_source_import all_imports
83 is_source_import (L _ (ImportDecl _ is_boot _ _ _)) = is_boot
84 get_imports = rnImportDecl this_mod
86 stuff1 <- mapM get_imports ordinary
87 stuff2 <- mapM get_imports source
88 return (stuff1 ++ stuff2)
90 -- NB: opt_NoImplicitPrelude is slightly different to import Prelude ();
91 -- because the former doesn't even look at Prelude.hi for instance
92 -- declarations, whereas the latter does.
93 mk_prel_imports this_mod implicit_prelude
95 || explicit_prelude_import
96 || not implicit_prelude
98 | otherwise = [preludeImportDecl]
99 explicit_prelude_import
100 = notNull [ () | L _ (ImportDecl mod _ _ _ _) <- imports,
101 unLoc mod == pRELUDE_NAME ]
103 preludeImportDecl :: LImportDecl RdrName
106 ImportDecl (L loc pRELUDE_NAME)
107 False {- Not a boot interface -}
108 False {- Not qualified -}
109 Nothing {- No "as" -}
110 Nothing {- No import list -}
112 loc = mkGeneralSrcSpan FSLIT("Implicit import declaration")
114 mkRdrEnvAndImports :: [LImportDecl Name] -> RnM (GlobalRdrEnv, ImportAvails)
115 mkRdrEnvAndImports imports
116 = do this_mod <- getModule
117 let get_imports = importsFromImportDecl this_mod
118 stuff <- mapM get_imports imports
119 let (imp_gbl_envs, imp_avails) = unzip stuff
120 gbl_env :: GlobalRdrEnv
121 gbl_env = foldr plusGlobalRdrEnv emptyGlobalRdrEnv imp_gbl_envs
123 all_avails :: ImportAvails
124 all_avails = foldr plusImportAvails emptyImportAvails imp_avails
126 return (gbl_env, all_avails)
131 rnImportDecl :: Module
132 -> LImportDecl RdrName
133 -> RnM (LImportDecl Name)
134 rnImportDecl this_mod (L loc importDecl@(ImportDecl loc_imp_mod_name want_boot qual_only as_mod imp_details))
136 do iface <- loadSrcInterface doc imp_mod_name want_boot
137 let qual_mod_name = case as_mod of
138 Nothing -> imp_mod_name
139 Just another_name -> another_name
140 imp_spec = ImpDeclSpec { is_mod = imp_mod_name, is_qual = qual_only,
141 is_dloc = loc, is_as = qual_mod_name }
142 total_avails <- ifaceExportNames (mi_exports iface)
143 importDecl' <- rnImportDecl' iface imp_spec importDecl total_avails
144 return (L loc importDecl')
145 where imp_mod_name = unLoc loc_imp_mod_name
146 doc = ppr imp_mod_name <+> ptext SLIT("is directly imported")
148 rnImportDecl' :: ModIface -> ImpDeclSpec -> ImportDecl RdrName -> NameSet -> RnM (ImportDecl Name)
149 rnImportDecl' iface decl_spec (ImportDecl mod_name want_boot qual_only as_mod Nothing) all_names
150 = return $ ImportDecl mod_name want_boot qual_only as_mod Nothing
151 rnImportDecl' iface decl_spec (ImportDecl mod_name want_boot qual_only as_mod (Just (want_hiding,import_items))) all_names
152 = do import_items_mbs <- mapM (srcSpanWrapper) import_items
153 let rn_import_items = concat . catMaybes $ import_items_mbs
154 return $ ImportDecl mod_name want_boot qual_only as_mod (Just (want_hiding,rn_import_items))
156 srcSpanWrapper (L span ieRdr)
157 = case get_item ieRdr of
159 -> do addErrAt span (badImportItemErr iface decl_spec ieRdr)
162 -> return (Just [L span ie | ie <- ieNames])
163 occ_env :: OccEnv Name -- Maps OccName to corresponding Name
164 occ_env = mkOccEnv [(nameOccName n, n) | n <- nameSetToList all_names]
165 -- This env will have entries for data constructors too,
166 -- they won't make any difference because naked entities like T
167 -- in an import list map to TcOccs, not VarOccs.
169 sub_env :: NameEnv [Name]
170 sub_env = mkSubNameEnv all_names
172 get_item :: IE RdrName -> Maybe [IE Name]
173 -- Empty result for a bad item.
174 -- Singleton result is typical case.
175 -- Can have two when we are hiding, and mention C which might be
176 -- both a class and a data constructor.
177 get_item item@(IEModuleContents _)
179 get_item (IEThingAll tc)
180 = do name <- check_name tc
181 return [IEThingAll name]
182 get_item (IEThingAbs tc)
183 | want_hiding -- hiding ( C )
184 -- Here the 'C' can be a data constructor
185 -- *or* a type/class, or even both
186 = case catMaybes [check_name tc, check_name (setRdrNameSpace tc srcDataName)] of
188 names -> return [ IEThingAbs n | n <- names ]
190 = do name <- check_name tc
191 return [IEThingAbs name]
192 get_item (IEThingWith n ns) -- import (C (A,B))
193 = do name <- check_name n
194 let env = mkOccEnv [(nameOccName s, s) | s <- subNames sub_env name]
195 mb_names = map (lookupOccEnv env . rdrNameOcc) ns
196 names <- sequence mb_names
197 return [IEThingWith name names]
199 = do name <- check_name n
202 check_name :: RdrName -> Maybe Name
204 = lookupOccEnv occ_env (rdrNameOcc rdrName)
207 importsFromImportDecl :: Module
209 -> RnM (GlobalRdrEnv, ImportAvails)
211 importsFromImportDecl this_mod
212 (L loc (ImportDecl loc_imp_mod_name want_boot qual_only as_mod imp_details))
216 -- If there's an error in loadInterface, (e.g. interface
217 -- file not found) we get lots of spurious errors from 'filterImports'
219 imp_mod_name = unLoc loc_imp_mod_name
220 doc = ppr imp_mod_name <+> ptext SLIT("is directly imported")
222 loadSrcInterface doc imp_mod_name want_boot `thenM` \ iface ->
224 -- Compiler sanity check: if the import didn't say
225 -- {-# SOURCE #-} we should not get a hi-boot file
226 WARN( not want_boot && mi_boot iface, ppr imp_mod_name )
228 -- Issue a user warning for a redundant {- SOURCE -} import
229 -- NB that we arrange to read all the ordinary imports before
230 -- any of the {- SOURCE -} imports
231 warnIf (want_boot && not (mi_boot iface))
232 (warnRedundantSourceImport imp_mod_name) `thenM_`
235 imp_mod = mi_module iface
236 deprecs = mi_deprecs iface
237 is_orph = mi_orphan iface
240 filtered_exports = filter not_this_mod (mi_exports iface)
241 not_this_mod (mod,_) = mod /= this_mod
242 -- If the module exports anything defined in this module, just ignore it.
243 -- Reason: otherwise it looks as if there are two local definition sites
244 -- for the thing, and an error gets reported. Easiest thing is just to
245 -- filter them out up front. This situation only arises if a module
246 -- imports itself, or another module that imported it. (Necessarily,
247 -- this invoves a loop.)
249 -- Tiresome consequence: if you say
254 -- module B( AType ) where
255 -- import {-# SOURCE #-} A( AType )
257 -- then you'll get a 'B does not export AType' message. Oh well.
259 qual_mod_name = case as_mod of
260 Nothing -> imp_mod_name
261 Just another_name -> another_name
262 imp_spec = ImpDeclSpec { is_mod = imp_mod_name, is_qual = qual_only,
263 is_dloc = loc, is_as = qual_mod_name }
265 -- Get the total imports, and filter them according to the import list
266 ifaceExportNames filtered_exports `thenM` \ total_avails ->
267 filterImports iface imp_spec
268 imp_details total_avails `thenM` \ (avail_env, gbl_env) ->
270 getDOpts `thenM` \ dflags ->
273 -- Compute new transitive dependencies
275 orphans | is_orph = ASSERT( not (imp_mod `elem` dep_orphs deps) )
276 imp_mod : dep_orphs deps
277 | otherwise = dep_orphs deps
279 pkg = modulePackageId (mi_module iface)
281 (dependent_mods, dependent_pkgs)
282 | pkg == thisPackage dflags =
283 -- Imported module is from the home package
284 -- Take its dependent modules and add imp_mod itself
285 -- Take its dependent packages unchanged
287 -- NB: (dep_mods deps) might include a hi-boot file
288 -- for the module being compiled, CM. Do *not* filter
289 -- this out (as we used to), because when we've
290 -- finished dealing with the direct imports we want to
291 -- know if any of them depended on CM.hi-boot, in
292 -- which case we should do the hi-boot consistency
293 -- check. See LoadIface.loadHiBootInterface
294 ((imp_mod_name, want_boot) : dep_mods deps, dep_pkgs deps)
297 -- Imported module is from another package
298 -- Dump the dependent modules
299 -- Add the package imp_mod comes from to the dependent packages
300 ASSERT2( not (pkg `elem` dep_pkgs deps), ppr pkg <+> ppr (dep_pkgs deps) )
301 ([], pkg : dep_pkgs deps)
303 -- True <=> import M ()
304 import_all = case imp_details of
305 Just (is_hiding, ls) -> not is_hiding && null ls
308 -- unqual_avails is the Avails that are visible in *unqualified* form
309 -- We need to know this so we know what to export when we see
310 -- module M ( module P ) where ...
311 -- Then we must export whatever came from P unqualified.
312 imports = ImportAvails {
313 imp_env = unitUFM qual_mod_name avail_env,
314 imp_mods = unitModuleEnv imp_mod (imp_mod, import_all, loc),
316 imp_dep_mods = mkModDeps dependent_mods,
317 imp_dep_pkgs = dependent_pkgs }
320 -- Complain if we import a deprecated module
321 ifOptM Opt_WarnDeprecations (
323 DeprecAll txt -> addWarn (moduleDeprec imp_mod_name txt)
327 returnM (gbl_env, imports)
329 warnRedundantSourceImport mod_name
330 = ptext SLIT("Unnecessary {-# SOURCE #-} in the import of module")
331 <+> quotes (ppr mod_name)
335 %************************************************************************
337 importsFromLocalDecls
339 %************************************************************************
341 From the top-level declarations of this module produce
342 * the lexical environment
344 created by its bindings.
346 Complain about duplicate bindings
349 importsFromLocalDecls :: HsGroup RdrName -> RnM TcGblEnv
350 importsFromLocalDecls group
351 = do { gbl_env <- getGblEnv
353 ; names <- getLocalDeclBinders gbl_env group
355 ; implicit_prelude <- doptM Opt_ImplicitPrelude
357 -- Optimisation: filter out names for built-in syntax
358 -- They just clutter up the environment (esp tuples), and the parser
359 -- will generate Exact RdrNames for them, so the cluttered
360 -- envt is no use. To avoid doing this filter all the time,
361 -- we use -fno-implicit-prelude as a clue that the filter is
362 -- worth while. Really, it's only useful for GHC.Base and GHC.Tuple.
364 -- It's worth doing because it makes the environment smaller for
365 -- every module that imports the Prelude
367 -- Note: don't filter the gbl_env (hence all_names, not filered_all_names
368 -- in defn of gres above). Stupid reason: when parsing
369 -- data type decls, the constructors start as Exact tycon-names,
370 -- and then get turned into data con names by zapping the name space;
371 -- but that stops them being Exact, so they get looked up.
372 -- Ditto in fixity decls; e.g. infix 5 :
373 -- Sigh. It doesn't matter because it only affects the Data.Tuple really.
374 -- The important thing is to trim down the exports.
376 | implicit_prelude = names
377 | otherwise = filter (not . isBuiltInSyntax) names ;
379 ; this_mod = tcg_mod gbl_env
380 ; imports = emptyImportAvails {
381 imp_env = unitUFM (moduleName this_mod) $
382 mkNameSet filtered_names
386 ; rdr_env' <- extendRdrEnvRn (tcg_rdr_env gbl_env) names
388 ; returnM (gbl_env { tcg_rdr_env = rdr_env',
389 tcg_imports = imports `plusImportAvails` tcg_imports gbl_env })
392 extendRdrEnvRn :: GlobalRdrEnv -> [Name] -> RnM GlobalRdrEnv
393 -- Add the new locally-bound names one by one, checking for duplicates as
394 -- we do so. Remember that in Template Haskell the duplicates
395 -- might *already be* in the GlobalRdrEnv from higher up the module
396 extendRdrEnvRn rdr_env names
397 = foldlM add_local rdr_env names
399 add_local rdr_env name
400 | gres <- lookupGlobalRdrEnv rdr_env (nameOccName name)
401 , (dup_gre:_) <- filter isLocalGRE gres -- Check for existing *local* defns
402 = do { addDupDeclErr (gre_name dup_gre) name
405 = return (extendGlobalRdrEnv rdr_env new_gre)
407 new_gre = GRE {gre_name = name, gre_prov = LocalDef}
410 @getLocalDeclBinders@ returns the names for an @HsDecl@. It's
411 used for source code.
413 *** See "THE NAMING STORY" in HsDecls ****
415 Instances of indexed types
416 ~~~~~~~~~~~~~~~~~~~~~~~~~~
417 Indexed data/newtype instances contain data constructors that we need to
418 collect, too. Moreover, we need to descend into the data/newtypes instances
419 of associated families.
421 We need to be careful with the handling of the type constructor of each type
422 instance as the family constructor is already defined, and we want to avoid
423 raising a duplicate declaration error. So, we make a new name for it, but
424 don't return it in the 'AvailInfo'.
427 getLocalDeclBinders :: TcGblEnv -> HsGroup RdrName -> RnM [Name]
428 getLocalDeclBinders gbl_env (HsGroup {hs_valds = ValBindsIn val_decls val_sigs,
429 hs_tyclds = tycl_decls,
430 hs_instds = inst_decls,
431 hs_fords = foreign_decls })
432 = do { tc_names_s <- mappM new_tc tycl_decls
433 ; at_names_s <- mappM inst_ats inst_decls
434 ; val_names <- mappM new_simple val_bndrs
435 ; return (foldr (++) val_names (tc_names_s ++ concat at_names_s)) }
437 mod = tcg_mod gbl_env
438 is_hs_boot = isHsBoot (tcg_src gbl_env) ;
439 val_bndrs | is_hs_boot = sig_hs_bndrs
440 | otherwise = for_hs_bndrs ++ val_hs_bndrs
441 -- In a hs-boot file, the value binders come from the
442 -- *signatures*, and there should be no foreign binders
444 new_simple rdr_name = newTopSrcBinder mod Nothing rdr_name
446 sig_hs_bndrs = [nm | L _ (TypeSig nm _) <- val_sigs]
447 val_hs_bndrs = collectHsBindLocatedBinders val_decls
448 for_hs_bndrs = [nm | L _ (ForeignImport nm _ _) <- foreign_decls]
451 | isIdxTyDecl (unLoc tc_decl)
452 = do { main_name <- lookupFamInstDeclBndr mod main_rdr
454 mappM (newTopSrcBinder mod (Just main_name)) sub_rdrs
455 ; return sub_names } -- main_name is not declared here!
457 = do { main_name <- newTopSrcBinder mod Nothing main_rdr
459 mappM (newTopSrcBinder mod (Just main_name)) sub_rdrs
460 ; return (main_name : sub_names) }
462 (main_rdr : sub_rdrs) = tyClDeclNames (unLoc tc_decl)
465 = mappM new_tc (instDeclATs (unLoc inst_decl))
469 %************************************************************************
471 \subsection{Filtering imports}
473 %************************************************************************
475 @filterImports@ takes the @ExportEnv@ telling what the imported module makes
476 available, and filters it through the import spec (if any).
479 filterImports :: ModIface
480 -> ImpDeclSpec -- The span for the entire import decl
481 -> Maybe (Bool, [LIE Name]) -- Import spec; True => hiding
482 -> NameSet -- What's available
483 -> RnM (NameSet, -- What's imported (qualified or unqualified)
484 GlobalRdrEnv) -- Same again, but in GRE form
486 -- Complains if import spec mentions things that the module doesn't export
487 -- Warns/informs if import spec contains duplicates.
489 mkGenericRdrEnv decl_spec names
490 = mkGlobalRdrEnv [ GRE { gre_name = name, gre_prov = Imported [imp_spec] }
491 | name <- nameSetToList names ]
493 imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }
495 filterImports iface decl_spec Nothing all_names
496 = return (all_names, mkGenericRdrEnv decl_spec all_names)
498 filterImports iface decl_spec (Just (want_hiding, import_items)) all_names
499 = mapM (addLocM get_item) import_items >>= \gres_s ->
500 let gres = concat gres_s
501 specified_names = mkNameSet (map gre_name gres)
502 in if not want_hiding then
503 return (specified_names, mkGlobalRdrEnv gres)
504 else let keep n = not (n `elemNameSet` specified_names)
505 pruned_avails = filterNameSet keep all_names
506 in return (pruned_avails, mkGenericRdrEnv decl_spec pruned_avails)
508 sub_env :: NameEnv [Name] -- Classify each name by its parent
509 sub_env = mkSubNameEnv all_names
511 succeed_with :: Bool -> [Name] -> RnM [GlobalRdrElt]
512 succeed_with all_explicit names
513 = do { loc <- getSrcSpanM
514 ; returnM (map (mk_gre loc) names) }
516 mk_gre loc name = GRE { gre_name = name,
517 gre_prov = Imported [imp_spec] }
519 imp_spec = ImpSpec { is_decl = decl_spec, is_item = item_spec }
520 item_spec = ImpSome { is_explicit = explicit, is_iloc = loc }
521 explicit = all_explicit || isNothing (nameParent_maybe name)
523 get_item :: IE Name -> RnM [GlobalRdrElt]
524 -- Empty result for a bad item.
525 -- Singleton result is typical case.
526 -- Can have two when we are hiding, and mention C which might be
527 -- both a class and a data constructor.
528 get_item item@(IEModuleContents _)
529 -- This case should be filtered out by 'rnImports'.
530 = panic "filterImports: IEModuleContents?"
532 get_item (IEThingAll name)
533 = case subNames sub_env name of
534 [] -> -- This occurs when you import T(..), but
535 -- only export T abstractly.
536 do ifOptM Opt_WarnDodgyImports (addWarn (dodgyImportWarn name))
537 succeed_with False [name]
538 names -> succeed_with False (name:names)
540 get_item (IEThingAbs name)
541 = succeed_with True [name]
543 get_item (IEThingWith name names)
544 = do { optIdxTypes <- doptM Opt_IndexedTypes
545 ; when (not optIdxTypes && any isTyConName names) $
546 addErr (typeItemErr (head . filter isTyConName $ names )
547 (text "in import list"))
548 ; succeed_with True (name:names) }
549 get_item (IEVar name)
550 = succeed_with True [name]
551 get_item (IEGroup _ _)
552 = succeed_with False []
554 = succeed_with False []
555 get_item (IEDocNamed _)
556 = succeed_with False []
560 %************************************************************************
562 \subsection{Export list processing}
564 %************************************************************************
566 Processing the export list.
568 You might think that we should record things that appear in the export
569 list as ``occurrences'' (using @addOccurrenceName@), but you'd be
570 wrong. We do check (here) that they are in scope, but there is no
571 need to slurp in their actual declaration (which is what
572 @addOccurrenceName@ forces).
574 Indeed, doing so would big trouble when compiling @PrelBase@, because
575 it re-exports @GHC@, which includes @takeMVar#@, whose type includes
576 @ConcBase.StateAndSynchVar#@, and so on...
579 type ExportAccum -- The type of the accumulating parameter of
580 -- the main worker function in rnExports
581 = ([ModuleName], -- 'module M's seen so far
582 ExportOccMap, -- Tracks exported occurrence names
583 NameSet) -- The accumulated exported stuff
584 emptyExportAccum = ([], emptyOccEnv, emptyNameSet)
586 type ExportOccMap = OccEnv (Name, IE RdrName)
587 -- Tracks what a particular exported OccName
588 -- in an export list refers to, and which item
589 -- it came from. It's illegal to export two distinct things
590 -- that have the same occurrence name
592 rnExports :: Maybe [LIE RdrName]
593 -> RnM (Maybe [LIE Name])
594 rnExports Nothing = return Nothing
595 rnExports (Just exports)
596 = do TcGblEnv { tcg_imports = ImportAvails { imp_env = imp_env } } <- getGblEnv
597 let sub_env :: NameEnv [Name] -- Classify each name by its parent
598 sub_env = mkSubNameEnv (foldUFM unionNameSets emptyNameSet imp_env)
599 rnExport (IEVar rdrName)
600 = do name <- lookupGlobalOccRn rdrName
602 rnExport (IEThingAbs rdrName)
603 = do name <- lookupGlobalOccRn rdrName
604 return (IEThingAbs name)
605 rnExport (IEThingAll rdrName)
606 = do name <- lookupGlobalOccRn rdrName
607 return (IEThingAll name)
608 rnExport ie@(IEThingWith rdrName rdrNames)
609 = do name <- lookupGlobalOccRn rdrName
610 if isUnboundName name
611 then return (IEThingWith name [])
613 let env = mkOccEnv [(nameOccName s, s) | s <- subNames sub_env name]
614 mb_names = map (lookupOccEnv env . rdrNameOcc) rdrNames
615 if any isNothing mb_names
616 then do addErr (exportItemErr ie)
617 return (IEThingWith name [])
618 else do let names = catMaybes mb_names
619 optIdxTypes <- doptM Opt_IndexedTypes
620 when (not optIdxTypes && any isTyConName names) $
621 addErr (typeItemErr ( head
624 (text "in export list"))
625 return (IEThingWith name names)
626 rnExport (IEModuleContents mod)
627 = return (IEModuleContents mod)
628 rnExport (IEGroup lev doc)
629 = do rn_doc <- rnHsDoc doc
630 return (IEGroup lev rn_doc)
632 = do rn_doc <- rnHsDoc doc
633 return (IEDoc rn_doc)
634 rnExport (IEDocNamed str)
635 = return (IEDocNamed str)
637 rn_exports <- mapM (wrapLocM rnExport) exports
638 return (Just rn_exports)
640 filterOutDocs = filter notDoc
642 notDoc (L _ (IEGroup _ _)) = False
643 notDoc (L _ (IEDoc _)) = False
644 notDoc (L _ (IEDocNamed _)) = False
647 mkExportNameSet :: Bool -- False => no 'module M(..) where' header at all
648 -> Maybe ([LIE Name], [LIE RdrName]) -- Nothing => no explicit export list
650 -- Complains if two distinct exports have same OccName
651 -- Warns about identical exports.
652 -- Complains about exports items not in scope
654 mkExportNameSet explicit_mod exports
655 = do TcGblEnv { tcg_rdr_env = rdr_env,
656 tcg_imports = imports } <- getGblEnv
658 -- If the module header is omitted altogether, then behave
659 -- as if the user had written "module Main(main) where..."
660 -- EXCEPT in interactive mode, when we behave as if he had
661 -- written "module Main where ..."
662 -- Reason: don't want to complain about 'main' not in scope
663 -- in interactive mode
664 ghc_mode <- getGhcMode
665 real_exports <- case () of
668 | ghc_mode == Interactive
671 -> do mainName <- lookupGlobalOccRn main_RDR_Unqual
672 return (Just ([noLoc (IEVar mainName)]
673 ,[noLoc (IEVar main_RDR_Unqual)]))
674 -- ToDo: the 'noLoc' here is unhelpful if 'main' turns out to be out of scope
676 -- we don't want to include Haddock comments
677 let real_exports' = fmap (\(a,b) -> (filterOutDocs a, filterOutDocs b)) real_exports
679 exports_from_avail real_exports' rdr_env imports
682 exports_from_avail Nothing rdr_env imports
683 = -- Export all locally-defined things
684 -- We do this by filtering the global RdrEnv,
685 -- keeping only things that are locally-defined
686 return (mkNameSet [ gre_name gre
687 | gre <- globalRdrEnvElts rdr_env,
690 exports_from_avail (Just (items,origItems)) rdr_env (ImportAvails { imp_env = imp_env })
691 = do (_, _, exports) <- foldlM do_litem emptyExportAccum (zip items origItems)
694 sub_env :: NameEnv [Name] -- Classify each name by its parent
695 sub_env = mkSubNameEnv (foldUFM unionNameSets emptyNameSet imp_env)
697 do_litem :: ExportAccum -> (LIE Name, LIE RdrName) -> RnM ExportAccum
698 do_litem acc (ieName, ieRdr)
699 = addLocM (exports_from_item acc (unLoc ieRdr)) ieName
701 exports_from_item :: ExportAccum -> IE RdrName -> IE Name -> RnM ExportAccum
702 exports_from_item acc@(mods, occs, exports) ieRdr@(IEModuleContents mod) ie
703 | mod `elem` mods -- Duplicate export of M
704 = do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
705 warnIf warn_dup_exports (dupModuleExport mod) ;
709 = case lookupUFM imp_env mod of
710 Nothing -> do addErr (modExportErr mod)
713 -> do let new_exports = filterNameSet (inScopeUnqual rdr_env) names
714 -- This check_occs not only finds conflicts between this item
715 -- and others, but also internally within this item. That is,
716 -- if 'M.x' is in scope in several ways, we'll have several
717 -- members of mod_avails with the same OccName.
718 occs' <- check_occs ieRdr occs (nameSetToList new_exports)
719 return (mod:mods, occs', exports `unionNameSets` new_exports)
721 exports_from_item acc@(mods, occs, exports) ieRdr ie
722 = if isUnboundName (ieName ie)
723 then return acc -- Avoid error cascade
724 else let new_exports = filterAvail ie sub_env in
725 do -- checkErr (not (null (drop 1 new_exports))) (exportItemErr ie)
726 checkForDodgyExport ie new_exports
727 occs' <- check_occs ieRdr occs new_exports
728 return (mods, occs', addListToNameSet exports new_exports)
730 -------------------------------
731 filterAvail :: IE Name -- Wanted
732 -> NameEnv [Name] -- Maps type/class names to their sub-names
735 filterAvail (IEVar n) subs = [n]
736 filterAvail (IEThingAbs n) subs = [n]
737 filterAvail (IEThingAll n) subs = n : subNames subs n
738 filterAvail (IEThingWith n ns) subs = n : ns
739 filterAvail (IEModuleContents _) _ = panic "filterAvail"
741 subNames :: NameEnv [Name] -> Name -> [Name]
742 subNames env n = lookupNameEnv env n `orElse` []
744 mkSubNameEnv :: NameSet -> NameEnv [Name]
745 -- Maps types and classes to their constructors/classops respectively
746 -- This mapping just makes it easier to deal with A(..) export items
748 = foldNameSet add_name emptyNameEnv names
751 | Just parent <- nameParent_maybe name
752 = extendNameEnv_C (\ns _ -> name:ns) env parent [name]
755 -------------------------------
756 inScopeUnqual :: GlobalRdrEnv -> Name -> Bool
757 -- Checks whether the Name is in scope unqualified,
758 -- regardless of whether it's ambiguous or not
759 inScopeUnqual env n = any unQualOK (lookupGRE_Name env n)
761 -------------------------------
762 checkForDodgyExport :: IE Name -> [Name] -> RnM ()
763 checkForDodgyExport ie@(IEThingAll tc) [n]
764 | isTcOcc (nameOccName n) = addWarn (dodgyExportWarn tc)
765 -- This occurs when you export T(..), but
766 -- only import T abstractly, or T is a synonym.
767 -- The single [n] is the type or class itself
768 | otherwise = addErr (exportItemErr ie)
769 -- This happes if you export x(..), which is bogus
770 checkForDodgyExport _ _ = return ()
772 -------------------------------
773 check_occs :: IE RdrName -> ExportOccMap -> [Name] -> RnM ExportOccMap
774 check_occs ie occs names
775 = foldlM check occs names
778 = case lookupOccEnv occs name_occ of
779 Nothing -> returnM (extendOccEnv occs name_occ (name, ie))
782 | name == name' -- Duplicate export
783 -> do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
784 warnIf warn_dup_exports (dupExportWarn name_occ ie ie') ;
787 | otherwise -- Same occ name but different names: an error
788 -> do { global_env <- getGlobalRdrEnv ;
789 addErr (exportClashErr global_env name' name ie' ie) ;
792 name_occ = nameOccName name
795 %*********************************************************
799 %*********************************************************
802 reportDeprecations :: DynFlags -> TcGblEnv -> RnM ()
803 reportDeprecations dflags tcg_env
804 = ifOptM Opt_WarnDeprecations $
805 do { (eps,hpt) <- getEpsAndHpt
806 -- By this time, typechecking is complete,
807 -- so the PIT is fully populated
808 ; mapM_ (check hpt (eps_PIT eps)) all_gres }
810 used_names = allUses (tcg_dus tcg_env)
811 -- Report on all deprecated uses; hence allUses
812 all_gres = globalRdrEnvElts (tcg_rdr_env tcg_env)
814 check hpt pit (GRE {gre_name = name, gre_prov = Imported (imp_spec:_)})
815 | name `elemNameSet` used_names
816 , Just deprec_txt <- lookupDeprec dflags hpt pit name
817 = addWarnAt (importSpecLoc imp_spec)
818 (sep [ptext SLIT("Deprecated use of") <+>
819 pprNonVarNameSpace (occNameSpace (nameOccName name)) <+>
821 (parens imp_msg) <> colon,
824 name_mod = nameModule name
825 imp_mod = importSpecModule imp_spec
826 imp_msg = ptext SLIT("imported from") <+> ppr imp_mod <> extra
827 extra | imp_mod == moduleName name_mod = empty
828 | otherwise = ptext SLIT(", but defined in") <+> ppr name_mod
830 check hpt pit ok_gre = returnM () -- Local, or not used, or not deprectated
831 -- The Imported pattern-match: don't deprecate locally defined names
832 -- For a start, we may be exporting a deprecated thing
833 -- Also we may use a deprecated thing in the defn of another
834 -- deprecated things. We may even use a deprecated thing in
835 -- the defn of a non-deprecated thing, when changing a module's
838 lookupDeprec :: DynFlags -> HomePackageTable -> PackageIfaceTable
839 -> Name -> Maybe DeprecTxt
840 lookupDeprec dflags hpt pit n
841 = case lookupIfaceByModule dflags hpt pit (nameModule n) of
842 Just iface -> mi_dep_fn iface n `seqMaybe` -- Bleat if the thing, *or
843 mi_dep_fn iface (nameParent n) -- its parent*, is deprec'd
845 | isWiredInName n -> Nothing
846 -- We have not necessarily loaded the .hi file for a
847 -- wired-in name (yet), although we *could*.
848 -- And we never deprecate them
850 | otherwise -> pprPanic "lookupDeprec" (ppr n)
851 -- By now all the interfaces should have been loaded
853 gre_is_used :: NameSet -> GlobalRdrElt -> Bool
854 gre_is_used used_names gre = gre_name gre `elemNameSet` used_names
857 %*********************************************************
861 %*********************************************************
864 reportUnusedNames :: Maybe [LIE RdrName] -- Export list
865 -> TcGblEnv -> RnM ()
866 reportUnusedNames export_decls gbl_env
867 = do { traceRn ((text "RUN") <+> (ppr (tcg_dus gbl_env)))
868 ; warnUnusedTopBinds unused_locals
869 ; warnUnusedModules unused_imp_mods
870 ; warnUnusedImports unused_imports
871 ; warnDuplicateImports defined_and_used
872 ; printMinimalImports minimal_imports }
874 used_names, all_used_names :: NameSet
875 used_names = findUses (tcg_dus gbl_env) emptyNameSet
876 -- NB: currently, if f x = g, we only treat 'g' as used if 'f' is used
879 all_used_names = used_names `unionNameSets`
880 mkNameSet (mapCatMaybes nameParent_maybe (nameSetToList used_names))
881 -- A use of C implies a use of T,
882 -- if C was brought into scope by T(..) or T(C)
884 -- Collect the defined names from the in-scope environment
885 defined_names :: [GlobalRdrElt]
886 defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)
888 -- Note that defined_and_used, defined_but_not_used
889 -- are both [GRE]; that's why we need defined_and_used
890 -- rather than just all_used_names
891 defined_and_used, defined_but_not_used :: [GlobalRdrElt]
892 (defined_and_used, defined_but_not_used)
893 = partition (gre_is_used all_used_names) defined_names
895 -- Filter out the ones that are
896 -- (a) defined in this module, and
897 -- (b) not defined by a 'deriving' clause
898 -- The latter have an Internal Name, so we can filter them out easily
899 unused_locals :: [GlobalRdrElt]
900 unused_locals = filter is_unused_local defined_but_not_used
901 is_unused_local :: GlobalRdrElt -> Bool
902 is_unused_local gre = isLocalGRE gre && isExternalName (gre_name gre)
904 unused_imports :: [GlobalRdrElt]
905 unused_imports = filter unused_imp defined_but_not_used
906 unused_imp (GRE {gre_prov = Imported imp_specs})
907 = not (all (module_unused . importSpecModule) imp_specs)
908 && or [exp | ImpSpec { is_item = ImpSome { is_explicit = exp } } <- imp_specs]
909 -- Don't complain about unused imports if we've already said the
910 -- entire import is unused
911 unused_imp other = False
913 -- To figure out the minimal set of imports, start with the things
914 -- that are in scope (i.e. in gbl_env). Then just combine them
915 -- into a bunch of avails, so they are properly grouped
917 -- BUG WARNING: this does not deal properly with qualified imports!
918 minimal_imports :: FiniteMap ModuleName AvailEnv
919 minimal_imports0 = foldr add_expall emptyFM expall_mods
920 minimal_imports1 = foldr add_name minimal_imports0 defined_and_used
921 minimal_imports = foldr add_inst_mod minimal_imports1 direct_import_mods
922 -- The last line makes sure that we retain all direct imports
923 -- even if we import nothing explicitly.
924 -- It's not necessarily redundant to import such modules. Consider
928 -- The import M() is not *necessarily* redundant, even if
929 -- we suck in no instance decls from M (e.g. it contains
930 -- no instance decls, or This contains no code). It may be
931 -- that we import M solely to ensure that M's orphan instance
932 -- decls (or those in its imports) are visible to people who
933 -- import This. Sigh.
934 -- There's really no good way to detect this, so the error message
935 -- in RnEnv.warnUnusedModules is weakened instead
937 -- We've carefully preserved the provenance so that we can
938 -- construct minimal imports that import the name by (one of)
939 -- the same route(s) as the programmer originally did.
940 add_name (GRE {gre_name = n, gre_prov = Imported imp_specs}) acc
941 = addToFM_C plusAvailEnv acc (importSpecModule (head imp_specs))
942 (unitAvailEnv (mk_avail n (nameParent_maybe n)))
946 -- Modules mentioned as 'module M' in the export list
947 expall_mods = case export_decls of
949 Just es -> [m | L _ (IEModuleContents m) <- es]
951 -- This is really bogus. The idea is that if we see 'module M' in
952 -- the export list we must retain the import decls that drive it
953 -- If we aren't careful we might see
954 -- module A( module M ) where
957 -- and suppose that N exports everything that M does. Then we
958 -- must not drop the import of M even though N brings it all into
961 -- BUG WARNING: 'module M' exports aside, what if M.x is mentioned?!
963 -- The reason that add_expall is bogus is that it doesn't take
964 -- qualified imports into account. But it's an improvement.
965 add_expall mod acc = addToFM_C plusAvailEnv acc mod emptyAvailEnv
967 -- n is the name of the thing, p is the name of its parent
968 mk_avail n (Just p) = AvailTC p [p,n]
969 mk_avail n Nothing | isTcOcc (nameOccName n) = AvailTC n [n]
970 | otherwise = Avail n
972 add_inst_mod (mod,_,_) acc
973 | mod_name `elemFM` acc = acc -- We import something already
974 | otherwise = addToFM acc mod_name emptyAvailEnv
976 mod_name = moduleName mod
977 -- Add an empty collection of imports for a module
978 -- from which we have sucked only instance decls
980 imports = tcg_imports gbl_env
982 direct_import_mods :: [(Module, Bool, SrcSpan)]
983 -- See the type of the imp_mods for this triple
984 direct_import_mods = moduleEnvElts (imp_mods imports)
986 -- unused_imp_mods are the directly-imported modules
987 -- that are not mentioned in minimal_imports1
988 -- [Note: not 'minimal_imports', because that includes directly-imported
989 -- modules even if we use nothing from them; see notes above]
991 -- BUG WARNING: does not deal correctly with multiple imports of the same module
992 -- becuase direct_import_mods has only one entry per module
993 unused_imp_mods = [(mod_name,loc) | (mod,no_imp,loc) <- direct_import_mods,
994 let mod_name = moduleName mod,
995 not (mod_name `elemFM` minimal_imports1),
998 -- The not no_imp part is not to complain about
999 -- import M (), which is an idiom for importing
1000 -- instance declarations
1002 module_unused :: ModuleName -> Bool
1003 module_unused mod = any (((==) mod) . fst) unused_imp_mods
1005 ---------------------
1006 warnDuplicateImports :: [GlobalRdrElt] -> RnM ()
1007 -- Given the GREs for names that are used, figure out which imports
1008 -- could be omitted without changing the top-level environment.
1010 -- NB: Given import Foo( T )
1011 -- import qualified Foo
1012 -- we do not report a duplicate import, even though Foo.T is brought
1013 -- into scope by both, because there's nothing you can *omit* without
1014 -- changing the top-level environment. So we complain only if it's
1015 -- explicitly named in both imports or neither.
1017 -- Furthermore, we complain about Foo.T only if
1018 -- there is no complaint about (unqualified) T
1020 warnDuplicateImports gres
1021 = ifOptM Opt_WarnUnusedImports $
1022 sequenceM_ [ warn name pr
1023 -- The 'head' picks the first offending group
1024 -- for this particular name
1025 | GRE { gre_name = name, gre_prov = Imported imps } <- gres
1026 , pr <- redundants imps ]
1028 warn name (red_imp, cov_imp)
1029 = addWarnAt (importSpecLoc red_imp)
1030 (vcat [ptext SLIT("Redundant import of:") <+> quotes pp_name,
1031 ptext SLIT("It is also") <+> ppr cov_imp])
1033 pp_name | is_qual red_decl = ppr (is_as red_decl) <> dot <> ppr occ
1034 | otherwise = ppr occ
1035 occ = nameOccName name
1036 red_decl = is_decl red_imp
1038 redundants :: [ImportSpec] -> [(ImportSpec,ImportSpec)]
1039 -- The returned pair is (redundant-import, covering-import)
1041 = [ (red_imp, cov_imp)
1043 , cov_imp <- take 1 (filter (covers red_imp) imps) ]
1045 -- "red_imp" is a putative redundant import
1046 -- "cov_imp" potentially covers it
1047 -- This test decides whether red_imp could be dropped
1049 -- NOTE: currently the test does not warn about
1052 -- even if the same underlying 'x' is involved, because dropping
1053 -- either import would change the qualified names in scope (M.x, N.x)
1054 -- But if the qualified names aren't used, the import is indeed redundant
1055 -- Sadly we don't know that. Oh well.
1056 covers red_imp@(ImpSpec { is_decl = red_decl, is_item = red_item })
1057 cov_imp@(ImpSpec { is_decl = cov_decl, is_item = cov_item })
1058 | red_loc == cov_loc
1059 = False -- Ignore diagonal elements
1060 | not (is_as red_decl == is_as cov_decl)
1061 = False -- They bring into scope different qualified names
1062 | not (is_qual red_decl) && is_qual cov_decl
1063 = False -- Covering one doesn't bring unqualified name into scope
1065 = not cov_selective -- Redundant one is selective and covering one isn't
1066 || red_later -- Both are explicit; tie-break using red_later
1068 = not cov_selective -- Neither import is selective
1069 && (is_mod red_decl == is_mod cov_decl) -- They import the same module
1070 && red_later -- Tie-break
1072 red_loc = importSpecLoc red_imp
1073 cov_loc = importSpecLoc cov_imp
1074 red_later = red_loc > cov_loc
1075 cov_selective = selectiveImpItem cov_item
1076 red_selective = selectiveImpItem red_item
1078 selectiveImpItem :: ImpItemSpec -> Bool
1079 selectiveImpItem ImpAll = False
1080 selectiveImpItem (ImpSome {}) = True
1082 -- ToDo: deal with original imports with 'qualified' and 'as M' clauses
1083 printMinimalImports :: FiniteMap ModuleName AvailEnv -- Minimal imports
1085 printMinimalImports imps
1086 = ifOptM Opt_D_dump_minimal_imports $ do {
1088 mod_ies <- mappM to_ies (fmToList imps) ;
1089 this_mod <- getModule ;
1090 rdr_env <- getGlobalRdrEnv ;
1091 ioToTcRn (do { h <- openFile (mkFilename this_mod) WriteMode ;
1092 printForUser h (mkPrintUnqualified rdr_env)
1093 (vcat (map ppr_mod_ie mod_ies)) })
1096 mkFilename this_mod = moduleNameString (moduleName this_mod) ++ ".imports"
1097 ppr_mod_ie (mod_name, ies)
1098 | mod_name == moduleName pRELUDE
1100 | null ies -- Nothing except instances comes from here
1101 = ptext SLIT("import") <+> ppr mod_name <> ptext SLIT("() -- Instances only")
1103 = ptext SLIT("import") <+> ppr mod_name <>
1104 parens (fsep (punctuate comma (map ppr ies)))
1106 to_ies (mod, avail_env) = do ies <- mapM to_ie (availEnvElts avail_env)
1109 to_ie :: AvailInfo -> RnM (IE Name)
1110 -- The main trick here is that if we're importing all the constructors
1111 -- we want to say "T(..)", but if we're importing only a subset we want
1112 -- to say "T(A,B,C)". So we have to find out what the module exports.
1113 to_ie (Avail n) = returnM (IEVar n)
1114 to_ie (AvailTC n [m]) = ASSERT( n==m )
1115 returnM (IEThingAbs n)
1116 to_ie (AvailTC n ns)
1117 = loadSrcInterface doc n_mod False `thenM` \ iface ->
1118 case [xs | (m,as) <- mi_exports iface,
1119 moduleName m == n_mod,
1121 x == nameOccName n] of
1122 [xs] | all_used xs -> returnM (IEThingAll n)
1123 | otherwise -> returnM (IEThingWith n (filter (/= n) ns))
1124 other -> pprTrace "to_ie" (ppr n <+> ppr n_mod <+> ppr other) $
1127 all_used avail_occs = all (`elem` map nameOccName ns) avail_occs
1128 doc = text "Compute minimal imports from" <+> ppr n
1129 n_mod = moduleName (nameModule n)
1133 %************************************************************************
1137 %************************************************************************
1140 badImportItemErr iface decl_spec ie
1141 = sep [ptext SLIT("Module"), quotes (ppr (is_mod decl_spec)), source_import,
1142 ptext SLIT("does not export"), quotes (ppr ie)]
1144 source_import | mi_boot iface = ptext SLIT("(hi-boot interface)")
1147 dodgyImportWarn item = dodgyMsg (ptext SLIT("import")) item
1148 dodgyExportWarn item = dodgyMsg (ptext SLIT("export")) item
1151 = sep [ ptext SLIT("The") <+> kind <+> ptext SLIT("item") <+> quotes (ppr (IEThingAll tc)),
1152 ptext SLIT("suggests that") <+> quotes (ppr tc) <+> ptext SLIT("has constructor or class methods"),
1153 ptext SLIT("but it has none; it is a type synonym or abstract type or class") ]
1156 = hsep [ ptext SLIT("Unknown module in export list: module"), quotes (ppr mod)]
1158 exportItemErr export_item
1159 = sep [ ptext SLIT("The export item") <+> quotes (ppr export_item),
1160 ptext SLIT("attempts to export constructors or class methods that are not visible here") ]
1162 typeItemErr name wherestr
1163 = sep [ ptext SLIT("Using 'type' tag on") <+> quotes (ppr name) <+> wherestr,
1164 ptext SLIT("Use -findexed-types to enable this extension") ]
1166 exportClashErr global_env name1 name2 ie1 ie2
1167 = vcat [ ptext SLIT("Conflicting exports for") <+> quotes (ppr occ) <> colon
1168 , ppr_export ie1 name1
1169 , ppr_export ie2 name2 ]
1171 occ = nameOccName name1
1172 ppr_export ie name = nest 2 (quotes (ppr ie) <+> ptext SLIT("exports") <+>
1173 quotes (ppr name) <+> pprNameProvenance (get_gre name))
1175 -- get_gre finds a GRE for the Name, so that we can show its provenance
1177 = case lookupGRE_Name global_env name of
1179 [] -> pprPanic "exportClashErr" (ppr name)
1181 addDupDeclErr :: Name -> Name -> TcRn ()
1182 addDupDeclErr name_a name_b
1183 = addErrAt (srcLocSpan loc2) $
1184 vcat [ptext SLIT("Multiple declarations of") <+> quotes (ppr name1),
1185 ptext SLIT("Declared at:") <+> vcat [ppr (nameSrcLoc name1), ppr loc2]]
1187 loc2 = nameSrcLoc name2
1188 (name1,name2) | nameSrcLoc name_a > nameSrcLoc name_b = (name_b,name_a)
1189 | otherwise = (name_a,name_b)
1190 -- Report the error at the later location
1192 dupExportWarn occ_name ie1 ie2
1193 = hsep [quotes (ppr occ_name),
1194 ptext SLIT("is exported by"), quotes (ppr ie1),
1195 ptext SLIT("and"), quotes (ppr ie2)]
1198 = hsep [ptext SLIT("Duplicate"),
1199 quotes (ptext SLIT("Module") <+> ppr mod),
1200 ptext SLIT("in export list")]
1202 moduleDeprec mod txt
1203 = sep [ ptext SLIT("Module") <+> quotes (ppr mod) <+> ptext SLIT("is deprecated:"),