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(..), HsBindGroup(..),
18 Sig(..), 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(..)
43 import Packages ( PackageIdH(..) )
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 ; implicit_prelude <- doptM Opt_ImplicitPrelude
80 all_imports = mk_prel_imports this_mod implicit_prelude ++ imports
81 (source, ordinary) = partition is_source_import all_imports
82 is_source_import (L _ (ImportDecl _ is_boot _ _ _)) = is_boot
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 implicit_prelude
105 | this_mod == pRELUDE
106 || explicit_prelude_import
107 || not implicit_prelude
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)
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 p_occ occs)
258 = do { p_name <- lookupOrig mod p_occ
259 ; ns <- mappM (lookup_sub p_name) occs
260 ; return (addListToNameSet acc ns) }
261 -- Remember that 'occs' is all the exported things, including
262 -- the parent. It's possible to export just class ops without
263 -- the class, via C( op ). If the class was exported too we'd
266 lookup_sub parent occ
267 = newGlobalBinder mod occ mb_parent noSrcLoc
269 mb_parent | occ == p_occ = Nothing
270 | otherwise = Just parent
272 -- The use of newGlobalBinder here (rather than lookupOrig)
273 -- ensures that the subordinate names record their parent;
274 -- and that in turn ensures that the GlobalRdrEnv
275 -- has the correct parent for all the names in its range.
276 -- For imported things, we only suck in the binding site later, if ever.
277 -- Reason for all this:
278 -- Suppose module M exports type A.T, and constructor A.MkT
279 -- Then, we know that A.MkT is a subordinate name of A.T,
280 -- even though we aren't at the binding site of A.T
281 -- And it's important, because we may simply re-export A.T
282 -- without ever sucking in the declaration itself.
284 warnRedundantSourceImport mod_name
285 = ptext SLIT("Unnecessary {- SOURCE -} in the import of module")
286 <+> quotes (ppr mod_name)
290 %************************************************************************
292 importsFromLocalDecls
294 %************************************************************************
296 From the top-level declarations of this module produce
297 * the lexical environment
299 created by its bindings.
301 Complain about duplicate bindings
304 importsFromLocalDecls :: HsGroup RdrName
305 -> RnM (GlobalRdrEnv, ImportAvails)
306 importsFromLocalDecls group
307 = getModule `thenM` \ this_mod ->
308 getLocalDeclBinders this_mod group `thenM` \ avails ->
309 -- The avails that are returned don't include the "system" names
311 all_names :: [Name] -- All the defns; no dups eliminated
312 all_names = [name | avail <- avails, name <- availNames avail]
315 (_, dups) = removeDups compare all_names
317 -- Check for duplicate definitions
318 -- The complaint will come out as "Multiple declarations of Foo.f" because
319 -- since 'f' is in the env twice, the unQualInScope used by the error-msg
320 -- printer returns False. It seems awkward to fix, unfortunately.
321 mappM_ addDupDeclErr dups `thenM_`
323 doptM Opt_ImplicitPrelude `thenM` \ implicit_prelude ->
325 prov = LocalDef this_mod
326 gbl_env = mkGlobalRdrEnv gres
327 gres = [ GRE { gre_name = name, gre_prov = prov}
330 -- Optimisation: filter out names for built-in syntax
331 -- They just clutter up the environment (esp tuples), and the parser
332 -- will generate Exact RdrNames for them, so the cluttered
333 -- envt is no use. To avoid doing this filter all the time,
334 -- we use -fno-implicit-prelude as a clue that the filter is
335 -- worth while. Really, it's only useful for GHC.Base and GHC.Tuple.
337 -- It's worth doing because it makes the environment smaller for
338 -- every module that imports the Prelude
340 -- Note: don't filter the gbl_env (hence all_names, not filered_all_names
341 -- in defn of gres above). Stupid reason: when parsing
342 -- data type decls, the constructors start as Exact tycon-names,
343 -- and then get turned into data con names by zapping the name space;
344 -- but that stops them being Exact, so they get looked up.
345 -- Ditto in fixity decls; e.g. infix 5 :
346 -- Sigh. It doesn't matter because it only affects the Data.Tuple really.
347 -- The important thing is to trim down the exports.
349 | implicit_prelude = all_names
350 | otherwise = filter (not . isBuiltInSyntax) all_names
352 imports = emptyImportAvails {
353 imp_env = unitModuleEnv this_mod $
354 mkNameSet filtered_names
357 returnM (gbl_env, imports)
361 %*********************************************************
363 \subsection{Getting binders out of a declaration}
365 %*********************************************************
367 @getLocalDeclBinders@ returns the names for an @HsDecl@. It's
368 used for source code.
370 *** See "THE NAMING STORY" in HsDecls ****
373 getLocalDeclBinders :: Module -> HsGroup RdrName -> RnM [AvailInfo]
374 getLocalDeclBinders mod (HsGroup {hs_valds = val_decls,
375 hs_tyclds = tycl_decls,
376 hs_fords = foreign_decls })
377 = -- For type and class decls, we generate Global names, with
378 -- no export indicator. They need to be global because they get
379 -- permanently bound into the TyCons and Classes. They don't need
380 -- an export indicator because they are all implicitly exported.
382 mappM new_tc tycl_decls `thenM` \ tc_avails ->
384 -- In a hs-boot file, the value binders come from the
385 -- *signatures*, and there should be no foreign binders
386 tcIsHsBoot `thenM` \ is_hs_boot ->
387 let val_bndrs | is_hs_boot = sig_hs_bndrs
388 | otherwise = for_hs_bndrs ++ val_hs_bndrs
390 mappM new_simple val_bndrs `thenM` \ names ->
392 returnM (tc_avails ++ map Avail names)
394 new_simple rdr_name = newTopSrcBinder mod Nothing rdr_name
396 sig_hs_bndrs = [nm | HsBindGroup _ lsigs _ <- val_decls,
397 L _ (Sig nm _) <- lsigs]
398 val_hs_bndrs = collectGroupBinders val_decls
399 for_hs_bndrs = [nm | L _ (ForeignImport nm _ _ _) <- foreign_decls]
402 = newTopSrcBinder mod Nothing main_rdr `thenM` \ main_name ->
403 mappM (newTopSrcBinder mod (Just main_name)) sub_rdrs `thenM` \ sub_names ->
404 returnM (AvailTC main_name (main_name : sub_names))
406 (main_rdr : sub_rdrs) = tyClDeclNames (unLoc tc_decl)
410 %************************************************************************
412 \subsection{Filtering imports}
414 %************************************************************************
416 @filterImports@ takes the @ExportEnv@ telling what the imported module makes
417 available, and filters it through the import spec (if any).
420 filterImports :: ModIface
421 -> ImportSpec -- The span for the entire import decl
422 -> Maybe (Bool, [Located (IE RdrName)]) -- Import spec; True => hiding
423 -> NameSet -- What's available
424 -> RnM (NameSet, -- What's imported (qualified or unqualified)
425 GlobalRdrEnv) -- Same again, but in GRE form
427 -- Complains if import spec mentions things that the module doesn't export
428 -- Warns/informs if import spec contains duplicates.
430 mkGenericRdrEnv imp_spec names
431 = mkGlobalRdrEnv [ GRE { gre_name = name, gre_prov = Imported [imp_spec] False }
432 | name <- nameSetToList names ]
434 filterImports iface imp_spec Nothing all_names
435 = returnM (all_names, mkGenericRdrEnv imp_spec all_names)
437 filterImports iface imp_spec (Just (want_hiding, import_items)) all_names
438 = mappM (addLocM get_item) import_items `thenM` \ gres_s ->
441 specified_names = mkNameSet (map gre_name gres)
443 if not want_hiding then
444 return (specified_names, mkGlobalRdrEnv gres)
447 keep n = not (n `elemNameSet` specified_names)
448 pruned_avails = filterNameSet keep all_names
450 return (pruned_avails, mkGenericRdrEnv imp_spec pruned_avails)
453 occ_env :: OccEnv Name -- Maps OccName to corresponding Name
454 occ_env = mkOccEnv [(nameOccName n, n) | n <- nameSetToList all_names]
455 -- This env will have entries for data constructors too,
456 -- they won't make any difference because naked entities like T
457 -- in an import list map to TcOccs, not VarOccs.
459 sub_env :: NameEnv [Name]
460 sub_env = mkSubNameEnv all_names
462 bale_out item = addErr (badImportItemErr iface imp_spec item) `thenM_`
465 succeed_with :: Bool -> [Name] -> RnM [GlobalRdrElt]
466 succeed_with all_explicit names
467 = do { loc <- getSrcSpanM
468 ; returnM (map (mk_gre loc) names) }
470 mk_gre loc name = GRE { gre_name = name,
471 gre_prov = Imported [this_imp_spec loc] (explicit name) }
472 this_imp_spec loc = imp_spec { is_loc = loc }
473 explicit name = all_explicit || isNothing (nameParent_maybe name)
475 get_item :: IE RdrName -> RnM [GlobalRdrElt]
476 -- Empty result for a bad item.
477 -- Singleton result is typical case.
478 -- Can have two when we are hiding, and mention C which might be
479 -- both a class and a data constructor.
480 get_item item@(IEModuleContents _)
483 get_item item@(IEThingAll tc)
484 = case check_item item of
487 [n] -> -- This occurs when you import T(..), but
488 -- only export T abstractly. The single [n]
489 -- in the AvailTC is the type or class itself
490 ifOptM Opt_WarnDodgyImports (addWarn (dodgyImportWarn tc)) `thenM_`
491 succeed_with False [n]
493 names -> succeed_with False names
495 get_item item@(IEThingAbs n)
496 | want_hiding -- hiding( C )
497 -- Here the 'C' can be a data constructor
498 -- *or* a type/class, or even both
499 = case concat [check_item item, check_item (IEVar data_n)] of
501 names -> succeed_with True names
503 data_n = setRdrNameSpace n srcDataName
506 = case check_item item of
508 names -> succeed_with True names
510 check_item :: IE RdrName -> [Name]
512 = case lookupOccEnv occ_env (rdrNameOcc (ieName item)) of
514 Just name -> filterAvail item name sub_env
518 %************************************************************************
520 \subsection{Export list processing}
522 %************************************************************************
524 Processing the export list.
526 You might think that we should record things that appear in the export
527 list as ``occurrences'' (using @addOccurrenceName@), but you'd be
528 wrong. We do check (here) that they are in scope, but there is no
529 need to slurp in their actual declaration (which is what
530 @addOccurrenceName@ forces).
532 Indeed, doing so would big trouble when compiling @PrelBase@, because
533 it re-exports @GHC@, which includes @takeMVar#@, whose type includes
534 @ConcBase.StateAndSynchVar#@, and so on...
537 type ExportAccum -- The type of the accumulating parameter of
538 -- the main worker function in exportsFromAvail
539 = ([Module], -- 'module M's seen so far
540 ExportOccMap, -- Tracks exported occurrence names
541 NameSet) -- The accumulated exported stuff
542 emptyExportAccum = ([], emptyOccEnv, emptyNameSet)
544 type ExportOccMap = OccEnv (Name, IE RdrName)
545 -- Tracks what a particular exported OccName
546 -- in an export list refers to, and which item
547 -- it came from. It's illegal to export two distinct things
548 -- that have the same occurrence name
551 exportsFromAvail :: Bool -- False => no 'module M(..) where' header at all
552 -> Maybe [Located (IE RdrName)] -- Nothing => no explicit export list
554 -- Complains if two distinct exports have same OccName
555 -- Warns about identical exports.
556 -- Complains about exports items not in scope
558 exportsFromAvail explicit_mod exports
559 = do { TcGblEnv { tcg_rdr_env = rdr_env,
560 tcg_imports = imports } <- getGblEnv ;
562 -- If the module header is omitted altogether, then behave
563 -- as if the user had written "module Main(main) where..."
564 -- EXCEPT in interactive mode, when we behave as if he had
565 -- written "module Main where ..."
566 -- Reason: don't want to complain about 'main' not in scope
567 -- in interactive mode
568 ghci_mode <- getGhciMode ;
570 | explicit_mod = exports
571 | ghci_mode == Interactive = Nothing
572 | otherwise = Just [noLoc (IEVar main_RDR_Unqual)] } ;
573 exports_from_avail real_exports rdr_env imports }
576 exports_from_avail Nothing rdr_env imports
577 = -- Export all locally-defined things
578 -- We do this by filtering the global RdrEnv,
579 -- keeping only things that are locally-defined
580 return (mkNameSet [ gre_name gre
581 | gre <- globalRdrEnvElts rdr_env,
584 exports_from_avail (Just items) rdr_env (ImportAvails { imp_env = imp_env })
585 = foldlM do_litem emptyExportAccum items `thenM` \ (_, _, exports) ->
588 sub_env :: NameEnv [Name] -- Classify each name by its parent
589 sub_env = mkSubNameEnv (foldModuleEnv unionNameSets emptyNameSet imp_env)
591 do_litem :: ExportAccum -> Located (IE RdrName) -> RnM ExportAccum
592 do_litem acc = addLocM (exports_from_item acc)
594 exports_from_item :: ExportAccum -> IE RdrName -> RnM ExportAccum
595 exports_from_item acc@(mods, occs, exports) ie@(IEModuleContents mod)
596 | mod `elem` mods -- Duplicate export of M
597 = do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
598 warnIf warn_dup_exports (dupModuleExport mod) ;
602 = case lookupModuleEnv imp_env mod of
603 Nothing -> addErr (modExportErr mod) `thenM_`
607 new_exports = filterNameSet (inScopeUnqual rdr_env) names
610 -- This check_occs not only finds conflicts between this item
611 -- and others, but also internally within this item. That is,
612 -- if 'M.x' is in scope in several ways, we'll have several
613 -- members of mod_avails with the same OccName.
614 check_occs ie occs (nameSetToList new_exports) `thenM` \ occs' ->
615 returnM (mod:mods, occs', exports `unionNameSets` new_exports)
617 exports_from_item acc@(mods, occs, exports) ie
618 = lookupGlobalOccRn (ieName ie) `thenM` \ name ->
619 if isUnboundName name then
620 returnM acc -- Avoid error cascade
622 new_exports = filterAvail ie name sub_env
624 checkErr (not (null new_exports)) (exportItemErr ie) `thenM_`
625 checkForDodgyExport ie new_exports `thenM_`
626 check_occs ie occs new_exports `thenM` \ occs' ->
627 returnM (mods, occs', addListToNameSet exports new_exports)
629 -------------------------------
630 filterAvail :: IE RdrName -- Wanted
631 -> Name -- The Name of the ieName of the item
632 -> NameEnv [Name] -- Maps type/class names to their sub-names
633 -> [Name] -- Empty if even one thing reqd is missing
635 filterAvail (IEVar _) n subs = [n]
636 filterAvail (IEThingAbs _) n subs = [n]
637 filterAvail (IEThingAll _) n subs = n : subNames subs n
638 filterAvail (IEThingWith _ rdrs) n subs
639 | any isNothing mb_names = []
640 | otherwise = n : catMaybes mb_names
642 env = mkOccEnv [(nameOccName s, s) | s <- subNames subs n]
643 mb_names = map (lookupOccEnv env . rdrNameOcc) rdrs
645 subNames :: NameEnv [Name] -> Name -> [Name]
646 subNames env n = lookupNameEnv env n `orElse` []
648 mkSubNameEnv :: NameSet -> NameEnv [Name]
649 -- Maps types and classes to their constructors/classops respectively
650 -- This mapping just makes it easier to deal with A(..) export items
652 = foldNameSet add_name emptyNameEnv names
655 | Just parent <- nameParent_maybe name
656 = extendNameEnv_C (\ns _ -> name:ns) env parent [name]
659 -------------------------------
660 inScopeUnqual :: GlobalRdrEnv -> Name -> Bool
661 -- Checks whether the Name is in scope unqualified,
662 -- regardless of whether it's ambiguous or not
663 inScopeUnqual env n = any unQualOK (lookupGRE_Name env n)
665 -------------------------------
666 checkForDodgyExport :: IE RdrName -> [Name] -> RnM ()
667 checkForDodgyExport ie@(IEThingAll tc) [n]
668 | isTcOcc (nameOccName n) = addWarn (dodgyExportWarn tc)
669 -- This occurs when you export T(..), but
670 -- only import T abstractly, or T is a synonym.
671 -- The single [n] is the type or class itself
672 | otherwise = addErr (exportItemErr ie)
673 -- This happes if you export x(..), which is bogus
674 checkForDodgyExport _ _ = return ()
676 -------------------------------
677 check_occs :: IE RdrName -> ExportOccMap -> [Name] -> RnM ExportOccMap
678 check_occs ie occs names
679 = foldlM check occs names
682 = case lookupOccEnv occs name_occ of
683 Nothing -> returnM (extendOccEnv occs name_occ (name, ie))
686 | name == name' -- Duplicate export
687 -> do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
688 warnIf warn_dup_exports (dupExportWarn name_occ ie ie') ;
691 | otherwise -- Same occ name but different names: an error
692 -> do { global_env <- getGlobalRdrEnv ;
693 addErr (exportClashErr global_env name name' ie ie') ;
696 name_occ = nameOccName name
699 %*********************************************************
703 %*********************************************************
706 reportDeprecations :: TcGblEnv -> RnM ()
707 reportDeprecations tcg_env
708 = ifOptM Opt_WarnDeprecations $
709 do { (eps,hpt) <- getEpsAndHpt
710 ; mapM_ (check hpt (eps_PIT eps)) all_gres }
712 used_names = findUses (tcg_dus tcg_env) emptyNameSet
713 all_gres = globalRdrEnvElts (tcg_rdr_env tcg_env)
715 check hpt pit (GRE {gre_name = name, gre_prov = Imported (imp_spec:_) _})
716 | name `elemNameSet` used_names
717 , Just deprec_txt <- lookupDeprec hpt pit name
718 = setSrcSpan (is_loc imp_spec) $
719 addWarn (sep [ptext SLIT("Deprecated use of") <+>
720 occNameFlavour (nameOccName name) <+>
725 name_mod = nameModule name
726 imp_mod = is_mod imp_spec
727 imp_msg = ptext SLIT("imported from") <+> ppr imp_mod <> extra
728 extra | imp_mod == name_mod = empty
729 | otherwise = ptext SLIT(", but defined in") <+> ppr name_mod
731 check hpt pit ok_gre = returnM () -- Local, or not used, or not deprectated
732 -- The Imported pattern-match: don't deprecate locally defined names
733 -- For a start, we may be exporting a deprecated thing
734 -- Also we may use a deprecated thing in the defn of another
735 -- deprecated things. We may even use a deprecated thing in
736 -- the defn of a non-deprecated thing, when changing a module's
739 lookupDeprec :: HomePackageTable -> PackageIfaceTable
740 -> Name -> Maybe DeprecTxt
741 lookupDeprec hpt pit n
742 = case lookupIface hpt pit (nameModule n) of
743 Just iface -> mi_dep_fn iface n `seqMaybe` -- Bleat if the thing, *or
744 mi_dep_fn iface (nameParent n) -- its parent*, is deprec'd
746 | isWiredInName n -> Nothing
747 -- We have not necessarily loaded the .hi file for a
748 -- wired-in name (yet), although we *could*.
749 -- And we never deprecate them
751 | otherwise -> pprPanic "lookupDeprec" (ppr n)
752 -- By now all the interfaces should have been loaded
754 gre_is_used :: NameSet -> GlobalRdrElt -> Bool
755 gre_is_used used_names gre = gre_name gre `elemNameSet` used_names
758 %*********************************************************
762 %*********************************************************
765 reportUnusedNames :: TcGblEnv -> RnM ()
766 reportUnusedNames gbl_env
767 = do { warnUnusedTopBinds unused_locals
768 ; warnUnusedModules unused_imp_mods
769 ; warnUnusedImports unused_imports
770 ; warnDuplicateImports dup_imps
771 ; printMinimalImports minimal_imports }
773 used_names, all_used_names :: NameSet
774 used_names = findUses (tcg_dus gbl_env) emptyNameSet
775 all_used_names = used_names `unionNameSets`
776 mkNameSet (mapCatMaybes nameParent_maybe (nameSetToList used_names))
777 -- A use of C implies a use of T,
778 -- if C was brought into scope by T(..) or T(C)
780 -- Collect the defined names from the in-scope environment
781 defined_names :: [GlobalRdrElt]
782 defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)
784 -- Note that defined_and_used, defined_but_not_used
785 -- are both [GRE]; that's why we need defined_and_used
786 -- rather than just all_used_names
787 defined_and_used, defined_but_not_used :: [GlobalRdrElt]
788 (defined_and_used, defined_but_not_used)
789 = partition (gre_is_used all_used_names) defined_names
791 -- Find the duplicate imports
792 dup_imps = filter is_dup defined_and_used
793 is_dup (GRE {gre_prov = Imported imp_spec True}) = not (isSingleton imp_spec)
796 -- Filter out the ones that are
797 -- (a) defined in this module, and
798 -- (b) not defined by a 'deriving' clause
799 -- The latter have an Internal Name, so we can filter them out easily
800 unused_locals :: [GlobalRdrElt]
801 unused_locals = filter is_unused_local defined_but_not_used
802 is_unused_local :: GlobalRdrElt -> Bool
803 is_unused_local gre = isLocalGRE gre && isExternalName (gre_name gre)
805 unused_imports :: [GlobalRdrElt]
806 unused_imports = filter unused_imp defined_but_not_used
807 unused_imp (GRE {gre_prov = Imported imp_specs True})
808 = not (all (module_unused . is_mod) imp_specs)
809 -- Don't complain about unused imports if we've already said the
810 -- entire import is unused
811 unused_imp other = False
813 -- To figure out the minimal set of imports, start with the things
814 -- that are in scope (i.e. in gbl_env). Then just combine them
815 -- into a bunch of avails, so they are properly grouped
816 minimal_imports :: FiniteMap Module AvailEnv
817 minimal_imports0 = emptyFM
818 minimal_imports1 = foldr add_name minimal_imports0 defined_and_used
819 minimal_imports = foldr add_inst_mod minimal_imports1 direct_import_mods
820 -- The last line makes sure that we retain all direct imports
821 -- even if we import nothing explicitly.
822 -- It's not necessarily redundant to import such modules. Consider
826 -- The import M() is not *necessarily* redundant, even if
827 -- we suck in no instance decls from M (e.g. it contains
828 -- no instance decls, or This contains no code). It may be
829 -- that we import M solely to ensure that M's orphan instance
830 -- decls (or those in its imports) are visible to people who
831 -- import This. Sigh.
832 -- There's really no good way to detect this, so the error message
833 -- in RnEnv.warnUnusedModules is weakened instead
835 -- We've carefully preserved the provenance so that we can
836 -- construct minimal imports that import the name by (one of)
837 -- the same route(s) as the programmer originally did.
838 add_name (GRE {gre_name = n, gre_prov = Imported imp_specs _}) acc
839 = addToFM_C plusAvailEnv acc (is_mod (head imp_specs))
840 (unitAvailEnv (mk_avail n (nameParent_maybe n)))
844 -- n is the name of the thing, p is the name of its parent
845 mk_avail n (Just p) = AvailTC p [p,n]
846 mk_avail n Nothing | isTcOcc (nameOccName n) = AvailTC n [n]
847 | otherwise = Avail n
849 add_inst_mod (mod,_,_) acc
850 | mod `elemFM` acc = acc -- We import something already
851 | otherwise = addToFM acc mod emptyAvailEnv
853 -- Add an empty collection of imports for a module
854 -- from which we have sucked only instance decls
856 imports = tcg_imports gbl_env
858 direct_import_mods :: [(Module, Maybe Bool, SrcSpan)]
859 -- See the type of the imp_mods for this triple
860 direct_import_mods = moduleEnvElts (imp_mods imports)
862 -- unused_imp_mods are the directly-imported modules
863 -- that are not mentioned in minimal_imports1
864 -- [Note: not 'minimal_imports', because that includes directly-imported
865 -- modules even if we use nothing from them; see notes above]
866 unused_imp_mods = [(mod,loc) | (mod,imp,loc) <- direct_import_mods,
867 not (mod `elemFM` minimal_imports1),
870 -- The Just False part is not to complain about
871 -- import M (), which is an idiom for importing
872 -- instance declarations
874 module_unused :: Module -> Bool
875 module_unused mod = any (((==) mod) . fst) unused_imp_mods
877 ---------------------
878 warnDuplicateImports :: [GlobalRdrElt] -> RnM ()
879 warnDuplicateImports gres
880 = ifOptM Opt_WarnUnusedImports (mapM_ warn gres)
882 warn (GRE { gre_name = name, gre_prov = Imported imps _ })
883 = addWarn ((quotes (ppr name) <+> ptext SLIT("is imported more than once:"))
884 $$ nest 2 (vcat (map ppr imps)))
887 -- ToDo: deal with original imports with 'qualified' and 'as M' clauses
888 printMinimalImports :: FiniteMap Module AvailEnv -- Minimal imports
890 printMinimalImports imps
891 = ifOptM Opt_D_dump_minimal_imports $ do {
893 mod_ies <- mappM to_ies (fmToList imps) ;
894 this_mod <- getModule ;
895 rdr_env <- getGlobalRdrEnv ;
896 ioToTcRn (do { h <- openFile (mkFilename this_mod) WriteMode ;
897 printForUser h (unQualInScope rdr_env)
898 (vcat (map ppr_mod_ie mod_ies)) })
901 mkFilename this_mod = moduleUserString this_mod ++ ".imports"
902 ppr_mod_ie (mod_name, ies)
903 | mod_name == pRELUDE
905 | null ies -- Nothing except instances comes from here
906 = ptext SLIT("import") <+> ppr mod_name <> ptext SLIT("() -- Instances only")
908 = ptext SLIT("import") <+> ppr mod_name <>
909 parens (fsep (punctuate comma (map ppr ies)))
911 to_ies (mod, avail_env) = mappM to_ie (availEnvElts avail_env) `thenM` \ ies ->
914 to_ie :: AvailInfo -> RnM (IE Name)
915 -- The main trick here is that if we're importing all the constructors
916 -- we want to say "T(..)", but if we're importing only a subset we want
917 -- to say "T(A,B,C)". So we have to find out what the module exports.
918 to_ie (Avail n) = returnM (IEVar n)
919 to_ie (AvailTC n [m]) = ASSERT( n==m )
920 returnM (IEThingAbs n)
922 = loadSrcInterface doc n_mod False `thenM` \ iface ->
923 case [xs | (m,as) <- mi_exports iface,
926 x == nameOccName n] of
927 [xs] | all_used xs -> returnM (IEThingAll n)
928 | otherwise -> returnM (IEThingWith n (filter (/= n) ns))
929 other -> pprTrace "to_ie" (ppr n <+> ppr n_mod <+> ppr other) $
932 all_used avail_occs = all (`elem` map nameOccName ns) avail_occs
933 doc = text "Compute minimal imports from" <+> ppr n
938 %************************************************************************
942 %************************************************************************
945 badImportItemErr iface imp_spec ie
946 = sep [ptext SLIT("Module"), quotes (ppr (is_mod imp_spec)), source_import,
947 ptext SLIT("does not export"), quotes (ppr ie)]
949 source_import | mi_boot iface = ptext SLIT("(hi-boot interface)")
952 dodgyImportWarn item = dodgyMsg (ptext SLIT("import")) item
953 dodgyExportWarn item = dodgyMsg (ptext SLIT("export")) item
956 = sep [ ptext SLIT("The") <+> kind <+> ptext SLIT("item") <+> quotes (ppr (IEThingAll tc)),
957 ptext SLIT("suggests that") <+> quotes (ppr tc) <+> ptext SLIT("has constructor or class methods"),
958 ptext SLIT("but it has none; it is a type synonym or abstract type or class") ]
961 = hsep [ ptext SLIT("Unknown module in export list: module"), quotes (ppr mod)]
963 exportItemErr export_item
964 = sep [ ptext SLIT("The export item") <+> quotes (ppr export_item),
965 ptext SLIT("attempts to export constructors or class methods that are not visible here") ]
967 exportClashErr global_env name1 name2 ie1 ie2
968 = vcat [ ptext SLIT("Conflicting exports for") <+> quotes (ppr occ) <> colon
969 , ppr_export ie1 name1
970 , ppr_export ie2 name2 ]
972 occ = nameOccName name1
973 ppr_export ie name = nest 2 (quotes (ppr ie) <+> ptext SLIT("exports") <+>
974 quotes (ppr name) <+> pprNameProvenance (get_gre name))
976 -- get_gre finds a GRE for the Name, so that we can show its provenance
978 = case lookupGRE_Name global_env name of
980 [] -> pprPanic "exportClashErr" (ppr name)
982 addDupDeclErr :: [Name] -> TcRn ()
985 vcat [ptext SLIT("Multiple declarations of") <+> quotes (ppr name1),
986 ptext SLIT("Declared at:") <+> vcat (map ppr sorted_locs)]
988 locs = map nameSrcLoc names
989 big_loc = foldr1 combineSrcSpans (map srcLocSpan locs)
991 sorted_locs = sortLe (<=) (sortLe (<=) locs)
993 dupExportWarn occ_name ie1 ie2
994 = hsep [quotes (ppr occ_name),
995 ptext SLIT("is exported by"), quotes (ppr ie1),
996 ptext SLIT("and"), quotes (ppr ie2)]
999 = hsep [ptext SLIT("Duplicate"),
1000 quotes (ptext SLIT("Module") <+> ppr mod),
1001 ptext SLIT("in export list")]
1003 moduleDeprec mod txt
1004 = sep [ ptext SLIT("Module") <+> quotes (ppr mod) <+> ptext SLIT("is deprecated:"),