2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[RnNames]{Extracting imported and top-level names in scope}
8 rnImports, importsFromLocalDecls, exportsFromAvail,
9 reportUnusedNames, reportDeprecations,
10 mkModDeps, exportsToAvails
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 )
30 import Name ( Name, nameSrcLoc, nameOccName, nameModule, isWiredInName,
31 nameParent, nameParent_maybe, isExternalName,
34 import OccName ( srcDataName, isTcOcc, occNameFlavour, OccEnv,
35 mkOccEnv, lookupOccEnv, emptyOccEnv, extendOccEnv )
36 import HscTypes ( GenAvailInfo(..), AvailInfo, Avails, GhciMode(..),
37 IfaceExport, HomePackageTable, PackageIfaceTable,
38 availName, availNames, availsToNameSet, unQualInScope,
39 Deprecs(..), ModIface(..), Dependencies(..),
40 lookupIface, ExternalPackageState(..),
43 import RdrName ( RdrName, rdrNameOcc, setRdrNameSpace,
44 GlobalRdrEnv, mkGlobalRdrEnv, GlobalRdrElt(..),
45 emptyGlobalRdrEnv, plusGlobalRdrEnv, globalRdrEnvElts,
46 unQualOK, lookupGRE_Name,
47 Provenance(..), ImportSpec(..),
48 isLocalGRE, pprNameProvenance )
50 import Maybes ( isNothing, catMaybes, mapCatMaybes, seqMaybe )
51 import SrcLoc ( noSrcLoc, Located(..), mkGeneralSrcSpan,
52 unLoc, noLoc, srcLocSpan, combineSrcSpans, SrcSpan )
53 import BasicTypes ( DeprecTxt )
54 import ListSetOps ( removeDups )
55 import Util ( sortLe, notNull, isSingleton )
56 import List ( partition )
57 import IO ( openFile, IOMode(..) )
62 %************************************************************************
66 %************************************************************************
69 rnImports :: [LImportDecl RdrName]
70 -> RnM (GlobalRdrEnv, ImportAvails)
73 = do { -- PROCESS IMPORT DECLS
74 -- Do the non {- SOURCE -} ones first, so that we get a helpful
75 -- warning for {- SOURCE -} ones that are unnecessary
77 ; opt_no_prelude <- doptM Opt_NoImplicitPrelude
79 all_imports = mk_prel_imports this_mod opt_no_prelude ++ imports
80 (source, ordinary) = partition is_source_import all_imports
81 is_source_import (L _ (ImportDecl _ is_boot _ _ _)) = is_boot
83 get_imports = importsFromImportDecl this_mod
85 ; stuff1 <- mappM get_imports ordinary
86 ; stuff2 <- mappM get_imports source
90 (imp_gbl_envs, imp_avails) = unzip (stuff1 ++ stuff2)
91 gbl_env :: GlobalRdrEnv
92 gbl_env = foldr plusGlobalRdrEnv emptyGlobalRdrEnv imp_gbl_envs
94 all_avails :: ImportAvails
95 all_avails = foldr plusImportAvails emptyImportAvails imp_avails
98 ; return (gbl_env, all_avails) }
100 -- NB: opt_NoImplicitPrelude is slightly different to import Prelude ();
101 -- because the former doesn't even look at Prelude.hi for instance
102 -- declarations, whereas the latter does.
103 mk_prel_imports this_mod no_prelude
104 | this_mod == pRELUDE
105 || explicit_prelude_import
109 | otherwise = [preludeImportDecl]
111 explicit_prelude_import
112 = notNull [ () | L _ (ImportDecl mod _ _ _ _) <- imports,
113 unLoc mod == pRELUDE ]
117 ImportDecl (L loc pRELUDE)
118 False {- Not a boot interface -}
119 False {- Not qualified -}
120 Nothing {- No "as" -}
121 Nothing {- No import list -}
123 loc = mkGeneralSrcSpan FSLIT("Implicit import declaration")
127 importsFromImportDecl :: Module
128 -> LImportDecl RdrName
129 -> RnM (GlobalRdrEnv, ImportAvails)
131 importsFromImportDecl this_mod
132 (L loc (ImportDecl loc_imp_mod_name want_boot qual_only as_mod imp_details))
136 -- If there's an error in loadInterface, (e.g. interface
137 -- file not found) we get lots of spurious errors from 'filterImports'
139 imp_mod_name = unLoc loc_imp_mod_name
140 doc = ppr imp_mod_name <+> ptext SLIT("is directly imported")
142 loadSrcInterface doc imp_mod_name want_boot `thenM` \ iface ->
144 -- Compiler sanity check: if the import didn't say
145 -- {-# SOURCE #-} we should not get a hi-boot file
146 WARN( not want_boot && mi_boot iface, ppr imp_mod_name )
148 -- Issue a user warning for a redundant {- SOURCE -} import
149 -- NB that we arrange to read all the ordinary imports before
150 -- any of the {- SOURCE -} imports
151 warnIf (want_boot && not (mi_boot iface))
152 (warnRedundantSourceImport imp_mod_name) `thenM_`
155 imp_mod = mi_module iface
156 deprecs = mi_deprecs iface
157 is_orph = mi_orphan iface
160 filtered_exports = filter not_this_mod (mi_exports iface)
161 not_this_mod (mod,_) = mod /= this_mod
162 -- If the module exports anything defined in this module, just ignore it.
163 -- Reason: otherwise it looks as if there are two local definition sites
164 -- for the thing, and an error gets reported. Easiest thing is just to
165 -- filter them out up front. This situation only arises if a module
166 -- imports itself, or another module that imported it. (Necessarily,
167 -- this invoves a loop.)
169 -- Tiresome consequence: if you say
174 -- module B( AType ) where
175 -- import {-# SOURCE #-} A( AType )
177 -- then you'll get a 'B does not export AType' message. Oh well.
179 qual_mod_name = case as_mod of
180 Nothing -> imp_mod_name
181 Just another_name -> another_name
182 imp_spec = ImportSpec { is_mod = imp_mod_name, is_qual = qual_only,
183 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_qual = unitModuleEnv qual_mod_name avail_env,
236 imp_mods = unitModuleEnv imp_mod (imp_mod, import_all, loc),
238 imp_dep_mods = mkModDeps dependent_mods,
239 imp_dep_pkgs = dependent_pkgs }
242 -- Complain if we import a deprecated module
243 ifOptM Opt_WarnDeprecations (
245 DeprecAll txt -> addWarn (moduleDeprec imp_mod_name txt)
249 returnM (gbl_env, imports)
251 exportsToAvails :: [IfaceExport] -> TcRnIf gbl lcl Avails
252 exportsToAvails exports
253 = do { avails_by_module <- mappM do_one exports
254 ; return (concat avails_by_module) }
256 do_one (mod_name, exports) = mapM (do_avail mod_name) exports
257 do_avail mod (Avail n) = do { n' <- lookupOrig mod n;
258 ; return (Avail n') }
259 do_avail mod (AvailTC n ns) = do { n' <- lookupOrig mod n
260 ; ns' <- mappM (lookup_sub n') ns
261 ; return (AvailTC n' ns') }
263 lookup_sub parent occ = newGlobalBinder mod occ (Just parent) noSrcLoc
264 -- Hack alert! Notice the newGlobalBinder. It ensures that the subordinate
265 -- names record their parent; and that in turn ensures that the GlobalRdrEnv
266 -- has the correct parent for all the names in its range.
267 -- For imported things, we only suck in the binding site later, if ever.
268 -- Reason for all this:
269 -- Suppose module M exports type A.T, and constructor A.MkT
270 -- Then, we know that A.MkT is a subordinate name of A.T,
271 -- even though we aren't at the binding site of A.T
272 -- And it's important, because we may simply re-export A.T
273 -- without ever sucking in the declaration itself.
275 warnRedundantSourceImport mod_name
276 = ptext SLIT("Unnecessary {- SOURCE -} in the import of module")
277 <+> quotes (ppr mod_name)
281 %************************************************************************
283 importsFromLocalDecls
285 %************************************************************************
287 From the top-level declarations of this module produce
288 * the lexical environment
290 created by its bindings.
292 Complain about duplicate bindings
295 importsFromLocalDecls :: HsGroup RdrName
296 -> RnM (GlobalRdrEnv, ImportAvails)
297 importsFromLocalDecls group
298 = getModule `thenM` \ this_mod ->
299 getLocalDeclBinders this_mod group `thenM` \ avails ->
300 -- The avails that are returned don't include the "system" names
302 all_names :: [Name] -- All the defns; no dups eliminated
303 all_names = [name | avail <- avails, name <- availNames avail]
306 (_, dups) = removeDups compare all_names
308 -- Check for duplicate definitions
309 -- The complaint will come out as "Multiple declarations of Foo.f" because
310 -- since 'f' is in the env twice, the unQualInScope used by the error-msg
311 -- printer returns False. It seems awkward to fix, unfortunately.
312 mappM_ addDupDeclErr dups `thenM_`
314 doptM Opt_NoImplicitPrelude `thenM` \ implicit_prelude ->
316 prov = LocalDef this_mod
317 gbl_env = mkGlobalRdrEnv gres
318 gres = [ GRE { gre_name = name, gre_prov = prov}
321 -- Optimisation: filter out names for built-in syntax
322 -- They just clutter up the environment (esp tuples), and the parser
323 -- will generate Exact RdrNames for them, so the cluttered
324 -- envt is no use. To avoid doing this filter all the time,
325 -- we use -fno-implicit-prelude as a clue that the filter is
326 -- worth while. Really, it's only useful for GHC.Base and GHC.Tuple.
328 -- It's worth doing because it makes the environment smaller for
329 -- every module that imports the Prelude
331 -- Note: don't filter the gbl_env (hence avails, not avails' in
332 -- defn of gbl_env above). Stupid reason: when parsing
333 -- data type decls, the constructors start as Exact tycon-names,
334 -- and then get turned into data con names by zapping the name space;
335 -- but that stops them being Exact, so they get looked up.
336 -- Ditto in fixity decls; e.g. infix 5 :
337 -- Sigh. It doesn't matter because it only affects the Data.Tuple really.
338 -- The important thing is to trim down the exports.
340 avails' | implicit_prelude = filter not_built_in_syntax avails
342 not_built_in_syntax a = not (all isBuiltInSyntax (availNames a))
343 -- Only filter it if all the names of the avail are built-in
344 -- In particular, lists have (:) which is not built in syntax
345 -- so we don't filter it out. [Sept 03: wrong: see isBuiltInSyntax]
347 avail_env = mkAvailEnv avails'
348 imports = emptyImportAvails {
349 imp_qual = unitModuleEnv this_mod avail_env,
353 returnM (gbl_env, imports)
357 %*********************************************************
359 \subsection{Getting binders out of a declaration}
361 %*********************************************************
363 @getLocalDeclBinders@ returns the names for an @HsDecl@. It's
364 used for source code.
366 *** See "THE NAMING STORY" in HsDecls ****
369 getLocalDeclBinders :: Module -> HsGroup RdrName -> RnM [AvailInfo]
370 getLocalDeclBinders mod (HsGroup {hs_valds = val_decls,
371 hs_tyclds = tycl_decls,
372 hs_fords = foreign_decls })
373 = -- For type and class decls, we generate Global names, with
374 -- no export indicator. They need to be global because they get
375 -- permanently bound into the TyCons and Classes. They don't need
376 -- an export indicator because they are all implicitly exported.
378 mappM new_tc tycl_decls `thenM` \ tc_avails ->
379 mappM new_simple (for_hs_bndrs ++ val_hs_bndrs) `thenM` \ simple_avails ->
380 returnM (tc_avails ++ simple_avails)
382 new_simple rdr_name = newTopSrcBinder mod Nothing rdr_name `thenM` \ name ->
385 val_hs_bndrs = collectGroupBinders val_decls
386 for_hs_bndrs = [nm | L _ (ForeignImport nm _ _ _) <- foreign_decls]
389 = newTopSrcBinder mod Nothing main_rdr `thenM` \ main_name ->
390 mappM (newTopSrcBinder mod (Just main_name)) sub_rdrs `thenM` \ sub_names ->
391 returnM (AvailTC main_name (main_name : sub_names))
393 (main_rdr : sub_rdrs) = tyClDeclNames (unLoc tc_decl)
397 %************************************************************************
399 \subsection{Filtering imports}
401 %************************************************************************
403 @filterImports@ takes the @ExportEnv@ telling what the imported module makes
404 available, and filters it through the import spec (if any).
407 filterImports :: ModIface
408 -> ImportSpec -- The span for the entire import decl
409 -> Maybe (Bool, [Located (IE RdrName)]) -- Import spec; True => hiding
410 -> [AvailInfo] -- What's available
411 -> RnM (AvailEnv, -- What's imported (qualified or unqualified)
412 GlobalRdrEnv) -- Same again, but in GRE form
414 -- Complains if import spec mentions things that the module doesn't export
415 -- Warns/informs if import spec contains duplicates.
417 mkGenericRdrEnv imp_spec avails
418 = mkGlobalRdrEnv [ GRE { gre_name = name, gre_prov = Imported [imp_spec] False }
419 | avail <- avails, name <- availNames avail ]
421 filterImports iface imp_spec Nothing total_avails
422 = returnM (mkAvailEnv total_avails,
423 mkGenericRdrEnv imp_spec total_avails)
425 filterImports iface imp_spec (Just (want_hiding, import_items)) total_avails
426 = mapAndUnzipM (addLocM get_item) import_items `thenM` \ (avails_s, gres) ->
428 avails = concat avails_s
430 if not want_hiding then
431 return (mkAvailEnv avails,
432 foldr plusGlobalRdrEnv emptyGlobalRdrEnv gres)
435 hidden = availsToNameSet avails
436 keep n = not (n `elemNameSet` hidden)
437 pruned_avails = pruneAvails keep total_avails
439 return (mkAvailEnv pruned_avails,
440 mkGenericRdrEnv imp_spec pruned_avails)
443 import_fm :: OccEnv AvailInfo
444 import_fm = mkOccEnv [ (nameOccName name, avail)
445 | avail <- total_avails,
446 name <- availNames avail]
447 -- Even though availNames returns data constructors too,
448 -- they won't make any difference because naked entities like T
449 -- in an import list map to TcOccs, not VarOccs.
451 bale_out item = addErr (badImportItemErr iface imp_spec item) `thenM_`
452 returnM ([], emptyGlobalRdrEnv)
454 succeed_with :: Bool -> AvailInfo -> RnM ([AvailInfo], GlobalRdrEnv)
455 succeed_with all_explicit avail
456 = do { loc <- getSrcSpanM
458 mkGlobalRdrEnv (map (mk_gre loc) (availNames avail))) }
460 mk_gre loc name = GRE { gre_name = name,
461 gre_prov = Imported [this_imp_spec loc] (explicit name) }
462 this_imp_spec loc = imp_spec { is_loc = loc }
463 explicit name = all_explicit || name == main_name
464 main_name = availName avail
466 get_item :: IE RdrName -> RnM ([AvailInfo], GlobalRdrEnv)
467 -- Empty result for a bad item.
468 -- Singleton result is typical case.
469 -- Can have two when we are hiding, and mention C which might be
470 -- both a class and a data constructor.
471 get_item item@(IEModuleContents _)
474 get_item item@(IEThingAll tc)
475 = case check_item item of
476 Nothing -> bale_out item
477 Just avail@(AvailTC _ [n]) -> -- This occurs when you import T(..), but
478 -- only export T abstractly. The single [n]
479 -- in the AvailTC is the type or class itself
480 ifOptM Opt_WarnDodgyImports (addWarn (dodgyImportWarn tc)) `thenM_`
481 succeed_with False avail
482 Just avail -> succeed_with False avail
484 get_item item@(IEThingAbs n)
485 | want_hiding -- hiding( C )
486 -- Here the 'C' can be a data constructor
487 -- *or* a type/class, or even both
488 = case catMaybes [check_item item, check_item (IEVar data_n)] of
490 avails -> returnM (avails, emptyGlobalRdrEnv)
491 -- The GlobalRdrEnv result is irrelevant when hiding
493 data_n = setRdrNameSpace n srcDataName
496 = case check_item item of
497 Nothing -> bale_out item
498 Just avail -> succeed_with True avail
501 | isNothing maybe_in_import_avails ||
502 isNothing maybe_filtered_avail
506 = Just filtered_avail
509 wanted_occ = rdrNameOcc (ieName item)
510 maybe_in_import_avails = lookupOccEnv import_fm wanted_occ
512 Just avail = maybe_in_import_avails
513 maybe_filtered_avail = filterAvail item avail
514 Just filtered_avail = maybe_filtered_avail
518 filterAvail :: IE RdrName -- Wanted
519 -> AvailInfo -- Available
520 -> Maybe AvailInfo -- Resulting available;
521 -- Nothing if (any of the) wanted stuff isn't there
523 filterAvail ie@(IEThingWith want wants) avail@(AvailTC n ns)
524 | sub_names_ok = Just (AvailTC n (filter is_wanted ns))
525 | otherwise = Nothing
527 is_wanted name = nameOccName name `elem` wanted_occs
528 sub_names_ok = all (`elem` avail_occs) wanted_occs
529 avail_occs = map nameOccName ns
530 wanted_occs = map rdrNameOcc (want:wants)
532 filterAvail (IEThingAbs _) (AvailTC n ns) = ASSERT( n `elem` ns )
535 filterAvail (IEThingAbs _) avail@(Avail n) = Just avail -- Type synonyms
537 filterAvail (IEVar _) avail@(Avail n) = Just avail
538 filterAvail (IEVar v) avail@(AvailTC n ns) = Just (AvailTC n (filter wanted ns))
540 wanted n = nameOccName n == occ
542 -- The second equation happens if we import a class op, thus
544 -- where op is a class operation
546 filterAvail (IEThingAll _) avail@(AvailTC _ _) = Just avail
547 -- We don't complain even if the IE says T(..), but
548 -- no constrs/class ops of T are available
549 -- Instead that's caught with a warning by the caller
551 filterAvail ie avail = Nothing
555 %************************************************************************
557 \subsection{Export list processing}
559 %************************************************************************
561 Processing the export list.
563 You might think that we should record things that appear in the export
564 list as ``occurrences'' (using @addOccurrenceName@), but you'd be
565 wrong. We do check (here) that they are in scope, but there is no
566 need to slurp in their actual declaration (which is what
567 @addOccurrenceName@ forces).
569 Indeed, doing so would big trouble when compiling @PrelBase@, because
570 it re-exports @GHC@, which includes @takeMVar#@, whose type includes
571 @ConcBase.StateAndSynchVar#@, and so on...
574 type ExportAccum -- The type of the accumulating parameter of
575 -- the main worker function in exportsFromAvail
576 = ([Module], -- 'module M's seen so far
577 ExportOccMap, -- Tracks exported occurrence names
578 NameSet) -- The accumulated exported stuff
579 emptyExportAccum = ([], emptyOccEnv, emptyNameSet)
581 type ExportOccMap = OccEnv (Name, IE RdrName)
582 -- Tracks what a particular exported OccName
583 -- in an export list refers to, and which item
584 -- it came from. It's illegal to export two distinct things
585 -- that have the same occurrence name
588 exportsFromAvail :: Bool -- False => no 'module M(..) where' header at all
589 -> Maybe [Located (IE RdrName)] -- Nothing => no explicit export list
591 -- Complains if two distinct exports have same OccName
592 -- Warns about identical exports.
593 -- Complains about exports items not in scope
595 exportsFromAvail explicit_mod exports
596 = do { TcGblEnv { tcg_rdr_env = rdr_env,
597 tcg_imports = imports } <- getGblEnv ;
599 -- If the module header is omitted altogether, then behave
600 -- as if the user had written "module Main(main) where..."
601 -- EXCEPT in interactive mode, when we behave as if he had
602 -- written "module Main where ..."
603 -- Reason: don't want to complain about 'main' not in scope
604 -- in interactive mode
605 ghci_mode <- getGhciMode ;
607 | explicit_mod = exports
608 | ghci_mode == Interactive = Nothing
609 | otherwise = Just [noLoc (IEVar main_RDR_Unqual)] } ;
610 exports_from_avail real_exports rdr_env imports }
613 exports_from_avail Nothing rdr_env imports
614 = -- Export all locally-defined things
615 -- We do this by filtering the global RdrEnv,
616 -- keeping only things that are locally-defined
617 return (mkNameSet [ gre_name gre
618 | gre <- globalRdrEnvElts rdr_env,
621 exports_from_avail (Just export_items) rdr_env
622 (ImportAvails { imp_qual = mod_avail_env,
623 imp_env = entity_avail_env })
624 = foldlM (exports_from_litem) emptyExportAccum
625 export_items `thenM` \ (_, _, exports) ->
629 exports_from_litem :: ExportAccum -> Located (IE RdrName) -> RnM ExportAccum
630 exports_from_litem acc = addLocM (exports_from_item acc)
632 exports_from_item :: ExportAccum -> IE RdrName -> RnM ExportAccum
633 exports_from_item acc@(mods, occs, exports) ie@(IEModuleContents mod)
634 | mod `elem` mods -- Duplicate export of M
635 = do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
636 warnIf warn_dup_exports (dupModuleExport mod) ;
640 = case lookupModuleEnv mod_avail_env mod of
641 Nothing -> addErr (modExportErr mod) `thenM_`
646 new_exports = [ name | avail <- availEnvElts avail_env,
647 name <- availNames avail,
648 inScopeUnqual rdr_env name ]
651 -- This check_occs not only finds conflicts between this item
652 -- and others, but also internally within this item. That is,
653 -- if 'M.x' is in scope in several ways, we'll have several
654 -- members of mod_avails with the same OccName.
655 check_occs ie occs new_exports `thenM` \ occs' ->
656 returnM (mod:mods, occs', addListToNameSet exports new_exports)
658 exports_from_item acc@(mods, occs, exports) ie
659 = lookupGlobalOccRn (ieName ie) `thenM` \ name ->
660 if isUnboundName name then
661 returnM acc -- Avoid error cascade
663 -- Get the AvailInfo for the parent of the specified name
665 parent = nameParent name
666 avail = lookupAvailEnv entity_avail_env parent
668 -- Filter out the bits we want
669 case filterAvail ie avail of {
670 Nothing -> -- Not enough availability
671 addErr (exportItemErr ie) `thenM_`
676 -- Phew! It's OK! Now to check the occurrence stuff!
679 new_exports = availNames export_avail
681 checkForDodgyExport ie new_exports `thenM_`
682 check_occs ie occs new_exports `thenM` \ occs' ->
683 returnM (mods, occs', addListToNameSet exports new_exports)
687 -------------------------------
688 inScopeUnqual :: GlobalRdrEnv -> Name -> Bool
689 -- Checks whether the Name is in scope unqualified,
690 -- regardless of whether it's ambiguous or not
691 inScopeUnqual env n = any unQualOK (lookupGRE_Name env n)
693 -------------------------------
694 checkForDodgyExport :: IE RdrName -> [Name] -> RnM ()
695 checkForDodgyExport (IEThingAll tc) [n] = addWarn (dodgyExportWarn tc)
696 -- This occurs when you import T(..), but
697 -- only export T abstractly. The single [n]
698 -- in the AvailTC is the type or class itself
699 checkForDodgyExport _ _ = return ()
701 -------------------------------
702 check_occs :: IE RdrName -> ExportOccMap -> [Name] -> RnM ExportOccMap
703 check_occs ie occs names
704 = foldlM check occs names
707 = case lookupOccEnv occs name_occ of
708 Nothing -> returnM (extendOccEnv occs name_occ (name, ie))
711 | name == name' -- Duplicate export
712 -> do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
713 warnIf warn_dup_exports (dupExportWarn name_occ ie ie') ;
716 | otherwise -- Same occ name but different names: an error
717 -> do { global_env <- getGlobalRdrEnv ;
718 addErr (exportClashErr global_env name name' ie ie') ;
721 name_occ = nameOccName name
724 %*********************************************************
728 %*********************************************************
731 reportDeprecations :: TcGblEnv -> RnM ()
732 reportDeprecations tcg_env
733 = ifOptM Opt_WarnDeprecations $
734 do { (eps,hpt) <- getEpsAndHpt
735 ; mapM_ (check hpt (eps_PIT eps)) all_gres }
737 used_names = findUses (tcg_dus tcg_env) emptyNameSet
738 all_gres = globalRdrEnvElts (tcg_rdr_env tcg_env)
740 check hpt pit (GRE {gre_name = name, gre_prov = Imported (imp_spec:_) _})
741 | name `elemNameSet` used_names
742 , Just deprec_txt <- lookupDeprec hpt pit name
743 = setSrcSpan (is_loc imp_spec) $
744 addWarn (sep [ptext SLIT("Deprecated use of") <+>
745 occNameFlavour (nameOccName name) <+>
750 name_mod = nameModule name
751 imp_mod = is_mod imp_spec
752 imp_msg = ptext SLIT("imported from") <+> ppr imp_mod <> extra
753 extra | imp_mod == name_mod = empty
754 | otherwise = ptext SLIT(", but defined in") <+> ppr name_mod
756 check hpt pit ok_gre = returnM () -- Local, or not used, or not deprectated
757 -- The Imported pattern-match: don't deprecate locally defined names
758 -- For a start, we may be exporting a deprecated thing
759 -- Also we may use a deprecated thing in the defn of another
760 -- deprecated things. We may even use a deprecated thing in
761 -- the defn of a non-deprecated thing, when changing a module's
764 lookupDeprec :: HomePackageTable -> PackageIfaceTable
765 -> Name -> Maybe DeprecTxt
766 lookupDeprec hpt pit n
767 = case lookupIface hpt pit (nameModule n) of
768 Just iface -> mi_dep_fn iface n `seqMaybe` -- Bleat if the thing, *or
769 mi_dep_fn iface (nameParent n) -- its parent*, is deprec'd
771 | isWiredInName n -> Nothing
772 -- We have not necessarily loaded the .hi file for a
773 -- wired-in name (yet), although we *could*.
774 -- And we never deprecate them
776 | otherwise -> pprPanic "lookupDeprec" (ppr n)
777 -- By now all the interfaces should have been loaded
779 gre_is_used :: NameSet -> GlobalRdrElt -> Bool
780 gre_is_used used_names gre = gre_name gre `elemNameSet` used_names
783 %*********************************************************
787 %*********************************************************
790 reportUnusedNames :: TcGblEnv -> RnM ()
791 reportUnusedNames gbl_env
792 = do { warnUnusedTopBinds unused_locals
793 ; warnUnusedModules unused_imp_mods
794 ; warnUnusedImports unused_imports
795 ; warnDuplicateImports dup_imps
796 ; printMinimalImports minimal_imports }
798 used_names, all_used_names :: NameSet
799 used_names = findUses (tcg_dus gbl_env) emptyNameSet
800 all_used_names = used_names `unionNameSets`
801 mkNameSet (mapCatMaybes nameParent_maybe (nameSetToList used_names))
802 -- A use of C implies a use of T,
803 -- if C was brought into scope by T(..) or T(C)
805 -- Collect the defined names from the in-scope environment
806 defined_names :: [GlobalRdrElt]
807 defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)
809 -- Note that defined_and_used, defined_but_not_used
810 -- are both [GRE]; that's why we need defined_and_used
811 -- rather than just all_used_names
812 defined_and_used, defined_but_not_used :: [GlobalRdrElt]
813 (defined_and_used, defined_but_not_used)
814 = partition (gre_is_used all_used_names) defined_names
816 -- Find the duplicate imports
817 dup_imps = filter is_dup defined_and_used
818 is_dup (GRE {gre_prov = Imported imp_spec True}) = not (isSingleton imp_spec)
821 -- Filter out the ones that are
822 -- (a) defined in this module, and
823 -- (b) not defined by a 'deriving' clause
824 -- The latter have an Internal Name, so we can filter them out easily
825 unused_locals :: [GlobalRdrElt]
826 unused_locals = filter is_unused_local defined_but_not_used
827 is_unused_local :: GlobalRdrElt -> Bool
828 is_unused_local gre = isLocalGRE gre && isExternalName (gre_name gre)
830 unused_imports :: [GlobalRdrElt]
831 unused_imports = filter unused_imp defined_but_not_used
832 unused_imp (GRE {gre_prov = Imported imp_specs True})
833 = not (all (module_unused . is_mod) imp_specs)
834 -- Don't complain about unused imports if we've already said the
835 -- entire import is unused
836 unused_imp other = False
838 -- To figure out the minimal set of imports, start with the things
839 -- that are in scope (i.e. in gbl_env). Then just combine them
840 -- into a bunch of avails, so they are properly grouped
841 minimal_imports :: FiniteMap Module AvailEnv
842 minimal_imports0 = emptyFM
843 minimal_imports1 = foldr add_name minimal_imports0 defined_and_used
844 minimal_imports = foldr add_inst_mod minimal_imports1 direct_import_mods
845 -- The last line makes sure that we retain all direct imports
846 -- even if we import nothing explicitly.
847 -- It's not necessarily redundant to import such modules. Consider
851 -- The import M() is not *necessarily* redundant, even if
852 -- we suck in no instance decls from M (e.g. it contains
853 -- no instance decls, or This contains no code). It may be
854 -- that we import M solely to ensure that M's orphan instance
855 -- decls (or those in its imports) are visible to people who
856 -- import This. Sigh.
857 -- There's really no good way to detect this, so the error message
858 -- in RnEnv.warnUnusedModules is weakened instead
860 -- We've carefully preserved the provenance so that we can
861 -- construct minimal imports that import the name by (one of)
862 -- the same route(s) as the programmer originally did.
863 add_name (GRE {gre_name = n, gre_prov = Imported imp_specs _}) acc
864 = addToFM_C plusAvailEnv acc (is_mod (head imp_specs))
865 (unitAvailEnv (mk_avail n (nameParent_maybe n)))
869 -- n is the name of the thing, p is the name of its parent
870 mk_avail n (Just p) = AvailTC p [p,n]
871 mk_avail n Nothing | isTcOcc (nameOccName n) = AvailTC n [n]
872 | otherwise = Avail n
874 add_inst_mod (mod,_,_) acc
875 | mod `elemFM` acc = acc -- We import something already
876 | otherwise = addToFM acc mod emptyAvailEnv
878 -- Add an empty collection of imports for a module
879 -- from which we have sucked only instance decls
881 imports = tcg_imports gbl_env
883 direct_import_mods :: [(Module, Maybe Bool, SrcSpan)]
884 -- See the type of the imp_mods for this triple
885 direct_import_mods = moduleEnvElts (imp_mods imports)
887 -- unused_imp_mods are the directly-imported modules
888 -- that are not mentioned in minimal_imports1
889 -- [Note: not 'minimal_imports', because that includes directly-imported
890 -- modules even if we use nothing from them; see notes above]
891 unused_imp_mods = [(mod,loc) | (mod,imp,loc) <- direct_import_mods,
892 not (mod `elemFM` minimal_imports1),
895 -- The Just False part is not to complain about
896 -- import M (), which is an idiom for importing
897 -- instance declarations
899 module_unused :: Module -> Bool
900 module_unused mod = any (((==) mod) . fst) unused_imp_mods
902 ---------------------
903 warnDuplicateImports :: [GlobalRdrElt] -> RnM ()
904 warnDuplicateImports gres
905 = ifOptM Opt_WarnUnusedImports (mapM_ warn gres)
907 warn (GRE { gre_name = name, gre_prov = Imported imps _ })
908 = addWarn ((quotes (ppr name) <+> ptext SLIT("is imported more than once:"))
909 $$ nest 2 (vcat (map ppr imps)))
912 -- ToDo: deal with original imports with 'qualified' and 'as M' clauses
913 printMinimalImports :: FiniteMap Module AvailEnv -- Minimal imports
915 printMinimalImports imps
916 = ifOptM Opt_D_dump_minimal_imports $ do {
918 mod_ies <- mappM to_ies (fmToList imps) ;
919 this_mod <- getModule ;
920 rdr_env <- getGlobalRdrEnv ;
921 ioToTcRn (do { h <- openFile (mkFilename this_mod) WriteMode ;
922 printForUser h (unQualInScope rdr_env)
923 (vcat (map ppr_mod_ie mod_ies)) })
926 mkFilename this_mod = moduleUserString this_mod ++ ".imports"
927 ppr_mod_ie (mod_name, ies)
928 | mod_name == pRELUDE
930 | null ies -- Nothing except instances comes from here
931 = ptext SLIT("import") <+> ppr mod_name <> ptext SLIT("() -- Instances only")
933 = ptext SLIT("import") <+> ppr mod_name <>
934 parens (fsep (punctuate comma (map ppr ies)))
936 to_ies (mod, avail_env) = mappM to_ie (availEnvElts avail_env) `thenM` \ ies ->
939 to_ie :: AvailInfo -> RnM (IE Name)
940 -- The main trick here is that if we're importing all the constructors
941 -- we want to say "T(..)", but if we're importing only a subset we want
942 -- to say "T(A,B,C)". So we have to find out what the module exports.
943 to_ie (Avail n) = returnM (IEVar n)
944 to_ie (AvailTC n [m]) = ASSERT( n==m )
945 returnM (IEThingAbs n)
947 = loadSrcInterface doc n_mod False `thenM` \ iface ->
948 case [xs | (m,as) <- mi_exports iface,
951 x == nameOccName n] of
952 [xs] | all_used xs -> returnM (IEThingAll n)
953 | otherwise -> returnM (IEThingWith n (filter (/= n) ns))
954 other -> pprTrace "to_ie" (ppr n <+> ppr n_mod <+> ppr other) $
957 all_used avail_occs = all (`elem` map nameOccName ns) avail_occs
958 doc = text "Compute minimal imports from" <+> ppr n
963 %************************************************************************
967 %************************************************************************
970 badImportItemErr iface imp_spec ie
971 = sep [ptext SLIT("Module"), quotes (ppr (is_mod imp_spec)), source_import,
972 ptext SLIT("does not export"), quotes (ppr ie)]
974 source_import | mi_boot iface = ptext SLIT("(hi-boot interface)")
977 dodgyImportWarn item = dodgyMsg (ptext SLIT("import")) item
978 dodgyExportWarn item = dodgyMsg (ptext SLIT("export")) item
981 = sep [ ptext SLIT("The") <+> kind <+> ptext SLIT("item") <+> quotes (ppr (IEThingAll tc)),
982 ptext SLIT("suggests that") <+> quotes (ppr tc) <+> ptext SLIT("has constructor or class methods"),
983 ptext SLIT("but it has none; it is a type synonym or abstract type or class") ]
986 = hsep [ ptext SLIT("Unknown module in export list: module"), quotes (ppr mod)]
988 exportItemErr export_item
989 = sep [ ptext SLIT("The export item") <+> quotes (ppr export_item),
990 ptext SLIT("attempts to export constructors or class methods that are not visible here") ]
992 exportClashErr global_env name1 name2 ie1 ie2
993 = vcat [ ptext SLIT("Conflicting exports for") <+> quotes (ppr occ) <> colon
994 , ppr_export ie1 name1
995 , ppr_export ie2 name2 ]
997 occ = nameOccName name1
998 ppr_export ie name = nest 2 (quotes (ppr ie) <+> ptext SLIT("exports") <+>
999 quotes (ppr name) <+> pprNameProvenance (get_gre name))
1001 -- get_gre finds a GRE for the Name, so that we can show its provenance
1003 = case lookupGRE_Name global_env name of
1005 [] -> pprPanic "exportClashErr" (ppr name)
1007 addDupDeclErr :: [Name] -> TcRn ()
1009 = addErrAt big_loc $
1010 vcat [ptext SLIT("Multiple declarations of") <+> quotes (ppr name1),
1011 ptext SLIT("Declared at:") <+> vcat (map ppr sorted_locs)]
1013 locs = map nameSrcLoc names
1014 big_loc = foldr1 combineSrcSpans (map srcLocSpan locs)
1016 sorted_locs = sortLe (<=) (sortLe (<=) locs)
1018 dupExportWarn occ_name ie1 ie2
1019 = hsep [quotes (ppr occ_name),
1020 ptext SLIT("is exported by"), quotes (ppr ie1),
1021 ptext SLIT("and"), quotes (ppr ie2)]
1024 = hsep [ptext SLIT("Duplicate"),
1025 quotes (ptext SLIT("Module") <+> ppr mod),
1026 ptext SLIT("in export list")]
1028 moduleDeprec mod txt
1029 = sep [ ptext SLIT("Module") <+> quotes (ppr mod) <+> ptext SLIT("is deprecated:"),