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_Name, isUnboundName,
28 import Module ( Module, ModuleName, moduleName, mkPackageModule,
29 moduleNameUserString, isHomeModule,
30 unitModuleEnvByName, unitModuleEnv,
31 lookupModuleEnvByName, moduleEnvElts )
32 import Name ( Name, nameSrcLoc, nameOccName, nameModuleName, isWiredInName,
33 nameParent, nameParent_maybe, isExternalName, nameModule,
37 import OccName ( srcDataName, isTcOcc, occNameFlavour, OccEnv,
38 mkOccEnv, lookupOccEnv, emptyOccEnv, extendOccEnv )
39 import HscTypes ( GenAvailInfo(..), AvailInfo, Avails, GhciMode(..),
40 IfaceExport, HomePackageTable, PackageIfaceTable,
41 availName, availNames, availsToNameSet, unQualInScope,
42 Deprecs(..), ModIface(..), Dependencies(..), lookupIface,
43 ExternalPackageState(..)
45 import RdrName ( RdrName, rdrNameOcc, setRdrNameSpace,
46 GlobalRdrEnv, mkGlobalRdrEnv, GlobalRdrElt(..),
47 emptyGlobalRdrEnv, plusGlobalRdrEnv, globalRdrEnvElts,
48 unQualOK, lookupGRE_Name,
49 Provenance(..), ImportSpec(..),
50 isLocalGRE, pprNameProvenance )
52 import Maybes ( isJust, isNothing, catMaybes, mapCatMaybes, seqMaybe )
53 import SrcLoc ( noSrcLoc, Located(..), mkGeneralSrcSpan,
54 unLoc, noLoc, srcLocSpan, SrcSpan )
55 import BasicTypes ( DeprecTxt )
56 import ListSetOps ( removeDups )
57 import Util ( sortLe, notNull, isSingleton )
58 import List ( partition )
59 import IO ( openFile, IOMode(..) )
64 %************************************************************************
68 %************************************************************************
71 rnImports :: [LImportDecl RdrName]
72 -> RnM (GlobalRdrEnv, ImportAvails)
75 = do { -- PROCESS IMPORT DECLS
76 -- Do the non {- SOURCE -} ones first, so that we get a helpful
77 -- warning for {- SOURCE -} ones that are unnecessary
79 ; opt_no_prelude <- doptM Opt_NoImplicitPrelude
81 all_imports = mk_prel_imports this_mod opt_no_prelude ++ imports
82 (source, ordinary) = partition is_source_import all_imports
83 is_source_import (L _ (ImportDecl _ is_boot _ _ _)) = is_boot
85 get_imports = importsFromImportDecl this_mod
87 ; stuff1 <- mappM get_imports ordinary
88 ; stuff2 <- mappM get_imports source
92 (imp_gbl_envs, imp_avails) = unzip (stuff1 ++ stuff2)
93 gbl_env :: GlobalRdrEnv
94 gbl_env = foldr plusGlobalRdrEnv emptyGlobalRdrEnv imp_gbl_envs
96 all_avails :: ImportAvails
97 all_avails = foldr plusImportAvails emptyImportAvails imp_avails
100 ; return (gbl_env, all_avails) }
102 -- NB: opt_NoImplicitPrelude is slightly different to import Prelude ();
103 -- because the former doesn't even look at Prelude.hi for instance
104 -- declarations, whereas the latter does.
105 mk_prel_imports this_mod no_prelude
106 | moduleName this_mod == pRELUDE_Name
107 || explicit_prelude_import
111 | otherwise = [preludeImportDecl]
113 explicit_prelude_import
114 = notNull [ () | L _ (ImportDecl mod _ _ _ _) <- imports,
115 unLoc mod == pRELUDE_Name ]
119 ImportDecl (L loc pRELUDE_Name)
120 False {- Not a boot interface -}
121 False {- Not qualified -}
122 Nothing {- No "as" -}
123 Nothing {- No import list -}
125 loc = mkGeneralSrcSpan FSLIT("Implicit import declaration")
129 importsFromImportDecl :: Module
130 -> LImportDecl RdrName
131 -> RnM (GlobalRdrEnv, ImportAvails)
133 importsFromImportDecl this_mod
134 (L loc (ImportDecl loc_imp_mod_name want_boot qual_only as_mod imp_details))
138 -- If there's an error in loadInterface, (e.g. interface
139 -- file not found) we get lots of spurious errors from 'filterImports'
141 imp_mod_name = unLoc loc_imp_mod_name
142 this_mod_name = moduleName this_mod
143 doc = ppr imp_mod_name <+> ptext SLIT("is directly imported")
145 loadSrcInterface doc imp_mod_name want_boot `thenM` \ iface ->
147 -- Compiler sanity check: if the import didn't say
148 -- {-# SOURCE #-} we should not get a hi-boot file
149 WARN( not want_boot && mi_boot iface, ppr imp_mod_name )
151 -- Issue a user warning for a redundant {- SOURCE -} import
152 -- NB that we arrange to read all the ordinary imports before
153 -- any of the {- SOURCE -} imports
154 warnIf (want_boot && not (mi_boot iface))
155 (warnRedundantSourceImport imp_mod_name) `thenM_`
158 imp_mod = mi_module iface
159 deprecs = mi_deprecs iface
160 is_orph = mi_orphan iface
163 filtered_exports = filter not_this_mod (mi_exports iface)
164 not_this_mod (mod,_) = mod /= this_mod_name
165 -- If the module exports anything defined in this module, just ignore it.
166 -- Reason: otherwise it looks as if there are two local definition sites
167 -- for the thing, and an error gets reported. Easiest thing is just to
168 -- filter them out up front. This situation only arises if a module
169 -- imports itself, or another module that imported it. (Necessarily,
170 -- this invoves a loop.)
172 -- Tiresome consequence: if you say
177 -- module B( AType ) where
178 -- import {-# SOURCE #-} A( AType )
180 -- then you'll get a 'B does not export AType' message. Oh well.
182 qual_mod_name = case as_mod of
183 Nothing -> imp_mod_name
184 Just another_name -> another_name
185 imp_spec = ImportSpec { is_mod = imp_mod_name, is_qual = qual_only,
186 is_loc = loc, is_as = qual_mod_name }
189 -- Get the total imports, and filter them according to the import list
190 exportsToAvails filtered_exports `thenM` \ total_avails ->
191 filterImports iface imp_spec
192 imp_details total_avails `thenM` \ (avail_env, gbl_env) ->
195 -- Compute new transitive dependencies
197 orphans | is_orph = ASSERT( not (imp_mod_name `elem` dep_orphs deps) )
198 imp_mod_name : dep_orphs deps
199 | otherwise = dep_orphs deps
201 (dependent_mods, dependent_pkgs)
202 | isHomeModule imp_mod
203 = -- Imported module is from the home package
204 -- Take its dependent modules and
205 -- (a) remove this_mod (might be there as a hi-boot)
206 -- (b) add imp_mod itself
207 -- Take its dependent packages unchanged
208 ((imp_mod_name, want_boot) : filter not_self (dep_mods deps), dep_pkgs deps)
211 = -- Imported module is from another package
212 -- Dump the dependent modules
213 -- Add the package imp_mod comes from to the dependent packages
214 ASSERT( not (mi_package iface `elem` dep_pkgs deps) )
215 ([], mi_package iface : dep_pkgs deps)
217 not_self (m, _) = m /= this_mod_name
219 import_all = case imp_details of
220 Just (is_hiding, ls) -- Imports are spec'd explicitly
221 | not is_hiding -> Just (not (null ls))
222 _ -> Nothing -- Everything is imported,
223 -- (or almost everything [hiding])
225 -- unqual_avails is the Avails that are visible in *unqualified* form
226 -- We need to know this so we know what to export when we see
227 -- module M ( module P ) where ...
228 -- Then we must export whatever came from P unqualified.
229 imports = ImportAvails {
230 imp_qual = unitModuleEnvByName qual_mod_name avail_env,
232 imp_mods = unitModuleEnv imp_mod (imp_mod, import_all, loc),
234 imp_dep_mods = mkModDeps dependent_mods,
235 imp_dep_pkgs = dependent_pkgs }
238 -- Complain if we import a deprecated module
239 ifOptM Opt_WarnDeprecations (
241 DeprecAll txt -> addWarn (moduleDeprec imp_mod_name txt)
245 returnM (gbl_env, imports)
247 exportsToAvails :: [IfaceExport] -> TcRnIf gbl lcl Avails
248 exportsToAvails exports
249 = do { avails_by_module <- mappM do_one exports
250 ; return (concat avails_by_module) }
252 do_one (mod_name, exports) = mapM (do_avail mod_name) exports
253 do_avail mod_nm (Avail n) = do { n' <- lookupOrig mod_nm n;
254 ; return (Avail n') }
255 do_avail mod_nm (AvailTC n ns) = do { n' <- lookupOrig mod_nm n
256 ; ns' <- mappM (lookup_sub n') ns
257 ; return (AvailTC n' ns') }
259 mod = mkPackageModule mod_nm -- Not necessarily right yet
260 lookup_sub parent occ = newGlobalBinder mod occ (Just parent) noSrcLoc
261 -- Hack alert! Notice the newGlobalBinder. It ensures that the subordinate
262 -- names record their parent; and that in turn ensures that the GlobalRdrEnv
263 -- has the correct parent for all the names in its range.
264 -- For imported things, we only suck in the binding site later, if ever.
265 -- Reason for all this:
266 -- Suppose module M exports type A.T, and constructor A.MkT
267 -- Then, we know that A.MkT is a subordinate name of A.T,
268 -- even though we aren't at the binding site of A.T
269 -- And it's important, because we may simply re-export A.T
270 -- without ever sucking in the declaration itself.
272 warnRedundantSourceImport mod_name
273 = ptext SLIT("Unnecessary {- SOURCE -} in the import of module")
274 <+> quotes (ppr mod_name)
278 %************************************************************************
280 importsFromLocalDecls
282 %************************************************************************
284 From the top-level declarations of this module produce
285 * the lexical environment
287 created by its bindings.
289 Complain about duplicate bindings
292 importsFromLocalDecls :: HsGroup RdrName
293 -> RnM (GlobalRdrEnv, ImportAvails)
294 importsFromLocalDecls group
295 = getModule `thenM` \ this_mod ->
296 getLocalDeclBinders this_mod group `thenM` \ avails ->
297 -- The avails that are returned don't include the "system" names
299 all_names :: [Name] -- All the defns; no dups eliminated
300 all_names = [name | avail <- avails, name <- availNames avail]
303 (_, dups) = removeDups compare all_names
305 -- Check for duplicate definitions
306 -- The complaint will come out as "Multiple declarations of Foo.f" because
307 -- since 'f' is in the env twice, the unQualInScope used by the error-msg
308 -- printer returns False. It seems awkward to fix, unfortunately.
309 mappM_ addDupDeclErr dups `thenM_`
311 doptM Opt_NoImplicitPrelude `thenM` \ implicit_prelude ->
313 mod_name = moduleName this_mod
314 prov = LocalDef mod_name
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 avails, not avails' in
330 -- defn of gbl_env 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 avails' | implicit_prelude = filter not_built_in_syntax avails
340 not_built_in_syntax a = not (all isBuiltInSyntax (availNames a))
341 -- Only filter it if all the names of the avail are built-in
342 -- In particular, lists have (:) which is not built in syntax
343 -- so we don't filter it out. [Sept 03: wrong: see isBuiltInSyntax]
345 avail_env = mkAvailEnv avails'
346 imports = emptyImportAvails {
347 imp_qual = unitModuleEnv this_mod avail_env,
351 returnM (gbl_env, imports)
355 %*********************************************************
357 \subsection{Getting binders out of a declaration}
359 %*********************************************************
361 @getLocalDeclBinders@ returns the names for an @HsDecl@. It's
362 used for source code.
364 *** See "THE NAMING STORY" in HsDecls ****
367 getLocalDeclBinders :: Module -> HsGroup RdrName -> RnM [AvailInfo]
368 getLocalDeclBinders mod (HsGroup {hs_valds = val_decls,
369 hs_tyclds = tycl_decls,
370 hs_fords = foreign_decls })
371 = -- For type and class decls, we generate Global names, with
372 -- no export indicator. They need to be global because they get
373 -- permanently bound into the TyCons and Classes. They don't need
374 -- an export indicator because they are all implicitly exported.
376 mappM new_tc tycl_decls `thenM` \ tc_avails ->
377 mappM new_simple (for_hs_bndrs ++ val_hs_bndrs) `thenM` \ simple_avails ->
378 returnM (tc_avails ++ simple_avails)
380 new_simple rdr_name = newTopSrcBinder mod Nothing rdr_name `thenM` \ name ->
383 val_hs_bndrs = collectGroupBinders val_decls
384 for_hs_bndrs = [nm | L _ (ForeignImport nm _ _ _) <- foreign_decls]
387 = newTopSrcBinder mod Nothing main_rdr `thenM` \ main_name ->
388 mappM (newTopSrcBinder mod (Just main_name)) sub_rdrs `thenM` \ sub_names ->
389 returnM (AvailTC main_name (main_name : sub_names))
391 (main_rdr : sub_rdrs) = tyClDeclNames (unLoc tc_decl)
395 %************************************************************************
397 \subsection{Filtering imports}
399 %************************************************************************
401 @filterImports@ takes the @ExportEnv@ telling what the imported module makes
402 available, and filters it through the import spec (if any).
405 filterImports :: ModIface
406 -> ImportSpec -- The span for the entire import decl
407 -> Maybe (Bool, [Located (IE RdrName)]) -- Import spec; True => hiding
408 -> [AvailInfo] -- What's available
409 -> RnM (AvailEnv, -- What's imported (qualified or unqualified)
410 GlobalRdrEnv) -- Same again, but in GRE form
412 -- Complains if import spec mentions things that the module doesn't export
413 -- Warns/informs if import spec contains duplicates.
415 mkGenericRdrEnv imp_spec avails
416 = mkGlobalRdrEnv [ GRE { gre_name = name, gre_prov = Imported [imp_spec] False }
417 | avail <- avails, name <- availNames avail ]
419 filterImports iface imp_spec Nothing total_avails
420 = returnM (mkAvailEnv total_avails,
421 mkGenericRdrEnv imp_spec total_avails)
423 filterImports iface imp_spec (Just (want_hiding, import_items)) total_avails
424 = mapAndUnzipM (addLocM get_item) import_items `thenM` \ (avails_s, gres) ->
426 avails = concat avails_s
428 if not want_hiding then
429 return (mkAvailEnv avails,
430 foldr plusGlobalRdrEnv emptyGlobalRdrEnv gres)
433 hidden = availsToNameSet avails
434 keep n = not (n `elemNameSet` hidden)
435 pruned_avails = pruneAvails keep total_avails
437 return (mkAvailEnv pruned_avails,
438 mkGenericRdrEnv imp_spec pruned_avails)
441 import_fm :: OccEnv AvailInfo
442 import_fm = mkOccEnv [ (nameOccName name, avail)
443 | avail <- total_avails,
444 name <- availNames avail]
445 -- Even though availNames returns data constructors too,
446 -- they won't make any difference because naked entities like T
447 -- in an import list map to TcOccs, not VarOccs.
449 bale_out item = addErr (badImportItemErr iface imp_spec item) `thenM_`
450 returnM ([], emptyGlobalRdrEnv)
452 succeed_with :: Bool -> AvailInfo -> RnM ([AvailInfo], GlobalRdrEnv)
453 succeed_with all_explicit avail
454 = do { loc <- getSrcSpanM
456 mkGlobalRdrEnv (map (mk_gre loc) (availNames avail))) }
458 mk_gre loc name = GRE { gre_name = name,
459 gre_prov = Imported [this_imp_spec loc] (explicit name) }
460 this_imp_spec loc = imp_spec { is_loc = loc }
461 explicit name = all_explicit || name == main_name
462 main_name = availName avail
464 get_item :: IE RdrName -> RnM ([AvailInfo], GlobalRdrEnv)
465 -- Empty result for a bad item.
466 -- Singleton result is typical case.
467 -- Can have two when we are hiding, and mention C which might be
468 -- both a class and a data constructor.
469 get_item item@(IEModuleContents _)
472 get_item item@(IEThingAll tc)
473 = case check_item item of
474 Nothing -> bale_out item
475 Just avail@(AvailTC _ [n]) -> -- This occurs when you import T(..), but
476 -- only export T abstractly. The single [n]
477 -- in the AvailTC is the type or class itself
478 ifOptM Opt_WarnDodgyImports (addWarn (dodgyImportWarn tc)) `thenM_`
479 succeed_with False avail
480 Just avail -> succeed_with False avail
482 get_item item@(IEThingAbs n)
483 | want_hiding -- hiding( C )
484 -- Here the 'C' can be a data constructor
485 -- *or* a type/class, or even both
486 = case catMaybes [check_item item, check_item (IEVar data_n)] of
488 avails -> returnM (avails, emptyGlobalRdrEnv)
489 -- The GlobalRdrEnv result is irrelevant when hiding
491 data_n = setRdrNameSpace n srcDataName
494 = case check_item item of
495 Nothing -> bale_out item
496 Just avail -> succeed_with True avail
499 | isNothing maybe_in_import_avails ||
500 isNothing maybe_filtered_avail
504 = Just filtered_avail
507 wanted_occ = rdrNameOcc (ieName item)
508 maybe_in_import_avails = lookupOccEnv import_fm wanted_occ
510 Just avail = maybe_in_import_avails
511 maybe_filtered_avail = filterAvail item avail
512 Just filtered_avail = maybe_filtered_avail
516 filterAvail :: IE RdrName -- Wanted
517 -> AvailInfo -- Available
518 -> Maybe AvailInfo -- Resulting available;
519 -- Nothing if (any of the) wanted stuff isn't there
521 filterAvail ie@(IEThingWith want wants) avail@(AvailTC n ns)
522 | sub_names_ok = Just (AvailTC n (filter is_wanted ns))
523 | otherwise = Nothing
525 is_wanted name = nameOccName name `elem` wanted_occs
526 sub_names_ok = all (`elem` avail_occs) wanted_occs
527 avail_occs = map nameOccName ns
528 wanted_occs = map rdrNameOcc (want:wants)
530 filterAvail (IEThingAbs _) (AvailTC n ns) = ASSERT( n `elem` ns )
533 filterAvail (IEThingAbs _) avail@(Avail n) = Just avail -- Type synonyms
535 filterAvail (IEVar _) avail@(Avail n) = Just avail
536 filterAvail (IEVar v) avail@(AvailTC n ns) = Just (AvailTC n (filter wanted ns))
538 wanted n = nameOccName n == occ
540 -- The second equation happens if we import a class op, thus
542 -- where op is a class operation
544 filterAvail (IEThingAll _) avail@(AvailTC _ _) = Just avail
545 -- We don't complain even if the IE says T(..), but
546 -- no constrs/class ops of T are available
547 -- Instead that's caught with a warning by the caller
549 filterAvail ie avail = Nothing
553 %************************************************************************
555 \subsection{Export list processing}
557 %************************************************************************
559 Processing the export list.
561 You might think that we should record things that appear in the export
562 list as ``occurrences'' (using @addOccurrenceName@), but you'd be
563 wrong. We do check (here) that they are in scope, but there is no
564 need to slurp in their actual declaration (which is what
565 @addOccurrenceName@ forces).
567 Indeed, doing so would big trouble when compiling @PrelBase@, because
568 it re-exports @GHC@, which includes @takeMVar#@, whose type includes
569 @ConcBase.StateAndSynchVar#@, and so on...
572 type ExportAccum -- The type of the accumulating parameter of
573 -- the main worker function in exportsFromAvail
574 = ([ModuleName], -- 'module M's seen so far
575 ExportOccMap, -- Tracks exported occurrence names
576 NameSet) -- The accumulated exported stuff
577 emptyExportAccum = ([], emptyOccEnv, emptyNameSet)
579 type ExportOccMap = OccEnv (Name, IE RdrName)
580 -- Tracks what a particular exported OccName
581 -- in an export list refers to, and which item
582 -- it came from. It's illegal to export two distinct things
583 -- that have the same occurrence name
586 exportsFromAvail :: Bool -- False => no 'module M(..) where' header at all
587 -> Maybe [Located (IE RdrName)] -- Nothing => no explicit export list
589 -- Complains if two distinct exports have same OccName
590 -- Warns about identical exports.
591 -- Complains about exports items not in scope
593 exportsFromAvail explicit_mod exports
594 = do { TcGblEnv { tcg_rdr_env = rdr_env,
595 tcg_imports = imports } <- getGblEnv ;
597 -- If the module header is omitted altogether, then behave
598 -- as if the user had written "module Main(main) where..."
599 -- EXCEPT in interactive mode, when we behave as if he had
600 -- written "module Main where ..."
601 -- Reason: don't want to complain about 'main' not in scope
602 -- in interactive mode
603 ghci_mode <- getGhciMode ;
605 | explicit_mod = exports
606 | ghci_mode == Interactive = Nothing
607 | otherwise = Just [noLoc (IEVar main_RDR_Unqual)] } ;
608 exports_from_avail real_exports rdr_env imports }
611 exports_from_avail Nothing rdr_env imports
612 = -- Export all locally-defined things
613 -- We do this by filtering the global RdrEnv,
614 -- keeping only things that are locally-defined
615 return (mkNameSet [ gre_name gre
616 | gre <- globalRdrEnvElts rdr_env,
619 exports_from_avail (Just export_items) rdr_env
620 (ImportAvails { imp_qual = mod_avail_env,
621 imp_env = entity_avail_env })
622 = foldlM (exports_from_litem) emptyExportAccum
623 export_items `thenM` \ (_, _, exports) ->
627 exports_from_litem :: ExportAccum -> Located (IE RdrName) -> RnM ExportAccum
628 exports_from_litem acc = addLocM (exports_from_item acc)
630 exports_from_item :: ExportAccum -> IE RdrName -> RnM ExportAccum
631 exports_from_item acc@(mods, occs, exports) ie@(IEModuleContents mod)
632 | mod `elem` mods -- Duplicate export of M
633 = do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
634 warnIf warn_dup_exports (dupModuleExport mod) ;
638 = case lookupModuleEnvByName mod_avail_env mod of
639 Nothing -> addErr (modExportErr mod) `thenM_`
644 new_exports = [ name | avail <- availEnvElts avail_env,
645 name <- availNames avail,
646 inScopeUnqual rdr_env name ]
649 -- This check_occs not only finds conflicts between this item
650 -- and others, but also internally within this item. That is,
651 -- if 'M.x' is in scope in several ways, we'll have several
652 -- members of mod_avails with the same OccName.
653 check_occs ie occs new_exports `thenM` \ occs' ->
654 returnM (mod:mods, occs', addListToNameSet exports new_exports)
656 exports_from_item acc@(mods, occs, exports) ie
657 = lookupGlobalOccRn (ieName ie) `thenM` \ name ->
658 if isUnboundName name then
659 returnM acc -- Avoid error cascade
661 -- Get the AvailInfo for the parent of the specified name
663 parent = nameParent name
664 avail = lookupAvailEnv entity_avail_env parent
666 -- Filter out the bits we want
667 case filterAvail ie avail of {
668 Nothing -> -- Not enough availability
669 addErr (exportItemErr ie) `thenM_`
674 -- Phew! It's OK! Now to check the occurrence stuff!
677 new_exports = availNames export_avail
679 checkForDodgyExport ie new_exports `thenM_`
680 check_occs ie occs new_exports `thenM` \ occs' ->
681 returnM (mods, occs', addListToNameSet exports new_exports)
685 -------------------------------
686 inScopeUnqual :: GlobalRdrEnv -> Name -> Bool
687 -- Checks whether the Name is in scope unqualified,
688 -- regardless of whether it's ambiguous or not
689 inScopeUnqual env n = any unQualOK (lookupGRE_Name env n)
691 -------------------------------
692 checkForDodgyExport :: IE RdrName -> [Name] -> RnM ()
693 checkForDodgyExport (IEThingAll tc) [n] = addWarn (dodgyExportWarn tc)
694 -- This occurs when you import T(..), but
695 -- only export T abstractly. The single [n]
696 -- in the AvailTC is the type or class itself
697 checkForDodgyExport _ _ = return ()
699 -------------------------------
700 check_occs :: IE RdrName -> ExportOccMap -> [Name] -> RnM ExportOccMap
701 check_occs ie occs names
702 = foldlM check occs names
705 = case lookupOccEnv occs name_occ of
706 Nothing -> returnM (extendOccEnv occs name_occ (name, ie))
709 | name == name' -- Duplicate export
710 -> do { warn_dup_exports <- doptM Opt_WarnDuplicateExports ;
711 warnIf warn_dup_exports (dupExportWarn name_occ ie ie') ;
714 | otherwise -- Same occ name but different names: an error
715 -> do { global_env <- getGlobalRdrEnv ;
716 addErr (exportClashErr global_env name name' ie ie') ;
719 name_occ = nameOccName name
722 %*********************************************************
726 %*********************************************************
729 reportDeprecations :: TcGblEnv -> RnM ()
730 reportDeprecations tcg_env
731 = ifOptM Opt_WarnDeprecations $
732 do { (eps,hpt) <- getEpsAndHpt
733 ; mapM_ (check hpt (eps_PIT eps)) all_gres }
735 used_names = findUses (tcg_dus tcg_env) emptyNameSet
736 all_gres = globalRdrEnvElts (tcg_rdr_env tcg_env)
738 check hpt pit (GRE {gre_name = name, gre_prov = Imported (imp_spec:_) _})
739 | name `elemNameSet` used_names
740 , Just deprec_txt <- lookupDeprec hpt pit name
741 = addSrcSpan (is_loc imp_spec) $
742 addWarn (sep [ptext SLIT("Deprecated use of") <+>
743 occNameFlavour (nameOccName name) <+>
748 name_mod = nameModuleName name
749 imp_mod = is_mod imp_spec
750 imp_msg = ptext SLIT("imported from") <+> ppr imp_mod <> extra
751 extra | imp_mod == name_mod = empty
752 | otherwise = ptext SLIT(", but defined in") <+> ppr name_mod
754 check hpt pit ok_gre = returnM () -- Local, or not used, or not deprectated
755 -- The Imported pattern-match: don't deprecate locally defined names
756 -- For a start, we may be exporting a deprecated thing
757 -- Also we may use a deprecated thing in the defn of another
758 -- deprecated things. We may even use a deprecated thing in
759 -- the defn of a non-deprecated thing, when changing a module's
762 lookupDeprec :: HomePackageTable -> PackageIfaceTable
763 -> Name -> Maybe DeprecTxt
764 lookupDeprec hpt pit n
765 = case lookupIface hpt pit (nameModule n) of
766 Just iface -> mi_dep_fn iface n `seqMaybe` -- Bleat if the thing, *or
767 mi_dep_fn iface (nameParent n) -- its parent*, is deprec'd
769 | isWiredInName n -> Nothing
770 -- We have not necessarily loaded the .hi file for a
771 -- wired-in name (yet), although we *could*.
772 -- And we never deprecate them
774 | otherwise -> pprPanic "lookupDeprec" (ppr n)
775 -- By now all the interfaces should have been loaded
777 gre_is_used :: NameSet -> GlobalRdrElt -> Bool
778 gre_is_used used_names gre = gre_name gre `elemNameSet` used_names
781 %*********************************************************
785 %*********************************************************
788 reportUnusedNames :: TcGblEnv -> RnM ()
789 reportUnusedNames gbl_env
790 = do { warnUnusedTopBinds unused_locals
791 ; warnUnusedModules unused_imp_mods
792 ; warnUnusedImports unused_imports
793 ; warnDuplicateImports dup_imps
794 ; printMinimalImports minimal_imports }
796 used_names, all_used_names :: NameSet
797 used_names = findUses (tcg_dus gbl_env) emptyNameSet
798 all_used_names = used_names `unionNameSets`
799 mkNameSet (mapCatMaybes nameParent_maybe (nameSetToList used_names))
800 -- A use of C implies a use of T,
801 -- if C was brought into scope by T(..) or T(C)
803 -- Collect the defined names from the in-scope environment
804 defined_names :: [GlobalRdrElt]
805 defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)
807 -- Note that defined_and_used, defined_but_not_used
808 -- are both [GRE]; that's why we need defined_and_used
809 -- rather than just all_used_names
810 defined_and_used, defined_but_not_used :: [GlobalRdrElt]
811 (defined_and_used, defined_but_not_used)
812 = partition (gre_is_used all_used_names) defined_names
814 -- Find the duplicate imports
815 dup_imps = filter is_dup defined_and_used
816 is_dup (GRE {gre_prov = Imported imp_spec True}) = not (isSingleton imp_spec)
819 -- Filter out the ones that are
820 -- (a) defined in this module, and
821 -- (b) not defined by a 'deriving' clause
822 -- The latter have an Internal Name, so we can filter them out easily
823 unused_locals :: [GlobalRdrElt]
824 unused_locals = filter is_unused_local defined_but_not_used
825 is_unused_local :: GlobalRdrElt -> Bool
826 is_unused_local gre = isLocalGRE gre && isExternalName (gre_name gre)
828 unused_imports :: [GlobalRdrElt]
829 unused_imports = filter unused_imp defined_but_not_used
830 unused_imp (GRE {gre_prov = Imported imp_specs True})
831 = not (all (module_unused . is_mod) imp_specs)
832 -- Don't complain about unused imports if we've already said the
833 -- entire import is unused
834 unused_imp other = False
836 -- To figure out the minimal set of imports, start with the things
837 -- that are in scope (i.e. in gbl_env). Then just combine them
838 -- into a bunch of avails, so they are properly grouped
839 minimal_imports :: FiniteMap ModuleName AvailEnv
840 minimal_imports0 = emptyFM
841 minimal_imports1 = foldr add_name minimal_imports0 defined_and_used
842 minimal_imports = foldr add_inst_mod minimal_imports1 direct_import_mods
843 -- The last line makes sure that we retain all direct imports
844 -- even if we import nothing explicitly.
845 -- It's not necessarily redundant to import such modules. Consider
849 -- The import M() is not *necessarily* redundant, even if
850 -- we suck in no instance decls from M (e.g. it contains
851 -- no instance decls, or This contains no code). It may be
852 -- that we import M solely to ensure that M's orphan instance
853 -- decls (or those in its imports) are visible to people who
854 -- import This. Sigh.
855 -- There's really no good way to detect this, so the error message
856 -- in RnEnv.warnUnusedModules is weakened instead
858 -- We've carefully preserved the provenance so that we can
859 -- construct minimal imports that import the name by (one of)
860 -- the same route(s) as the programmer originally did.
861 add_name (GRE {gre_name = n, gre_prov = Imported imp_specs _}) acc
862 = addToFM_C plusAvailEnv acc (is_mod (head imp_specs))
863 (unitAvailEnv (mk_avail n (nameParent_maybe n)))
867 -- n is the name of the thing, p is the name of its parent
868 mk_avail n (Just p) = AvailTC p [p,n]
869 mk_avail n Nothing | isTcOcc (nameOccName n) = AvailTC n [n]
870 | otherwise = Avail n
872 add_inst_mod (mod,_,_) acc
873 | mod_name `elemFM` acc = acc -- We import something already
874 | otherwise = addToFM acc mod_name emptyAvailEnv
876 mod_name = moduleName mod
877 -- Add an empty collection of imports for a module
878 -- from which we have sucked only instance decls
880 imports = tcg_imports gbl_env
882 direct_import_mods :: [(Module, Maybe Bool, SrcSpan)]
883 -- See the type of the imp_mods for this triple
884 direct_import_mods = moduleEnvElts (imp_mods imports)
886 -- unused_imp_mods are the directly-imported modules
887 -- that are not mentioned in minimal_imports1
888 -- [Note: not 'minimal_imports', because that includes directly-imported
889 -- modules even if we use nothing from them; see notes above]
890 unused_imp_mods = [(mod_name,loc) | (mod,imp,loc) <- direct_import_mods,
891 let mod_name = moduleName mod,
892 not (mod_name `elemFM` minimal_imports1),
893 mod_name /= pRELUDE_Name,
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 :: ModuleName -> 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 ModuleName 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 = moduleNameUserString (moduleName this_mod) ++ ".imports"
927 ppr_mod_ie (mod_name, ies)
928 | mod_name == pRELUDE_Name
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
959 n_mod = nameModuleName 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 ()
1008 addDupDeclErr (n:ns)
1009 = addErrAt (srcLocSpan (nameSrcLoc n)) $
1010 vcat [ptext SLIT("Multiple declarations of") <+> quotes (ppr n),
1011 nest 2 (ptext SLIT("other declarations at:")),
1012 nest 4 (vcat (map ppr sorted_locs))]
1014 sorted_locs = sortLe occ'ed_before (map nameSrcLoc ns)
1015 occ'ed_before a b = case compare a b of
1020 dupExportWarn occ_name ie1 ie2
1021 = hsep [quotes (ppr occ_name),
1022 ptext SLIT("is exported by"), quotes (ppr ie1),
1023 ptext SLIT("and"), quotes (ppr ie2)]
1026 = hsep [ptext SLIT("Duplicate"),
1027 quotes (ptext SLIT("Module") <+> ppr mod),
1028 ptext SLIT("in export list")]
1030 moduleDeprec mod txt
1031 = sep [ ptext SLIT("Module") <+> quotes (ppr mod) <+> ptext SLIT("is deprecated:"),