2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[RnNames]{Extracting imported and top-level names in scope}
8 rnImports, importsFromLocalDecls,
9 reportUnusedNames, reportDeprecations,
10 mkModDeps, exportsToAvails, exportsFromAvail
13 #include "HsVersions.h"
15 import CmdLineOpts ( DynFlag(..) )
16 import HsSyn ( IE(..), ieName, ImportDecl(..), LImportDecl,
17 ForeignDecl(..), HsGroup(..),
18 collectGroupBinders, tyClDeclNames
21 import IfaceEnv ( lookupOrig, newGlobalBinder )
22 import LoadIface ( loadSrcInterface )
26 import PrelNames ( pRELUDE, isUnboundName, main_RDR_Unqual )
27 import Module ( Module, moduleUserString,
28 unitModuleEnv, unitModuleEnv,
29 lookupModuleEnv, moduleEnvElts, foldModuleEnv )
30 import Name ( Name, nameSrcLoc, nameOccName, nameModule, isWiredInName,
31 nameParent, nameParent_maybe, isExternalName,
35 import OccName ( srcDataName, isTcOcc, occNameFlavour, OccEnv,
36 mkOccEnv, lookupOccEnv, emptyOccEnv, extendOccEnv )
37 import HscTypes ( GenAvailInfo(..), AvailInfo, GhciMode(..),
38 IfaceExport, HomePackageTable, PackageIfaceTable,
39 availNames, unQualInScope,
40 Deprecs(..), ModIface(..), Dependencies(..),
41 lookupIface, ExternalPackageState(..),
44 import RdrName ( RdrName, rdrNameOcc, setRdrNameSpace,
45 GlobalRdrEnv, mkGlobalRdrEnv, GlobalRdrElt(..),
46 emptyGlobalRdrEnv, plusGlobalRdrEnv, globalRdrEnvElts,
47 unQualOK, lookupGRE_Name,
48 Provenance(..), ImportSpec(..),
49 isLocalGRE, pprNameProvenance )
51 import Maybes ( isNothing, catMaybes, mapCatMaybes, seqMaybe, orElse )
52 import SrcLoc ( noSrcLoc, Located(..), mkGeneralSrcSpan,
53 unLoc, noLoc, srcLocSpan, combineSrcSpans, SrcSpan )
54 import BasicTypes ( DeprecTxt )
55 import ListSetOps ( removeDups )
56 import Util ( sortLe, notNull, isSingleton )
57 import List ( partition )
58 import IO ( openFile, IOMode(..) )
63 %************************************************************************
67 %************************************************************************
70 rnImports :: [LImportDecl RdrName]
71 -> RnM (GlobalRdrEnv, ImportAvails)
74 = do { -- PROCESS IMPORT DECLS
75 -- Do the non {- SOURCE -} ones first, so that we get a helpful
76 -- warning for {- SOURCE -} ones that are unnecessary
78 ; opt_no_prelude <- doptM Opt_NoImplicitPrelude
80 all_imports = mk_prel_imports this_mod opt_no_prelude ++ imports
81 (source, ordinary) = partition is_source_import all_imports
82 is_source_import (L _ (ImportDecl _ is_boot _ _ _)) = is_boot
84 get_imports = importsFromImportDecl this_mod
86 ; stuff1 <- mappM get_imports ordinary
87 ; stuff2 <- mappM get_imports source
91 (imp_gbl_envs, imp_avails) = unzip (stuff1 ++ stuff2)
92 gbl_env :: GlobalRdrEnv
93 gbl_env = foldr plusGlobalRdrEnv emptyGlobalRdrEnv imp_gbl_envs
95 all_avails :: ImportAvails
96 all_avails = foldr plusImportAvails emptyImportAvails imp_avails
99 ; return (gbl_env, all_avails) }
101 -- NB: opt_NoImplicitPrelude is slightly different to import Prelude ();
102 -- because the former doesn't even look at Prelude.hi for instance
103 -- declarations, whereas the latter does.
104 mk_prel_imports this_mod no_prelude
105 | this_mod == pRELUDE
106 || explicit_prelude_import
110 | otherwise = [preludeImportDecl]
112 explicit_prelude_import
113 = notNull [ () | L _ (ImportDecl mod _ _ _ _) <- imports,
114 unLoc mod == pRELUDE ]
118 ImportDecl (L loc pRELUDE)
119 False {- Not a boot interface -}
120 False {- Not qualified -}
121 Nothing {- No "as" -}
122 Nothing {- No import list -}
124 loc = mkGeneralSrcSpan FSLIT("Implicit import declaration")
128 importsFromImportDecl :: Module
129 -> LImportDecl RdrName
130 -> RnM (GlobalRdrEnv, ImportAvails)
132 importsFromImportDecl this_mod
133 (L loc (ImportDecl loc_imp_mod_name want_boot qual_only as_mod imp_details))
137 -- If there's an error in loadInterface, (e.g. interface
138 -- file not found) we get lots of spurious errors from 'filterImports'
140 imp_mod_name = unLoc loc_imp_mod_name
141 doc = ppr imp_mod_name <+> ptext SLIT("is directly imported")
143 loadSrcInterface doc imp_mod_name want_boot `thenM` \ iface ->
145 -- Compiler sanity check: if the import didn't say
146 -- {-# SOURCE #-} we should not get a hi-boot file
147 WARN( not want_boot && mi_boot iface, ppr imp_mod_name )
149 -- Issue a user warning for a redundant {- SOURCE -} import
150 -- NB that we arrange to read all the ordinary imports before
151 -- any of the {- SOURCE -} imports
152 warnIf (want_boot && not (mi_boot iface))
153 (warnRedundantSourceImport imp_mod_name) `thenM_`
156 imp_mod = mi_module iface
157 deprecs = mi_deprecs iface
158 is_orph = mi_orphan iface
161 filtered_exports = filter not_this_mod (mi_exports iface)
162 not_this_mod (mod,_) = mod /= this_mod
163 -- If the module exports anything defined in this module, just ignore it.
164 -- Reason: otherwise it looks as if there are two local definition sites
165 -- for the thing, and an error gets reported. Easiest thing is just to
166 -- filter them out up front. This situation only arises if a module
167 -- imports itself, or another module that imported it. (Necessarily,
168 -- this invoves a loop.)
170 -- Tiresome consequence: if you say
175 -- module B( AType ) where
176 -- import {-# SOURCE #-} A( AType )
178 -- then you'll get a 'B does not export AType' message. Oh well.
180 qual_mod_name = case as_mod of
181 Nothing -> imp_mod_name
182 Just another_name -> another_name
183 imp_spec = ImportSpec { is_mod = imp_mod_name, is_qual = qual_only,
184 is_loc = loc, is_as = qual_mod_name }
186 -- Get the total imports, and filter them according to the import list
187 exportsToAvails filtered_exports `thenM` \ total_avails ->
188 filterImports iface imp_spec
189 imp_details total_avails `thenM` \ (avail_env, gbl_env) ->
191 getDOpts `thenM` \ dflags ->
194 -- Compute new transitive dependencies
196 orphans | is_orph = ASSERT( not (imp_mod_name `elem` dep_orphs deps) )
197 imp_mod_name : dep_orphs deps
198 | otherwise = dep_orphs deps
200 (dependent_mods, dependent_pkgs)
201 = case mi_package iface of
203 -- Imported module is from the home package
204 -- Take its dependent modules and add imp_mod itself
205 -- Take its dependent packages unchanged
207 -- NB: (dep_mods deps) might include a hi-boot file
208 -- for the module being compiled, CM. Do *not* filter
209 -- this out (as we used to), because when we've
210 -- finished dealing with the direct imports we want to
211 -- know if any of them depended on CM.hi-boot, in
212 -- which case we should do the hi-boot consistency
213 -- check. See LoadIface.loadHiBootInterface
214 ((imp_mod_name, want_boot) : dep_mods deps, dep_pkgs deps)
216 ExternalPackage pkg ->
217 -- Imported module is from another package
218 -- Dump the dependent modules
219 -- Add the package imp_mod comes from to the dependent packages
220 ASSERT2( not (pkg `elem` dep_pkgs deps), ppr pkg <+> ppr (dep_pkgs deps) )
221 ([], pkg : dep_pkgs deps)
223 import_all = case imp_details of
224 Just (is_hiding, ls) -- Imports are spec'd explicitly
225 | not is_hiding -> Just (not (null ls))
226 _ -> Nothing -- Everything is imported,
227 -- (or almost everything [hiding])
229 -- unqual_avails is the Avails that are visible in *unqualified* form
230 -- We need to know this so we know what to export when we see
231 -- module M ( module P ) where ...
232 -- Then we must export whatever came from P unqualified.
233 imports = ImportAvails {
234 imp_env = unitModuleEnv qual_mod_name avail_env,
235 imp_mods = unitModuleEnv imp_mod (imp_mod, import_all, loc),
237 imp_dep_mods = mkModDeps dependent_mods,
238 imp_dep_pkgs = dependent_pkgs }
241 -- Complain if we import a deprecated module
242 ifOptM Opt_WarnDeprecations (
244 DeprecAll txt -> addWarn (moduleDeprec imp_mod_name txt)
248 returnM (gbl_env, imports)
250 exportsToAvails :: [IfaceExport] -> TcRnIf gbl lcl NameSet
251 exportsToAvails exports
252 = foldlM do_one emptyNameSet exports
254 do_one acc (mod, exports) = foldlM (do_avail mod) acc exports
255 do_avail mod acc (Avail n) = do { n' <- lookupOrig mod n;
256 ; return (addOneToNameSet acc n') }
257 do_avail mod acc (AvailTC n ns) = do { n' <- lookupOrig mod n
258 ; ns' <- mappM (lookup_sub n') ns
259 ; return (addListToNameSet acc (n':ns')) }
261 lookup_sub parent occ = newGlobalBinder mod occ (Just parent) noSrcLoc
262 -- Hack alert! Notice the newGlobalBinder. It ensures that the subordinate
263 -- names record their parent; and that in turn ensures that the GlobalRdrEnv
264 -- has the correct parent for all the names in its range.
265 -- For imported things, we only suck in the binding site later, if ever.
266 -- Reason for all this:
267 -- Suppose module M exports type A.T, and constructor A.MkT
268 -- Then, we know that A.MkT is a subordinate name of A.T,
269 -- even though we aren't at the binding site of A.T
270 -- And it's important, because we may simply re-export A.T
271 -- without ever sucking in the declaration itself.
273 warnRedundantSourceImport mod_name
274 = ptext SLIT("Unnecessary {- SOURCE -} in the import of module")
275 <+> quotes (ppr mod_name)
279 %************************************************************************
281 importsFromLocalDecls
283 %************************************************************************
285 From the top-level declarations of this module produce
286 * the lexical environment
288 created by its bindings.
290 Complain about duplicate bindings
293 importsFromLocalDecls :: HsGroup RdrName
294 -> RnM (GlobalRdrEnv, ImportAvails)
295 importsFromLocalDecls group
296 = getModule `thenM` \ this_mod ->
297 getLocalDeclBinders this_mod group `thenM` \ avails ->
298 -- The avails that are returned don't include the "system" names
300 all_names :: [Name] -- All the defns; no dups eliminated
301 all_names = [name | avail <- avails, name <- availNames avail]
304 (_, dups) = removeDups compare all_names
306 -- Check for duplicate definitions
307 -- The complaint will come out as "Multiple declarations of Foo.f" because
308 -- since 'f' is in the env twice, the unQualInScope used by the error-msg
309 -- printer returns False. It seems awkward to fix, unfortunately.
310 mappM_ addDupDeclErr dups `thenM_`
312 doptM Opt_NoImplicitPrelude `thenM` \ implicit_prelude ->
314 prov = LocalDef this_mod
315 gbl_env = mkGlobalRdrEnv gres
316 gres = [ GRE { gre_name = name, gre_prov = prov}
319 -- Optimisation: filter out names for built-in syntax
320 -- They just clutter up the environment (esp tuples), and the parser
321 -- will generate Exact RdrNames for them, so the cluttered
322 -- envt is no use. To avoid doing this filter all the time,
323 -- we use -fno-implicit-prelude as a clue that the filter is
324 -- worth while. Really, it's only useful for GHC.Base and GHC.Tuple.
326 -- It's worth doing because it makes the environment smaller for
327 -- every module that imports the Prelude
329 -- Note: don't filter the gbl_env (hence all_names, not filered_all_names
330 -- in defn of gres above). Stupid reason: when parsing
331 -- data type decls, the constructors start as Exact tycon-names,
332 -- and then get turned into data con names by zapping the name space;
333 -- but that stops them being Exact, so they get looked up.
334 -- Ditto in fixity decls; e.g. infix 5 :
335 -- Sigh. It doesn't matter because it only affects the Data.Tuple really.
336 -- The important thing is to trim down the exports.
338 | implicit_prelude = filter (not . isBuiltInSyntax) all_names
339 | otherwise = all_names
341 imports = emptyImportAvails {
342 imp_env = unitModuleEnv this_mod $
343 mkNameSet filtered_names
346 returnM (gbl_env, imports)
350 %*********************************************************
352 \subsection{Getting binders out of a declaration}
354 %*********************************************************
356 @getLocalDeclBinders@ returns the names for an @HsDecl@. It's
357 used for source code.
359 *** See "THE NAMING STORY" in HsDecls ****
362 getLocalDeclBinders :: Module -> HsGroup RdrName -> RnM [AvailInfo]
363 getLocalDeclBinders mod (HsGroup {hs_valds = val_decls,
364 hs_tyclds = tycl_decls,
365 hs_fords = foreign_decls })
366 = -- For type and class decls, we generate Global names, with
367 -- no export indicator. They need to be global because they get
368 -- permanently bound into the TyCons and Classes. They don't need
369 -- an export indicator because they are all implicitly exported.
371 mappM new_tc tycl_decls `thenM` \ tc_avails ->
372 mappM new_simple (for_hs_bndrs ++ val_hs_bndrs) `thenM` \ simple_avails ->
373 returnM (tc_avails ++ simple_avails)
375 new_simple rdr_name = newTopSrcBinder mod Nothing rdr_name `thenM` \ name ->
378 val_hs_bndrs = collectGroupBinders val_decls
379 for_hs_bndrs = [nm | L _ (ForeignImport nm _ _ _) <- foreign_decls]
382 = newTopSrcBinder mod Nothing main_rdr `thenM` \ main_name ->
383 mappM (newTopSrcBinder mod (Just main_name)) sub_rdrs `thenM` \ sub_names ->
384 returnM (AvailTC main_name (main_name : sub_names))
386 (main_rdr : sub_rdrs) = tyClDeclNames (unLoc tc_decl)
390 %************************************************************************
392 \subsection{Filtering imports}
394 %************************************************************************
396 @filterImports@ takes the @ExportEnv@ telling what the imported module makes
397 available, and filters it through the import spec (if any).
400 filterImports :: ModIface
401 -> ImportSpec -- The span for the entire import decl
402 -> Maybe (Bool, [Located (IE RdrName)]) -- Import spec; True => hiding
403 -> NameSet -- What's available
404 -> RnM (NameSet, -- What's imported (qualified or unqualified)
405 GlobalRdrEnv) -- Same again, but in GRE form
407 -- Complains if import spec mentions things that the module doesn't export
408 -- Warns/informs if import spec contains duplicates.
410 mkGenericRdrEnv imp_spec names
411 = mkGlobalRdrEnv [ GRE { gre_name = name, gre_prov = Imported [imp_spec] False }
412 | name <- nameSetToList names ]
414 filterImports iface imp_spec Nothing all_names
415 = returnM (all_names, mkGenericRdrEnv imp_spec all_names)
417 filterImports iface imp_spec (Just (want_hiding, import_items)) all_names
418 = mappM (addLocM get_item) import_items `thenM` \ gres_s ->
421 specified_names = mkNameSet (map gre_name gres)
423 if not want_hiding then
424 return (specified_names, mkGlobalRdrEnv gres)
427 keep n = not (n `elemNameSet` specified_names)
428 pruned_avails = filterNameSet keep all_names
430 return (pruned_avails, mkGenericRdrEnv imp_spec pruned_avails)
433 occ_env :: OccEnv Name -- Maps OccName to corresponding Name
434 occ_env = mkOccEnv [(nameOccName n, n) | n <- nameSetToList all_names]
435 -- This env will have entries for data constructors too,
436 -- they won't make any difference because naked entities like T
437 -- in an import list map to TcOccs, not VarOccs.
439 sub_env :: NameEnv [Name]
440 sub_env = mkSubNameEnv all_names
442 bale_out item = addErr (badImportItemErr iface imp_spec item) `thenM_`
445 succeed_with :: Bool -> [Name] -> RnM [GlobalRdrElt]
446 succeed_with all_explicit names
447 = do { loc <- getSrcSpanM
448 ; returnM (map (mk_gre loc) names) }
450 mk_gre loc name = GRE { gre_name = name,
451 gre_prov = Imported [this_imp_spec loc] (explicit name) }
452 this_imp_spec loc = imp_spec { is_loc = loc }
453 explicit name = all_explicit || isNothing (nameParent_maybe name)
455 get_item :: IE RdrName -> RnM [GlobalRdrElt]
456 -- Empty result for a bad item.
457 -- Singleton result is typical case.
458 -- Can have two when we are hiding, and mention C which might be
459 -- both a class and a data constructor.
460 get_item item@(IEModuleContents _)
463 get_item item@(IEThingAll tc)
464 = case check_item item of
467 [n] -> -- This occurs when you import T(..), but
468 -- only export T abstractly. The single [n]
469 -- in the AvailTC is the type or class itself
470 ifOptM Opt_WarnDodgyImports (addWarn (dodgyImportWarn tc)) `thenM_`
471 succeed_with False [n]
473 names -> succeed_with False names
475 get_item item@(IEThingAbs n)
476 | want_hiding -- hiding( C )
477 -- Here the 'C' can be a data constructor
478 -- *or* a type/class, or even both
479 = case concat [check_item item, check_item (IEVar data_n)] of
481 names -> succeed_with True names
483 data_n = setRdrNameSpace n srcDataName
486 = case check_item item of
488 names -> succeed_with True names
490 check_item :: IE RdrName -> [Name]
492 = case lookupOccEnv occ_env (rdrNameOcc (ieName item)) of
494 Just name -> filterAvail item name sub_env
498 %************************************************************************
500 \subsection{Export list processing}
502 %************************************************************************
504 Processing the export list.
506 You might think that we should record things that appear in the export
507 list as ``occurrences'' (using @addOccurrenceName@), but you'd be
508 wrong. We do check (here) that they are in scope, but there is no
509 need to slurp in their actual declaration (which is what
510 @addOccurrenceName@ forces).
512 Indeed, doing so would big trouble when compiling @PrelBase@, because
513 it re-exports @GHC@, which includes @takeMVar#@, whose type includes
514 @ConcBase.StateAndSynchVar#@, and so on...
517 type ExportAccum -- The type of the accumulating parameter of
518 -- the main worker function in exportsFromAvail
519 = ([Module], -- 'module M's seen so far
520 ExportOccMap, -- Tracks exported occurrence names
521 NameSet) -- The accumulated exported stuff
522 emptyExportAccum = ([], emptyOccEnv, emptyNameSet)
524 type ExportOccMap = OccEnv (Name, IE RdrName)
525 -- Tracks what a particular exported OccName
526 -- in an export list refers to, and which item
527 -- it came from. It's illegal to export two distinct things
528 -- that have the same occurrence name
531 exportsFromAvail :: Bool -- False => no 'module M(..) where' header at all
532 -> Maybe [Located (IE RdrName)] -- Nothing => no explicit export list
534 -- Complains if two distinct exports have same OccName
535 -- Warns about identical exports.
536 -- Complains about exports items not in scope
538 exportsFromAvail explicit_mod exports
539 = do { TcGblEnv { tcg_rdr_env = rdr_env,
540 tcg_imports = imports } <- getGblEnv ;
542 -- If the module header is omitted altogether, then behave
543 -- as if the user had written "module Main(main) where..."
544 -- EXCEPT in interactive mode, when we behave as if he had
545 -- written "module Main where ..."
546 -- Reason: don't want to complain about 'main' not in scope
547 -- in interactive mode
548 ghci_mode <- getGhciMode ;
550 | explicit_mod = exports
551 | ghci_mode == Interactive = Nothing
552 | otherwise = Just [noLoc (IEVar main_RDR_Unqual)] } ;
553 exports_from_avail real_exports rdr_env imports }
556 exports_from_avail Nothing rdr_env imports
557 = -- Export all locally-defined things
558 -- We do this by filtering the global RdrEnv,
559 -- keeping only things that are locally-defined
560 return (mkNameSet [ gre_name gre
561 | gre <- globalRdrEnvElts rdr_env,
564 exports_from_avail (Just items) rdr_env (ImportAvails { imp_env = imp_env })
565 = foldlM do_litem emptyExportAccum items `thenM` \ (_, _, exports) ->
568 sub_env :: NameEnv [Name] -- Classify each name by its parent
569 sub_env = mkSubNameEnv (foldModuleEnv unionNameSets emptyNameSet imp_env)
571 do_litem :: ExportAccum -> Located (IE RdrName) -> RnM ExportAccum
572 do_litem acc = addLocM (exports_from_item acc)
574 exports_from_item :: ExportAccum -> IE RdrName -> RnM ExportAccum
575 exports_from_item acc@(mods, occs, exports) ie@(IEModuleContents mod)
576 | mod `elem` mods -- Duplicate export of M
577 = do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
578 warnIf warn_dup_exports (dupModuleExport mod) ;
582 = case lookupModuleEnv imp_env mod of
583 Nothing -> addErr (modExportErr mod) `thenM_`
587 new_exports = filterNameSet (inScopeUnqual rdr_env) names
590 -- This check_occs not only finds conflicts between this item
591 -- and others, but also internally within this item. That is,
592 -- if 'M.x' is in scope in several ways, we'll have several
593 -- members of mod_avails with the same OccName.
594 check_occs ie occs (nameSetToList new_exports) `thenM` \ occs' ->
595 returnM (mod:mods, occs', exports `unionNameSets` new_exports)
597 exports_from_item acc@(mods, occs, exports) ie
598 = lookupGlobalOccRn (ieName ie) `thenM` \ name ->
599 if isUnboundName name then
600 returnM acc -- Avoid error cascade
602 new_exports = filterAvail ie name sub_env
604 checkErr (not (null new_exports)) (exportItemErr ie) `thenM_`
605 checkForDodgyExport ie new_exports `thenM_`
606 check_occs ie occs new_exports `thenM` \ occs' ->
607 returnM (mods, occs', addListToNameSet exports new_exports)
609 -------------------------------
610 filterAvail :: IE RdrName -- Wanted
611 -> Name -- The Name of the ieName of the item
612 -> NameEnv [Name] -- Maps type/class names to their sub-names
613 -> [Name] -- Empty if even one thing reqd is missing
615 filterAvail (IEVar _) n subs = [n]
616 filterAvail (IEThingAbs _) n subs = [n]
617 filterAvail (IEThingAll _) n subs = n : subNames subs n
618 filterAvail (IEThingWith _ rdrs) n subs
619 | any isNothing mb_names = []
620 | otherwise = n : catMaybes mb_names
622 env = mkOccEnv [(nameOccName s, s) | s <- subNames subs n]
623 mb_names = map (lookupOccEnv env . rdrNameOcc) rdrs
625 subNames :: NameEnv [Name] -> Name -> [Name]
626 subNames env n = lookupNameEnv env n `orElse` []
628 mkSubNameEnv :: NameSet -> NameEnv [Name]
629 -- Maps types and classes to their constructors/classops respectively
630 -- This mapping just makes it easier to deal with A(..) export items
632 = foldNameSet add_name emptyNameEnv names
635 | Just parent <- nameParent_maybe name
636 = extendNameEnv_C (\ns _ -> name:ns) env parent [name]
639 -------------------------------
640 inScopeUnqual :: GlobalRdrEnv -> Name -> Bool
641 -- Checks whether the Name is in scope unqualified,
642 -- regardless of whether it's ambiguous or not
643 inScopeUnqual env n = any unQualOK (lookupGRE_Name env n)
645 -------------------------------
646 checkForDodgyExport :: IE RdrName -> [Name] -> RnM ()
647 checkForDodgyExport ie@(IEThingAll tc) [n]
648 | isTcOcc (nameOccName n) = addWarn (dodgyExportWarn tc)
649 -- This occurs when you export T(..), but
650 -- only import T abstractly, or T is a synonym.
651 -- The single [n] is the type or class itself
652 | otherwise = addErr (exportItemErr ie)
653 -- This happes if you export x(..), which is bogus
654 checkForDodgyExport _ _ = return ()
656 -------------------------------
657 check_occs :: IE RdrName -> ExportOccMap -> [Name] -> RnM ExportOccMap
658 check_occs ie occs names
659 = foldlM check occs names
662 = case lookupOccEnv occs name_occ of
663 Nothing -> returnM (extendOccEnv occs name_occ (name, ie))
666 | name == name' -- Duplicate export
667 -> do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
668 warnIf warn_dup_exports (dupExportWarn name_occ ie ie') ;
671 | otherwise -- Same occ name but different names: an error
672 -> do { global_env <- getGlobalRdrEnv ;
673 addErr (exportClashErr global_env name name' ie ie') ;
676 name_occ = nameOccName name
679 %*********************************************************
683 %*********************************************************
686 reportDeprecations :: TcGblEnv -> RnM ()
687 reportDeprecations tcg_env
688 = ifOptM Opt_WarnDeprecations $
689 do { (eps,hpt) <- getEpsAndHpt
690 ; mapM_ (check hpt (eps_PIT eps)) all_gres }
692 used_names = findUses (tcg_dus tcg_env) emptyNameSet
693 all_gres = globalRdrEnvElts (tcg_rdr_env tcg_env)
695 check hpt pit (GRE {gre_name = name, gre_prov = Imported (imp_spec:_) _})
696 | name `elemNameSet` used_names
697 , Just deprec_txt <- lookupDeprec hpt pit name
698 = setSrcSpan (is_loc imp_spec) $
699 addWarn (sep [ptext SLIT("Deprecated use of") <+>
700 occNameFlavour (nameOccName name) <+>
705 name_mod = nameModule name
706 imp_mod = is_mod imp_spec
707 imp_msg = ptext SLIT("imported from") <+> ppr imp_mod <> extra
708 extra | imp_mod == name_mod = empty
709 | otherwise = ptext SLIT(", but defined in") <+> ppr name_mod
711 check hpt pit ok_gre = returnM () -- Local, or not used, or not deprectated
712 -- The Imported pattern-match: don't deprecate locally defined names
713 -- For a start, we may be exporting a deprecated thing
714 -- Also we may use a deprecated thing in the defn of another
715 -- deprecated things. We may even use a deprecated thing in
716 -- the defn of a non-deprecated thing, when changing a module's
719 lookupDeprec :: HomePackageTable -> PackageIfaceTable
720 -> Name -> Maybe DeprecTxt
721 lookupDeprec hpt pit n
722 = case lookupIface hpt pit (nameModule n) of
723 Just iface -> mi_dep_fn iface n `seqMaybe` -- Bleat if the thing, *or
724 mi_dep_fn iface (nameParent n) -- its parent*, is deprec'd
726 | isWiredInName n -> Nothing
727 -- We have not necessarily loaded the .hi file for a
728 -- wired-in name (yet), although we *could*.
729 -- And we never deprecate them
731 | otherwise -> pprPanic "lookupDeprec" (ppr n)
732 -- By now all the interfaces should have been loaded
734 gre_is_used :: NameSet -> GlobalRdrElt -> Bool
735 gre_is_used used_names gre = gre_name gre `elemNameSet` used_names
738 %*********************************************************
742 %*********************************************************
745 reportUnusedNames :: TcGblEnv -> RnM ()
746 reportUnusedNames gbl_env
747 = do { warnUnusedTopBinds unused_locals
748 ; warnUnusedModules unused_imp_mods
749 ; warnUnusedImports unused_imports
750 ; warnDuplicateImports dup_imps
751 ; printMinimalImports minimal_imports }
753 used_names, all_used_names :: NameSet
754 used_names = findUses (tcg_dus gbl_env) emptyNameSet
755 all_used_names = used_names `unionNameSets`
756 mkNameSet (mapCatMaybes nameParent_maybe (nameSetToList used_names))
757 -- A use of C implies a use of T,
758 -- if C was brought into scope by T(..) or T(C)
760 -- Collect the defined names from the in-scope environment
761 defined_names :: [GlobalRdrElt]
762 defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)
764 -- Note that defined_and_used, defined_but_not_used
765 -- are both [GRE]; that's why we need defined_and_used
766 -- rather than just all_used_names
767 defined_and_used, defined_but_not_used :: [GlobalRdrElt]
768 (defined_and_used, defined_but_not_used)
769 = partition (gre_is_used all_used_names) defined_names
771 -- Find the duplicate imports
772 dup_imps = filter is_dup defined_and_used
773 is_dup (GRE {gre_prov = Imported imp_spec True}) = not (isSingleton imp_spec)
776 -- Filter out the ones that are
777 -- (a) defined in this module, and
778 -- (b) not defined by a 'deriving' clause
779 -- The latter have an Internal Name, so we can filter them out easily
780 unused_locals :: [GlobalRdrElt]
781 unused_locals = filter is_unused_local defined_but_not_used
782 is_unused_local :: GlobalRdrElt -> Bool
783 is_unused_local gre = isLocalGRE gre && isExternalName (gre_name gre)
785 unused_imports :: [GlobalRdrElt]
786 unused_imports = filter unused_imp defined_but_not_used
787 unused_imp (GRE {gre_prov = Imported imp_specs True})
788 = not (all (module_unused . is_mod) imp_specs)
789 -- Don't complain about unused imports if we've already said the
790 -- entire import is unused
791 unused_imp other = False
793 -- To figure out the minimal set of imports, start with the things
794 -- that are in scope (i.e. in gbl_env). Then just combine them
795 -- into a bunch of avails, so they are properly grouped
796 minimal_imports :: FiniteMap Module AvailEnv
797 minimal_imports0 = emptyFM
798 minimal_imports1 = foldr add_name minimal_imports0 defined_and_used
799 minimal_imports = foldr add_inst_mod minimal_imports1 direct_import_mods
800 -- The last line makes sure that we retain all direct imports
801 -- even if we import nothing explicitly.
802 -- It's not necessarily redundant to import such modules. Consider
806 -- The import M() is not *necessarily* redundant, even if
807 -- we suck in no instance decls from M (e.g. it contains
808 -- no instance decls, or This contains no code). It may be
809 -- that we import M solely to ensure that M's orphan instance
810 -- decls (or those in its imports) are visible to people who
811 -- import This. Sigh.
812 -- There's really no good way to detect this, so the error message
813 -- in RnEnv.warnUnusedModules is weakened instead
815 -- We've carefully preserved the provenance so that we can
816 -- construct minimal imports that import the name by (one of)
817 -- the same route(s) as the programmer originally did.
818 add_name (GRE {gre_name = n, gre_prov = Imported imp_specs _}) acc
819 = addToFM_C plusAvailEnv acc (is_mod (head imp_specs))
820 (unitAvailEnv (mk_avail n (nameParent_maybe n)))
824 -- n is the name of the thing, p is the name of its parent
825 mk_avail n (Just p) = AvailTC p [p,n]
826 mk_avail n Nothing | isTcOcc (nameOccName n) = AvailTC n [n]
827 | otherwise = Avail n
829 add_inst_mod (mod,_,_) acc
830 | mod `elemFM` acc = acc -- We import something already
831 | otherwise = addToFM acc mod emptyAvailEnv
833 -- Add an empty collection of imports for a module
834 -- from which we have sucked only instance decls
836 imports = tcg_imports gbl_env
838 direct_import_mods :: [(Module, Maybe Bool, SrcSpan)]
839 -- See the type of the imp_mods for this triple
840 direct_import_mods = moduleEnvElts (imp_mods imports)
842 -- unused_imp_mods are the directly-imported modules
843 -- that are not mentioned in minimal_imports1
844 -- [Note: not 'minimal_imports', because that includes directly-imported
845 -- modules even if we use nothing from them; see notes above]
846 unused_imp_mods = [(mod,loc) | (mod,imp,loc) <- direct_import_mods,
847 not (mod `elemFM` minimal_imports1),
850 -- The Just False part is not to complain about
851 -- import M (), which is an idiom for importing
852 -- instance declarations
854 module_unused :: Module -> Bool
855 module_unused mod = any (((==) mod) . fst) unused_imp_mods
857 ---------------------
858 warnDuplicateImports :: [GlobalRdrElt] -> RnM ()
859 warnDuplicateImports gres
860 = ifOptM Opt_WarnUnusedImports (mapM_ warn gres)
862 warn (GRE { gre_name = name, gre_prov = Imported imps _ })
863 = addWarn ((quotes (ppr name) <+> ptext SLIT("is imported more than once:"))
864 $$ nest 2 (vcat (map ppr imps)))
867 -- ToDo: deal with original imports with 'qualified' and 'as M' clauses
868 printMinimalImports :: FiniteMap Module AvailEnv -- Minimal imports
870 printMinimalImports imps
871 = ifOptM Opt_D_dump_minimal_imports $ do {
873 mod_ies <- mappM to_ies (fmToList imps) ;
874 this_mod <- getModule ;
875 rdr_env <- getGlobalRdrEnv ;
876 ioToTcRn (do { h <- openFile (mkFilename this_mod) WriteMode ;
877 printForUser h (unQualInScope rdr_env)
878 (vcat (map ppr_mod_ie mod_ies)) })
881 mkFilename this_mod = moduleUserString this_mod ++ ".imports"
882 ppr_mod_ie (mod_name, ies)
883 | mod_name == pRELUDE
885 | null ies -- Nothing except instances comes from here
886 = ptext SLIT("import") <+> ppr mod_name <> ptext SLIT("() -- Instances only")
888 = ptext SLIT("import") <+> ppr mod_name <>
889 parens (fsep (punctuate comma (map ppr ies)))
891 to_ies (mod, avail_env) = mappM to_ie (availEnvElts avail_env) `thenM` \ ies ->
894 to_ie :: AvailInfo -> RnM (IE Name)
895 -- The main trick here is that if we're importing all the constructors
896 -- we want to say "T(..)", but if we're importing only a subset we want
897 -- to say "T(A,B,C)". So we have to find out what the module exports.
898 to_ie (Avail n) = returnM (IEVar n)
899 to_ie (AvailTC n [m]) = ASSERT( n==m )
900 returnM (IEThingAbs n)
902 = loadSrcInterface doc n_mod False `thenM` \ iface ->
903 case [xs | (m,as) <- mi_exports iface,
906 x == nameOccName n] of
907 [xs] | all_used xs -> returnM (IEThingAll n)
908 | otherwise -> returnM (IEThingWith n (filter (/= n) ns))
909 other -> pprTrace "to_ie" (ppr n <+> ppr n_mod <+> ppr other) $
912 all_used avail_occs = all (`elem` map nameOccName ns) avail_occs
913 doc = text "Compute minimal imports from" <+> ppr n
918 %************************************************************************
922 %************************************************************************
925 badImportItemErr iface imp_spec ie
926 = sep [ptext SLIT("Module"), quotes (ppr (is_mod imp_spec)), source_import,
927 ptext SLIT("does not export"), quotes (ppr ie)]
929 source_import | mi_boot iface = ptext SLIT("(hi-boot interface)")
932 dodgyImportWarn item = dodgyMsg (ptext SLIT("import")) item
933 dodgyExportWarn item = dodgyMsg (ptext SLIT("export")) item
936 = sep [ ptext SLIT("The") <+> kind <+> ptext SLIT("item") <+> quotes (ppr (IEThingAll tc)),
937 ptext SLIT("suggests that") <+> quotes (ppr tc) <+> ptext SLIT("has constructor or class methods"),
938 ptext SLIT("but it has none; it is a type synonym or abstract type or class") ]
941 = hsep [ ptext SLIT("Unknown module in export list: module"), quotes (ppr mod)]
943 exportItemErr export_item
944 = sep [ ptext SLIT("The export item") <+> quotes (ppr export_item),
945 ptext SLIT("attempts to export constructors or class methods that are not visible here") ]
947 exportClashErr global_env name1 name2 ie1 ie2
948 = vcat [ ptext SLIT("Conflicting exports for") <+> quotes (ppr occ) <> colon
949 , ppr_export ie1 name1
950 , ppr_export ie2 name2 ]
952 occ = nameOccName name1
953 ppr_export ie name = nest 2 (quotes (ppr ie) <+> ptext SLIT("exports") <+>
954 quotes (ppr name) <+> pprNameProvenance (get_gre name))
956 -- get_gre finds a GRE for the Name, so that we can show its provenance
958 = case lookupGRE_Name global_env name of
960 [] -> pprPanic "exportClashErr" (ppr name)
962 addDupDeclErr :: [Name] -> TcRn ()
965 vcat [ptext SLIT("Multiple declarations of") <+> quotes (ppr name1),
966 ptext SLIT("Declared at:") <+> vcat (map ppr sorted_locs)]
968 locs = map nameSrcLoc names
969 big_loc = foldr1 combineSrcSpans (map srcLocSpan locs)
971 sorted_locs = sortLe (<=) (sortLe (<=) locs)
973 dupExportWarn occ_name ie1 ie2
974 = hsep [quotes (ppr occ_name),
975 ptext SLIT("is exported by"), quotes (ppr ie1),
976 ptext SLIT("and"), quotes (ppr ie2)]
979 = hsep [ptext SLIT("Duplicate"),
980 quotes (ptext SLIT("Module") <+> ppr mod),
981 ptext SLIT("in export list")]
984 = sep [ ptext SLIT("Module") <+> quotes (ppr mod) <+> ptext SLIT("is deprecated:"),